pantheon-opencode 1.6.0-beta.9 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +126 -376
  4. package/README.md +83 -610
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +366 -132
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +19 -11
  10. package/plugin.json +1 -1
  11. package/pyproject.toml +6 -2
  12. package/scripts/_pantheon_paths.py +24 -0
  13. package/scripts/build-agents-md.mjs +368 -69
  14. package/scripts/changelog-merge.mjs +161 -0
  15. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  16. package/scripts/docs-check-changelog.mjs +204 -0
  17. package/scripts/docs-link-check.mjs +314 -0
  18. package/scripts/docs-media.mjs +157 -0
  19. package/scripts/doctor.mjs +828 -40
  20. package/scripts/install/agents-md.mjs +2 -2
  21. package/scripts/install/backup.mjs +648 -0
  22. package/scripts/install/cli-ui.mjs +303 -72
  23. package/scripts/install/component-selection.mjs +61 -0
  24. package/scripts/install/config-migration.mjs +583 -27
  25. package/scripts/install/exit-codes.mjs +26 -0
  26. package/scripts/install/file-inventory.mjs +555 -0
  27. package/scripts/install/health-check.mjs +31 -25
  28. package/scripts/install/interactive.mjs +78 -383
  29. package/scripts/install/migrate.mjs +49 -25
  30. package/scripts/install/model-picker.mjs +218 -250
  31. package/scripts/install/opencode-version.mjs +83 -21
  32. package/scripts/install/opencode.mjs +1413 -154
  33. package/scripts/install/plan-artifact.mjs +517 -0
  34. package/scripts/install/plan.mjs +475 -0
  35. package/scripts/install/plugin.mjs +214 -27
  36. package/scripts/install/prompt-result.mjs +2 -0
  37. package/scripts/install/shared.mjs +256 -99
  38. package/scripts/install/state.mjs +63 -8
  39. package/scripts/install/strings.mjs +60 -4
  40. package/scripts/install/venv.mjs +90 -47
  41. package/scripts/install/verify.mjs +128 -0
  42. package/scripts/install/vision-prompt.mjs +173 -0
  43. package/scripts/install-mcp.mjs +2 -2
  44. package/scripts/manifest-inventory.mjs +49 -3
  45. package/scripts/mcp_persistence.py +1535 -1050
  46. package/scripts/memory_mcp.py +12 -843
  47. package/scripts/node-engine-policy.mjs +85 -0
  48. package/scripts/package-evidence.mjs +10 -2
  49. package/scripts/postinstall.mjs +26 -26
  50. package/scripts/probe-pantheon-cost.mjs +118 -19
  51. package/scripts/prune.mjs +9 -3
  52. package/scripts/reconcile.mjs +325 -0
  53. package/scripts/release-gates.mjs +682 -0
  54. package/scripts/restore.mjs +222 -0
  55. package/scripts/run-node-tests.mjs +24 -8
  56. package/scripts/sync-artifacts.mjs +19 -7
  57. package/scripts/sync-tui.mjs +5 -1
  58. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  59. package/scripts/uninstall.mjs +369 -34
  60. package/scripts/update.mjs +164 -0
  61. package/scripts/validate-node-engine-policy.mjs +13 -0
  62. package/scripts/version-check.mjs +34 -1
  63. package/scripts/versioning.mjs +23 -3
  64. package/scripts/vision-status.mjs +682 -0
  65. package/skills-lock.json +8 -8
  66. package/src/agents/aphrodite.md +13 -10
  67. package/src/agents/apollo.md +4 -5
  68. package/src/agents/athena.md +74 -46
  69. package/src/agents/demeter.md +10 -7
  70. package/src/agents/gaia.md +0 -1
  71. package/src/agents/hephaestus.md +4 -3
  72. package/src/agents/hermes.md +10 -9
  73. package/src/agents/iris.md +6 -1
  74. package/src/agents/mnemosyne.md +10 -4
  75. package/src/agents/nyx.md +4 -4
  76. package/src/agents/prometheus.md +12 -11
  77. package/src/agents/talos.md +6 -0
  78. package/src/agents/zeus.md +84 -56
  79. package/src/instructions/agent-return-format.instructions.md +12 -41
  80. package/src/instructions/memory-protocol.instructions.md +5 -11
  81. package/src/instructions/test-economy.instructions.md +12 -0
  82. package/src/instructions/yagni.instructions.md +6 -15
  83. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  84. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  85. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  86. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  87. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  88. package/src/mcp/_pantheon_paths.py +24 -0
  89. package/src/mcp/mcp_codemap_module.py +86 -18
  90. package/src/mcp/mcp_persistence.py +1535 -1050
  91. package/src/mcp/memory_mcp.py +444 -94
  92. package/src/mcp/pantheon_vision.py +285 -41
  93. package/src/mcp/requirements-mcp.txt +5 -0
  94. package/src/pantheon/context-pruner.ts +541 -0
  95. package/src/pantheon/cost-command.ts +814 -60
  96. package/src/pantheon/goal-loop.ts +11 -8
  97. package/src/pantheon/memory-context.ts +1017 -0
  98. package/src/pantheon/model-agents.ts +19 -0
  99. package/src/pantheon/model-command.ts +218 -56
  100. package/src/pantheon/model-pricing.ts +536 -0
  101. package/src/pantheon/presets.mjs +2 -0
  102. package/src/pantheon/task-result-guard.ts +50 -14
  103. package/src/pantheon/v2-bounded-read.ts +640 -0
  104. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  105. package/src/pantheon/v2-execute-after.ts +135 -24
  106. package/src/pantheon/v2-model-overrides.ts +275 -0
  107. package/src/pantheon/v2-tools.ts +89 -35
  108. package/src/pantheon/v2-unsupported.mjs +2 -3
  109. package/src/pantheon/v2-vision.ts +622 -0
  110. package/src/pantheon/vision-local.ts +531 -0
  111. package/src/pantheon/vision.ts +1160 -115
  112. package/src/plugin-v2.ts +654 -162
  113. package/src/plugin.ts +15 -11
  114. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  115. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  116. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  117. package/src/plugins/tui/dist/tui.js +1 -1
  118. package/src/plugins/tui/package-lock.json +6 -6
  119. package/src/plugins/tui/package.json +5 -4
  120. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  121. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  122. package/src/routing.yml +50 -5
  123. package/src/skills/agent-coordination/SKILL.md +7 -2
  124. package/src/skills/artifact-management/SKILL.md +5 -1
  125. package/src/skills/auto-continue/SKILL.md +14 -6
  126. package/src/skills/codemap/SKILL.md +1 -1
  127. package/src/skills/memory-bank/SKILL.md +21 -13
  128. package/src/skills/session-goal/SKILL.md +12 -22
  129. package/src/skills/spec-driven-development/SKILL.md +3 -1
  130. package/src/skills/worktrees/SKILL.md +30 -11
  131. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -1,90 +1,170 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * build-agents-md.mjs — Generate the repo AGENTS.md from canonical sources.
