pantheon-opencode 1.5.2 → 1.6.0-beta.10

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 (146) hide show
  1. package/.pantheon/code-mode/README.md +4 -2
  2. package/.pantheon/code-mode/checkpoint_session.py +138 -102
  3. package/.pantheon/code-mode/compress-inline.py +102 -57
  4. package/.pantheon/code-mode/manifest.json +2 -8
  5. package/AGENTS.global.md +182 -0
  6. package/AGENTS.md +10 -891
  7. package/CHANGELOG.md +343 -0
  8. package/README.md +577 -79
  9. package/README.pt-BR.md +345 -60
  10. package/bin/pantheon-init.mjs +26 -3
  11. package/commands/pantheon-audit.md +7 -1
  12. package/commands/pantheon-consolidate.md +1 -1
  13. package/commands/pantheon-deepwork.md +14 -3
  14. package/commands/pantheon-focus.md +17 -0
  15. package/commands/pantheon-optimize.md +2 -2
  16. package/commands/pantheon-vision.md +61 -12
  17. package/package.json +30 -11
  18. package/plugin.json +2 -2
  19. package/pyproject.toml +11 -16
  20. package/scripts/build-agents-md.mjs +376 -58
  21. package/scripts/changelog-merge.mjs +161 -0
  22. package/scripts/check-plugin-v2-coverage.mjs +213 -0
  23. package/scripts/ci-validate-yaml.py +7 -5
  24. package/scripts/{code_mode_server.py → code_mode.py} +119 -27
  25. package/scripts/cost.mjs +244 -41
  26. package/scripts/doctor.mjs +236 -29
  27. package/scripts/install/agents-md.mjs +4 -4
  28. package/scripts/install/cli-ui.mjs +1 -1
  29. package/scripts/install/config-migration.mjs +319 -6
  30. package/scripts/install/health-check.mjs +26 -37
  31. package/scripts/install/interactive.mjs +7 -7
  32. package/scripts/install/migrate.mjs +1 -1
  33. package/scripts/install/opencode-version.mjs +246 -4
  34. package/scripts/install/opencode.mjs +627 -179
  35. package/scripts/install/plugin.mjs +43 -9
  36. package/scripts/install/shared.mjs +120 -12
  37. package/scripts/install/vision-prompt.mjs +161 -0
  38. package/scripts/install-mcp.mjs +28 -9
  39. package/scripts/{mcp_persistence_server.py → mcp_persistence.py} +392 -78
  40. package/{src/mcp/mcp_resources_server.py → scripts/mcp_resources.py} +2 -2
  41. package/scripts/{memory_mcp_server.py → memory_mcp.py} +372 -198
  42. package/scripts/postinstall.mjs +0 -7
  43. package/scripts/probe-context-rehydrate.mjs +36 -13
  44. package/scripts/probe-pantheon-cost.mjs +71 -15
  45. package/scripts/prune.mjs +2 -2
  46. package/scripts/run-node-tests.mjs +189 -0
  47. package/scripts/sync-artifacts.mjs +26 -13
  48. package/scripts/sync-tui.mjs +24 -3
  49. package/scripts/test-opencode-v2-sandbox.sh +1913 -0
  50. package/scripts/validate-routing.mjs +43 -3
  51. package/scripts/validate-sandbox-install.mjs +138 -0
  52. package/scripts/versioning.mjs +13 -1
  53. package/scripts/vision-status.mjs +682 -0
  54. package/skills-lock.json +15 -16
  55. package/src/agents/aphrodite.md +20 -37
  56. package/src/agents/apollo.md +7 -3
  57. package/src/agents/athena.md +63 -35
  58. package/src/agents/demeter.md +8 -28
  59. package/src/agents/gaia.md +1 -1
  60. package/src/agents/hephaestus.md +10 -21
  61. package/src/agents/hermes.md +15 -38
  62. package/src/agents/iris.md +1 -1
  63. package/src/agents/mnemosyne.md +23 -60
  64. package/src/agents/nyx.md +1 -1
  65. package/src/agents/prometheus.md +16 -20
  66. package/src/agents/talos.md +10 -2
  67. package/src/agents/themis.md +5 -5
  68. package/src/agents/zeus.md +99 -130
  69. package/src/instructions/agent-return-format.instructions.md +18 -3
  70. package/src/instructions/backend-standards.instructions.md +2 -0
  71. package/src/instructions/frontend-standards.instructions.md +3 -1
  72. package/src/instructions/memory-protocol.instructions.md +11 -110
  73. package/src/instructions/zeus-anti-stall.instructions.md +14 -61
  74. package/src/instructions/zeus-communication-rules.instructions.md +0 -1
  75. package/src/instructions/zeus-council-synthesis.instructions.md +32 -260
  76. package/src/instructions/zeus-memory-operations.instructions.md +26 -0
  77. package/src/instructions/zeus-timeout-retry.instructions.md +40 -87
  78. package/src/mcp/{code_mode_server.py → code_mode.py} +119 -27
  79. package/src/mcp/eval_store.py +2 -2
  80. package/src/mcp/mcp_codemap_module.py +559 -129
  81. package/src/mcp/{mcp_persistence_server.py → mcp_persistence.py} +392 -78
  82. package/{scripts/mcp_resources_server.py → src/mcp/mcp_resources.py} +2 -2
  83. package/src/mcp/{memory_mcp_server.py → memory_mcp.py} +373 -250
  84. package/src/mcp/{pantheon_vision_server.py → pantheon_vision.py} +396 -40
  85. package/src/mcp/requirements-mcp.txt +10 -6
  86. package/src/mcp/requirements-vision.txt +4 -2
  87. package/src/pantheon/cost-command.ts +399 -101
  88. package/src/pantheon/delegation-enforce.ts +10 -1
  89. package/src/pantheon/model-command.ts +18 -7
  90. package/src/pantheon/presets.d.mts +0 -8
  91. package/src/pantheon/presets.mjs +5 -32
  92. package/src/pantheon/todo-enforcer.ts +1 -1
  93. package/src/pantheon/v2-bounded-read.ts +640 -0
  94. package/src/pantheon/v2-delegation-enforce.ts +214 -0
  95. package/src/pantheon/v2-execute-after.ts +186 -0
  96. package/src/pantheon/v2-tools.ts +429 -0
  97. package/src/pantheon/v2-unsupported.d.mts +11 -0
  98. package/src/pantheon/v2-unsupported.mjs +90 -0
  99. package/src/pantheon/v2-vision.ts +622 -0
  100. package/src/pantheon/vision-local.ts +531 -0
  101. package/src/pantheon/vision.ts +1161 -116
  102. package/src/plugin-v2.ts +1244 -288
  103. package/src/plugin.ts +12 -9
  104. package/src/plugins/tui/dist/server.d.ts +1 -2
  105. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  106. package/src/plugins/tui/dist/tui-v2.d.ts +154 -0
  107. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -0
  108. package/src/plugins/tui/dist/tui-v2.js +659 -0
  109. package/src/plugins/tui/dist/tui-v2.js.map +1 -0
  110. package/src/plugins/tui/dist/tui.d.ts +85 -82
  111. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  112. package/src/plugins/tui/dist/tui.js +72 -59
  113. package/src/plugins/tui/index-v2.ts +6 -0
  114. package/src/plugins/tui/package-lock.json +5504 -1341
  115. package/src/plugins/tui/package.json +25 -15
  116. package/src/plugins/tui/src/index-v2.tsx +734 -0
  117. package/src/plugins/tui/src/index.tsx +106 -85
  118. package/src/plugins/tui/src/opencode-v2.d.ts +13 -0
  119. package/src/plugins/tui/tsconfig.build.json +5 -0
  120. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  121. package/src/plugins/tui/tsdown.config.ts +22 -2
  122. package/src/plugins/tui/tui-v2.ts +2 -0
  123. package/src/plugins/tui/tui.ts +3 -0
  124. package/src/routing.yml +11 -22
  125. package/src/skills/README.md +34 -39
  126. package/src/skills/agent-coordination/SKILL.md +7 -2
  127. package/src/skills/artifact-management/SKILL.md +12 -5
  128. package/src/skills/auto-continue/SKILL.md +54 -95
  129. package/src/skills/code-review-checklist/SKILL.md +5 -5
  130. package/src/skills/context-compression/SKILL.md +26 -879
  131. package/src/skills/session-goal/SKILL.md +14 -5
  132. package/src/skills/spec-driven-development/SKILL.md +3 -1
  133. package/src/skills/tdd-with-agents/SKILL.md +18 -10
  134. package/.pantheon/code-mode/eval-llm-judge.py +0 -255
  135. package/.pantheon/code-mode/eval-monte-carlo.py +0 -368
  136. package/.pantheon/code-mode/eval-run.py +0 -197
  137. package/.pantheon/code-mode/eval-static.py +0 -321
  138. package/.pantheon/code-mode/session-end-save.py +0 -186
  139. package/.pantheon/code-mode/session-end-save.sh +0 -18
  140. package/opencode.json +0 -58
  141. package/scripts/recover-zenodo-deposition.mjs +0 -146
  142. package/scripts/test-opencode-v1-v2-sandbox.sh +0 -862
  143. package/scripts/validate-zenodo-release.mjs +0 -154
  144. package/scripts/zenodo-artifact.mjs +0 -94
  145. package/scripts/zenodo-release-state.mjs +0 -53
  146. package/src/skills/orchestration-workflow/SKILL.md +0 -311
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Merge pending [Unreleased] notes into an already-promoted version section.
3
+ * This supports release candidates whose versioned changelog section exists
4
+ * before the final beta changes are ready, without creating a duplicate entry
5
+ * or advancing the package version.
6
+ */
7
+
8
+ const UNRELEASED_TEMPLATE = `
9
+
10
+ <!-- Add new changes here. Running \`node scripts/versioning.mjs apply\` will
11
+ move this section to a versioned entry and reset the template below. -->
12
+
13
+ ## 🆕 What's New
14
+
15
+ ## 🐞 Fixed
16
+
17
+ ## ⚠️ Known Issues
18
+
19
+ ## ✅ Closed Issues
20
+ `
21
+
22
+ const TEMPLATE_COMMENT = /<!-- Add new changes here\.[\s\S]*?reset the template below\. -->/g
23
+ const ESCAPED_TEMPLATE_COMMENT =
24
+ /&lt;!-- Add new changes here\.[\s\S]*?reset the template below\. --&gt;/g
25
+
26
+ function escapeRegExp(value) {
27
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
28
+ }
29
+
30
+ function findSection(lines, heading) {
31
+ const matches = []
32
+ for (let index = 0; index < lines.length; index += 1) {
33
+ if (lines[index] === heading) matches.push(index)
34
+ }
35
+ if (matches.length > 1) throw new Error(`CHANGELOG.md has duplicate section: ${heading}`)
36
+ if (matches.length === 0) return null
37
+ const start = matches[0]
38
+ let end = start + 1
39
+ while (end < lines.length && !/^## \[/.test(lines[end])) end += 1
40
+ return { start, end }
41
+ }
42
+
43
+ function parseBody(body) {
44
+ const withoutComments = body.replace(TEMPLATE_COMMENT, '').replace(ESCAPED_TEMPLATE_COMMENT, '')
45
+ const lines = withoutComments.split('\n')
46
+ const preamble = []
47
+ const sections = new Map()
48
+ let current = null
49
+
50
+ for (const line of lines) {
51
+ const heading = /^## (.+)$/.exec(line)
52
+ if (heading) {
53
+ current = heading[1]
54
+ if (!sections.has(current)) sections.set(current, [])
55
+ continue
56
+ }
57
+ if (current === null) preamble.push(line)
58
+ else sections.get(current).push(line)
59
+ }
60
+
61
+ const meaningful = (items) => items.join('\n').trim().length > 0
62
+ for (const [heading, content] of sections) {
63
+ if (!meaningful(content)) sections.delete(heading)
64
+ else {
65
+ sections.set(
66
+ heading,
67
+ content
68
+ .join('\n')
69
+ .replace(/\n{3,}/g, '\n\n')
70
+ .trim()
71
+ .split('\n'),
72
+ )
73
+ }
74
+ }
75
+ return {
76
+ preamble: preamble.join('\n').trim(),
77
+ sections,
78
+ }
79
+ }
80
+
81
+ function mergeBodies(existingBody, pendingBody) {
82
+ const existing = parseBody(existingBody)
83
+ const pending = parseBody(pendingBody)
84
+ const preamble = [existing.preamble, pending.preamble].filter(Boolean).join('\n\n')
85
+ const sections = new Map(existing.sections)
86
+
87
+ for (const [heading, content] of pending.sections) {
88
+ if (!sections.has(heading)) {
89
+ sections.set(heading, content)
90
+ continue
91
+ }
92
+ const previous = sections.get(heading)
93
+ const previousText = previous.join('\n').trim()
94
+ const pendingText = content.join('\n').trim()
95
+ sections.set(heading, [`${previousText}\n\n${pendingText}`])
96
+ }
97
+
98
+ const rendered = []
99
+ if (preamble) rendered.push(preamble)
100
+ for (const [heading, content] of sections) {
101
+ if (rendered.length > 0) rendered.push('')
102
+ rendered.push(`## ${heading}`, '', content.join('\n').trim())
103
+ }
104
+ return rendered.join('\n').trim()
105
+ }
106
+
107
+ /**
108
+ * Merge [Unreleased] into an existing exact version heading, preserving its
109
+ * date and existing notes. Returns null when the version section does not yet
110
+ * exist so the caller can use the normal promotion path.
111
+ *
112
+ * @param {string} changelogText complete changelog
113
+ * @param {string} version semantic version, with or without a leading v
114
+ * @returns {{changed: boolean, content: string}|null}
115
+ */
116
+ export function mergeUnreleasedIntoVersion(changelogText, version) {
117
+ const normalized = String(version).trim().replace(/^v/i, '')
118
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(normalized)) {
119
+ throw new Error(`invalid changelog version: ${version}`)
120
+ }
121
+
122
+ const lines = changelogText.split('\n')
123
+ const unreleased = findSection(lines, '## [Unreleased]')
124
+ if (!unreleased) throw new Error('CHANGELOG.md is missing the [Unreleased] section')
125
+
126
+ const escaped = escapeRegExp(normalized)
127
+ const targetPattern = new RegExp(`^## \\[v?${escaped}\\](?: - \\d{4}-\\d{2}-\\d{2})?$`)
128
+ const targetMatches = []
129
+ for (let index = 0; index < lines.length; index += 1) {
130
+ if (targetPattern.test(lines[index])) targetMatches.push(index)
131
+ }
132
+ if (targetMatches.length > 1) {
133
+ throw new Error(`CHANGELOG.md has duplicate version sections: ${normalized}`)
134
+ }
135
+ if (targetMatches.length === 0) return null
136
+
137
+ const target = findSection(lines, lines[targetMatches[0]])
138
+ if (!target) throw new Error(`CHANGELOG.md is missing version section: ${normalized}`)
139
+
140
+ const pendingBody = lines.slice(unreleased.start + 1, unreleased.end).join('\n')
141
+ const existingBody = lines.slice(target.start + 1, target.end).join('\n')
142
+ const mergedBody = mergeBodies(existingBody, pendingBody)
143
+ const afterTarget = [lines[target.start], '', mergedBody].join('\n').trimEnd()
144
+ const updatedLines = [
145
+ ...lines.slice(0, target.start),
146
+ afterTarget,
147
+ ...(target.end < lines.length ? [''] : []),
148
+ ...lines.slice(target.end),
149
+ ]
150
+ .join('\n')
151
+ .split('\n')
152
+ const updatedUnreleased = findSection(updatedLines, '## [Unreleased]')
153
+ if (!updatedUnreleased) throw new Error('merged CHANGELOG.md lost the [Unreleased] section')
154
+ const content = [
155
+ ...updatedLines.slice(0, updatedUnreleased.start),
156
+ `## [Unreleased]${UNRELEASED_TEMPLATE}`,
157
+ ...updatedLines.slice(updatedUnreleased.end),
158
+ ].join('\n')
159
+
160
+ return { changed: content !== changelogText, content }
161
+ }
@@ -0,0 +1,213 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { dirname, join, resolve } from 'node:path'
5
+ import { fileURLToPath, pathToFileURL } from 'node:url'
6
+
7
+ export const REQUIRED_NODE_VERSION = 'v24.15.0'
8
+ export const LINE_THRESHOLD_NUMERATOR = 4
9
+ export const LINE_THRESHOLD_DENOMINATOR = 5
10
+
11
+ function integerField(value, name, minimum) {
12
+ const label = minimum === 0 ? 'non-negative' : 'positive'
13
+ if (!/^\d+$/.test(value)) {
14
+ throw new Error(`${name} must be a ${label} integer`)
15
+ }
16
+ const parsed = Number(value)
17
+ if (!Number.isSafeInteger(parsed) || parsed < minimum) {
18
+ throw new Error(`${name} must be a ${label} integer`)
19
+ }
20
+ return parsed
21
+ }
22
+
23
+ function normalizeSourcePath(source, repoRoot) {
24
+ const path = source.startsWith('file:') ? fileURLToPath(source) : source
25
+ return resolve(repoRoot, path)
26
+ }
27
+
28
+ function exactlyOneField(lines, name) {
29
+ const values = lines.filter((line) => line.startsWith(`${name}:`))
30
+ if (values.length !== 1) {
31
+ throw new Error(`target LCOV record must contain exactly one ${name} field`)
32
+ }
33
+ return values[0].slice(name.length + 1)
34
+ }
35
+
36
+ function optionalPair(lines, foundName, hitName) {
37
+ const foundFields = lines.filter((line) => line.startsWith(`${foundName}:`))
38
+ const hitFields = lines.filter((line) => line.startsWith(`${hitName}:`))
39
+ if (foundFields.length === 0 && hitFields.length === 0) return null
40
+ if (foundFields.length !== 1 || hitFields.length !== 1) {
41
+ throw new Error(`target LCOV record must contain one ${foundName}/${hitName} pair`)
42
+ }
43
+
44
+ const found = integerField(foundFields[0].slice(foundName.length + 1), foundName, 0)
45
+ const hit = integerField(hitFields[0].slice(hitName.length + 1), hitName, 0)
46
+ if (hit > found) throw new Error(`${hitName} ${hit} exceeds ${foundName} ${found}`)
47
+ return { hit, found }
48
+ }
49
+
50
+ /** Parse and validate the single LCOV record for the exact target source. */
51
+ export function parseTargetLcov(report, repoRoot, targetPath) {
52
+ if (typeof report !== 'string' || report.trim() === '') {
53
+ throw new Error('LCOV report is empty')
54
+ }
55
+ const normalizedRoot = resolve(repoRoot)
56
+ const normalizedTarget = resolve(targetPath)
57
+ const records = []
58
+ let current = []
59
+ for (const line of report.split(/\r?\n/)) {
60
+ if (line === 'end_of_record') {
61
+ if (current.length > 0) records.push(current)
62
+ current = []
63
+ } else if (line.trim() !== '') {
64
+ current.push(line)
65
+ }
66
+ }
67
+ if (current.length > 0) records.push(current)
68
+
69
+ const targetRecords = []
70
+ for (const lines of records) {
71
+ const sourceFields = lines.filter((line) => line.startsWith('SF:'))
72
+ const matchingSources = sourceFields.filter(
73
+ (line) => normalizeSourcePath(line.slice(3), normalizedRoot) === normalizedTarget,
74
+ )
75
+ if (matchingSources.length === 0) continue
76
+ if (sourceFields.length !== 1 || matchingSources.length !== 1) {
77
+ throw new Error('target LCOV record must contain exactly one SF entry')
78
+ }
79
+ targetRecords.push(lines)
80
+ }
81
+
82
+ if (targetRecords.length !== 1) {
83
+ throw new Error(
84
+ `expected exactly one LCOV record for ${normalizedTarget}; found ${targetRecords.length} LCOV records`,
85
+ )
86
+ }
87
+
88
+ const lines = targetRecords[0]
89
+ const lineRecords = new Map()
90
+ for (const entry of lines.filter((line) => line.startsWith('DA:'))) {
91
+ const fields = entry.slice(3).split(',')
92
+ if (fields.length < 2 || fields.length > 3) {
93
+ throw new Error('DA entry must contain a line number and execution count')
94
+ }
95
+ const lineNumber = integerField(fields[0], 'DA line number', 1)
96
+ const count = integerField(fields[1], 'DA count', 0)
97
+ if (lineRecords.has(lineNumber)) {
98
+ throw new Error(`duplicate DA line number ${lineNumber}`)
99
+ }
100
+ lineRecords.set(lineNumber, count)
101
+ }
102
+
103
+ const found = integerField(exactlyOneField(lines, 'LF'), 'LF', 1)
104
+ const hit = integerField(exactlyOneField(lines, 'LH'), 'LH', 0)
105
+ if (hit > found) throw new Error(`LH ${hit} exceeds LF ${found}`)
106
+ if (found !== lineRecords.size) {
107
+ throw new Error(`LF ${found} does not equal ${lineRecords.size} unique DA entries`)
108
+ }
109
+
110
+ const coveredRecords = [...lineRecords.values()].filter((count) => count > 0).length
111
+ if (hit !== coveredRecords) {
112
+ throw new Error(`LH ${hit} does not equal ${coveredRecords} covered DA entries`)
113
+ }
114
+
115
+ return {
116
+ sourcePath: normalizedTarget,
117
+ lines: { hit, found },
118
+ branches: optionalPair(lines, 'BRF', 'BRH'),
119
+ functions: optionalPair(lines, 'FNF', 'FNH'),
120
+ }
121
+ }
122
+
123
+ /** Compare using integer arithmetic so the 80% boundary cannot round down. */
124
+ export function passesLineThreshold(coverage) {
125
+ return (
126
+ BigInt(coverage.lines.hit) * BigInt(LINE_THRESHOLD_DENOMINATOR) >=
127
+ BigInt(coverage.lines.found) * BigInt(LINE_THRESHOLD_NUMERATOR)
128
+ )
129
+ }
130
+
131
+ function formatMetric(metric) {
132
+ if (metric == null || metric.found === 0) return 'not reported'
133
+ return `${metric.hit}/${metric.found} (${((metric.hit / metric.found) * 100).toFixed(2)}%)`
134
+ }
135
+
136
+ function listTypeScriptTests(repoRoot) {
137
+ const directory = join(repoRoot, 'tests', 'pantheon')
138
+ return readdirSync(directory)
139
+ .filter((file) => file.endsWith('.test.ts'))
140
+ .sort()
141
+ .map((file) => join(directory, file))
142
+ }
143
+
144
+ function runCoverage() {
145
+ if (process.version !== REQUIRED_NODE_VERSION) {
146
+ throw new Error(
147
+ `plugin-v2 coverage requires Node ${REQUIRED_NODE_VERSION}; got ${process.version}`,
148
+ )
149
+ }
150
+
151
+ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
152
+ const targetPath = resolve(repoRoot, 'src', 'plugin-v2.ts')
153
+ const testFiles = listTypeScriptTests(repoRoot)
154
+ if (testFiles.length === 0) throw new Error('no tests/pantheon/*.test.ts files found')
155
+
156
+ const tempRoot = mkdtempSync(join(tmpdir(), 'pantheon-plugin-v2-coverage-'))
157
+ try {
158
+ const lcovPath = join(tempRoot, 'coverage.lcov')
159
+ const nodeOptions = [process.env.NODE_OPTIONS, '--conditions=import'].filter(Boolean).join(' ')
160
+ const args = [
161
+ '--experimental-test-coverage',
162
+ '--enable-source-maps',
163
+ '--import',
164
+ 'tsx',
165
+ '--test',
166
+ '--test-concurrency=1',
167
+ '--test-reporter=spec',
168
+ '--test-reporter=lcov',
169
+ '--test-reporter-destination=stdout',
170
+ `--test-reporter-destination=${lcovPath}`,
171
+ ...testFiles,
172
+ ]
173
+ const result = spawnSync(process.execPath, args, {
174
+ cwd: repoRoot,
175
+ encoding: 'utf8',
176
+ env: { ...process.env, NODE_OPTIONS: nodeOptions },
177
+ maxBuffer: 32 * 1024 * 1024,
178
+ })
179
+ if (result.stdout) process.stdout.write(result.stdout)
180
+ if (result.stderr) process.stderr.write(result.stderr)
181
+ if (result.error) throw new Error(`TypeScript test command failed: ${result.error.message}`)
182
+ if (result.status !== 0) {
183
+ throw new Error(`TypeScript test command exited ${result.status ?? 'without a status'}`)
184
+ }
185
+
186
+ let report
187
+ try {
188
+ report = readFileSync(lcovPath, 'utf8')
189
+ } catch (error) {
190
+ throw new Error(`LCOV report was not generated: ${error.message}`)
191
+ }
192
+ const coverage = parseTargetLcov(report, repoRoot, targetPath)
193
+ console.log(`Coverage source: ${coverage.sourcePath}`)
194
+ console.log(`Lines: ${formatMetric(coverage.lines)}`)
195
+ console.log(`Branches (informational): ${formatMetric(coverage.branches)}`)
196
+ console.log(`Functions (informational): ${formatMetric(coverage.functions)}`)
197
+ if (!passesLineThreshold(coverage)) {
198
+ throw new Error('src/plugin-v2.ts line coverage is below the required 80%')
199
+ }
200
+ console.log('src/plugin-v2.ts line coverage: PASS (>= 80%)')
201
+ } finally {
202
+ rmSync(tempRoot, { recursive: true, force: true })
203
+ }
204
+ }
205
+
206
+ if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
207
+ try {
208
+ runCoverage()
209
+ } catch (error) {
210
+ console.error(`Plugin V2 coverage gate: ${error.message}`)
211
+ process.exitCode = 1
212
+ }
213
+ }
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env python3
2
2
  """Validate agent YAML frontmatter in CI."""
3
+
3
4
  import os
4
5
  import re
5
6
  import sys
@@ -7,18 +8,19 @@ import sys
7
8
  import yaml
8
9
 
9
10
  errors = 0
10
- for f in sorted(os.listdir('src/agents')):
11
- if not f.endswith('.md'):
11
+ for f in sorted(os.listdir("src/agents")):
12
+ if not f.endswith(".md"):
12
13
  continue
13
14
  with open(f"src/agents/{f}", encoding="utf-8") as agent_file:
14
15
  content = agent_file.read()
15
- match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
16
+ match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
16
17
  if match:
17
18
  try:
18
19
  yaml.safe_load(match.group(1))
19
20
  except yaml.YAMLError as e:
20
- print(f'FAIL: {f}: {e}')
21
+ print(f"FAIL: {f}: {e}")
21
22
  errors += 1
22
23
 
23
- print(f'{sum(1 for _ in os.listdir("src/agents") if _.endswith(".md")) - errors}/{sum(1 for _ in os.listdir("src/agents") if _.endswith(".md"))} agents valid')
24
+ agent_count = sum(1 for _ in os.listdir("src/agents") if _.endswith(".md"))
25
+ print(f"{agent_count - errors}/{agent_count} agents valid")
24
26
  sys.exit(errors)
@@ -5,12 +5,12 @@ Provides a confined execution environment for orchestration scripts
5
5
  via MCP tools and resources.
6
6
 
7
7
  Usage:
8
- python scripts/code_mode_server.py
8
+ python scripts/code_mode.py
9
9
 
10
10
  Or via MCP client (stdio transport):
11
11
  pantheon-code-mode:
12
12
  command: python
13
- args: ["scripts/code_mode_server.py"]
13
+ args: ["scripts/code_mode.py"]
14
14
  """
15
15
 
16
16
  from __future__ import annotations
@@ -20,6 +20,11 @@ import hashlib
20
20
  import json
21
21
  import logging
22
22
  import os
23
+
24
+ try:
25
+ import resource
26
+ except (ImportError, OSError, ValueError): # pragma: no cover - platform-specific
27
+ resource = None # type: ignore[assignment]
23
28
  import shutil
24
29
  import signal
25
30
  import stat
@@ -31,7 +36,7 @@ from typing import Any
31
36
 
32
37
  import yaml
33
38
  from _pantheon_paths import pantheon_home, pantheon_project
34
- from mcp.server.fastmcp import FastMCP
39
+ from fastmcp import FastMCP
35
40
 
36
41
  # ── Constants ─────────────────────────────────────────────────────────────────
37
42
  ALLOWED_EXTENSIONS: frozenset[str] = frozenset({".sh", ".py"})
@@ -125,6 +130,88 @@ def _build_script_env(
125
130
  return env
126
131
 
127
132
 
133
+ # Additional tasks a sandboxed script may create beyond the UID's current
134
+ # count. RLIMIT_NPROC is a per-real-UID limit on the *total* number of
135
+ # processes AND threads, so the sandbox floor must clear everything the host
136
+ # already owns before a script can fork at all. This headroom is the actual
137
+ # anti-fork-bomb budget: the script still cannot exceed current + headroom.
138
+ NPROC_HEADROOM: int = 64
139
+
140
+
141
+ def _uid_task_count() -> int | None:
142
+ """Count the tasks (processes + threads) this real UID already owns.
143
+
144
+ The kernel compares the post-fork total against RLIMIT_NPROC, so this is
145
+ the number the sandbox limit has to exceed. Returns *None* when the count
146
+ cannot be established (no readable ``/proc``), which makes the caller
147
+ fail open on ``--nproc`` rather than pin a value that may be too low and
148
+ break every script.
149
+
150
+ The tally is one too high per process: ``/proc/<pid>/task`` already lists
151
+ the thread-group leader, so the extra ``1`` counts it twice. That bias
152
+ only widens the derived limit (the fail-open direction), so it is left in
153
+ place deliberately.
154
+ """
155
+ uid = os.getuid()
156
+ count = 0
157
+ try:
158
+ pids = os.listdir("/proc")
159
+ except OSError:
160
+ return None
161
+ for pid in pids:
162
+ if not pid.isdigit():
163
+ continue
164
+ proc_dir = f"/proc/{pid}"
165
+ try:
166
+ if os.stat(proc_dir).st_uid != uid:
167
+ continue
168
+ # ``/proc/<pid>/task`` already includes the thread-group leader,
169
+ # so the extra 1 counts it twice (over-count by one per process).
170
+ count += 1 + len(os.listdir(f"{proc_dir}/task"))
171
+ except OSError:
172
+ # Process exited between listdir and stat, or is not ours to read.
173
+ continue
174
+ return count
175
+
176
+
177
+ def _sandbox_nproc() -> str | None:
178
+ """Return the ``--nproc`` value for a sandboxed script, or *None*.
179
+
180
+ Derived from the host rather than hardcoded: the value is the UID's
181
+ current task count plus ``NPROC_HEADROOM``, clamped to the hard limit
182
+ (``prlimit`` fails with EPERM above it, and an unprivileged process cannot
183
+ raise its soft limit past the hard one).
184
+
185
+ Returns *None* when the count or the limit cannot be read, in which case
186
+ the caller omits ``--nproc``. ``--as`` and ``--cpu`` still apply, so the
187
+ sandbox keeps its memory and CPU boundaries.
188
+ """
189
+ current = _uid_task_count()
190
+ if current is None:
191
+ _log.warning(
192
+ "code-mode: cannot count this UID's tasks; omitting --nproc, so "
193
+ "the sandboxed script's fork budget is unbounded"
194
+ )
195
+ return None
196
+ if resource is None:
197
+ _log.warning(
198
+ "code-mode: cannot read RLIMIT_NPROC; omitting --nproc, so the "
199
+ "sandboxed script's fork budget is unbounded"
200
+ )
201
+ return None
202
+ try:
203
+ _soft, hard = resource.getrlimit(resource.RLIMIT_NPROC)
204
+ except (OSError, ValueError):
205
+ _log.warning(
206
+ "code-mode: cannot read RLIMIT_NPROC; omitting --nproc, so the "
207
+ "sandboxed script's fork budget is unbounded"
208
+ )
209
+ return None
210
+ if hard == getattr(resource, "RLIM_INFINITY", -1):
211
+ return str(current + NPROC_HEADROOM)
212
+ return str(max(1, min(current + NPROC_HEADROOM, hard)))
213
+
214
+
128
215
  def _prlimit_prefix(
129
216
  prlimit_path: str | None,
130
217
  timeout_s: int = SCRIPT_TIMEOUT,
@@ -132,21 +219,34 @@ def _prlimit_prefix(
132
219
  """Return a ``prlimit`` command prefix to wrap a subprocess, or *None*.
133
220
 
134
221
  On Linux with ``prlimit`` available the prefix adds:
135
- --nproc=512 --as=1073741824 --cpu=<timeout_s + 5>
136
-
137
- On non-Linux or when *prlimit_path* is falsy, returns *None* (fail-open).
222
+ --nproc=<uid task count + NPROC_HEADROOM> --as=1073741824
223
+ --cpu=<timeout_s + 5>
224
+
225
+ ``--nproc`` is derived per invocation by :func:`_sandbox_nproc` rather
226
+ than hardcoded. RLIMIT_NPROC is a per-real-UID total across processes AND
227
+ threads, so a fixed value below the host's current usage makes the very
228
+ first ``fork()`` inside the sandbox fail with EAGAIN — which is exactly
229
+ what a hardcoded ``--nproc=512`` did on a host already running more than
230
+ 512 tasks. The isolation property is unchanged: a script still cannot
231
+ create more than ``NPROC_HEADROOM`` additional tasks.
232
+
233
+ On non-Linux, when *prlimit_path* is falsy, or when the nproc limit cannot
234
+ be derived, the flag is omitted (fail-open); ``--as``/``--cpu`` remain.
138
235
  """
139
236
  if not prlimit_path:
140
237
  return None
141
238
 
142
239
  cpu_limit = timeout_s + 5
143
- return [
144
- prlimit_path,
145
- "--nproc=512",
240
+ prefix = [prlimit_path]
241
+ nproc = _sandbox_nproc()
242
+ if nproc is not None:
243
+ prefix.append(f"--nproc={nproc}")
244
+ prefix += [
146
245
  "--as=1073741824", # 1 GiB in bytes
147
246
  f"--cpu={cpu_limit}",
148
247
  "--",
149
248
  ]
249
+ return prefix
150
250
 
151
251
 
152
252
  def _detect_prlimit() -> str | None:
@@ -226,7 +326,9 @@ def _packaged_scripts_dir() -> Path | None:
226
326
  return None
227
327
 
228
328
 
229
- def _resolve_scripts_dir(candidates: list[Path], *, allow_packaged: bool = True) -> Path | None:
329
+ def _resolve_scripts_dir(
330
+ candidates: list[Path], *, allow_packaged: bool = True
331
+ ) -> Path | None:
230
332
  """Select the first usable candidate, optionally trying the package copy."""
231
333
  for candidate in candidates:
232
334
  if _has_usable_scripts(candidate):
@@ -377,9 +479,7 @@ def _load_manifest(scripts_dir: Path | None = None) -> dict[str, str]:
377
479
  ) from None
378
480
 
379
481
  if not isinstance(data, dict):
380
- raise ManifestError(
381
- "CORRUPT_DATA", "Code-mode manifest must be a JSON object."
382
- )
482
+ raise ManifestError("CORRUPT_DATA", "Code-mode manifest must be a JSON object.")
383
483
 
384
484
  if data.get("version") != 1:
385
485
  raise ManifestError(
@@ -527,7 +627,6 @@ def _contract_result(
527
627
  return f"[{status}] {message}"
528
628
 
529
629
 
530
-
531
630
  def _format_output(
532
631
  stdout: str,
533
632
  stderr: str,
@@ -818,22 +917,15 @@ async def execute_code_script(
818
917
  timeout_s=timeout_s,
819
918
  status="TIMEOUT",
820
919
  )
821
- except FileNotFoundError:
822
- return _build_result(
823
- "",
824
- f"Script '{script_name}' not found or interpreter missing.",
825
- -1,
826
- timed_out=False,
827
- duration_ms=0,
828
- metadata=metadata,
829
- json_output=json_output,
830
- timeout_s=timeout_s,
831
- status="UNAVAILABLE",
832
- )
833
920
  except OSError as e:
921
+ error = (
922
+ f"Script '{script_name}' not found or interpreter missing."
923
+ if isinstance(e, FileNotFoundError)
924
+ else f"Failed to execute script: {e}"
925
+ )
834
926
  return _build_result(
835
927
  "",
836
- f"Failed to execute script: {e}",
928
+ error,
837
929
  -1,
838
930
  timed_out=False,
839
931
  duration_ms=0,