pantheon-opencode 2.1.6 → 2.2.0-beta.2

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 (63) hide show
  1. package/AGENTS.global.md +2 -2
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +64 -0
  4. package/README.md +13 -9
  5. package/README.pt-BR.md +13 -9
  6. package/bin/pantheon-init.mjs +1 -1
  7. package/commands/pantheon-audit.md +4 -5
  8. package/commands/pantheon-model.md +1 -2
  9. package/package.json +8 -2
  10. package/plugin.json +1 -1
  11. package/prompts/dynamic/agora-generated.txt +2 -2
  12. package/prompts/dynamic/orchestrate-generated.txt +4 -4
  13. package/prompts/sketch.prompt.md +1 -1
  14. package/pyproject.toml +1 -1
  15. package/scripts/build-agents-md.mjs +73 -12
  16. package/scripts/build-plugin.mjs +3 -1
  17. package/scripts/hooks/format-multi-language.sh +30 -29
  18. package/scripts/install-mcp.mjs +55 -27
  19. package/scripts/prune.mjs +124 -2
  20. package/scripts/setup.mjs +1 -1
  21. package/scripts/themis_heuristic_scan.py +3 -5
  22. package/skills-lock.json +1 -1
  23. package/src/agents/aphrodite.md +1 -1
  24. package/src/agents/athena.md +6 -14
  25. package/src/agents/demeter.md +1 -1
  26. package/src/agents/hermes.md +3 -2
  27. package/src/agents/iris.md +4 -6
  28. package/src/agents/prometheus.md +3 -7
  29. package/src/agents/roster.json +567 -0
  30. package/src/agents/zeus.md +3 -0
  31. package/src/instructions/agent-return-format.instructions.md +1 -1
  32. package/src/instructions/zeus-anti-stall.instructions.md +11 -35
  33. package/src/instructions/zeus-council-synthesis.instructions.md +17 -49
  34. package/src/instructions/zeus-timeout-retry.instructions.md +12 -80
  35. package/src/mcp/mcp_codemap_module.py +6 -5
  36. package/src/mcp/pantheon-mcp-server.mjs +875 -0
  37. package/src/pantheon/agent-forge-tool.ts +316 -0
  38. package/src/pantheon/auto-permissions.ts +31 -1
  39. package/src/pantheon/codemap-tools.ts +525 -0
  40. package/src/pantheon/deepwork/plan-tracker.ts +63 -2
  41. package/src/pantheon/execute-after.ts +21 -0
  42. package/src/pantheon/hook-engine.ts +2 -1
  43. package/src/pantheon/native-memory-tools.ts +686 -0
  44. package/src/pantheon/presets.mjs +15 -0
  45. package/src/pantheon/step-ledger.ts +259 -0
  46. package/src/pantheon/swe-eval-harness.ts +211 -0
  47. package/src/pantheon/tools.ts +62 -7
  48. package/src/plugin/index.js +2091 -136
  49. package/src/plugin/index.ts +1 -14
  50. package/src/plugin.ts +167 -10
  51. package/src/plugins/tui/dist/tui.d.ts +66 -0
  52. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  53. package/src/plugins/tui/dist/tui.js +1259 -367
  54. package/src/plugins/tui/dist/tui.js.map +1 -1
  55. package/src/plugins/tui/package-lock.json +2 -2
  56. package/src/plugins/tui/package.json +1 -1
  57. package/src/plugins/tui/src/index.tsx +632 -71
  58. package/src/plugins/tui/src/pantheon-settings.tsx +78 -14
  59. package/src/plugins/tui/src/quota-state.ts +190 -0
  60. package/src/plugins/tui/src/tui-prefs.ts +169 -12
  61. package/src/routing.yml +3 -0
  62. package/src/skills/auto-continue/references/auto-continue-details.md +2 -31
  63. /package/scripts/{setup-v2-config.mjs → setup-config.mjs} +0 -0
@@ -0,0 +1,525 @@
1
+ /**
2
+ * Native In-Process Codebase Structural Graph & Symbol Indexer (`codemap-tools.ts`).
3
+ *
4
+ * Replaces the legacy Python `mcp_codemap_module.py` with a fast, polyglot
5
+ * TypeScript symbol and dependency graph indexer backed by `node:sqlite`.
6
+ * Extracts functions, classes, interfaces, types, and import/call relationships
7
+ * across TypeScript, JavaScript, Python, Go, and Rust without spawning Python.
8
+ *
9
+ * Exposes `code_index`, `code_query`, and `code_neighbors` as native plugin tools.
10
+ *
11
+ * @module pantheon/codemap-tools
12
+ */
13
+
14
+ import { createHash } from 'node:crypto'
15
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
16
+ import { extname, join, relative, resolve, sep } from 'node:path'
17
+ import { DatabaseSync } from 'node:sqlite'
18
+ import { resolveToolCwd } from './tool-context.ts'
19
+ import type { PantheonToolDef, PantheonToolResult } from './tools.ts'
20
+
21
+ export interface CodeEntity {
22
+ readonly name: string
23
+ readonly kind: 'function' | 'class' | 'interface' | 'type' | 'variable' | 'module'
24
+ readonly file: string
25
+ readonly line: number
26
+ readonly signature: string
27
+ }
28
+
29
+ export interface CodeRelation {
30
+ readonly source: string
31
+ readonly target: string
32
+ readonly kind: 'imports' | 'calls' | 'extends'
33
+ readonly file: string
34
+ readonly line: number
35
+ }
36
+
37
+ const IGNORED_DIRS = new Set([
38
+ '.git',
39
+ 'node_modules',
40
+ 'dist',
41
+ 'build',
42
+ '.venv',
43
+ '__pycache__',
44
+ '.pytest_cache',
45
+ '.pantheon',
46
+ '.opencode',
47
+ 'coverage',
48
+ ])
49
+
50
+ const SUPPORTED_EXT_LANG: Record<string, string> = {
51
+ '.ts': 'typescript',
52
+ '.tsx': 'typescript',
53
+ '.js': 'javascript',
54
+ '.jsx': 'javascript',
55
+ '.mjs': 'javascript',
56
+ '.py': 'python',
57
+ '.go': 'go',
58
+ '.rs': 'rust',
59
+ }
60
+
61
+ const codemapDbCache = new Map<string, DatabaseSync>()
62
+
63
+ function getCodemapDb(workspaceDir: string): DatabaseSync {
64
+ const memoryDir = join(workspaceDir, '.pantheon', 'memory')
65
+ mkdirSync(memoryDir, { recursive: true })
66
+ const canonicalBase = realpathSync(memoryDir)
67
+ const dbPath = resolve(canonicalBase, 'memory.db')
68
+ const prefix = canonicalBase.endsWith(sep) ? canonicalBase : `${canonicalBase}${sep}`
69
+ if (!dbPath.startsWith(prefix)) {
70
+ throw new Error('Path traversal denied for codemap database')
71
+ }
72
+ const cached = codemapDbCache.get(dbPath)
73
+ if (cached) return cached
74
+
75
+ const db = new DatabaseSync(dbPath)
76
+ db.exec(`
77
+ CREATE TABLE IF NOT EXISTS code_files (
78
+ path TEXT PRIMARY KEY,
79
+ hash TEXT NOT NULL,
80
+ language TEXT NOT NULL,
81
+ indexed_at TEXT NOT NULL
82
+ );
83
+ CREATE TABLE IF NOT EXISTS code_entities (
84
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
85
+ name TEXT NOT NULL,
86
+ kind TEXT NOT NULL,
87
+ file TEXT NOT NULL,
88
+ line INTEGER NOT NULL,
89
+ signature TEXT NOT NULL
90
+ );
91
+ CREATE INDEX IF NOT EXISTS idx_code_entities_name ON code_entities(name);
92
+ CREATE INDEX IF NOT EXISTS idx_code_entities_file ON code_entities(file);
93
+ CREATE TABLE IF NOT EXISTS code_relations (
94
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
95
+ source TEXT NOT NULL,
96
+ target TEXT NOT NULL,
97
+ kind TEXT NOT NULL,
98
+ file TEXT NOT NULL,
99
+ line INTEGER NOT NULL
100
+ );
101
+ CREATE INDEX IF NOT EXISTS idx_code_relations_source ON code_relations(source);
102
+ CREATE INDEX IF NOT EXISTS idx_code_relations_target ON code_relations(target);
103
+ `)
104
+ codemapDbCache.set(dbPath, db)
105
+ return db
106
+ }
107
+
108
+ export function extractSymbolsAndRelations(
109
+ relPath: string,
110
+ content: string,
111
+ language: string,
112
+ ): { entities: CodeEntity[]; relations: CodeRelation[] } {
113
+ const entities: CodeEntity[] = []
114
+ const relations: CodeRelation[] = []
115
+ const lines = content.split(/\r?\n/)
116
+
117
+ for (let i = 0; i < lines.length; i++) {
118
+ const rawLine = lines[i] ?? ''
119
+ const trimmed = rawLine.trim()
120
+ const lineNo = i + 1
121
+ if (
122
+ !trimmed ||
123
+ trimmed.startsWith('//') ||
124
+ trimmed.startsWith('#') ||
125
+ trimmed.startsWith('*')
126
+ ) {
127
+ continue
128
+ }
129
+
130
+ if (language === 'typescript' || language === 'javascript') {
131
+ const fnMatch = trimmed.match(
132
+ /^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/,
133
+ )
134
+ if (fnMatch?.[1]) {
135
+ entities.push({
136
+ name: fnMatch[1],
137
+ kind: 'function',
138
+ file: relPath,
139
+ line: lineNo,
140
+ signature: trimmed.slice(0, 120),
141
+ })
142
+ continue
143
+ }
144
+ const classMatch = trimmed.match(
145
+ /^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)(?:\s+extends\s+([A-Za-z_$][\w$]*))?/,
146
+ )
147
+ if (classMatch?.[1]) {
148
+ entities.push({
149
+ name: classMatch[1],
150
+ kind: 'class',
151
+ file: relPath,
152
+ line: lineNo,
153
+ signature: trimmed.slice(0, 120),
154
+ })
155
+ if (classMatch[2]) {
156
+ relations.push({
157
+ source: classMatch[1],
158
+ target: classMatch[2],
159
+ kind: 'extends',
160
+ file: relPath,
161
+ line: lineNo,
162
+ })
163
+ }
164
+ continue
165
+ }
166
+ const ifaceMatch = trimmed.match(/^(?:export\s+)?(interface|type)\s+([A-Za-z_$][\w$]*)/)
167
+ if (ifaceMatch?.[1] && ifaceMatch[2]) {
168
+ entities.push({
169
+ name: ifaceMatch[2],
170
+ kind: ifaceMatch[1] === 'interface' ? 'interface' : 'type',
171
+ file: relPath,
172
+ line: lineNo,
173
+ signature: trimmed.slice(0, 120),
174
+ })
175
+ continue
176
+ }
177
+ const constMatch = trimmed.match(/^export\s+(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=/)
178
+ if (constMatch?.[1]) {
179
+ entities.push({
180
+ name: constMatch[1],
181
+ kind: 'variable',
182
+ file: relPath,
183
+ line: lineNo,
184
+ signature: trimmed.slice(0, 120),
185
+ })
186
+ continue
187
+ }
188
+ const importMatch = trimmed.match(/from\s+['"]([^'"]+)['"]/)
189
+ if (importMatch?.[1] && trimmed.startsWith('import ')) {
190
+ relations.push({
191
+ source: relPath,
192
+ target: importMatch[1],
193
+ kind: 'imports',
194
+ file: relPath,
195
+ line: lineNo,
196
+ })
197
+ }
198
+ } else if (language === 'python') {
199
+ const defMatch = trimmed.match(/^(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/)
200
+ if (defMatch?.[1]) {
201
+ entities.push({
202
+ name: defMatch[1],
203
+ kind: 'function',
204
+ file: relPath,
205
+ line: lineNo,
206
+ signature: trimmed.slice(0, 120),
207
+ })
208
+ continue
209
+ }
210
+ const pyClassMatch = trimmed.match(/^class\s+([A-Za-z_]\w*)(?:\(([^)]+)\))?:/)
211
+ if (pyClassMatch?.[1]) {
212
+ entities.push({
213
+ name: pyClassMatch[1],
214
+ kind: 'class',
215
+ file: relPath,
216
+ line: lineNo,
217
+ signature: trimmed.slice(0, 120),
218
+ })
219
+ if (pyClassMatch[2]) {
220
+ relations.push({
221
+ source: pyClassMatch[1],
222
+ target: pyClassMatch[2].split(',')[0]?.trim() ?? pyClassMatch[2],
223
+ kind: 'extends',
224
+ file: relPath,
225
+ line: lineNo,
226
+ })
227
+ }
228
+ continue
229
+ }
230
+ const pyImportMatch = trimmed.match(/^(?:from\s+([\w.]+)\s+import|import\s+([\w.]+))/)
231
+ const targetMod = pyImportMatch?.[1] ?? pyImportMatch?.[2]
232
+ if (targetMod) {
233
+ relations.push({
234
+ source: relPath,
235
+ target: targetMod,
236
+ kind: 'imports',
237
+ file: relPath,
238
+ line: lineNo,
239
+ })
240
+ }
241
+ } else if (language === 'go') {
242
+ const goFnMatch = trimmed.match(/^func\s+(?:\([^)]+\)\s+)?([A-Za-z_]\w*)\s*\(/)
243
+ if (goFnMatch?.[1]) {
244
+ entities.push({
245
+ name: goFnMatch[1],
246
+ kind: 'function',
247
+ file: relPath,
248
+ line: lineNo,
249
+ signature: trimmed.slice(0, 120),
250
+ })
251
+ }
252
+ } else if (language === 'rust') {
253
+ const rsFnMatch = trimmed.match(/^(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/)
254
+ if (rsFnMatch?.[1]) {
255
+ entities.push({
256
+ name: rsFnMatch[1],
257
+ kind: 'function',
258
+ file: relPath,
259
+ line: lineNo,
260
+ signature: trimmed.slice(0, 120),
261
+ })
262
+ }
263
+ }
264
+ }
265
+
266
+ return { entities, relations }
267
+ }
268
+
269
+ function collectSourceFiles(currentDir: string, maxFiles = 500): string[] {
270
+ const results: string[] = []
271
+ function walk(dir: string): void {
272
+ if (results.length >= maxFiles) return
273
+ let entries: Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>
274
+ try {
275
+ entries = readdirSync(dir, { withFileTypes: true })
276
+ } catch {
277
+ return
278
+ }
279
+ for (const entry of entries) {
280
+ if (results.length >= maxFiles) return
281
+ const name = String(entry.name)
282
+ if (entry.isDirectory()) {
283
+ if (!IGNORED_DIRS.has(name) && !name.startsWith('.')) {
284
+ walk(join(dir, name))
285
+ }
286
+ } else if (entry.isFile()) {
287
+ const ext = extname(name).toLowerCase()
288
+ if (ext in SUPPORTED_EXT_LANG) {
289
+ results.push(join(dir, name))
290
+ }
291
+ }
292
+ }
293
+ }
294
+ walk(currentDir)
295
+ return results
296
+ }
297
+
298
+ function jsonResult(payload: unknown): PantheonToolResult {
299
+ return { output: JSON.stringify(payload) }
300
+ }
301
+
302
+ export function createCodemapTools(fallbackDir?: string): PantheonToolDef[] {
303
+ return [
304
+ {
305
+ name: 'code_index',
306
+ description:
307
+ 'Index codebase symbols (functions, classes, interfaces, types) and import/inheritance edges into SQLite.',
308
+ input: {
309
+ type: 'object',
310
+ additionalProperties: false,
311
+ properties: {
312
+ path: {
313
+ type: 'string',
314
+ description:
315
+ 'Optional relative subdirectory or file path within the workspace to index',
316
+ },
317
+ force: {
318
+ type: 'boolean',
319
+ description: 'Re-index files even when SHA-256 hash is unchanged',
320
+ },
321
+ },
322
+ },
323
+ output: {},
324
+ execute: async (input, context) => {
325
+ try {
326
+ const cwd = resolveToolCwd(context, fallbackDir)
327
+ const canonicalRoot = realpathSync(cwd)
328
+ const subPath =
329
+ typeof input.path === 'string' && input.path.trim() ? input.path.trim() : '.'
330
+ const targetPath = resolve(canonicalRoot, subPath)
331
+ const rootPrefix = canonicalRoot.endsWith(sep) ? canonicalRoot : `${canonicalRoot}${sep}`
332
+ if (targetPath !== canonicalRoot && !targetPath.startsWith(rootPrefix)) {
333
+ return jsonResult({ ok: false, error: 'path escapes workspace root' })
334
+ }
335
+ if (!existsSync(targetPath)) {
336
+ return jsonResult({ ok: false, error: `path not found: ${subPath}` })
337
+ }
338
+
339
+ const force = input.force === true
340
+ const db = getCodemapDb(canonicalRoot)
341
+ const st = statSync(targetPath)
342
+ const files = st.isFile() ? [targetPath] : collectSourceFiles(targetPath)
343
+
344
+ let indexed = 0
345
+ let skipped = 0
346
+ let entitiesCount = 0
347
+ let relationsCount = 0
348
+ const nowIso = new Date().toISOString()
349
+
350
+ for (const filePath of files) {
351
+ const ext = extname(filePath).toLowerCase()
352
+ const lang = SUPPORTED_EXT_LANG[ext]
353
+ if (!lang) continue
354
+ const relFile = relative(canonicalRoot, filePath).replace(/\\/g, '/')
355
+ const content = readFileSync(filePath, 'utf8')
356
+ const hash = createHash('sha256').update(content).digest('hex')
357
+
358
+ const existing = db
359
+ .prepare('SELECT hash FROM code_files WHERE path = ?')
360
+ .get(relFile) as { hash?: string } | undefined
361
+ if (!force && existing?.hash === hash) {
362
+ skipped += 1
363
+ continue
364
+ }
365
+
366
+ const { entities, relations } = extractSymbolsAndRelations(relFile, content, lang)
367
+ db.prepare('DELETE FROM code_entities WHERE file = ?').run(relFile)
368
+ db.prepare('DELETE FROM code_relations WHERE file = ?').run(relFile)
369
+
370
+ const insertEnt = db.prepare(
371
+ 'INSERT INTO code_entities (name, kind, file, line, signature) VALUES (?, ?, ?, ?, ?)',
372
+ )
373
+ for (const ent of entities) {
374
+ insertEnt.run(ent.name, ent.kind, ent.file, ent.line, ent.signature)
375
+ entitiesCount += 1
376
+ }
377
+
378
+ const insertRel = db.prepare(
379
+ 'INSERT INTO code_relations (source, target, kind, file, line) VALUES (?, ?, ?, ?, ?)',
380
+ )
381
+ for (const rel of relations) {
382
+ insertRel.run(rel.source, rel.target, rel.kind, rel.file, rel.line)
383
+ relationsCount += 1
384
+ }
385
+
386
+ db.prepare(
387
+ 'INSERT OR REPLACE INTO code_files (path, hash, language, indexed_at) VALUES (?, ?, ?, ?)',
388
+ ).run(relFile, hash, lang, nowIso)
389
+ indexed += 1
390
+ }
391
+
392
+ return jsonResult({
393
+ ok: true,
394
+ indexed,
395
+ skipped,
396
+ entities: entitiesCount,
397
+ relations: relationsCount,
398
+ })
399
+ } catch (err) {
400
+ return jsonResult({
401
+ ok: false,
402
+ error: err instanceof Error ? err.message : String(err),
403
+ })
404
+ }
405
+ },
406
+ },
407
+ {
408
+ name: 'code_query',
409
+ description:
410
+ 'Query indexed symbols (functions, classes, interfaces, types) by name prefix or substring.',
411
+ input: {
412
+ type: 'object',
413
+ additionalProperties: false,
414
+ required: ['query'],
415
+ properties: {
416
+ query: { type: 'string', description: 'Symbol name or substring to search for' },
417
+ kind: {
418
+ type: 'string',
419
+ description: 'Optional filter: function, class, interface, type, variable',
420
+ },
421
+ limit: { type: 'number', description: 'Max results (default 25)' },
422
+ },
423
+ },
424
+ output: {},
425
+ execute: async (input, context) => {
426
+ try {
427
+ const q = typeof input.query === 'string' ? input.query.trim() : ''
428
+ if (!q) return jsonResult({ ok: false, error: 'query is required', results: [] })
429
+ const limit =
430
+ typeof input.limit === 'number' && Number.isFinite(input.limit) && input.limit > 0
431
+ ? Math.min(Math.floor(input.limit), 100)
432
+ : 25
433
+ const cwd = resolveToolCwd(context, fallbackDir)
434
+ const db = getCodemapDb(cwd)
435
+ const escaped = q.replace(/[\\%_]/g, '\\$&')
436
+ let sql = `
437
+ SELECT name, kind, file, line, signature
438
+ FROM code_entities
439
+ WHERE name LIKE ? ESCAPE '\\'
440
+ `
441
+ const params: Array<string | number> = [`%${escaped}%`]
442
+ if (typeof input.kind === 'string' && input.kind.trim()) {
443
+ sql += ' AND kind = ?'
444
+ params.push(input.kind.trim())
445
+ }
446
+ sql +=
447
+ ' ORDER BY CASE WHEN name = ? THEN 0 WHEN name LIKE ? THEN 1 ELSE 2 END, file, line LIMIT ?'
448
+ params.push(q, `${escaped}%`, limit)
449
+ const rows = db.prepare(sql).all(...params)
450
+ return jsonResult({ ok: true, count: rows.length, results: rows })
451
+ } catch (err) {
452
+ return jsonResult({
453
+ ok: false,
454
+ error: err instanceof Error ? err.message : String(err),
455
+ })
456
+ }
457
+ },
458
+ },
459
+ {
460
+ name: 'code_neighbors',
461
+ description:
462
+ 'Find structural neighbors (imports, callers, subclasses) for a symbol or file path.',
463
+ input: {
464
+ type: 'object',
465
+ additionalProperties: false,
466
+ required: ['target'],
467
+ properties: {
468
+ target: { type: 'string', description: 'Symbol name or relative file path' },
469
+ direction: {
470
+ type: 'string',
471
+ enum: ['both', 'outgoing', 'incoming'],
472
+ description: 'Edge direction to traverse (default both)',
473
+ },
474
+ },
475
+ },
476
+ output: {},
477
+ execute: async (input, context) => {
478
+ try {
479
+ const target = typeof input.target === 'string' ? input.target.trim() : ''
480
+ if (!target) return jsonResult({ ok: false, error: 'target is required', neighbors: [] })
481
+ const direction = typeof input.direction === 'string' ? input.direction : 'both'
482
+ const cwd = resolveToolCwd(context, fallbackDir)
483
+ const db = getCodemapDb(cwd)
484
+ const escaped = target.replace(/[\\%_]/g, '\\$&')
485
+
486
+ const outgoing =
487
+ direction === 'incoming'
488
+ ? []
489
+ : db
490
+ .prepare(
491
+ `SELECT source, target, kind, file, line
492
+ FROM code_relations
493
+ WHERE source = ? OR source LIKE ? ESCAPE '\\'
494
+ LIMIT 50`,
495
+ )
496
+ .all(target, `%${escaped}%`)
497
+
498
+ const incoming =
499
+ direction === 'outgoing'
500
+ ? []
501
+ : db
502
+ .prepare(
503
+ `SELECT source, target, kind, file, line
504
+ FROM code_relations
505
+ WHERE target = ? OR target LIKE ? ESCAPE '\\'
506
+ LIMIT 50`,
507
+ )
508
+ .all(target, `%${escaped}%`)
509
+
510
+ return jsonResult({
511
+ ok: true,
512
+ target,
513
+ outgoing,
514
+ incoming,
515
+ })
516
+ } catch (err) {
517
+ return jsonResult({
518
+ ok: false,
519
+ error: err instanceof Error ? err.message : String(err),
520
+ })
521
+ }
522
+ },
523
+ },
524
+ ]
525
+ }
@@ -9,6 +9,8 @@
9
9
  import { existsSync } from 'node:fs'
10
10
  import { appendFile, mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises'
11
11
  import { join } from 'node:path'
12
+ import { createExecutionReceipt } from '../execution-receipt.ts'
13
+ import { ThemisReflexController } from '../themis-reflex.ts'
12
14
  import { generateMarkdownDocument } from './plan-projection.ts'
13
15
  import {
14
16
  type DeepworkPlan,
@@ -41,7 +43,20 @@ export function deepworkRootDir(cwd = process.cwd()): string {
41
43
  }
42
44
 
43
45
  export function deepworkPlanDir(cwd = process.cwd(), slug: string): string {
44
- return join(deepworkRootDir(cwd), slug)
46
+ const safeSlug = String(slug ?? '').trim()
47
+ if (
48
+ !safeSlug ||
49
+ safeSlug === '.' ||
50
+ safeSlug === '..' ||
51
+ safeSlug.includes('..') ||
52
+ safeSlug.includes('/') ||
53
+ safeSlug.includes('\\')
54
+ ) {
55
+ throw new Error(
56
+ `Invalid deepwork plan slug "${slug}": path traversal or separator characters are not allowed`,
57
+ )
58
+ }
59
+ return join(deepworkRootDir(cwd), safeSlug)
45
60
  }
46
61
 
47
62
  export function deepworkPlanJsonPath(cwd = process.cwd(), slug: string): string {
@@ -482,8 +497,12 @@ export async function updateTaskState(
482
497
  })
483
498
  }
484
499
 
500
+ const deepworkReflexController = new ThemisReflexController({ maxRetries: 2 })
501
+
485
502
  /**
486
503
  * Record verification of an acceptance criterion.
504
+ * Emits a cryptographic Execution Proof Receipt on PantheonBus when verified,
505
+ * and evaluates failed checks through ThemisReflexController for self-healing.
487
506
  */
488
507
  export async function verifyTaskAcceptance(
489
508
  cwd = process.cwd(),
@@ -530,10 +549,52 @@ export async function verifyTaskAcceptance(
530
549
  const nextPlan: DeepworkPlan = { ...plan, tasks: updatedTasks }
531
550
  await writePlan(cwd, nextPlan)
532
551
 
552
+ const taskKey = `${slug}:${taskId}`
553
+ const agentId = task.agent ?? 'specialist'
554
+ let receiptId: string | undefined
555
+ let reflexAction: string | undefined
556
+
557
+ try {
558
+ if (verified) {
559
+ deepworkReflexController.evaluate(taskKey, agentId, [])
560
+ const receipt = createExecutionReceipt({
561
+ taskID: taskKey,
562
+ agent: agentId,
563
+ files: [
564
+ { path: `${slug}/${taskId}#${checkIndex}`, content: resolvedProof ?? 'verified' },
565
+ ],
566
+ testSlice: {
567
+ command: currentAcc.check,
568
+ exitCode: 0,
569
+ durationMs: 0,
570
+ },
571
+ })
572
+ receiptId = receipt.receiptId
573
+ } else {
574
+ const decision = deepworkReflexController.evaluate(taskKey, agentId, [
575
+ {
576
+ file: `${slug}/${taskId}`,
577
+ error: resolvedProof ?? `Acceptance check #${checkIndex} failed: ${currentAcc.check}`,
578
+ },
579
+ ])
580
+ reflexAction = decision.action
581
+ }
582
+ } catch {
583
+ /* best-effort bus telemetry */
584
+ }
585
+
533
586
  await appendJournal(cwd, slug, {
534
587
  type: 'acceptance_verified',
535
588
  timestamp: new Date().toISOString(),
536
- payload: { taskId, checkIndex, verified, proof, allVerified },
589
+ payload: {
590
+ taskId,
591
+ checkIndex,
592
+ verified,
593
+ proof,
594
+ allVerified,
595
+ ...(receiptId ? { receiptId } : {}),
596
+ ...(reflexAction ? { reflexAction } : {}),
597
+ },
537
598
  })
538
599
 
539
600
  return (await readPlan(cwd, slug)) ?? nextPlan
@@ -33,6 +33,7 @@
33
33
  * @module pantheon/execute-after
34
34
  */
35
35
 
36
+ import { existsSync, readFileSync } from 'node:fs'
36
37
  import {
37
38
  type ContextSandboxConfig,
38
39
  createContextSandbox,
@@ -269,6 +270,26 @@ export function createV2ExecuteAfter(
269
270
  await sandbox(input, output)
270
271
  await readEnhancer(input, output)
271
272
 
273
+ // Post-edit structural diagnostic check for JSON files: surfaces syntax
274
+ // corruption in the same turn so the specialist fixes it immediately.
275
+ const lowerTool = tool.trim().toLowerCase()
276
+ if (lowerTool === 'edit' || lowerTool === 'write' || lowerTool === 'hashline_edit') {
277
+ const rawArgs = (payload.input ?? {}) as Record<string, unknown>
278
+ const editedPath = rawArgs.filePath ?? rawArgs.file_path ?? rawArgs.file
279
+ if (
280
+ typeof editedPath === 'string' &&
281
+ editedPath.endsWith('.json') &&
282
+ existsSync(editedPath)
283
+ ) {
284
+ try {
285
+ JSON.parse(readFileSync(editedPath, 'utf8'))
286
+ } catch (jsonErr) {
287
+ const msg = jsonErr instanceof Error ? jsonErr.message : String(jsonErr)
288
+ output.output = `${output.output}\n[Pantheon Diagnostic] JSON syntax error in ${editedPath}: ${msg}`
289
+ }
290
+ }
291
+ }
292
+
272
293
  if (output.output !== original.text) {
273
294
  writeText(result as V2ToolResult, original.field, output.output, original.text, tool)
274
295
  }
@@ -294,7 +294,8 @@ export function formatterApplies(tool: string, input: unknown): boolean {
294
294
  const normalized = tool.trim().toLowerCase()
295
295
  if (normalized === 'edit' || normalized === 'write' || normalized === 'hashline_edit') {
296
296
  if (input !== null && typeof input === 'object') {
297
- return formattablePath((input as Record<string, unknown>).file_path)
297
+ const rec = input as Record<string, unknown>
298
+ return formattablePath(rec.file_path ?? rec.filePath ?? rec.file ?? rec.path)
298
299
  }
299
300
  return false
300
301
  }