3
+ * build-agents-md.mjs — Generate BOTH AGENTS.md artifacts from canonical sources.
4
4
  *
5
- * AGENTS.md is the single instruction file BOTH OpenCode V1 and V2 load
6
- * (V1 auto-discovers it, V2 loads it explicitly; the `instructions` config
7
- * key is accepted-but-ignored by V2). To keep instruction content in parity
8
- * across both versions without duplication, this script consolidates:
5
+ * AGENTS.md files are instruction files BOTH OpenCode V1 and V2 load (V1
6
+ * auto-discovers them, V2 loads them explicitly; the `instructions` config
7
+ * key is accepted-but-ignored by V2). Every session pays for global AND
8
+ * project AGENTS.md content, so a single duplicated file is paid twice per
9
+ * session. To keep the payload disjoint (beta-10 latency slice, phase 1),
10
+ * this script emits TWO artifacts in ONE pass over the same sources:
9
11
  *
10
- * (a) a static header (project description + agent table + setup notes)
11
- * (b) shared instruction bodies embedded under a `## <name>` section marker;
12
- * agent-scoped bodies are rendered into only their matching agent prompt
12
+ * AGENTS.md — repo-specific setup only (build commands, sandbox
13
+ * rules, conventions). Loaded by sessions in THIS repo.
14
+ * AGENTS.global.md — repo-agnostic content only (agent table + shared
15
+ * instruction bodies embedded under a `## <name>`
16
+ * section marker). The installer/sync emits this into
17
+ * the user's global config dir as AGENTS.md.
13
18
  *
14
- * into AGENTS.md plus selective agent prompt content. The instruction files
15
- * remain the source of truth; AGENTS.md is a committed build artifact, never
16
- * hand-edited.
19
+ * Zero overlap: each rule lives in exactly one artifact. Agent-scoped
20
+ * instruction bodies are still rendered into only their matching agent
21
+ * prompt. The instruction files remain the source of truth; both artifacts
22
+ * are committed build artifacts, never hand-edited. Each carries a version
23
+ * header (generated-at + short git sha) so a stale artifact is detectable;
24
+ * `--check` ignores that volatile line and byte-compares everything else.
17
25
  *
18
26
  * Usage:
19
- * node scripts/build-agents-md.mjs # write AGENTS.md to repo root
20
- * node scripts/build-agents-md.mjs --check # exit 1 if AGENTS.md is stale
27
+ * node scripts/build-agents-md.mjs # write both artifacts
28
+ * node scripts/build-agents-md.mjs --check # exit 1 if either is stale
21
29
  *
22
30
  * No runtime dependencies (Node >= 18, stdlib only). Idempotent: running it
23
- * twice produces byte-identical output.
31
+ * twice produces byte-identical output (the version header is derived from
32
+ * git, not the wall clock).
24
33
  */
34
+ import { execFileSync } from 'node:child_process'
25
35
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
26
36
  import { dirname, join, resolve } from 'node:path'
27
37
  import { fileURLToPath } from 'node:url'
38
+ import { ACTIONS, fingerprintOutput, isRecording, recordChange } from './install/plan.mjs'
39
+ import { assertNoSymlinkAncestors, assertPathWithin, verifyRegularFile } from './install/verify.mjs'
28
40
 
29
41
  const __dirname = dirname(fileURLToPath(import.meta.url))
30
42
  export const ROOT = join(__dirname, '..')
31
43
  const INSTRUCTIONS_DIR = join(ROOT, 'src', 'instructions')
32
- const AGENTS_MD_PATH = join(ROOT, 'AGENTS.md')
44
+ export const AGENTS_MD_PATH = join(ROOT, 'AGENTS.md')
45
+ export const AGENTS_GLOBAL_MD_PATH = join(ROOT, 'AGENTS.global.md')
33
46
 
34
47
  // ---------------------------------------------------------------------------
35
- // Static header — preserved verbatim from the original AGENTS.md (agent table,
36
- // setup notes, sandbox rules, conventions). Backticks are escaped for the
37
- // template literal.
48
+ // Managed region — both artifacts are fully machine-generated; the sentinels
49
+ // let the installer refresh the region while preserving any user content
50
+ // around it (conservative migration: non-managed content is never deleted).
38
51
  // ---------------------------------------------------------------------------
39
- const STATIC_HEADER = `# Pantheon Agent System — OpenCode
52
+ export const MANAGED_BEGIN =
53
+ '<!-- pantheon:generated:begin — Pantheon-managed region; regenerated on install/upgrade, never edit inside -->'
54
+ export const MANAGED_END =
55
+ '<!-- pantheon:generated:end — user content outside this region is preserved verbatim -->'
40
56
 
41
- This project uses the Pantheon multi-agent framework with 14 specialized agents.
57
+ /** Header comment every generator version has emitted, old and new. */
58
+ const GENERATED_BY = '<!-- Generated by scripts/build-agents-md.mjs — do not edit directly. -->'
59
+ const VERSION_LINE_RE = /^<!-- pantheon:agents-md v2 artifact=(?:global|project) [^\n]*-->$/gm
60
+
61
+ /**
62
+ * Normalize the volatile version line so `--check` can byte-compare content
63
+ * across commits (the sha/generated-at intentionally lag HEAD by one commit).
64
+ *
65
+ * @param {string} content - Artifact content
66
+ * @returns {string} Content with the version line reduced to a fixed stub
67
+ */
68
+ export function stripVersionLine(content) {
69
+ return content.replace(VERSION_LINE_RE, '<!-- pantheon:agents-md v2 -->')
70
+ }
71
+
72
+ /**
73
+ * Short git sha + commit date of HEAD — deterministic per commit, so the
74
+ * version header never breaks byte-determinism while still dating artifacts.
75
+ * Falls back to "unknown" outside a git worktree (npm tarball installs).
76
+ *
77
+ * @param {string} [root] - Repository root to run git in
78
+ * @returns {{ sha: string, date: string }}
79
+ */
80
+ export function readGitInfo(root = ROOT) {
81
+ try {
82
+ const opts = { cwd: root, encoding: 'utf8' }
83
+ return {
84
+ sha: execFileSync('git', ['rev-parse', '--short=7', 'HEAD'], opts).trim(),
85
+ date: execFileSync('git', ['log', '-1', '--format=%cI'], opts).trim(),
86
+ }
87
+ } catch {
88
+ return { sha: 'unknown', date: 'unknown' }
89
+ }
90
+ }
91
+
92
+ /**
93
+ * The `pantheon:agents-md` version line embedded in every artifact.
94
+ *
95
+ * @param {'global' | 'project'} artifact - Which artifact the line stamps
96
+ * @param {{ sha: string, date: string }} git - Git info from readGitInfo()
97
+ * @returns {string}
98
+ */
99
+ function versionLine(artifact, git) {
100
+ return `<!-- pantheon:agents-md v2 artifact=${artifact} generated-at=${git.date} sha=${git.sha} -->`
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // Static headers — GLOBAL is repo-agnostic (safe for any project), PROJECT is
105
+ // repo-specific (this repository's setup). Zero overlap by construction.
106
+ // Backticks are escaped for the template literal.
107
+ // ---------------------------------------------------------------------------
108
+ const GLOBAL_HEADER = `# Pantheon Agent System — OpenCode
42
109
 
43
110
  ## Available Agents
44
111
 
45
112
  | Agent | Role |
46
113
  |-------|------|
47
- | @aphrodite | Frontend specialist — React 19, TypeScript strict, WCAG accessibility, responsive design, TDD, modern API patterns, deprecated npm detection. Uses discovery/review proportionally to scope and risk. |
48
- | @apollo | Read-only investigation scout — 3–10 parallel searches across codebase, external docs, and GitHub. Called by: athena, zeus, hermes, aphrodite, demeter. No edits, no commands. |
49
- | @athena | Strategic planner & architect — research-first, plan-only, never implements. Plans include quality gates (ruff/Biome, dep detection, LTS policy). Calls apollo for discovery. |
50
- | @demeter | Database specialist — SQLAlchemy 2.0, Alembic, query optimization, N+1 prevention, TDD migrations, modern DB libs. Preserves review gates for schema/data changes. |
51
- | @gaia | Remote sensing domain specialist — satellite image processing, spectral analysis, SAR, change detection, time series, ML/DL classification. Read-only analysis of geospatial data. |
52
- | @hephaestus | AI tooling & pipelines specialist — LangChain/LangGraph chains, RAG architecture, vector stores, embedding strategies. Forges AI infrastructure. Calls apollo, sends to themis. |
53
- | @hermes | Backend specialist — FastAPI, Python, async, TDD (RED→GREEN→REFACTOR), modern Python stdlib, obsolete lib detection. Uses discovery/review proportionally to scope and risk. |
54
- | @iris | GitHub operations specialist — branches, pull requests, issues, releases, tags. Called by zeus after review. Never pushes or merges without explicit human approval. Integrates with VS Code GitHub Pull Requests extension. |
55
- | @mnemosyne | Memory bank quality owner — initializes .pantheon/memory-bank/, writes ADRs and task records on explicit request. Called by zeus. Never invoked automatically after phases. |
56
- | @nyx | Observability & monitoring specialist — OpenTelemetry tracing, token/cost tracking, agent performance analytics, LangSmith integration. Calls apollo for discovery, sends to themis. |
57
- | @prometheus | Infrastructure + model provider specialist — Docker, CI/CD, multi-model routing, cost optimization, provider abstraction |
58
- | @talos | Hotfix express lane — direct fixes for small bugs, CSS, typos, minor logic. No TDD ceremony, no orchestration overhead. Standalone, no subagents. Escalates complex issues to zeus. |
59
- | @themis | Quality & security gate — ruff/Biome linting, dead/legacy code detection, OWASP Top 10, applicable coverage requirements, correctness, deprecation audit. Reviews material/sensitive changes. |
60
- | @zeus | Central orchestrator — never implements. Delegates to: athena, apollo, hermes, aphrodite, demeter, prometheus, themis, iris, mnemosyne, talos, hephaestus, nyx |
114
+ | @aphrodite | Frontend — React 19, strict TypeScript, WCAG, responsive design, deprecated npm detection. |
115
+ | @apollo | Read-only investigation scout — 3–10 parallel searches (codebase, docs, GitHub). No edits, no commands. |
116
+ | @athena | Planner/architect — research-first, plan-only, never implements. Plans carry quality gates (ruff/Biome, dep detection, LTS policy). |
117
+ | @demeter | Database — SQLAlchemy 2.0, Alembic, query optimization, N+1 prevention, migrations; preserves schema/data review gates. |
118
+ | @gaia | Remote sensing — satellite/spectral analysis, SAR, change detection, time series, ML/DL classification; read-only. |
119
+ | @hephaestus | AI pipelines — LangChain/LangGraph, RAG, vector stores, embeddings. |
120
+ | @hermes | Backend — FastAPI, Python, async, modern stdlib, obsolete lib detection. |
121
+ | @iris | GitHub ops — branches, PRs, issues, releases, tags; called by zeus after review. Never pushes or merges without explicit human approval. |
122
+ | @mnemosyne | Memory bank — initializes .pantheon/memory-bank/; writes ADRs/task records only on explicit request. Called by zeus, never automatically. |
123
+ | @nyx | Observability — OpenTelemetry tracing, token/cost tracking, agent analytics, LangSmith. |
124
+ | @prometheus | Infrastructure + model providers — Docker, CI/CD, multi-model routing, cost optimization, provider abstraction. |
125
+ | @talos | Hotfix lane — small bugs, CSS, typos, minor logic; no TDD ceremony, standalone, no subagents. Escalates complex issues to zeus. |
126
+ | @themis | Quality/security gate — ruff/Biome, dead/legacy code, OWASP Top 10, coverage, correctness, deprecation audit. Reviews material/sensitive changes. |
127
+ | @zeus | Central orchestrator — never implements. Delegates to: athena, apollo, hermes, aphrodite, demeter, prometheus, themis, iris, mnemosyne, talos, hephaestus, nyx. |
128
+ `
129
+
130
+ const PROJECT_HEADER = `# Pantheon — Repository Setup
61
131
 
62
132
  ## OpenCode Setup
63
133
 
64
- See [INSTALLATION.md](docs/INSTALLATION.md) for setup instructions.
134
+ Setup: [INSTALLATION.md](docs/INSTALLATION.md).
65
135
 
66
- - Build: \`npm test\`
67
- - Test: \`npm test\`
136
+ - Build/Test: \`npm test\`
68
137
  - Lint: \`npm run lint\`
69
138
 
70
139
  ## Teste de Instalação Global (sandbox)
71
140
 
72
- Para validar a instalação global do pacote pantheon-opencode COMO UM USUÁRIO REAL, use o sandbox isolado em \`~/pantheon-sandbox/\` (fora do repo, HOME + prefix npm + venv próprios). O ambiente de dev mistura 3 instalações + config global + venv — NÃO serve para testar instalação/empacotamento.
141
+ Valide a instalação global COMO UM USUÁRIO REAL no sandbox \`~/pantheon-sandbox/\` (fora do repo; HOME, prefix npm e venv próprios); o ambiente de dev NÃO serve para empacotamento.
73
142
 
74
- - Rodar: \`bash ~/pantheon-sandbox/run-test.sh\` (opencode mcp list 5/5 connected + doctor 0 erros + abre TUI isolado)
75
- - Regra para agentes: ao validar instalação global (npm pack, \`init\`, MCPs, hooks), usar o sandbox — NUNCA testar no ambiente de dev
143
+ - Rodar: \`bash ~/pantheon-sandbox/run-test.sh\` (MCPs, doctor, TUI)
144
+ - Regra para agentes: valide instalação global (npm pack, \`init\`, MCPs, hooks) no sandbox — NUNCA no ambiente de dev
76
145
  - Descarte: \`rm -rf ~/pantheon-sandbox\`
77
- - Detalhes: ver \`~/pantheon-sandbox/README.md\`
146
+ - Detalhes: \`~/pantheon-sandbox/README.md\`
147
+
148
+ ## Worktrees
149
+
150
+ - Nunca crie worktrees dentro do projeto principal; use \`<project-parent>/.pantheon-worktrees/<basename-do-repo>/<task>\`.
151
+ - \`.pantheon/workflows/\` e \`.pantheon/worktrees/\` não são o padrão para worktrees.
78
152
 
79
153
  ## Conventions
80
154
 
81
155
  - TDD: RED→GREEN→REFACTOR for testable behavior; use focused checks for micro-edits
82
- - Honor repository coverage thresholds when relevant; preserve stronger auth/security/data-integrity gates
156
+ - Stronger gates (auth, security, data-integrity, coverage) are canonical in the global \`Test Economy\` section
83
157
  - Async/await on all I/O
84
158
  - Type hints on all functions
85
- - PRs always update the README — every pull request must document newly added features, behaviors, env vars, or commands in the README before being opened.
159
+ - PRs always update the README: document new features, behaviors, env vars, and commands before opening.
86
160
  `
87
161
 
162
+ const INSTRUCTIONS_PREAMBLE = `---
163
+
164
+ # Agent Instructions
165
+
166
+ Shared rules from \`src/instructions/*.instructions.md\`, identical for OpenCode V1 and V2 (V2 ignores \`instructions\`). Repo-specific setup stays in that project's AGENTS.md, so no rule loads twice; agent-scoped rules live only in the matching prompt.`
167
+
88
168
  // ---------------------------------------------------------------------------
89
169
  // Frontmatter parsing (stdlib only — no yaml dependency)
90
170
  // ---------------------------------------------------------------------------
@@ -157,43 +237,200 @@ export function readInstructions() {
157
237
  // ---------------------------------------------------------------------------
158
238
 
159
239
  /**
160
- * Generate the full AGENTS.md content.
240
+ * Generate the GLOBAL AGENTS.md content (repo-agnostic): agent table + the
241
+ * shared instruction bodies. This is the content installed into the user's
242
+ * global config dir as AGENTS.md.
161
243
  *
162
244
  * @param {Array<{ file: string, name: string, body: string, agents?: string[] }>} instructions
245
+ * @param {{ sha: string, date: string }} git - Git info from readGitInfo()
163
246
  * @returns {string}
164
247
  */
165
- export function generateAgentsMd(instructions) {
248
+ export function generateGlobalAgentsMd(instructions, git = readGitInfo()) {
166
249
  const sharedInstructions = instructions.filter(
167
250
  (instr) => !instr.agents || instr.agents.includes('*'),
168
251
  )
169
252
  const sections = [
170
- '<!-- Generated by scripts/build-agents-md.mjs — do not edit directly. -->',
171
- '<!-- Source of truth: src/instructions/*.instructions.md (AGENTS.md is a committed build artifact). -->',
253
+ MANAGED_BEGIN,
254
+ GENERATED_BY,
255
+ '<!-- Source of truth: src/instructions/*.instructions.md + the static sections in this script. -->',
256
+ versionLine('global', git),
172
257
  '',
173
- STATIC_HEADER.trimEnd(),
174
- '',
175
- '---',
176
- '',
177
- '# Agent Instructions',
178
- '',
179
- 'The following sections are consolidated from `src/instructions/*.instructions.md`',
180
- 'so both OpenCode V1 (auto-loads AGENTS.md) and V2 (loads AGENTS.md, ignores the',
181
- '`instructions` config key) receive identical shared rules. Agent-scoped rules',
182
- 'are rendered into only the matching installed agent prompts.',
258
+ GLOBAL_HEADER.trimEnd(),
259
+ INSTRUCTIONS_PREAMBLE,
183
260
  '',
184
261
  ]
185
262
  for (const instr of sharedInstructions) {
263
+ // The section marker below already carries the title; drop a duplicated
264
+ // leading H1 from the instruction body (agent prompts keep it intact).
265
+ const body = instr.body.replace(/^\s*#\s[^\n]*\n+/, '')
186
266
  sections.push(
187
267
  `<!-- Source: src/instructions/${instr.file} -->`,
188
268
  `## ${instr.name}`,
189
269
  '',
190
- instr.body.trimEnd(),
270
+ body.trimEnd(),
191
271
  '',
192
272
  )
193
273
  }
274
+ sections.push(MANAGED_END)
275
+ return `${sections.join('\n').trimEnd()}\n`
276
+ }
277
+
278
+ /**
279
+ * Generate the PROJECT AGENTS.md content (repo-specific setup only). Shared
280
+ * rules deliberately live in the global artifact so a session never pays for
281
+ * the same rule twice.
282
+ *
283
+ * @param {{ sha: string, date: string }} git - Git info from readGitInfo()
284
+ * @returns {string}
285
+ */
286
+ export function generateProjectAgentsMd(git = readGitInfo()) {
287
+ const sections = [
288
+ MANAGED_BEGIN,
289
+ GENERATED_BY,
290
+ '<!-- Source of truth: project sections in scripts/build-agents-md.mjs. -->',
291
+ versionLine('project', git),
292
+ '',
293
+ PROJECT_HEADER.trimEnd(),
294
+ MANAGED_END,
295
+ ]
194
296
  return `${sections.join('\n').trimEnd()}\n`
195
297
  }
196
298
 
299
+ // ---------------------------------------------------------------------------
300
+ // Managed-region writer — shared by the installer (scripts/install/opencode.mjs)
301
+ // and the postinstall freshness sync (scripts/sync-artifacts.mjs).
302
+ // ---------------------------------------------------------------------------
303
+
304
+ /**
305
+ * Write an AGENTS.md artifact conservatively:
306
+ *
307
+ * - missing target → write generated content ('created')
308
+ * - managed region present → replace ONLY the region; any user content
309
+ * around it is preserved ('updated' when the
310
+ * file is pure managed content, 'merged' when
311
+ * foreign content was kept)
312
+ * - legacy generated file → the whole file is machine-generated per its
313
+ * own header; upgrade in place ('upgraded')
314
+ * - foreign file → never clobber: append the managed region
315
+ * below the user's content ('merged')
316
+ *
317
+ * Byte-compare idempotent: identical content returns 'skipped' untouched.
318
+ *
319
+ * @param {string} filePath - Destination AGENTS.md path
320
+ * @param {string} generated - Generated artifact content (incl. sentinels)
321
+ * @param {boolean} [dryRun=false] - Do not write when true
322
+ * @returns {'created' | 'skipped' | 'updated' | 'upgraded' | 'merged'}
323
+ */
324
+ export function writeAgentsMdManaged(filePath, generated, dryRun = false, recorder = null) {
325
+ assertPathWithin(dirname(filePath), filePath)
326
+ assertNoSymlinkAncestors(filePath)
327
+ const existing = existsSync(filePath) ? readFileSync(filePath, 'utf8') : null
328
+ if (existing === null) {
329
+ if (!dryRun) {
330
+ assertNoSymlinkAncestors(dirname(filePath))
331
+ mkdirSync(dirname(filePath), { recursive: true })
332
+ assertNoSymlinkAncestors(filePath)
333
+ writeFileSync(filePath, generated, 'utf8')
334
+ verifyRegularFile(filePath, generated)
335
+ }
336
+ recordChange(
337
+ {
338
+ path: filePath,
339
+ action: ACTIONS.CREATE,
340
+ bytes: Buffer.byteLength(generated, 'utf8'),
341
+ outputFingerprint: fingerprintOutput(generated),
342
+ },
343
+ recorder,
344
+ )
345
+ return 'created'
346
+ }
347
+ if (existing === generated) {
348
+ recordChange(
349
+ {
350
+ path: filePath,
351
+ action: ACTIONS.UNCHANGED,
352
+ bytes: Buffer.byteLength(existing, 'utf8'),
353
+ outputFingerprint: fingerprintOutput(existing),
354
+ },
355
+ recorder,
356
+ )
357
+ return 'skipped'
358
+ }
359
+
360
+ const begin = existing.indexOf(MANAGED_BEGIN)
361
+ const end = existing.indexOf(MANAGED_END)
362
+ if (begin !== -1 && end !== -1 && end > begin) {
363
+ const before = existing.slice(0, begin)
364
+ const after = existing.slice(end + MANAGED_END.length)
365
+ const next = `${before}${generated}${after}`
366
+ if (next === existing) {
367
+ recordChange(
368
+ {
369
+ path: filePath,
370
+ action: ACTIONS.UNCHANGED,
371
+ bytes: Buffer.byteLength(existing, 'utf8'),
372
+ outputFingerprint: fingerprintOutput(existing),
373
+ },
374
+ recorder,
375
+ )
376
+ return 'skipped'
377
+ }
378
+ if (!dryRun) {
379
+ assertNoSymlinkAncestors(filePath)
380
+ writeFileSync(filePath, next, 'utf8')
381
+ verifyRegularFile(filePath, next)
382
+ }
383
+ recordChange(
384
+ {
385
+ path: filePath,
386
+ action: ACTIONS.UPDATE,
387
+ bytes: Buffer.byteLength(next, 'utf8'),
388
+ outputFingerprint: fingerprintOutput(next),
389
+ },
390
+ recorder,
391
+ )
392
+ return before.trim() === '' && after.trim() === '' ? 'updated' : 'merged'
393
+ }
394
+
395
+ if (existing.startsWith(GENERATED_BY)) {
396
+ // Legacy format: the header declares the whole file machine-generated.
397
+ if (!dryRun) {
398
+ assertNoSymlinkAncestors(filePath)
399
+ writeFileSync(filePath, generated, 'utf8')
400
+ verifyRegularFile(filePath, generated)
401
+ }
402
+ recordChange(
403
+ {
404
+ path: filePath,
405
+ action: ACTIONS.UPDATE,
406
+ bytes: Buffer.byteLength(generated, 'utf8'),
407
+ outputFingerprint: fingerprintOutput(generated),
408
+ },
409
+ recorder,
410
+ )
411
+ return 'upgraded'
412
+ }
413
+
414
+ // Foreign content: preserve it verbatim and append the managed region.
415
+ const separator = existing.endsWith('\n') ? '\n' : '\n\n'
416
+ const payload = `${existing}${separator}${generated}`
417
+ if (!dryRun) {
418
+ assertNoSymlinkAncestors(filePath)
419
+ writeFileSync(filePath, payload, 'utf8')
420
+ verifyRegularFile(filePath, payload)
421
+ }
422
+ recordChange(
423
+ {
424
+ path: filePath,
425
+ action: ACTIONS.UPDATE,
426
+ bytes: Buffer.byteLength(payload, 'utf8'),
427
+ outputFingerprint: fingerprintOutput(payload),
428
+ },
429
+ recorder,
430
+ )
431
+ return 'merged'
432
+ }
433
+
197
434
  const GENERATED_AGENT_BLOCK =
198
435
  /\n?<!-- Pantheon selective instructions: generated -->[\s\S]*?<!-- \/Pantheon selective instructions -->\n?/g
199
436
 
@@ -258,11 +495,23 @@ export function generateAgentPrompt(agentName, prompt, instructions = readInstru
258
495
  * @param {string} targetDir - OpenCode agents directory
259
496
  * @param {boolean} dryRun - Do not write when true
260
497
  * @param {boolean} existingOnly - Refresh installed prompts without adding missing agents
498
+ * @param {(change: object) => void} [recorder] - optional change recorder for --dry-run preview
261
499
  * @returns {{ created: number, skipped: number }}
262
500
  */
263
- export function copyAgentPrompts(sourceDir, targetDir, dryRun = false, existingOnly = false) {
501
+ export function copyAgentPrompts(
502
+ sourceDir,
503
+ targetDir,
504
+ dryRun = false,
505
+ existingOnly = false,
506
+ recorder = null,
507
+ ) {
508
+ assertNoSymlinkAncestors(targetDir)
264
509
  const instructions = readInstructions()
265
- if (!dryRun && !existingOnly) mkdirSync(targetDir, { recursive: true })
510
+ if (!dryRun && !existingOnly) {
511
+ assertNoSymlinkAncestors(targetDir)
512
+ mkdirSync(targetDir, { recursive: true })
513
+ assertNoSymlinkAncestors(targetDir)
514
+ }
266
515
  let created = 0
267
516
  let skipped = 0
268
517
  for (const file of readdirSync(sourceDir)
@@ -274,13 +523,41 @@ export function copyAgentPrompts(sourceDir, targetDir, dryRun = false, existingO
274
523
  const agentName = file.replace(/\.md$/, '')
275
524
  const output = generateAgentPrompt(agentName, readFileSync(sourcePath, 'utf8'), instructions)
276
525
  const targetPath = join(targetDir, file)
526
+ assertPathWithin(targetDir, targetPath)
527
+ assertNoSymlinkAncestors(targetPath)
277
528
  if (existingOnly && !existsSync(targetPath)) continue
278
529
  const existing = existsSync(targetPath) ? readFileSync(targetPath, 'utf8') : null
279
530
  if (existing === output) {
280
531
  skipped++
532
+ if (isRecording(recorder)) {
533
+ recordChange(
534
+ {
535
+ path: targetPath,
536
+ action: ACTIONS.UNCHANGED,
537
+ bytes: Buffer.byteLength(output, 'utf8'),
538
+ outputFingerprint: fingerprintOutput(output),
539
+ },
540
+ recorder,
541
+ )
542
+ }
281
543
  } else {
282
- if (!dryRun) writeFileSync(targetPath, output, 'utf8')
544
+ if (!dryRun) {
545
+ assertNoSymlinkAncestors(targetPath)
546
+ writeFileSync(targetPath, output, 'utf8')
547
+ verifyRegularFile(targetPath, output)
548
+ }
283
549
  created++
550
+ if (isRecording(recorder)) {
551
+ recordChange(
552
+ {
553
+ path: targetPath,
554
+ action: existing === null ? ACTIONS.CREATE : ACTIONS.UPDATE,
555
+ bytes: Buffer.byteLength(output, 'utf8'),
556
+ outputFingerprint: fingerprintOutput(output),
557
+ },
558
+ recorder,
559
+ )
560
+ }
284
561
  }
285
562
  }
286
563
  return { created, skipped }
@@ -308,21 +585,43 @@ function main() {
308
585
  const sharedCount = instructions.filter(
309
586
  (instr) => !instr.agents || instr.agents.includes('*'),
310
587
  ).length
311
- const content = generateAgentsMd(instructions)
588
+ const global = generateGlobalAgentsMd(instructions)
589
+ const project = generateProjectAgentsMd()
312
590
 
313
591
  if (checkOnly) {
314
- const existing = existsSync(AGENTS_MD_PATH) ? readFileSync(AGENTS_MD_PATH, 'utf8') : ''
315
- if (existing !== content) {
316
- console.error(`❌ AGENTS.md is stale — run: node scripts/build-agents-md.mjs`)
592
+ const stale = []
593
+ const existingGlobal = existsSync(AGENTS_GLOBAL_MD_PATH)
594
+ ? readFileSync(AGENTS_GLOBAL_MD_PATH, 'utf8')
595
+ : ''
596
+ const existingProject = existsSync(AGENTS_MD_PATH) ? readFileSync(AGENTS_MD_PATH, 'utf8') : ''
597
+ if (stripVersionLine(existingGlobal) !== stripVersionLine(global)) {
598
+ stale.push('AGENTS.global.md')
599
+ }
600
+ if (stripVersionLine(existingProject) !== stripVersionLine(project)) {
601
+ stale.push('AGENTS.md')
602
+ }
603
+ if (stale.length > 0) {
604
+ console.error(
605
+ `❌ ${stale.join(' and ')} ${
606
+ stale.length > 1 ? 'are' : 'is'
607
+ } stale — run: node scripts/build-agents-md.mjs`,
608
+ )
317
609
  process.exit(1)
318
610
  }
319
- console.log(`✅ AGENTS.md is up to date (${sharedCount} shared instruction sections)`)
611
+ console.log(
612
+ `✅ AGENTS.md and AGENTS.global.md are up to date (${sharedCount} shared instruction sections)`,
613
+ )
320
614
  return
321
615
  }
322
616
 
323
- writeFileSync(AGENTS_MD_PATH, content, 'utf8')
324
- const lines = logicalLineCount(content)
325
- console.log(`✅ Generated AGENTS.md (${sharedCount} shared instruction sections, ${lines} lines)`)
617
+ writeFileSync(AGENTS_GLOBAL_MD_PATH, global, 'utf8')
618
+ writeFileSync(AGENTS_MD_PATH, project, 'utf8')
619
+ verifyRegularFile(AGENTS_GLOBAL_MD_PATH, global)
620
+ verifyRegularFile(AGENTS_MD_PATH, project)
621
+ console.log(
622
+ `✅ Generated AGENTS.md (${logicalLineCount(project)} lines) + AGENTS.global.md ` +
623
+ `(${logicalLineCount(global)} lines, ${sharedCount} shared instruction sections)`,
624
+ )
326
625
  }
327
626
 
328
627
  if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {