Skip to content

fix(session-context): select top-level opencode sessions, add --root flag#445

Merged
rhuanbarreto merged 4 commits into
mainfrom
claude/giggly-floating-willow
Jul 2, 2026
Merged

fix(session-context): select top-level opencode sessions, add --root flag#445
rhuanbarreto merged 4 commits into
mainfrom
claude/giggly-floating-willow

Conversation

@rhuanbarreto

Copy link
Copy Markdown
Contributor

Problem

archgate session-context opencode --skip 1 returned the wrong session. Evidence from a real opencode.db: the lessons-learned skill ran --skip 1 in the main dev session and got back a "General process ADR review (@general subagent)" child session — 17 entries of [tool: bash] noise instead of the development transcript.

Two compounding causes:

  1. Sub-agent child sessions polluted recency selection. opencode stores each sub-agent run as a child session (parent_id set) sharing the parent's directory, so the --skip index was meaningless (e.g. 1 top-level + 4 child sessions for the same project).
  2. The --skip 1 guidance was built on a false premise. opencode skills run inline in the calling session (no own session row — verified in the DB: the tool call is recorded in the parent session), so --skip 1 skipped the exact session it was meant to read.

Fix

  • Recency selection only considers top-level sessions (parent_id IS NULL); --session-id can still read any session, including children
  • New --root flag resolves a --session-id child session to its top-level ancestor by walking the parent_id chain (cycle-guarded); without --session-id it is an explicit alias for the new default
  • Skip-overflow error message and available list now reflect top-level sessions
  • Docs (en/nb/pt-br + regenerated llms-full.txt): corrected matching description (session directory field, not path metadata), documented --root

Verification

  • Simulated old vs new logic against a real 28 MB opencode.db: old --skip 1 → sub-agent session in 2/2 projects; new default/--root → correct main session; --session-id <child> --root → resolves to main; --skip 1 now errors honestly
  • bun run validate green (1316 tests), archgate check 39/39, reviewer skill APPROVED
  • New tests: child-session exclusion, explicit child read via --session-id, skip indexing over top-level only, --root chain walk (incl. grandchild)

Release sequencing

The companion plugins-repo PR updates the opencode archgate-lessons-learned SKILL.md to use --root. This CLI change must release first — the skill references the new flag (with a plain-command fallback for older CLIs).

https://claude.ai/code/session_011LcL4xUi6VWYRyz7LpiC6L

…flag

opencode stores sub-agent runs as child sessions (parent_id set) that
share the parent's directory, so recency-based selection with --skip
returned sub-agent transcripts instead of the main development session.
opencode skills also run inline in the calling session (they do not
create their own session row), so the shipped '--skip 1' guidance
skipped the very session it was meant to read.

- Only top-level sessions (parent_id IS NULL) participate in recency
  selection; --session-id can still read any session, incl. children
- New --root flag resolves a --session-id child session to its
  top-level ancestor by walking the parent_id chain (cycle-guarded)
- Skip-overflow error and available list now reflect top-level sessions
- Docs updated (en/nb/pt-br): accurate directory-matching semantics,
  new --root row, reworded --skip

Verified end-to-end against a real opencode.db where '--skip 1'
returned a '@general subagent' child session instead of the parent
development session.

Claude-Session: https://claude.ai/code/session_011LcL4xUi6VWYRyz7LpiC6L
Signed-off-by: Rhuan Barreto <rhuan@barreto.work>
@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: ee76dcc8-b3b9-4fd7-9c22-b9f00e36bfcb

📥 Commits

Reviewing files that changed from the base of the PR and between 918c087 and 57d1a2d.

📒 Files selected for processing (2)
  • .claude/agent-memory/archgate-developer/MEMORY.md
  • .claude/agent-memory/archgate-developer/project_session_context_skip_root_fix.md
📜 Recent review details
⏰ Context from checks skipped due to timeout. (4)
  • GitHub Check: Smoke Test (Windows) / Windows
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (csharp)
  • GitHub Check: Cloudflare Pages
⚠️ CI failures not shown inline (2)

GitHub Actions: DCO / DCO Sign-off Check: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run base="a53b30507a139db915271095a5a29ccefbd7cecf"
 �[36;1mbase="a53b30507a139db915271095a5a29ccefbd7cecf"�[0m
 �[36;1mhead="57d1a2dcf7ba61a90c1b7a14997335897d6e9419"�[0m
 �[36;1mfailed=0�[0m
 �[36;1m�[0m
 �[36;1mfor sha in $(git rev-list --no-merges "$base".."$head"); do�[0m
 �[36;1m  if ! git log -1 --format='%B' "$sha" | grep -qiE '^Signed-off-by: .+ <.+>'; then�[0m
 �[36;1m    echo "::error::Commit $sha is missing a DCO Signed-off-by line."�[0m

GitHub Actions: DCO / 0_DCO Sign-off Check.txt: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run base="a53b30507a139db915271095a5a29ccefbd7cecf"
 �[36;1mbase="a53b30507a139db915271095a5a29ccefbd7cecf"�[0m
 �[36;1mhead="57d1a2dcf7ba61a90c1b7a14997335897d6e9419"�[0m
 �[36;1mfailed=0�[0m
 �[36;1m�[0m
 �[36;1mfor sha in $(git rev-list --no-merges "$base".."$head"); do�[0m
 �[36;1m  if ! git log -1 --format='%B' "$sha" | grep -qiE '^Signed-off-by: .+ <.+>'; then�[0m
 �[36;1m    echo "::error::Commit $sha is missing a DCO Signed-off-by line."�[0m
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-06-11T12:50:28.661Z
Learnt from: rhuanbarreto
Repo: archgate/cli PR: 406
File: .claude/agent-memory/archgate-developer/feedback_prefer_tests_over_adr_rules.md:8-18
Timestamp: 2026-06-11T12:50:28.661Z
Learning: In `archgate/cli`, for markdown files under `.claude/agent-memory/`, follow the established convention: use YAML frontmatter (with a `name:` field used as the document title) and do not require a top-level `#` (H1) heading. During code review, do not flag missing first-line/first-top-level H1 headings (e.g., MD041) for these agent-memory files since markdownlint is not part of the repo’s `bun run validate` lint pipeline (oxlint/oxfmt only).

Applied to files:

  • .claude/agent-memory/archgate-developer/project_session_context_skip_root_fix.md
  • .claude/agent-memory/archgate-developer/MEMORY.md
🔇 Additional comments (2)
.claude/agent-memory/archgate-developer/MEMORY.md (1)

46-49: LGTM!

.claude/agent-memory/archgate-developer/project_session_context_skip_root_fix.md (1)

1-16: LGTM!


📝 Walkthrough

Walkthrough

This PR changes opencode session-context selection semantics: sessions are matched by comparing their directory field to the project root, and sub-agent child sessions (identified via a new parent_id field) are excluded from recency/skip-based selection so the newest top-level session is preferred by default. A new --root CLI flag and corresponding root option in readOpencodeSession resolve a targeted child session up its parent_id chain to its top-level ancestor, with cycle protection. Documentation across English, Norwegian, and Portuguese locales, plus llms-full.txt, was updated to reflect these semantics and the new flag. Tests were refactored with new helper functions and expanded coverage for parent/child selection scenarios. Two agent-memory files were also updated with operational notes.

Changes

Cohort / File(s) Summary
Core selection logic (src/helpers/session-context-opencode.ts) Added root option, parent_id tracking, top-level-only skip/recency filtering, ancestor-walk resolution, updated message fetch and returned sessionId
CLI wiring (src/commands/session-context/opencode.ts) Added --root flag wired to helper, updated --skip help text
Tests (tests/commands/..., tests/helpers/...) Updated call-site expectations, added test helpers (makeSimpleSession, insertMessage, insertPart), added/refactored tests for child-session exclusion, sessionId targeting, skip limits, and root resolution
Documentation (public + en/nb/pt-br mdx) Rewrote opencode session matching description, --skip/--session-id semantics, added --root flag documentation and usage examples
Agent memory (.claude/agent-memory/...) Added operational notes and a new project fix record documenting the skip/root behavior change

Sequence Diagram(s)

sequenceDiagram
  participant CLI as opencode command
  participant Helper as readOpencodeSession
  participant DB as SQLite session table

  CLI->>Helper: readOpencodeSession(options incl. root, skip, sessionId)
  Helper->>DB: query sessions with parent_id
  DB-->>Helper: session rows
  Helper->>Helper: select top-level session via skip/recency or sessionId
  alt root true and selected has parent_id
    Helper->>Helper: walk parent_id chain to top-level ancestor
  end
  Helper->>DB: fetch messages for selected.id
  DB-->>Helper: message rows
  Helper-->>CLI: transcript and sessionId
Loading

Related PRs: None identified.

Suggested labels: documentation, enhancement, cli

Suggested reviewers: archgate-developer

Poem
A rabbit dug through parent trees,
past sub-agent burrows, deep and breezy,
found the root where sessions start,
skipping siblings, playing it smart.
With --root in paw, the path is clear—
top-level warrens, session found here! 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: top-level session selection and the new --root flag.
Description check ✅ Passed The description matches the PR and explains the bug, fix, docs, and verification.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 1, 2026

Copy link
Copy Markdown

Deploying archgate-cli with  Cloudflare Pages  Cloudflare Pages

Latest commit: 57d1a2d
Status: ✅  Deploy successful!
Preview URL: https://e1dcb158.archgate-cli.pages.dev
Branch Preview URL: https://claude-giggly-floating-willo.archgate-cli.pages.dev

View logs

@rhuanbarreto

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Code Coverage

Metric Value
Lines 90.0% (6961 / 7734)
Threshold 90% minimum — met
Platforms Linux + Windows

Full HTML report available in workflow artifacts.

Per-directory breakdown
Directory Coverage Lines
src/commands/ 88.1% 1879 / 2133
src/engine/ 90.9% 1463 / 1610
src/formats/ 100.0% 142 / 142
src/helpers/ 90.3% 3477 / 3849

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/public/llms-full.txt`:
- Around line 4391-4402: docs/public/llms-full.txt is stale and needs to be
regenerated from the source docs. Run the llms-full generator script and commit
the updated output so the generated content matches the current docs; use the
existing docs/public/llms-full.txt entry and the
docs/scripts/generate-llms-full.ts generator as the identifiers to locate the
fix.

In `@docs/src/content/docs/pt-br/reference/cli/session-context.mdx`:
- Around line 63-68: The `--skip` table row in the session context docs is
missing the “always” nuance present in the other locales. Update the Portuguese
text for that row in the session options table so it explicitly says sub-agent
sessions are always excluded, matching the meaning used by the corresponding
`--skip` descriptions elsewhere.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 1511ef46-164b-4e30-9cf1-f0b9762eaa93

📥 Commits

Reviewing files that changed from the base of the PR and between a53b305 and 05f5ba4.

📒 Files selected for processing (9)
  • .claude/agent-memory/archgate-developer/MEMORY.md
  • docs/public/llms-full.txt
  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • docs/src/content/docs/reference/cli/session-context.mdx
  • src/commands/session-context/opencode.ts
  • src/helpers/session-context-opencode.ts
  • tests/commands/session-context/opencode.test.ts
  • tests/helpers/session-context-opencode.test.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: Cloudflare Pages
⚠️ CI failures not shown inline (11)

GitHub Actions: DCO / DCO Sign-off Check: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run base="a53b30507a139db915271095a5a29ccefbd7cecf"
 �[36;1mbase="a53b30507a139db915271095a5a29ccefbd7cecf"�[0m
 �[36;1mhead="05f5ba45d879572fc420096be0cae45b2fa31050"�[0m
 �[36;1mfailed=0�[0m
 �[36;1m�[0m
 �[36;1mfor sha in $(git rev-list --no-merges "$base".."$head"); do�[0m
 �[36;1m  if ! git log -1 --format='%B' "$sha" | grep -qiE '^Signed-off-by: .+ <.+>'; then�[0m
 �[36;1m    echo "::error::Commit $sha is missing a DCO Signed-off-by line."�[0m

GitHub Actions: DCO / 0_DCO Sign-off Check.txt: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run base="a53b30507a139db915271095a5a29ccefbd7cecf"
 �[36;1mbase="a53b30507a139db915271095a5a29ccefbd7cecf"�[0m
 �[36;1mhead="05f5ba45d879572fc420096be0cae45b2fa31050"�[0m
 �[36;1mfailed=0�[0m
 �[36;1m�[0m
 �[36;1mfor sha in $(git rev-list --no-merges "$base".."$head"); do�[0m
 �[36;1m  if ! git log -1 --format='%B' "$sha" | grep -qiE '^Signed-off-by: .+ <.+>'; then�[0m
 �[36;1m    echo "::error::Commit $sha is missing a DCO Signed-off-by line."�[0m

GitHub Actions: Code Quality: PR #445 / Analyze (go): Code Quality: PR #445

Conclusion: failure

View job details

"bundleSupportsIncludeLogs":true,"bundleSupportsOverlay":true,"databaseInterpretResultsSupportsSarifRunProperty":true,"featuresInVersionResult":true,"indirectTracingSupportsStaticBinaries":false,"informsAboutUnsupportedPathFilters":true,"supportsPython312":true,"mrvaPackCreate":true,"threatModelOption":true,"traceCommandUseBuildMode":true,"v2ramSizing":true,"mrvaPackCreateMultipleQueries":true,"setsCodeqlRunnerEnvVar":true,"sarifMergeRunsFromEqualCategory":true,"forceOverwrite":true,"generateSummarySymbolMap":true,"pythonDefaultIsToNotExtractStdlib":true,"queryServerRunQueries":true,"queryServerTrimCacheWithMode":true,"builtinExtractorsSpecifyDefaultQueries":true,"bqrsDiffResultSets":true,"bundleSupportsIncludeOption":true,"suppressesMissingFileBaselineWarning":true}}}
   CODEQL_ACTION_GO_BINARY: /home/runner/work/_temp/codeql-action-go-tracing/bin/go
   CODEQL_RAM: 14575
   CODEQL_THREADS: 4
   CODEQL_PROXY_HOST:
   CODEQL_PROXY_PORT:
   CODEQL_PROXY_CA_CERTIFICATE:
   CODEQL_PROXY_URLS:
 ##[endgroup]
 ##[group]Attempting to automatically build go code
 [command]/opt/hostedtoolcache/CodeQL/2.25.6/x64/codeql/codeql database trace-command --use-build-mode --working-dir /home/runner/work/cli/cli /home/runner/work/_temp/codeql_databases/go
 Picked up JAVA_TOOL_OPTIONS:  -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false
 Running command in /home/runner/work/cli/cli: [/opt/hostedtoolcache/CodeQL/2.25.6/x64/codeql/go/tools/autobuild.sh]
 [] [build-stderr] 2026/07/01 22:51:40 Autobuilder was built with go1.26.0, environment has go1.24.13
 [] [build-stderr] 2026/07/01 22:51:40 LGTM_SRC is /home/runner/work/cli/cli
 [] [build-stderr] 2026/07/01 22:51:40 Found no go.work files in the workspace; looking for go.mod files...
 [] [build-stderr] 2026/07/01 22:51:40 Found 1 go.mod files in: shims/go/go.mod.
 [] [build-stderr] 2026/07/01 22:51:40 Found 1 go.mod file(s).
 [] [build-stderr] 2026/07/01 22:51:40 Import path is 'github.com/archgate/cli'
 [] [build-stderr] 2026/07/0...

GitHub Actions: Code Quality: PR #445 / 4_Analyze (go).txt: Code Quality: PR #445

Conclusion: failure

View job details

1 Extracting types for package crypto/aes.
 [] [build-stderr] 2026/07/01 22:51:51 Done extracting types for package crypto/aes.
 [] [build-stderr] 2026/07/01 22:51:51 Processing package crypto/des.
 [] [build-stderr] 2026/07/01 22:51:51 Extracting types for package crypto/des.
 [] [build-stderr] 2026/07/01 22:51:51 Done extracting types for package crypto/des.
 [] [build-stderr] 2026/07/01 22:51:51 Processing package crypto/internal/fips140/nistec/fiat.
 [] [build-stderr] 2026/07/01 22:51:51 Extracting types for package crypto/internal/fips140/nistec/fiat.
 [] [build-stderr] 2026/07/01 22:51:51 Done extracting types for package crypto/internal/fips140/nistec/fiat.
 [] [build-stderr] 2026/07/01 22:51:51 Processing package crypto/internal/fips140/nistec.
 [] [build-stderr] 2026/07/01 22:51:51 Extracting types for package crypto/internal/fips140/nistec.
 [] [build-stderr] 2026/07/01 22:51:51 Done extracting types for package crypto/internal/fips140/nistec.
 [] [build-stderr] 2026/07/01 22:51:51 Processing package crypto/internal/fips140/ecdh.
 [] [build-stderr] 2026/07/01 22:51:51 Extracting types for package crypto/internal/fips140/ecdh.
 [] [build-stderr] 2026/07/01 22:51:51 Done extracting types for package crypto/internal/fips140/ecdh.
 [] [build-stderr] 2026/07/01 22:51:51 Processing package crypto/internal/fips140/edwards25519/field.
 [] [build-stderr] 2026/07/01 22:51:51 Extracting types for package crypto/internal/fips140/edwards25519/field.
 [] [build-stderr] 2026/07/01 22:51:51 Done extracting types for package crypto/internal/fips140/edwards25519/field.
 [] [build-stderr] 2026/07/01 22:51:51 Processing package crypto/ecdh.
 [] [build-stderr] 2026/07/01 22:51:51 Extracting types for package crypto/ecdh.
 [] [build-stderr] 2026/07/01 22:51:51 Done extracting types for package crypto/ecdh.
 [] [build-stderr] 2026/07/01 22:51:51 Processing package crypto/elliptic.
 [] [build-stderr] 2026/07/01 22:51:51 Extracting types for package crypto/elliptic.
 [] [build-...

GitHub Actions: Validate / Validate Code: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run # shim-tests is skipped when no shim files changed — treat skipped as success.
 �[36;1m# shim-tests is skipped when no shim files changed — treat skipped as success.�[0m
 �[36;1mSHIM_OK="skipped"�[0m
 �[36;1mif [[ "$SHIM_OK" == "skipped" ]]; then SHIM_OK="success"; fi�[0m
 �[36;1m�[0m
 �[36;1mif [[ "success" != "success" ]] || \�[0m
 �[36;1m   [[ "$SHIM_OK" != "success" ]] || \�[0m
 �[36;1m   [[ "success" != "success" ]] || \�[0m
 �[36;1m   [[ "success" != "success" ]] || \�[0m
 �[36;1m   [[ "success" != "success" ]]; then�[0m
 �[36;1m  echo "::error::One or more jobs failed:"�[0m

GitHub Actions: Validate / 0_Validate Code.txt: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run # shim-tests is skipped when no shim files changed — treat skipped as success.
 �[36;1m# shim-tests is skipped when no shim files changed — treat skipped as success.�[0m
 �[36;1mSHIM_OK="skipped"�[0m
 �[36;1mif [[ "$SHIM_OK" == "skipped" ]]; then SHIM_OK="success"; fi�[0m
 �[36;1m�[0m
 �[36;1mif [[ "success" != "success" ]] || \�[0m
 �[36;1m   [[ "$SHIM_OK" != "success" ]] || \�[0m
 �[36;1m   [[ "success" != "success" ]] || \�[0m
 �[36;1m   [[ "success" != "success" ]] || \�[0m
 �[36;1m   [[ "success" != "success" ]]; then�[0m
 �[36;1m  echo "::error::One or more jobs failed:"�[0m

GitHub Actions: Validate / Lint, Test & Check: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run bun run docs/scripts/generate-llms-full.ts
 �[36;1mbun run docs/scripts/generate-llms-full.ts�[0m
 �[36;1mgit diff --exit-code docs/public/llms-full.txt || {�[0m
 �[36;1m  echo "::error::docs/public/llms-full.txt is out of date. Run 'bun run docs/scripts/generate-llms-full.ts' and commit the result."�[0m

GitHub Actions: Validate / 1_Coverage Report.txt: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run COVERAGE="90.0"
 �[36;1mCOVERAGE="90.0"�[0m
 �[36;1mMIN_COVERAGE=90�[0m
 �[36;1mBELOW=$(awk "BEGIN{print ($COVERAGE < $MIN_COVERAGE) ? 1 : 0}")�[0m
 �[36;1mif [ "$BELOW" = "1" ]; then�[0m
 �[36;1m  echo "::error::Code coverage is ${COVERAGE}%, which is below the minimum threshold of ${MIN_COVERAGE}%."�[0m

GitHub Actions: Validate / Smoke Test (Linux) _ Linux: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run if [ -z "$ARCHGATE_VERSION" ]; then
 �[36;1mif [ -z "$ARCHGATE_VERSION" ]; then�[0m
 �[36;1m  # Find the newest release that already has the Linux asset uploaded.�[0m
 �[36;1m  # On release-commit pushes the Validate and Release workflows start�[0m
 �[36;1m  # concurrently, so the latest tag may exist before its binaries are�[0m
 �[36;1m  # uploaded by release-binaries.yml — hitting a 404.�[0m
 �[36;1m  asset="archgate-linux-x64.tar.gz"�[0m
 �[36;1m  tags="$(gh release list --limit 5 --json tagName --jq '.[].tagName' 2>/dev/null || true)"�[0m
 �[36;1m  if [ -z "$tags" ]; then�[0m
 �[36;1m    echo "::warning::No releases found, skipping install.sh smoke test"�[0m
 �[36;1m    exit 0�[0m
 �[36;1m  fi�[0m
 �[36;1m  found=""�[0m
 �[36;1m  for tag in $tags; do�[0m
 �[36;1m    assets="$(gh release view "$tag" --json assets --jq '.assets[].name' 2>/dev/null || true)"�[0m
 �[36;1m    if echo "$assets" | grep -qF "$asset"; then�[0m
 �[36;1m      ARCHGATE_VERSION="$tag"�[0m
 �[36;1m      found=1�[0m
 �[36;1m      break�[0m
 �[36;1m    fi�[0m
 �[36;1m  done�[0m
 �[36;1m  if [ -z "$found" ]; then�[0m
 �[36;1m    echo "::warning::No release with $asset found, skipping install.sh smoke test"�[0m
 �[36;1m    exit 0�[0m
 �[36;1m  fi�[0m
 �[36;1m  export ARCHGATE_VERSION�[0m
 �[36;1mfi�[0m
 �[36;1mecho "Testing install.sh with version $ARCHGATE_VERSION"�[0m
 �[36;1m�[0m
 �[36;1mexport ARCHGATE_INSTALL_DIR="$(mktemp -d)"�[0m
 �[36;1m�[0m
 �[36;1msh install.sh�[0m
 �[36;1m�[0m
 �[36;1mif [ ! -f "$ARCHGATE_INSTALL_DIR/archgate" ]; then�[0m
 �[36;1m  echo "::error::archgate binary not found at $ARCHGATE_INSTALL_DIR/archgate after install"�[0m

GitHub Actions: Validate / Coverage Report: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run COVERAGE="90.0"
 �[36;1mCOVERAGE="90.0"�[0m
 �[36;1mMIN_COVERAGE=90�[0m
 �[36;1mBELOW=$(awk "BEGIN{print ($COVERAGE < $MIN_COVERAGE) ? 1 : 0}")�[0m
 �[36;1mif [ "$BELOW" = "1" ]; then�[0m
 �[36;1m  echo "::error::Code coverage is ${COVERAGE}%, which is below the minimum threshold of ${MIN_COVERAGE}%."�[0m

GitHub Actions: Validate / 3_Smoke Test (Linux) _ Linux.txt: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run if [ -z "$ARCHGATE_VERSION" ]; then
 �[36;1mif [ -z "$ARCHGATE_VERSION" ]; then�[0m
 �[36;1m  # Find the newest release that already has the Linux asset uploaded.�[0m
 �[36;1m  # On release-commit pushes the Validate and Release workflows start�[0m
 �[36;1m  # concurrently, so the latest tag may exist before its binaries are�[0m
 �[36;1m  # uploaded by release-binaries.yml — hitting a 404.�[0m
 �[36;1m  asset="archgate-linux-x64.tar.gz"�[0m
 �[36;1m  tags="$(gh release list --limit 5 --json tagName --jq '.[].tagName' 2>/dev/null || true)"�[0m
 �[36;1m  if [ -z "$tags" ]; then�[0m
 �[36;1m    echo "::warning::No releases found, skipping install.sh smoke test"�[0m
 �[36;1m    exit 0�[0m
 �[36;1m  fi�[0m
 �[36;1m  found=""�[0m
 �[36;1m  for tag in $tags; do�[0m
 �[36;1m    assets="$(gh release view "$tag" --json assets --jq '.assets[].name' 2>/dev/null || true)"�[0m
 �[36;1m    if echo "$assets" | grep -qF "$asset"; then�[0m
 �[36;1m      ARCHGATE_VERSION="$tag"�[0m
 �[36;1m      found=1�[0m
 �[36;1m      break�[0m
 �[36;1m    fi�[0m
 �[36;1m  done�[0m
 �[36;1m  if [ -z "$found" ]; then�[0m
 �[36;1m    echo "::warning::No release with $asset found, skipping install.sh smoke test"�[0m
 �[36;1m    exit 0�[0m
 �[36;1m  fi�[0m
 �[36;1m  export ARCHGATE_VERSION�[0m
 �[36;1mfi�[0m
 �[36;1mecho "Testing install.sh with version $ARCHGATE_VERSION"�[0m
 �[36;1m�[0m
 �[36;1mexport ARCHGATE_INSTALL_DIR="$(mktemp -d)"�[0m
 �[36;1m�[0m
 �[36;1msh install.sh�[0m
 �[36;1m�[0m
 �[36;1mif [ ! -f "$ARCHGATE_INSTALL_DIR/archgate" ]; then�[0m
 �[36;1m  echo "::error::archgate binary not found at $ARCHGATE_INSTALL_DIR/archgate after install"�[0m
🧰 Additional context used
📓 Path-based instructions (22)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Use TypeScript strict mode, ESNext target, and ES modules throughout
Use safeParse() when validating with Zod schemas
Use minimal dependencies; prefer Bun built-ins per ARCH-006

Files:

  • tests/commands/session-context/opencode.test.ts
  • src/commands/session-context/opencode.ts
  • tests/helpers/session-context-opencode.test.ts
  • src/helpers/session-context-opencode.ts
tests/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Test files must mirror src/ directory structure with fixtures in tests/fixtures/

Files:

  • tests/commands/session-context/opencode.test.ts
  • tests/helpers/session-context-opencode.test.ts
**/*.{ts,tsx,json}

📄 CodeRabbit inference engine (CLAUDE.md)

Runtime must use Bun (>=1.2.21), not Node.js compatible

Files:

  • tests/commands/session-context/opencode.test.ts
  • src/commands/session-context/opencode.ts
  • tests/helpers/session-context-opencode.test.ts
  • src/helpers/session-context-opencode.ts
tests/**/*.test.ts

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-005-testing-standards.md)

tests/**/*.test.ts: Use Bun's built-in test runner (bun:test) for all test files, and place tests under tests/ mirroring the src/ directory structure with <module-name>.test.ts naming.
Use temp directories (mkdtemp) for filesystem tests, and clean them up in afterEach or afterAll.
Close external SDK instances (servers, clients, transports, connections) in afterEach or afterAll, managing their lifecycle in hooks rather than inside individual test bodies.
When a test creates a temporary git repository and runs git commit, configure local user.email and user.name immediately after git init.
Test public module interfaces, not private implementation details.
Use descriptive test names that explain the expected behavior.
Every runnable test()/it() must contain at least one expect() assertion; smoke tests must make the contract explicit with expect(() => fn()).not.toThrow() or await expect(promise).resolves.toBeUndefined().
Use test.skip, test.skipIf, or test.todo for intentionally empty or disabled tests; do not use bare return or empty callbacks to skip work.
If the first expect() is being added to a previously assertion-less test file, add expect to the bun:test import.
When mocking fetch in tests, assign directly to globalThis.fetch and restore the original or use mock.restore() afterward.
Wrap spyOn() and inline mockImplementation() usage in try/finally, or create and restore spies in hooks, so mockRestore() always runs.
Only raise a per-test timeout above the global bun test --timeout 60000; never set a shorter per-test timeout.
Mock first-party modules with import * as mod plus spyOn(mod, "fn"), not mock.module().
When a test needs to redirect user-scope paths, mock os.homedir() instead of relying on HOME/Bun.env.HOME; restore the spy in test hooks.
Do not depend on network access in unit tests.
Do not leave temp files after test runs.
Do not leave external SDK instances open after tests...

Files:

  • tests/commands/session-context/opencode.test.ts
  • tests/helpers/session-context-opencode.test.ts
**/*.{ts,tsx,js,jsx,mjs,cjs}

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-006-dependency-policy.md)

**/*.{ts,tsx,js,jsx,mjs,cjs}: Use Bun built-ins for file I/O (Bun.file, Bun.write), HTTP, subprocess execution (Bun.spawn), globbing (Bun.Glob), and testing (bun:test).
Do not use Node.js-specific APIs when Bun alternatives exist; for example, use Bun.file() instead of fs.readFile() for simple reads.
Prefer node: built-in modules such as node:util, node:path, and node:fs over npm alternatives.
Do not use utility libraries for single functions, such as importing lodash for one helper like pick.
Do not use path aliases (tsconfig paths); use relative imports with Bun's native module resolution.
Do not install packages globally during development; use bunx for one-off tools.

Files:

  • tests/commands/session-context/opencode.test.ts
  • src/commands/session-context/opencode.ts
  • tests/helpers/session-context-opencode.test.ts
  • src/helpers/session-context-opencode.ts
tests/**/*.ts

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-009-platform-detection-helper.md)

In test files, use _resetPlatformCache() to simulate different platforms instead of mocking or mutating process.platform directly.

Files:

  • tests/commands/session-context/opencode.test.ts
  • tests/helpers/session-context-opencode.test.ts
{src,tests}/**/*.ts

📄 CodeRabbit inference engine (.archgate/adrs/LEGAL-001-spdx-license-headers.md)

{src,tests}/**/*.ts: Every TypeScript source file in src/ and tests/ must begin with // SPDX-License-Identifier: Apache-2.0 followed by // Copyright 2026 Archgate.
If a TypeScript file has a shebang line (for example #!/usr/bin/env bun in src/cli.ts), the SPDX license header must appear immediately after the shebang.
Use single-line // comments for the SPDX header; do not use block comments (/* */) or alternate license identifiers.

Files:

  • tests/commands/session-context/opencode.test.ts
  • src/commands/session-context/opencode.ts
  • tests/helpers/session-context-opencode.test.ts
  • src/helpers/session-context-opencode.ts
**

⚙️ CodeRabbit configuration file

**: # CLAUDE.md

Archgate is a CLI tool for AI governance via Architecture Decision Records (ADRs) — combining human-readable docs with machine-checkable rules. The CLI dogfoods itself via ADRs in .archgate/adrs/. AI features are delivered as a Claude Code plugin (../plugins/claude-code), not via direct API calls.

Technology Stack

  • Runtime: Bun (>=1.2.21) — not Node.js compatible
  • Language: TypeScript (strict mode, ESNext, ES modules)
  • CLI framework: Commander.js (@commander-js/extra-typings)
  • Linter: Oxlint | Formatter: Oxfmt | Dead exports: Knip | Commits: Conventional Commits

Commands

bun run src/cli.ts <command>  # run CLI locally
bun run lint                  # oxlint
bun run typecheck             # tsc --build
bun run format                # oxfmt --write
bun run format:check          # oxfmt --check
bun run test                  # all tests (not bare `bun test` — picks up --timeout; see GEN-003)
bun run knip                  # dead export detection
bun run validate              # MANDATORY: lint + typecheck + format + test + ADR check + knip + build check
bun run build:check            # verify build compiles (CI builds binaries via release workflow)
bun run commit                # conventional commit wizard

Validation Gate

bun run validate must pass before any task is considered complete. Fail-fast pipeline: lint → typecheck → format → test → ADR check → knip → build check. Mirrors CI in .github/workflows/code-pull-request.yml.

Git Hooks (Git 2.54+)

Config-based hooks in .githooks run validation locally before commits and pushes:

  • pre-commit: lint + typecheck + format:check (~15s)
  • pre-push: full bun run validate (~60s, mirrors CI)

Activate once per clone:

git config --local include.path ../.githooks

Opt out of a specific hook: git config --local hook.<name>.enabled false. Skip all hooks for a single commit: git commit --no-verify.

GitHub Act...

Files:

  • tests/commands/session-context/opencode.test.ts
  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • src/commands/session-context/opencode.ts
  • docs/public/llms-full.txt
  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • tests/helpers/session-context-opencode.test.ts
  • src/helpers/session-context-opencode.ts

⚙️ CodeRabbit configuration file

**: This project uses Archgate — an AI governance framework based on
Architecture Decision Records (ADRs). The ADRs in .archgate/adrs/
are the authoritative rules for this codebase. Each ADR has a companion
.rules.ts file with automated checks that run via archgate check.

When reviewing, you must:

  1. Treat ADR violations as blocking issues, not suggestions.
  2. Cite the specific ADR ID when flagging a violation (e.g., "Violates ARCH-006").
  3. Focus on semantic and contextual violations that automated rules cannot catch —
    the .rules.ts files already cover syntactic/structural patterns.
  4. If you are unsure whether something violates an ADR, flag it as a question
    rather than approving it.

Files:

  • tests/commands/session-context/opencode.test.ts
  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • src/commands/session-context/opencode.ts
  • docs/public/llms-full.txt
  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • tests/helpers/session-context-opencode.test.ts
  • src/helpers/session-context-opencode.ts
docs/src/content/docs/reference/cli/!(index).mdx

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-015-cli-command-documentation-coverage.md)

Every top-level CLI command must have a corresponding reference page at docs/src/content/docs/reference/cli/<name>.mdx, and every non-index.mdx page in that directory must correspond to exactly one top-level command.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
docs/src/content/docs/reference/cli/*.mdx

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-015-cli-command-documentation-coverage.md)

Do not create separate reference pages for subcommands; subcommand documentation must stay inline within the parent command’s .mdx page.

Every parent CLI reference page in docs/src/content/docs/reference/cli/ must contain headings for its direct subcommands using the exact archgate <parent> <sub> format, and must not keep headings for subcommands that no longer exist.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
{src/commands/{*.ts,*/index.ts},docs/src/content/docs/reference/cli/!(index).mdx}

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-015-cli-command-documentation-coverage.md)

{src/commands/{*.ts,*/index.ts},docs/src/content/docs/reference/cli/!(index).mdx}: When a top-level command is added, its docs page must be added in the same change; when a top-level command is removed, its matching docs page must be deleted in the same change.
Keep command and documentation stems aligned when renaming a top-level command file; renaming src/commands/<name>.ts or src/commands/<name>/index.ts must be paired with renaming docs/src/content/docs/reference/cli/<name>.mdx.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
docs/src/content/docs/**/*.mdx

📄 CodeRabbit inference engine (.archgate/adrs/GEN-001-documentation-site.md)

docs/src/content/docs/**/*.mdx: Use MDX (.mdx) for all content pages under docs/src/content/docs/.
Escape literal curly braces in MDX when showing template syntax; do not use bare {} in prose or code-fence labels.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • docs/src/content/docs/nb/reference/cli/session-context.mdx
{docs/src/content/docs/**/*.mdx,docs/astro.config.mjs}

📄 CodeRabbit inference engine (.archgate/adrs/GEN-001-documentation-site.md)

When adding a new documentation page, create the MDX file in docs/src/content/docs/<category>/<slug>.mdx and add the page to docs/astro.config.mjs sidebar configuration.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • docs/src/content/docs/nb/reference/cli/session-context.mdx
docs/src/content/docs/reference/**/*.mdx

📄 CodeRabbit inference engine (.archgate/adrs/GEN-001-documentation-site.md)

Keep reference pages accurate to the CLI source code; when CLI APIs change, update the corresponding reference docs in the same PR.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
docs/src/content/docs/**

📄 CodeRabbit inference engine (.archgate/adrs/GEN-001-documentation-site.md)

Do not create documentation content files outside docs/src/content/docs/; Starlight content must live in that exact directory structure.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • docs/src/content/docs/nb/reference/cli/session-context.mdx
docs/src/content/docs/**/*.{mdx,md}

📄 CodeRabbit inference engine (.archgate/adrs/GEN-002-docs-i18n.md)

docs/src/content/docs/**/*.{mdx,md}: For every English docs page under docs/src/content/docs/, create a translated file in each locale directory with the exact same relative path and filename, and ensure every locale file corresponds to an existing root file (no orphan translations).
When adding or modifying English documentation content, update the corresponding locale files in the same pull request.
Translate all user-facing prose in docs pages, including titles, descriptions, headings, paragraphs, list items, table text, and admonition content.
Translate user-visible text props in Starlight components such as <Card title="..."> and <LinkCard description="...">.
Keep code blocks, CLI commands, file paths, TypeScript identifiers, technical terms, import statements, component names, and link/href/slug attribute values in English.
Keep internal links unchanged and do not add locale prefixes (for example, use /guides/... rather than /pt-br/guides/...).
Preserve MDX curly-brace escaping (\{\}) in translated content.
Preserve Starlight component import statements identically in translated files.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • docs/src/content/docs/nb/reference/cli/session-context.mdx
docs/src/content/docs/pt-br/**/*.{mdx,md}

📄 CodeRabbit inference engine (.archgate/adrs/GEN-002-docs-i18n.md)

Use correct Portuguese diacritical marks in Brazilian Portuguese translations; never write unaccented Portuguese.

Files:

  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
src/commands/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

src/commands/**/*.ts: Commands must export register*Command(program) function that handles I/O only, with no business logic
Use styleText() from node:util for output formatting; support --json flag for machine-readable output and auto-compact JSON in non-TTY/non-CI contexts
Exit with code 0 for success, 1 for violations, 2 for internal errors, and 130 for user cancellation (SIGINT)

src/commands/**/*.ts: Each command module under src/commands/ must export a register*Command(program) function, with one command per file (or one command group via index.ts).
Command files must be thin: they should only parse arguments, call engine/helpers, and format output; business logic must live in src/engine/, src/helpers/, or src/formats/.
Command modules must not use executableDir() for command discovery, must not call .parse() themselves, and must not spawn child processes for subcommand execution.
Subcommand groups should live in nested directories with an index.ts that composes child commands (for example, src/commands/adr/index.ts).

src/commands/**/*.ts: In command files under src/commands/**/*.ts, options that need type narrowing beyond plain strings MUST use new Option() with .addOption() instead of plain .option().
In src/commands/**/*.ts, import Option from @commander-js/extra-typings alongside Command so typed options get full type inference.
In src/commands/**/*.ts, enum-like options with a fixed set of allowed values must use .choices() on an Option to provide runtime validation and compile-time type narrowing.
In src/commands/**/*.ts, options that require type conversion must use .argParser() on an Option object, not a parser function passed as the third argument to .option().
In src/commands/**/*.ts, register typed options with .addOption() rather than .option().
In src/commands/**/*.ts, pass both the choices array and default values with as const when using .choices() and .default() to pr...

Files:

  • src/commands/session-context/opencode.ts
src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

AI features must be delivered as a Claude Code plugin (../plugins/claude-code), not via direct API calls

src/**/*.ts: Use logError() from src/helpers/log.ts for user-facing errors instead of printing errors directly.
Exit with code 1 for expected failures such as missing config, invalid input, or validation violations.
Let unexpected errors crash naturally so they are treated as internal errors with exit code 2.
Include actionable suggestions in user-facing error messages whenever possible.
Write user-facing errors to stderr via logError(); do not send them to stdout.
When findProjectRoot() returns null for commands that do not require .archgate/, fall back to process.cwd() as the path key or working directory.
Catch ExitPromptError from Inquirer in the top-level error boundary and treat it as user cancellation: exit with code 130 without logging an error or sending it to Sentry.
Do not use console.error() directly; use logError() for consistent formatting.
Do not exit with codes other than 0, 1, 2, or 130.
Do not send user-cancellation errors such as Inquirer ExitPromptError to Sentry; filter them in beforeSend.

src/**/*.ts: Use styleText(format, text) from node:util for all terminal colors and formatting in CLI source files; do not use raw ANSI escape codes or third-party color libraries.
Commands that produce structured results and support --json must emit machine-readable JSON to stdout with no colors or decorative formatting.
When a command supports --json, use formatJSON() from src/helpers/output.ts for JSON serialization, and pass forcePretty: true when the user explicitly provided --json.
Use isAgentContext() from src/helpers/output.ts to enable auto-JSON behavior for commands that support both human-readable and JSON output modes.
CLI output must not include emoji; use text symbols and colors instead.
Send normal command output to stdout with console.log(), and send errors, warnings, and de...

Files:

  • src/commands/session-context/opencode.ts
  • src/helpers/session-context-opencode.ts
src/**/!(*platform).ts

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-009-platform-detection-helper.md)

src/**/!(*platform).ts: In src/ TypeScript source files, do not read process.platform directly; use src/helpers/platform.ts (isWindows(), isMacOS(), isLinux(), isWSL(), getPlatformInfo()) for all platform detection.
Use the centralized platform helper instead of duplicating OS/WSL detection logic inline anywhere in src/ TypeScript source.
When behavior differs between Linux and Windows, account for WSL by using isWSL() rather than assuming `

Files:

  • src/commands/session-context/opencode.ts
  • src/helpers/session-context-opencode.ts
docs/src/content/docs/nb/**/*.{mdx,md}

📄 CodeRabbit inference engine (.archgate/adrs/GEN-002-docs-i18n.md)

Use Norwegian Bokmål (not Nynorsk) for Norwegian translations, with the informal du form and correct Norwegian characters (æ, ø, å).

Files:

  • docs/src/content/docs/nb/reference/cli/session-context.mdx
src/{helpers,engine}/**/*.ts

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-002-error-handling.md)

Do not use console.log(), console.warn(), or console.info() directly in helper or engine files; use logInfo() or logWarn() instead. Command files are exempt because they are the I/O layer.

Files:

  • src/helpers/session-context-opencode.ts
🧠 Learnings (1)
📚 Learning: 2026-06-11T12:50:28.661Z
Learnt from: rhuanbarreto
Repo: archgate/cli PR: 406
File: .claude/agent-memory/archgate-developer/feedback_prefer_tests_over_adr_rules.md:8-18
Timestamp: 2026-06-11T12:50:28.661Z
Learning: In `archgate/cli`, for markdown files under `.claude/agent-memory/`, follow the established convention: use YAML frontmatter (with a `name:` field used as the document title) and do not require a top-level `#` (H1) heading. During code review, do not flag missing first-line/first-top-level H1 headings (e.g., MD041) for these agent-memory files since markdownlint is not part of the repo’s `bun run validate` lint pipeline (oxlint/oxfmt only).

Applied to files:

  • .claude/agent-memory/archgate-developer/MEMORY.md
🪛 GitHub Actions: Validate / 6_Lint, Test & Check.txt
docs/public/llms-full.txt

[error] 1-1: CI check failed: docs/public/llms-full.txt is out of date. Run 'bun run docs/scripts/generate-llms-full.ts' and commit the result.

🪛 GitHub Actions: Validate / Lint, Test & Check
docs/public/llms-full.txt

[error] 1-1: docs/public/llms-full.txt is out of date. Run 'bun run docs/scripts/generate-llms-full.ts' and commit the result.

🪛 LanguageTool
docs/src/content/docs/pt-br/reference/cli/session-context.mdx

[uncategorized] ~57-~57: Pontuação duplicada
Context: ...essão principal de desenvolvimento. Use --session-id para ler uma sessão específi...

(DOUBLE_PUNCTUATION_XML)


[style] ~65-~65: Evite abreviações de internet. Considere escrever “não” por extenso. Se quis dizer “n”, coloque entre aspas.
Context: ...----------------------------------- | | --max-entries <n> | Máximo de entradas a retornar (padr...

(INTERNET_ABBREVIATIONS)


[style] ~66-~66: Evite abreviações de internet. Considere escrever “não” por extenso. Se quis dizer “n”, coloque entre aspas.
Context: ... | | --skip <n> | Pular as N sessões de nível ...

(INTERNET_ABBREVIATIONS)


[grammar] ~66-~66: Possível erro de concordância de número.
Context: ...>` | Pular as N sessões de nível superior mais recentes (sessões de sub-agente são excluídas) ...

(GENERAL_NUMBER_AGREEMENT_ERRORS)

🔇 Additional comments (7)
.claude/agent-memory/archgate-developer/MEMORY.md (1)

46-48: LGTM!

src/helpers/session-context-opencode.ts (1)

26-32: LGTM!

Also applies to: 55-68, 98-103, 125-162, 174-174, 223-223

src/commands/session-context/opencode.ts (1)

19-19: LGTM!

Also applies to: 31-42

tests/commands/session-context/opencode.test.ts (1)

187-187: LGTM!

tests/helpers/session-context-opencode.test.ts (1)

91-97: LGTM!

Also applies to: 129-175, 207-208, 224-224, 243-253, 356-368, 384-483

docs/src/content/docs/reference/cli/session-context.mdx (1)

57-68: LGTM!

docs/src/content/docs/nb/reference/cli/session-context.mdx (1)

57-68: LGTM!

Comment thread docs/public/llms-full.txt
Comment thread docs/src/content/docs/pt-br/reference/cli/session-context.mdx
- Port the sibling fan-out regression test from #444, adapted to the
  new semantics (--skip 1 errors honestly; default and --root resolve
  the parent) with unconditional control assertions
- Enrich the root option JSDoc with the inline-skill / sibling fan-out
  rationale
- Document the multi-top-level-session caveat and deterministic
  resolution via --session-id <id> --root in the CLI reference
  (en/nb/pt-br) and regenerate llms-full.txt
- pt-br: add the missing "sempre" nuance to the --skip row
- Port agent-memory captures from #444 (generated plugins skill files;
  session-context skip/root fix incl. the open claude-code/cursor
  follow-up)

Claude-Session: https://claude.ai/code/session_01SGjSjrywTnZDcUqgHWGrTj
Signed-off-by: Rhuan Barreto <rhuan@barreto.work>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/helpers/session-context-opencode.ts (2)

135-172: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

No test coverage for the cycle-protection path in the --root walk.

The seen set guards against a parent_id cycle causing an infinite loop, but this is a safety-critical path (prevents a hang) that doesn't appear to be exercised by any of the added tests (fan-out, skip, explicit child read, root resolution). Consider adding a regression test with a synthetic cycle (e.g. A's parent_id → B, B's parent_id → A) to lock in the termination behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/helpers/session-context-opencode.ts` around lines 135 - 172, Add a
regression test for the `options.root` parent-walk in
`session-context-opencode.ts` to cover the `seen` cycle guard. Create a
synthetic session chain with a `parent_id` loop (for example, two sessions
pointing to each other) and verify the selection logic terminates and returns a
stable result instead of hanging. Place the test alongside the existing session
selection coverage so `matching`, `selected`, and the `--root` traversal
behavior are exercised together.

135-172: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Root-walk byId map spans all sessions, not just the matched project — consider scoping to matching.

The --root ancestor walk builds byId from allSessions (unfiltered by directory) rather than the directory-filtered matching list. Per the documented invariant, sub-agent children always share their parent's directory, so this is currently safe — but if that invariant is ever violated (e.g. a sub-agent spawned with a different cwd, or corrupted parent_id data), the walk would silently resolve to — and return transcript data for — a session from a different project, with no indication to the caller.

Separately, when byId.get(selected.parent_id) misses (dangling parent_id), the loop breaks and selected is returned as-is even though it may not be the true root — again silently, with no signal that resolution was incomplete.

Building byId from matching instead of allSessions would contain any leakage to the current project as a defense-in-depth measure, at no behavioral cost when the invariant holds.

🛡️ Suggested defensive fix
     let selected = target;
     if (options?.root === true) {
-      const byId = new Map(allSessions.map((s) => [s.id, s]));
+      const byId = new Map(matching.map((s) => [s.id, s]));
       const seen = new Set<string>();

Since this depends on an assumption about opencode's own session-graph invariants (that sub-agents always inherit the parent's directory), it would help to confirm this against opencode's actual behavior/schema.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/helpers/session-context-opencode.ts` around lines 135 - 172, The --root
ancestor walk in session-context-opencode should not resolve parents from the
global allSessions set because that can leak across projects if parent_id or
directory invariants are broken. Update the root-walk logic around the
selected/byId lookup so the ancestor map is built from matching instead of
allSessions, keeping resolution scoped to the current project. Also make the
missing-parent case in the while loop explicit in the SessionContext selection
flow so a dangling parent_id does not silently return a non-root session as if
root resolution succeeded.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/helpers/session-context-opencode.ts`:
- Around line 135-172: Add a regression test for the `options.root` parent-walk
in `session-context-opencode.ts` to cover the `seen` cycle guard. Create a
synthetic session chain with a `parent_id` loop (for example, two sessions
pointing to each other) and verify the selection logic terminates and returns a
stable result instead of hanging. Place the test alongside the existing session
selection coverage so `matching`, `selected`, and the `--root` traversal
behavior are exercised together.
- Around line 135-172: The --root ancestor walk in session-context-opencode
should not resolve parents from the global allSessions set because that can leak
across projects if parent_id or directory invariants are broken. Update the
root-walk logic around the selected/byId lookup so the ancestor map is built
from matching instead of allSessions, keeping resolution scoped to the current
project. Also make the missing-parent case in the while loop explicit in the
SessionContext selection flow so a dangling parent_id does not silently return a
non-root session as if root resolution succeeded.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 9f40ee50-0585-4bbb-bb16-dc3ce8cfca1a

📥 Commits

Reviewing files that changed from the base of the PR and between 05f5ba4 and 918c087.

📒 Files selected for processing (9)
  • .claude/agent-memory/archgate-developer/MEMORY.md
  • .claude/agent-memory/archgate-developer/project_plugins_generated_skill_files.md
  • .claude/agent-memory/archgate-developer/project_session_context_skip_root_fix.md
  • docs/public/llms-full.txt
  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • docs/src/content/docs/reference/cli/session-context.mdx
  • src/helpers/session-context-opencode.ts
  • tests/helpers/session-context-opencode.test.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (6)
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Smoke Test (Windows) / Windows
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (csharp)
  • GitHub Check: Cloudflare Pages
⚠️ CI failures not shown inline (2)

GitHub Actions: DCO / DCO Sign-off Check: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run base="a53b30507a139db915271095a5a29ccefbd7cecf"
 �[36;1mbase="a53b30507a139db915271095a5a29ccefbd7cecf"�[0m
 �[36;1mhead="918c0870091f6d8fa41744424f6cb43d90f889a4"�[0m
 �[36;1mfailed=0�[0m
 �[36;1m�[0m
 �[36;1mfor sha in $(git rev-list --no-merges "$base".."$head"); do�[0m
 �[36;1m  if ! git log -1 --format='%B' "$sha" | grep -qiE '^Signed-off-by: .+ <.+>'; then�[0m
 �[36;1m    echo "::error::Commit $sha is missing a DCO Signed-off-by line."�[0m

GitHub Actions: DCO / 0_DCO Sign-off Check.txt: fix(session-context): select top-level opencode sessions, add --root flag

Conclusion: failure

View job details

##[group]Run base="a53b30507a139db915271095a5a29ccefbd7cecf"
 �[36;1mbase="a53b30507a139db915271095a5a29ccefbd7cecf"�[0m
 �[36;1mhead="918c0870091f6d8fa41744424f6cb43d90f889a4"�[0m
 �[36;1mfailed=0�[0m
 �[36;1m�[0m
 �[36;1mfor sha in $(git rev-list --no-merges "$base".."$head"); do�[0m
 �[36;1m  if ! git log -1 --format='%B' "$sha" | grep -qiE '^Signed-off-by: .+ <.+>'; then�[0m
 �[36;1m    echo "::error::Commit $sha is missing a DCO Signed-off-by line."�[0m
🧰 Additional context used
📓 Path-based instructions (21)
docs/src/content/docs/**/*.mdx

📄 CodeRabbit inference engine (.archgate/adrs/GEN-001-documentation-site.md)

docs/src/content/docs/**/*.mdx: Use MDX (.mdx) for all content pages under docs/src/content/docs/.
Escape literal curly braces in MDX when showing template syntax; do not use bare {} in prose or code-fence labels.

Files:

  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
{docs/src/content/docs/**/*.mdx,docs/astro.config.mjs}

📄 CodeRabbit inference engine (.archgate/adrs/GEN-001-documentation-site.md)

When adding a new documentation page, create the MDX file in docs/src/content/docs/<category>/<slug>.mdx and add the page to docs/astro.config.mjs sidebar configuration.

Files:

  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
docs/src/content/docs/**

📄 CodeRabbit inference engine (.archgate/adrs/GEN-001-documentation-site.md)

Do not create documentation content files outside docs/src/content/docs/; Starlight content must live in that exact directory structure.

Files:

  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
docs/src/content/docs/**/*.{mdx,md}

📄 CodeRabbit inference engine (.archgate/adrs/GEN-002-docs-i18n.md)

docs/src/content/docs/**/*.{mdx,md}: For every English docs page under docs/src/content/docs/, create a translated file in each locale directory with the exact same relative path and filename, and ensure every locale file corresponds to an existing root file (no orphan translations).
When adding or modifying English documentation content, update the corresponding locale files in the same pull request.
Translate all user-facing prose in docs pages, including titles, descriptions, headings, paragraphs, list items, table text, and admonition content.
Translate user-visible text props in Starlight components such as <Card title="..."> and <LinkCard description="...">.
Keep code blocks, CLI commands, file paths, TypeScript identifiers, technical terms, import statements, component names, and link/href/slug attribute values in English.
Keep internal links unchanged and do not add locale prefixes (for example, use /guides/... rather than /pt-br/guides/...).
Preserve MDX curly-brace escaping (\{\}) in translated content.
Preserve Starlight component import statements identically in translated files.

Files:

  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
docs/src/content/docs/nb/**/*.{mdx,md}

📄 CodeRabbit inference engine (.archgate/adrs/GEN-002-docs-i18n.md)

Use Norwegian Bokmål (not Nynorsk) for Norwegian translations, with the informal du form and correct Norwegian characters (æ, ø, å).

Files:

  • docs/src/content/docs/nb/reference/cli/session-context.mdx
**

⚙️ CodeRabbit configuration file

**: # CLAUDE.md

Archgate is a CLI tool for AI governance via Architecture Decision Records (ADRs) — combining human-readable docs with machine-checkable rules. The CLI dogfoods itself via ADRs in .archgate/adrs/. AI features are delivered as a Claude Code plugin (../plugins/claude-code), not via direct API calls.

Technology Stack

  • Runtime: Bun (>=1.2.21) — not Node.js compatible
  • Language: TypeScript (strict mode, ESNext, ES modules)
  • CLI framework: Commander.js (@commander-js/extra-typings)
  • Linter: Oxlint | Formatter: Oxfmt | Dead exports: Knip | Commits: Conventional Commits

Commands

bun run src/cli.ts <command>  # run CLI locally
bun run lint                  # oxlint
bun run typecheck             # tsc --build
bun run format                # oxfmt --write
bun run format:check          # oxfmt --check
bun run test                  # all tests (not bare `bun test` — picks up --timeout; see GEN-003)
bun run knip                  # dead export detection
bun run validate              # MANDATORY: lint + typecheck + format + test + ADR check + knip + build check
bun run build:check            # verify build compiles (CI builds binaries via release workflow)
bun run commit                # conventional commit wizard

Validation Gate

bun run validate must pass before any task is considered complete. Fail-fast pipeline: lint → typecheck → format → test → ADR check → knip → build check. Mirrors CI in .github/workflows/code-pull-request.yml.

Git Hooks (Git 2.54+)

Config-based hooks in .githooks run validation locally before commits and pushes:

  • pre-commit: lint + typecheck + format:check (~15s)
  • pre-push: full bun run validate (~60s, mirrors CI)

Activate once per clone:

git config --local include.path ../.githooks

Opt out of a specific hook: git config --local hook.<name>.enabled false. Skip all hooks for a single commit: git commit --no-verify.

GitHub Act...

Files:

  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • docs/public/llms-full.txt
  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • src/helpers/session-context-opencode.ts
  • tests/helpers/session-context-opencode.test.ts

⚙️ CodeRabbit configuration file

**: This project uses Archgate — an AI governance framework based on
Architecture Decision Records (ADRs). The ADRs in .archgate/adrs/
are the authoritative rules for this codebase. Each ADR has a companion
.rules.ts file with automated checks that run via archgate check.

When reviewing, you must:

  1. Treat ADR violations as blocking issues, not suggestions.
  2. Cite the specific ADR ID when flagging a violation (e.g., "Violates ARCH-006").
  3. Focus on semantic and contextual violations that automated rules cannot catch —
    the .rules.ts files already cover syntactic/structural patterns.
  4. If you are unsure whether something violates an ADR, flag it as a question
    rather than approving it.

Files:

  • docs/src/content/docs/nb/reference/cli/session-context.mdx
  • docs/public/llms-full.txt
  • docs/src/content/docs/reference/cli/session-context.mdx
  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
  • src/helpers/session-context-opencode.ts
  • tests/helpers/session-context-opencode.test.ts
docs/src/content/docs/reference/cli/!(index).mdx

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-015-cli-command-documentation-coverage.md)

Every top-level CLI command must have a corresponding reference page at docs/src/content/docs/reference/cli/<name>.mdx, and every non-index.mdx page in that directory must correspond to exactly one top-level command.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
docs/src/content/docs/reference/cli/*.mdx

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-015-cli-command-documentation-coverage.md)

Do not create separate reference pages for subcommands; subcommand documentation must stay inline within the parent command’s .mdx page.

Every parent CLI reference page in docs/src/content/docs/reference/cli/ must contain headings for its direct subcommands using the exact archgate <parent> <sub> format, and must not keep headings for subcommands that no longer exist.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
{src/commands/{*.ts,*/index.ts},docs/src/content/docs/reference/cli/!(index).mdx}

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-015-cli-command-documentation-coverage.md)

{src/commands/{*.ts,*/index.ts},docs/src/content/docs/reference/cli/!(index).mdx}: When a top-level command is added, its docs page must be added in the same change; when a top-level command is removed, its matching docs page must be deleted in the same change.
Keep command and documentation stems aligned when renaming a top-level command file; renaming src/commands/<name>.ts or src/commands/<name>/index.ts must be paired with renaming docs/src/content/docs/reference/cli/<name>.mdx.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
docs/src/content/docs/reference/**/*.mdx

📄 CodeRabbit inference engine (.archgate/adrs/GEN-001-documentation-site.md)

Keep reference pages accurate to the CLI source code; when CLI APIs change, update the corresponding reference docs in the same PR.

Files:

  • docs/src/content/docs/reference/cli/session-context.mdx
docs/src/content/docs/pt-br/**/*.{mdx,md}

📄 CodeRabbit inference engine (.archgate/adrs/GEN-002-docs-i18n.md)

Use correct Portuguese diacritical marks in Brazilian Portuguese translations; never write unaccented Portuguese.

Files:

  • docs/src/content/docs/pt-br/reference/cli/session-context.mdx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Use TypeScript strict mode, ESNext target, and ES modules throughout
Use safeParse() when validating with Zod schemas
Use minimal dependencies; prefer Bun built-ins per ARCH-006

Files:

  • src/helpers/session-context-opencode.ts
  • tests/helpers/session-context-opencode.test.ts
**/*.{ts,tsx,json}

📄 CodeRabbit inference engine (CLAUDE.md)

Runtime must use Bun (>=1.2.21), not Node.js compatible

Files:

  • src/helpers/session-context-opencode.ts
  • tests/helpers/session-context-opencode.test.ts
src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

AI features must be delivered as a Claude Code plugin (../plugins/claude-code), not via direct API calls

src/**/*.ts: Use logError() from src/helpers/log.ts for user-facing errors instead of printing errors directly.
Exit with code 1 for expected failures such as missing config, invalid input, or validation violations.
Let unexpected errors crash naturally so they are treated as internal errors with exit code 2.
Include actionable suggestions in user-facing error messages whenever possible.
Write user-facing errors to stderr via logError(); do not send them to stdout.
When findProjectRoot() returns null for commands that do not require .archgate/, fall back to process.cwd() as the path key or working directory.
Catch ExitPromptError from Inquirer in the top-level error boundary and treat it as user cancellation: exit with code 130 without logging an error or sending it to Sentry.
Do not use console.error() directly; use logError() for consistent formatting.
Do not exit with codes other than 0, 1, 2, or 130.
Do not send user-cancellation errors such as Inquirer ExitPromptError to Sentry; filter them in beforeSend.

src/**/*.ts: Use styleText(format, text) from node:util for all terminal colors and formatting in CLI source files; do not use raw ANSI escape codes or third-party color libraries.
Commands that produce structured results and support --json must emit machine-readable JSON to stdout with no colors or decorative formatting.
When a command supports --json, use formatJSON() from src/helpers/output.ts for JSON serialization, and pass forcePretty: true when the user explicitly provided --json.
Use isAgentContext() from src/helpers/output.ts to enable auto-JSON behavior for commands that support both human-readable and JSON output modes.
CLI output must not include emoji; use text symbols and colors instead.
Send normal command output to stdout with console.log(), and send errors, warnings, and de...

Files:

  • src/helpers/session-context-opencode.ts
src/{helpers,engine}/**/*.ts

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-002-error-handling.md)

Do not use console.log(), console.warn(), or console.info() directly in helper or engine files; use logInfo() or logWarn() instead. Command files are exempt because they are the I/O layer.

Files:

  • src/helpers/session-context-opencode.ts
**/*.{ts,tsx,js,jsx,mjs,cjs}

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-006-dependency-policy.md)

**/*.{ts,tsx,js,jsx,mjs,cjs}: Use Bun built-ins for file I/O (Bun.file, Bun.write), HTTP, subprocess execution (Bun.spawn), globbing (Bun.Glob), and testing (bun:test).
Do not use Node.js-specific APIs when Bun alternatives exist; for example, use Bun.file() instead of fs.readFile() for simple reads.
Prefer node: built-in modules such as node:util, node:path, and node:fs over npm alternatives.
Do not use utility libraries for single functions, such as importing lodash for one helper like pick.
Do not use path aliases (tsconfig paths); use relative imports with Bun's native module resolution.
Do not install packages globally during development; use bunx for one-off tools.

Files:

  • src/helpers/session-context-opencode.ts
  • tests/helpers/session-context-opencode.test.ts
src/**/!(*platform).ts

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-009-platform-detection-helper.md)

src/**/!(*platform).ts: In src/ TypeScript source files, do not read process.platform directly; use src/helpers/platform.ts (isWindows(), isMacOS(), isLinux(), isWSL(), getPlatformInfo()) for all platform detection.
Use the centralized platform helper instead of duplicating OS/WSL detection logic inline anywhere in src/ TypeScript source.
When behavior differs between Linux and Windows, account for WSL by using isWSL() rather than assuming `

Files:

  • src/helpers/session-context-opencode.ts
{src,tests}/**/*.ts

📄 CodeRabbit inference engine (.archgate/adrs/LEGAL-001-spdx-license-headers.md)

{src,tests}/**/*.ts: Every TypeScript source file in src/ and tests/ must begin with // SPDX-License-Identifier: Apache-2.0 followed by // Copyright 2026 Archgate.
If a TypeScript file has a shebang line (for example #!/usr/bin/env bun in src/cli.ts), the SPDX license header must appear immediately after the shebang.
Use single-line // comments for the SPDX header; do not use block comments (/* */) or alternate license identifiers.

Files:

  • src/helpers/session-context-opencode.ts
  • tests/helpers/session-context-opencode.test.ts
tests/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Test files must mirror src/ directory structure with fixtures in tests/fixtures/

Files:

  • tests/helpers/session-context-opencode.test.ts
tests/**/*.test.ts

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-005-testing-standards.md)

tests/**/*.test.ts: Use Bun's built-in test runner (bun:test) for all test files, and place tests under tests/ mirroring the src/ directory structure with <module-name>.test.ts naming.
Use temp directories (mkdtemp) for filesystem tests, and clean them up in afterEach or afterAll.
Close external SDK instances (servers, clients, transports, connections) in afterEach or afterAll, managing their lifecycle in hooks rather than inside individual test bodies.
When a test creates a temporary git repository and runs git commit, configure local user.email and user.name immediately after git init.
Test public module interfaces, not private implementation details.
Use descriptive test names that explain the expected behavior.
Every runnable test()/it() must contain at least one expect() assertion; smoke tests must make the contract explicit with expect(() => fn()).not.toThrow() or await expect(promise).resolves.toBeUndefined().
Use test.skip, test.skipIf, or test.todo for intentionally empty or disabled tests; do not use bare return or empty callbacks to skip work.
If the first expect() is being added to a previously assertion-less test file, add expect to the bun:test import.
When mocking fetch in tests, assign directly to globalThis.fetch and restore the original or use mock.restore() afterward.
Wrap spyOn() and inline mockImplementation() usage in try/finally, or create and restore spies in hooks, so mockRestore() always runs.
Only raise a per-test timeout above the global bun test --timeout 60000; never set a shorter per-test timeout.
Mock first-party modules with import * as mod plus spyOn(mod, "fn"), not mock.module().
When a test needs to redirect user-scope paths, mock os.homedir() instead of relying on HOME/Bun.env.HOME; restore the spy in test hooks.
Do not depend on network access in unit tests.
Do not leave temp files after test runs.
Do not leave external SDK instances open after tests...

Files:

  • tests/helpers/session-context-opencode.test.ts
tests/**/*.ts

📄 CodeRabbit inference engine (.archgate/adrs/ARCH-009-platform-detection-helper.md)

In test files, use _resetPlatformCache() to simulate different platforms instead of mocking or mutating process.platform directly.

Files:

  • tests/helpers/session-context-opencode.test.ts
🧠 Learnings (1)
📚 Learning: 2026-06-11T12:50:28.661Z
Learnt from: rhuanbarreto
Repo: archgate/cli PR: 406
File: .claude/agent-memory/archgate-developer/feedback_prefer_tests_over_adr_rules.md:8-18
Timestamp: 2026-06-11T12:50:28.661Z
Learning: In `archgate/cli`, for markdown files under `.claude/agent-memory/`, follow the established convention: use YAML frontmatter (with a `name:` field used as the document title) and do not require a top-level `#` (H1) heading. During code review, do not flag missing first-line/first-top-level H1 headings (e.g., MD041) for these agent-memory files since markdownlint is not part of the repo’s `bun run validate` lint pipeline (oxlint/oxfmt only).

Applied to files:

  • .claude/agent-memory/archgate-developer/project_plugins_generated_skill_files.md
  • .claude/agent-memory/archgate-developer/project_session_context_skip_root_fix.md
  • .claude/agent-memory/archgate-developer/MEMORY.md
🪛 LanguageTool
docs/src/content/docs/pt-br/reference/cli/session-context.mdx

[style] ~67-~67: Evite abreviações de internet. Considere escrever “não” por extenso. Se quis dizer “n”, coloque entre aspas.
Context: ...----------------------------------- | | --max-entries <n> | Máximo de entradas a retornar (padr...

(INTERNET_ABBREVIATIONS)


[style] ~68-~68: Evite abreviações de internet. Considere escrever “não” por extenso. Se quis dizer “n”, coloque entre aspas.
Context: ... | | --skip <n> | Pular as N sessões de nível ...

(INTERNET_ABBREVIATIONS)


[grammar] ~68-~68: Possível erro de concordância de número.
Context: ...>` | Pular as N sessões de nível superior mais recentes (sessões de sub-agente são sempre exclu...

(GENERAL_NUMBER_AGREEMENT_ERRORS)

🪛 markdownlint-cli2 (0.22.1)
.claude/agent-memory/archgate-developer/project_plugins_generated_skill_files.md

[warning] 8-8: First line in a file should be a top-level heading

(MD041, first-line-heading, first-line-h1)

.claude/agent-memory/archgate-developer/project_session_context_skip_root_fix.md

[warning] 8-8: First line in a file should be a top-level heading

(MD041, first-line-heading, first-line-h1)

🔇 Additional comments (12)
.claude/agent-memory/archgate-developer/MEMORY.md (1)

46-48: LGTM!

Also applies to: 86-90

.claude/agent-memory/archgate-developer/project_plugins_generated_skill_files.md (1)

8-12: LGTM!

.claude/agent-memory/archgate-developer/project_session_context_skip_root_fix.md (1)

8-16: LGTM!

docs/src/content/docs/pt-br/reference/cli/session-context.mdx (2)

65-70: Previously-flagged "sempre" nuance now present.

The earlier review comment about the pt-br --skip row dropping the "always" nuance is resolved — line 68 now reads "sessões de sub-agente são sempre excluídas", matching en/nb.


57-64: LGTM!

Also applies to: 103-108

src/helpers/session-context-opencode.ts (3)

26-43: LGTM!


105-113: LGTM!


184-184: LGTM!

Also applies to: 233-233

tests/helpers/session-context-opencode.test.ts (1)

452-480: LGTM! Good regression coverage for the exact fan-out scenario described in the PR objective (newer siblings must not shadow the parent).

docs/public/llms-full.txt (1)

4391-4404: LGTM! Content is consistent with the updated docs/src/content/docs/reference/cli/session-context.mdx, and the previously-flagged staleness issue appears resolved.

Also applies to: 4438-4442

docs/src/content/docs/nb/reference/cli/session-context.mdx (1)

57-70: LGTM!

Also applies to: 103-108

docs/src/content/docs/reference/cli/session-context.mdx (1)

57-70: LGTM!

Also applies to: 103-108

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 2, 2026
- Haiku reviewer await-on-sync false positive recurred (ARCH-NONE)
- Git Bash /tmp paths are invisible to Windows-native tools
- plugins-repo validate fails locally on Windows (service test /tmp
  sqlite path); use build/check-artifacts scripts locally instead

Claude-Session: https://claude.ai/code/session_01SGjSjrywTnZDcUqgHWGrTj
Signed-off-by: Rhuan Barreto <rhuan@barreto.work>
The plugins repo is private while this repo is public — the ported
memory files exposed its internals (repo paths, build scripts, service
test structure). Remove the generated-skill-files memory and the
Sibling Repo section, and sanitize the remaining notes to only
reference the publicly distributed plugin behavior. The detailed
memories move to the private plugins repo.

Claude-Session: https://claude.ai/code/session_01SGjSjrywTnZDcUqgHWGrTj
Signed-off-by: Rhuan Barreto <rhuan@barreto.work>
@rhuanbarreto rhuanbarreto merged commit 29b13f4 into main Jul 2, 2026
21 checks passed
@rhuanbarreto rhuanbarreto deleted the claude/giggly-floating-willow branch July 2, 2026 08:46
@archgatebot archgatebot Bot mentioned this pull request Jul 1, 2026
rhuanbarreto added a commit that referenced this pull request Jul 2, 2026
…ip and its false premise (#446)

## Problem

Follow-up to #445. The `--skip` flag on every session-context subcommand
existed for one advertised purpose: "skip the sub-agent's own session to
read the parent." Verified false on real data (skills run inline;
Agent-tool sub-agents create no project session files; zero
`isSidechain` entries). With that premise dead, positional recency
guessing had no remaining role — reading the current conversation needs
no knobs, and addressing an earlier session should be explicit.

## New API (breaking)

Each editor subcommand is now a command group; the editor is the
namespace, so no `--editor` flag anywhere:

| Command | Purpose |
|---|---|
| `session-context <editor> [--max-entries]` | Read the **current
conversation** (default action) |
| `session-context <editor> list` | That editor's sessions for the
project as JSON (`id` + `updatedAt`; opencode adds `title`, lists
top-level sessions only) |
| `session-context <editor> show <session-id> [--max-entries]` | Read a
specific session; `--root` exists only on `opencode show` (child →
top-level ancestor) |

Removed: `--skip` everywhere; `--session-id` flags; `--root` from the
opencode read. (Intermediate shapes iterated on this unreleased branch —
per-editor `--list`/`--session-id` flags, then top-level `list`/`show`
subcommands with `--editor` — are also gone.)

## Notes

- Sub-subcommands are documented as `####` blocks inside each editor's
docs section — same pattern as `adr domain`, matching ARCH-016's
one-level rule scope
- list/show behavior tests spawn the real CLI with HOME/USERPROFILE/XDG
redirected (Bun's `mock.module` state is process-global across test
files, so in-process tests would race the sibling tests' helper mocks)
- `bun run validate` green (1349 tests, 39/39 ADR checks); live smoke
test: `claude-code list`, `claude-code show <real-id>` verified against
real stores; `session-context list` and `--session-id` correctly
rejected
- Docs rewritten in en/nb/pt-br; `llms-full.txt` regenerated; agent
memory updated with the final API

## Release sequencing

The distributed lessons-learned skill's escape-hatch text references
`<editor> list`/`<editor> show` — **this CLI must release before the
plugin change ships**, and the plugin release should follow promptly
(already-installed skills referencing `--skip 1` will hit their
error-fallback path on the new CLI).

https://claude.ai/code/session_01SGjSjrywTnZDcUqgHWGrTj

---------

Signed-off-by: Rhuan Barreto <rhuan@barreto.work>
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
rhuanbarreto pushed a commit that referenced this pull request Jul 3, 2026
# archgate

## [0.46.0](v0.45.7...v0.46.0)
(2026-07-02)

### ⚠ BREAKING CHANGES

* **session-context:** per-editor list/show subcommands; remove --skip
and its false premise (#446)

### Features

* **session-context:** per-editor list/show subcommands; remove --skip
and its false premise
([#446](#446))
([dd96230](dd96230))

### Bug Fixes

* **ci:** read POSTHOG_PROJECT_ID from secrets, not vars, in release
annotation ([#443](#443))
([a53b305](a53b305))
* detect opencode Desktop app installs, not just the CLI
([#439](#439))
([ed92b2b](ed92b2b))
* **hooks:** force bash shell for WorktreeCreate hook on Windows
([#442](#442))
([9da86cf](9da86cf))
* **release:** cap breaking-change bumps to minor while pre-1.0
([#447](#447))
([3df6c91](3df6c91)),
closes [#446](#446)
[#440](#440)
[#440](#440)
[#440](#440)
* repair broken WorktreeCreate hook and add PR approval policy
([#441](#441))
([de5e97d](de5e97d))
* **session-context:** select top-level opencode sessions, add --root
flag ([#445](#445))
([29b13f4](29b13f4))

---
This PR was generated with
[simple-release](https://github.com/TrigenSoftware/simple-release).

<details>
<summary>📄 Cheatsheet</summary>
<br>



You can configure the bot's behavior through a pull request comment
using the `!simple-release/set-options` command.

### Command Format

````md
!simple-release/set-options

```json
{
  "bump": {},
  "publish": {}
}
```
````

### Useful Parameters

#### Bump

| Parameter | Type | Description |
|-----------|------|-------------|
| `version` | `string` | Force set specific version |
| `as` | `'major' \| 'minor' \| 'patch' \| 'prerelease'` | Release type
|
| `prerelease` | `string` | Pre-release identifier (e.g., "alpha",
"beta") |
| `firstRelease` | `boolean` | Whether this is the first release |
| `skip` | `boolean` | Skip version bump |
| `byProject` | `Record<string, object>` | Per-project bump options for
monorepos |

#### Publish

| Parameter | Type | Description |
|-----------|------|-------------|
| `skip` | `boolean` | Skip publishing |
| `access` | `'public' \| 'restricted'` | Package access level |
| `tag` | `string` | Tag for npm publication |

### Usage Examples

#### Force specific version

````md
!simple-release/set-options

```json
{
  "bump": {
    "version": "2.0.0"
  }
}
```
````

#### Force major bump

````md
!simple-release/set-options

```json
{
  "bump": {
    "as": "major"
  }
}
```
````

#### Create alpha pre-release

````md
!simple-release/set-options

```json
{
  "bump": {
    "prerelease": "alpha"
  }
}
```
````

#### Publish with specific access and tag

````md
!simple-release/set-options

```json
{
  "bump": {
    "prerelease": "beta"
  },
  "publish": {
    "access": "public",
    "tag": "beta"
  }
}
```
````

### Access Restrictions

The command can only be used by users with permissions:
- repository owner
- organization member
- collaborator

### Notes

- The last comment with `!simple-release/set-options` command takes
priority
- JSON must be valid, otherwise the command will be ignored
- Parameters apply only to the current release execution
- The command can be updated by editing the comment or adding a new one


</details>

<!--
  Please do not edit this comment.
  simple-release-pull-request: true
  simple-release-branch-from: release
  simple-release-branch-to: main
-->

Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant