harness-reflex 0.0.0-stage → 0.3.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 (164) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +266 -2
  3. package/USER_GUIDE.md +639 -0
  4. package/dist/adapters/agy.d.ts +8 -0
  5. package/dist/adapters/agy.js +80 -0
  6. package/dist/adapters/agy.js.map +1 -0
  7. package/dist/adapters/claude.d.ts +13 -0
  8. package/dist/adapters/claude.js +46 -0
  9. package/dist/adapters/claude.js.map +1 -0
  10. package/dist/adapters/codex.d.ts +139 -0
  11. package/dist/adapters/codex.js +368 -0
  12. package/dist/adapters/codex.js.map +1 -0
  13. package/dist/backend/defaults.d.ts +31 -0
  14. package/dist/backend/defaults.js +32 -0
  15. package/dist/backend/defaults.js.map +1 -0
  16. package/dist/backend/factory.d.ts +11 -0
  17. package/dist/backend/factory.js +40 -0
  18. package/dist/backend/factory.js.map +1 -0
  19. package/dist/backend/jev.d.ts +524 -0
  20. package/dist/backend/jev.js +1486 -0
  21. package/dist/backend/jev.js.map +1 -0
  22. package/dist/backend/mock.d.ts +26 -0
  23. package/dist/backend/mock.js +320 -0
  24. package/dist/backend/mock.js.map +1 -0
  25. package/dist/backend/route-prompt.d.ts +37 -0
  26. package/dist/backend/route-prompt.js +42 -0
  27. package/dist/backend/route-prompt.js.map +1 -0
  28. package/dist/backend/simple-jev.d.ts +35 -0
  29. package/dist/backend/simple-jev.js +273 -0
  30. package/dist/backend/simple-jev.js.map +1 -0
  31. package/dist/backend/types.d.ts +270 -0
  32. package/dist/backend/types.js +5 -0
  33. package/dist/backend/types.js.map +1 -0
  34. package/dist/cli/index.d.ts +2 -0
  35. package/dist/cli/index.js +278 -0
  36. package/dist/cli/index.js.map +1 -0
  37. package/dist/core/calibrate.d.ts +56 -0
  38. package/dist/core/calibrate.js +144 -0
  39. package/dist/core/calibrate.js.map +1 -0
  40. package/dist/core/closing.d.ts +90 -0
  41. package/dist/core/closing.js +111 -0
  42. package/dist/core/closing.js.map +1 -0
  43. package/dist/core/evidence.d.ts +119 -0
  44. package/dist/core/evidence.js +209 -0
  45. package/dist/core/evidence.js.map +1 -0
  46. package/dist/core/gate.d.ts +25 -0
  47. package/dist/core/gate.js +114 -0
  48. package/dist/core/gate.js.map +1 -0
  49. package/dist/core/judge.d.ts +221 -0
  50. package/dist/core/judge.js +251 -0
  51. package/dist/core/judge.js.map +1 -0
  52. package/dist/core/ledger.d.ts +67 -0
  53. package/dist/core/ledger.js +173 -0
  54. package/dist/core/ledger.js.map +1 -0
  55. package/dist/core/orchestrate-closing.d.ts +237 -0
  56. package/dist/core/orchestrate-closing.js +250 -0
  57. package/dist/core/orchestrate-closing.js.map +1 -0
  58. package/dist/core/orchestrate-correction.d.ts +209 -0
  59. package/dist/core/orchestrate-correction.js +141 -0
  60. package/dist/core/orchestrate-correction.js.map +1 -0
  61. package/dist/core/orchestrate-host.d.ts +225 -0
  62. package/dist/core/orchestrate-host.js +80 -0
  63. package/dist/core/orchestrate-host.js.map +1 -0
  64. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  65. package/dist/core/orchestrate-stagnation.js +270 -0
  66. package/dist/core/orchestrate-stagnation.js.map +1 -0
  67. package/dist/core/orchestrate.d.ts +357 -0
  68. package/dist/core/orchestrate.js +418 -0
  69. package/dist/core/orchestrate.js.map +1 -0
  70. package/dist/core/policy.d.ts +122 -0
  71. package/dist/core/policy.js +102 -0
  72. package/dist/core/policy.js.map +1 -0
  73. package/dist/core/prune-plan.d.ts +141 -0
  74. package/dist/core/prune-plan.js +390 -0
  75. package/dist/core/prune-plan.js.map +1 -0
  76. package/dist/core/prune.d.ts +30 -0
  77. package/dist/core/prune.js +73 -0
  78. package/dist/core/prune.js.map +1 -0
  79. package/dist/core/route.d.ts +35 -0
  80. package/dist/core/route.js +39 -0
  81. package/dist/core/route.js.map +1 -0
  82. package/dist/core/score.d.ts +40 -0
  83. package/dist/core/score.js +49 -0
  84. package/dist/core/score.js.map +1 -0
  85. package/dist/core/screen.d.ts +22 -0
  86. package/dist/core/screen.js +117 -0
  87. package/dist/core/screen.js.map +1 -0
  88. package/dist/core/stagnation.d.ts +23 -0
  89. package/dist/core/stagnation.js +93 -0
  90. package/dist/core/stagnation.js.map +1 -0
  91. package/dist/core/text.d.ts +36 -0
  92. package/dist/core/text.js +66 -0
  93. package/dist/core/text.js.map +1 -0
  94. package/dist/hook/cli.d.ts +9 -0
  95. package/dist/hook/cli.js +52 -0
  96. package/dist/hook/cli.js.map +1 -0
  97. package/dist/hook/contract.d.ts +125 -0
  98. package/dist/hook/contract.js +159 -0
  99. package/dist/hook/contract.js.map +1 -0
  100. package/dist/hook/decision.d.ts +97 -0
  101. package/dist/hook/decision.js +955 -0
  102. package/dist/hook/decision.js.map +1 -0
  103. package/dist/hook/memory-store.d.ts +81 -0
  104. package/dist/hook/memory-store.js +157 -0
  105. package/dist/hook/memory-store.js.map +1 -0
  106. package/dist/hook/payload.d.ts +55 -0
  107. package/dist/hook/payload.js +129 -0
  108. package/dist/hook/payload.js.map +1 -0
  109. package/dist/hook/run.d.ts +48 -0
  110. package/dist/hook/run.js +218 -0
  111. package/dist/hook/run.js.map +1 -0
  112. package/dist/hook/store-port.d.ts +72 -0
  113. package/dist/hook/store-port.js +2 -0
  114. package/dist/hook/store-port.js.map +1 -0
  115. package/dist/index.d.ts +18 -0
  116. package/dist/index.js +19 -0
  117. package/dist/index.js.map +1 -0
  118. package/dist/mcp/server.d.ts +12 -0
  119. package/dist/mcp/server.js +368 -0
  120. package/dist/mcp/server.js.map +1 -0
  121. package/dist/ports/audit.d.ts +18 -0
  122. package/dist/ports/audit.js +11 -0
  123. package/dist/ports/audit.js.map +1 -0
  124. package/dist/ports/clock.d.ts +14 -0
  125. package/dist/ports/clock.js +11 -0
  126. package/dist/ports/clock.js.map +1 -0
  127. package/dist/ports/decision.d.ts +75 -0
  128. package/dist/ports/decision.js +2 -0
  129. package/dist/ports/decision.js.map +1 -0
  130. package/dist/ports/index.d.ts +14 -0
  131. package/dist/ports/index.js +2 -0
  132. package/dist/ports/index.js.map +1 -0
  133. package/dist/ports/log.d.ts +22 -0
  134. package/dist/ports/log.js +12 -0
  135. package/dist/ports/log.js.map +1 -0
  136. package/dist/ports/state.d.ts +46 -0
  137. package/dist/ports/state.js +13 -0
  138. package/dist/ports/state.js.map +1 -0
  139. package/dist/state/clock.d.ts +40 -0
  140. package/dist/state/clock.js +43 -0
  141. package/dist/state/clock.js.map +1 -0
  142. package/dist/state/file-store.d.ts +340 -0
  143. package/dist/state/file-store.js +849 -0
  144. package/dist/state/file-store.js.map +1 -0
  145. package/dist/state/paths.d.ts +41 -0
  146. package/dist/state/paths.js +73 -0
  147. package/dist/state/paths.js.map +1 -0
  148. package/docs/USER_GUIDE.en.md +721 -0
  149. package/docs/claude-code.md +281 -0
  150. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  151. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  152. package/docs/dsh-plugin.md +578 -0
  153. package/docs/reflex-ui-regression-2026-10-20.md +34 -0
  154. package/docs/release-checklist-v0.1.0.md +315 -0
  155. package/docs/release-handbook-porting-notes.md +106 -0
  156. package/docs/release-handbook.md +393 -0
  157. package/docs/release-notes-v0.1.0.md +63 -0
  158. package/docs/release-notes-v0.3.0.md +152 -0
  159. package/docs/research/claude-code-harness.md +607 -0
  160. package/docs/research/pi-harness.md +621 -0
  161. package/experiments/data/calibration_sample.json +14 -0
  162. package/experiments/index.ts +29 -0
  163. package/experiments/runner.ts +156 -0
  164. package/package.json +82 -4
@@ -0,0 +1,80 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ export class AgyAdapter {
4
+ /**
5
+ * Generates Antigravity (AGY) plugin bundle inside .agents/plugins/harness-reflex/
6
+ */
7
+ static configureAgy(workspaceDir, binaryPath) {
8
+ const pluginDir = path.join(workspaceDir, '.agents', 'plugins', 'harness-reflex');
9
+ const rulesDir = path.join(pluginDir, 'rules');
10
+ fs.mkdirSync(rulesDir, { recursive: true });
11
+ // 1. plugin.json
12
+ const pluginManifest = {
13
+ name: 'harness-reflex',
14
+ description: 'System 1 decision runtime & Jev compatibility layer for Antigravity',
15
+ version: '0.1.0'
16
+ };
17
+ fs.writeFileSync(path.join(pluginDir, 'plugin.json'), JSON.stringify(pluginManifest, null, 2), 'utf8');
18
+ // 2. mcp_config.json
19
+ const mcpConfig = {
20
+ mcpServers: {
21
+ 'harness-reflex': {
22
+ command: 'node',
23
+ args: [binaryPath, 'mcp'],
24
+ env: {
25
+ SYSTEM_ONE_BACKEND: process.env.SYSTEM_ONE_BACKEND || process.env.REFLEX_BACKEND || 'mock',
26
+ SYSTEM_ONE_API_KEY: process.env.SYSTEM_ONE_API_KEY || process.env.JEV_API_KEY || '',
27
+ SYSTEM_ONE_BASE_URL: process.env.SYSTEM_ONE_BASE_URL || process.env.JEV_BASE_URL || ''
28
+ }
29
+ }
30
+ }
31
+ };
32
+ fs.writeFileSync(path.join(pluginDir, 'mcp_config.json'), JSON.stringify(mcpConfig, null, 2), 'utf8');
33
+ // 3. hooks.json
34
+ const hooksConfig = {
35
+ 'reflex-guard': {
36
+ enabled: true,
37
+ PostToolUse: [
38
+ {
39
+ matcher: 'run_command',
40
+ hooks: [
41
+ {
42
+ type: 'command',
43
+ command: `node "${binaryPath}" hook posttooluse`
44
+ }
45
+ ]
46
+ }
47
+ ],
48
+ Stop: [
49
+ {
50
+ type: 'command',
51
+ command: `node "${binaryPath}" hook stop`
52
+ }
53
+ ]
54
+ }
55
+ };
56
+ fs.writeFileSync(path.join(pluginDir, 'hooks.json'), JSON.stringify(hooksConfig, null, 2), 'utf8');
57
+ // 4. rules/AGENTS.md
58
+ const ruleContent = `# Harness Reflex Guidelines
59
+
60
+ You are equipped with the **Harness Reflex** System 1 Decision Runtime.
61
+
62
+ ### Core Guidelines:
63
+ 1. **Evidence Verification Gate (\`reflex_gate\`)**:
64
+ - Before presenting final completion to the user or closing an objective, verify each acceptance criterion against actual output/diffs using \`reflex_gate\`.
65
+ - Never assume success based on absence of errors. If \`reflex_gate\` returns \`escalate\` or \`contradicted\`, continue fixing.
66
+
67
+ 2. **Tool Output Pruning (\`reflex_prune\`)**:
68
+ - For bulky stdout from test suites, greps, or builds, use \`reflex_prune\` to extract relevant diagnostic lines and save context window.
69
+
70
+ 3. **Stagnation Recovery (\`reflex_detect_stagnation\`)**:
71
+ - If an edit or command fails multiple times, invoke \`reflex_detect_stagnation\` to break loops and obtain corrective suggestions.
72
+
73
+ 4. **Audit Ledger (\`reflex_status_ledger\`)**:
74
+ - Access the decision ledger to observe token savings, decision latencies, and pass rates.
75
+ `;
76
+ fs.writeFileSync(path.join(rulesDir, 'AGENTS.md'), ruleContent, 'utf8');
77
+ return { pluginDir };
78
+ }
79
+ }
80
+ //# sourceMappingURL=agy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agy.js","sourceRoot":"","sources":["../../src/adapters/agy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,MAAM,OAAO,UAAU;IACrB;;OAEG;IACH,MAAM,CAAC,YAAY,CAAC,YAAoB,EAAE,UAAkB;QAC1D,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,gBAAgB,CAAC,CAAC;QAClF,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAE/C,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAE5C,iBAAiB;QACjB,MAAM,cAAc,GAAG;YACrB,IAAI,EAAE,gBAAgB;YACtB,WAAW,EAAE,qEAAqE;YAClF,OAAO,EAAE,OAAO;SACjB,CAAC;QACF,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,aAAa,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QAEvG,qBAAqB;QACrB,MAAM,SAAS,GAAG;YAChB,UAAU,EAAE;gBACV,gBAAgB,EAAE;oBAChB,OAAO,EAAE,MAAM;oBACf,IAAI,EAAE,CAAC,UAAU,EAAE,KAAK,CAAC;oBACzB,GAAG,EAAE;wBACH,kBAAkB,EAAE,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,MAAM;wBAC1F,kBAAkB,EAAE,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,EAAE;wBACnF,mBAAmB,EAAE,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,EAAE;qBACvF;iBACF;aACF;SACF,CAAC;QACF,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,iBAAiB,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QAEtG,gBAAgB;QAChB,MAAM,WAAW,GAAG;YAClB,cAAc,EAAE;gBACd,OAAO,EAAE,IAAI;gBACb,WAAW,EAAE;oBACX;wBACE,OAAO,EAAE,aAAa;wBACtB,KAAK,EAAE;4BACL;gCACE,IAAI,EAAE,SAAS;gCACf,OAAO,EAAE,SAAS,UAAU,oBAAoB;6BACjD;yBACF;qBACF;iBACF;gBACD,IAAI,EAAE;oBACJ;wBACE,IAAI,EAAE,SAAS;wBACf,OAAO,EAAE,SAAS,UAAU,aAAa;qBAC1C;iBACF;aACF;SACF,CAAC;QACF,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QAEnG,qBAAqB;QACrB,MAAM,WAAW,GAAG;;;;;;;;;;;;;;;;;CAiBvB,CAAC;QACE,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,WAAW,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC;QAExE,OAAO,EAAE,SAAS,EAAE,CAAC;IACvB,CAAC;CACF","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nexport class AgyAdapter {\n /**\n * Generates Antigravity (AGY) plugin bundle inside .agents/plugins/harness-reflex/\n */\n static configureAgy(workspaceDir: string, binaryPath: string): { pluginDir: string } {\n const pluginDir = path.join(workspaceDir, '.agents', 'plugins', 'harness-reflex');\n const rulesDir = path.join(pluginDir, 'rules');\n\n fs.mkdirSync(rulesDir, { recursive: true });\n\n // 1. plugin.json\n const pluginManifest = {\n name: 'harness-reflex',\n description: 'System 1 decision runtime & Jev compatibility layer for Antigravity',\n version: '0.1.0'\n };\n fs.writeFileSync(path.join(pluginDir, 'plugin.json'), JSON.stringify(pluginManifest, null, 2), 'utf8');\n\n // 2. mcp_config.json\n const mcpConfig = {\n mcpServers: {\n 'harness-reflex': {\n command: 'node',\n args: [binaryPath, 'mcp'],\n env: {\n SYSTEM_ONE_BACKEND: process.env.SYSTEM_ONE_BACKEND || process.env.REFLEX_BACKEND || 'mock',\n SYSTEM_ONE_API_KEY: process.env.SYSTEM_ONE_API_KEY || process.env.JEV_API_KEY || '',\n SYSTEM_ONE_BASE_URL: process.env.SYSTEM_ONE_BASE_URL || process.env.JEV_BASE_URL || ''\n }\n }\n }\n };\n fs.writeFileSync(path.join(pluginDir, 'mcp_config.json'), JSON.stringify(mcpConfig, null, 2), 'utf8');\n\n // 3. hooks.json\n const hooksConfig = {\n 'reflex-guard': {\n enabled: true,\n PostToolUse: [\n {\n matcher: 'run_command',\n hooks: [\n {\n type: 'command',\n command: `node \"${binaryPath}\" hook posttooluse`\n }\n ]\n }\n ],\n Stop: [\n {\n type: 'command',\n command: `node \"${binaryPath}\" hook stop`\n }\n ]\n }\n };\n fs.writeFileSync(path.join(pluginDir, 'hooks.json'), JSON.stringify(hooksConfig, null, 2), 'utf8');\n\n // 4. rules/AGENTS.md\n const ruleContent = `# Harness Reflex Guidelines\n\nYou are equipped with the **Harness Reflex** System 1 Decision Runtime.\n\n### Core Guidelines:\n1. **Evidence Verification Gate (\\`reflex_gate\\`)**:\n - Before presenting final completion to the user or closing an objective, verify each acceptance criterion against actual output/diffs using \\`reflex_gate\\`.\n - Never assume success based on absence of errors. If \\`reflex_gate\\` returns \\`escalate\\` or \\`contradicted\\`, continue fixing.\n\n2. **Tool Output Pruning (\\`reflex_prune\\`)**:\n - For bulky stdout from test suites, greps, or builds, use \\`reflex_prune\\` to extract relevant diagnostic lines and save context window.\n\n3. **Stagnation Recovery (\\`reflex_detect_stagnation\\`)**:\n - If an edit or command fails multiple times, invoke \\`reflex_detect_stagnation\\` to break loops and obtain corrective suggestions.\n\n4. **Audit Ledger (\\`reflex_status_ledger\\`)**:\n - Access the decision ledger to observe token savings, decision latencies, and pass rates.\n`;\n fs.writeFileSync(path.join(rulesDir, 'AGENTS.md'), ruleContent, 'utf8');\n\n return { pluginDir };\n }\n}\n"]}
@@ -0,0 +1,13 @@
1
+ export declare class ClaudeAdapter {
2
+ /**
3
+ * Generates or updates Claude Code MCP config (.mcp.json or claude_desktop_config.json)
4
+ */
5
+ static configureMcp(workspaceDir: string, binaryPath: string): {
6
+ configPath: string;
7
+ created: boolean;
8
+ };
9
+ /**
10
+ * Generates guidelines for Claude Code's CLAUDE.md
11
+ */
12
+ static getClaudePromptGuidelines(): string;
13
+ }
@@ -0,0 +1,46 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ export class ClaudeAdapter {
4
+ /**
5
+ * Generates or updates Claude Code MCP config (.mcp.json or claude_desktop_config.json)
6
+ */
7
+ static configureMcp(workspaceDir, binaryPath) {
8
+ const mcpJsonPath = path.join(workspaceDir, '.mcp.json');
9
+ let config = { mcpServers: {} };
10
+ if (fs.existsSync(mcpJsonPath)) {
11
+ try {
12
+ config = JSON.parse(fs.readFileSync(mcpJsonPath, 'utf8'));
13
+ if (!config.mcpServers)
14
+ config.mcpServers = {};
15
+ }
16
+ catch {
17
+ config = { mcpServers: {} };
18
+ }
19
+ }
20
+ config.mcpServers['harness-reflex'] = {
21
+ command: 'node',
22
+ args: [binaryPath, 'mcp'],
23
+ env: {
24
+ SYSTEM_ONE_BACKEND: process.env.SYSTEM_ONE_BACKEND || process.env.REFLEX_BACKEND || 'mock',
25
+ SYSTEM_ONE_API_KEY: process.env.SYSTEM_ONE_API_KEY || process.env.JEV_API_KEY || '',
26
+ SYSTEM_ONE_BASE_URL: process.env.SYSTEM_ONE_BASE_URL || process.env.JEV_BASE_URL || ''
27
+ }
28
+ };
29
+ fs.writeFileSync(mcpJsonPath, JSON.stringify(config, null, 2), 'utf8');
30
+ return { configPath: mcpJsonPath, created: true };
31
+ }
32
+ /**
33
+ * Generates guidelines for Claude Code's CLAUDE.md
34
+ */
35
+ static getClaudePromptGuidelines() {
36
+ return `
37
+ ## Harness Reflex (System 1 Decision & Verification)
38
+ You have access to the \`harness-reflex\` MCP tools:
39
+ - **reflex_gate**: BEFORE declaring any task complete or claiming success, ALWAYS run \`reflex_gate\` to verify your claims against test output or diffs. If the gate fails or escalates, do NOT stop.
40
+ - **reflex_prune**: When dealing with build logs or test outputs exceeding 50 lines, prune them using \`reflex_prune\` to avoid context bloat.
41
+ - **reflex_detect_stagnation**: If you find yourself retrying the same command or editing the same lines more than twice, invoke \`reflex_detect_stagnation\` to get an objective diagnosis.
42
+ - **reflex_status_ledger**: Check your token savings and decision metrics at any time.
43
+ `;
44
+ }
45
+ }
46
+ //# sourceMappingURL=claude.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude.js","sourceRoot":"","sources":["../../src/adapters/claude.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,MAAM,OAAO,aAAa;IACxB;;OAEG;IACH,MAAM,CAAC,YAAY,CAAC,YAAoB,EAAE,UAAkB;QAC1D,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,WAAW,CAAC,CAAC;QACzD,IAAI,MAAM,GAAQ,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;QAErC,IAAI,EAAE,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;YAC/B,IAAI,CAAC;gBACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC;gBAC1D,IAAI,CAAC,MAAM,CAAC,UAAU;oBAAE,MAAM,CAAC,UAAU,GAAG,EAAE,CAAC;YACjD,CAAC;YAAC,MAAM,CAAC;gBACP,MAAM,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;YAC9B,CAAC;QACH,CAAC;QAED,MAAM,CAAC,UAAU,CAAC,gBAAgB,CAAC,GAAG;YACpC,OAAO,EAAE,MAAM;YACf,IAAI,EAAE,CAAC,UAAU,EAAE,KAAK,CAAC;YACzB,GAAG,EAAE;gBACH,kBAAkB,EAAE,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,MAAM;gBAC1F,kBAAkB,EAAE,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,EAAE;gBACnF,mBAAmB,EAAE,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,EAAE;aACvF;SACF,CAAC;QAEF,EAAE,CAAC,aAAa,CAAC,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACvE,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IACpD,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,yBAAyB;QAC9B,OAAO;;;;;;;CAOV,CAAC;IACA,CAAC;CACF","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nexport class ClaudeAdapter {\n /**\n * Generates or updates Claude Code MCP config (.mcp.json or claude_desktop_config.json)\n */\n static configureMcp(workspaceDir: string, binaryPath: string): { configPath: string; created: boolean } {\n const mcpJsonPath = path.join(workspaceDir, '.mcp.json');\n let config: any = { mcpServers: {} };\n\n if (fs.existsSync(mcpJsonPath)) {\n try {\n config = JSON.parse(fs.readFileSync(mcpJsonPath, 'utf8'));\n if (!config.mcpServers) config.mcpServers = {};\n } catch {\n config = { mcpServers: {} };\n }\n }\n\n config.mcpServers['harness-reflex'] = {\n command: 'node',\n args: [binaryPath, 'mcp'],\n env: {\n SYSTEM_ONE_BACKEND: process.env.SYSTEM_ONE_BACKEND || process.env.REFLEX_BACKEND || 'mock',\n SYSTEM_ONE_API_KEY: process.env.SYSTEM_ONE_API_KEY || process.env.JEV_API_KEY || '',\n SYSTEM_ONE_BASE_URL: process.env.SYSTEM_ONE_BASE_URL || process.env.JEV_BASE_URL || ''\n }\n };\n\n fs.writeFileSync(mcpJsonPath, JSON.stringify(config, null, 2), 'utf8');\n return { configPath: mcpJsonPath, created: true };\n }\n\n /**\n * Generates guidelines for Claude Code's CLAUDE.md\n */\n static getClaudePromptGuidelines(): string {\n return `\n## Harness Reflex (System 1 Decision & Verification)\nYou have access to the \\`harness-reflex\\` MCP tools:\n- **reflex_gate**: BEFORE declaring any task complete or claiming success, ALWAYS run \\`reflex_gate\\` to verify your claims against test output or diffs. If the gate fails or escalates, do NOT stop.\n- **reflex_prune**: When dealing with build logs or test outputs exceeding 50 lines, prune them using \\`reflex_prune\\` to avoid context bloat.\n- **reflex_detect_stagnation**: If you find yourself retrying the same command or editing the same lines more than twice, invoke \\`reflex_detect_stagnation\\` to get an objective diagnosis.\n- **reflex_status_ledger**: Check your token savings and decision metrics at any time.\n`;\n }\n}\n"]}
@@ -0,0 +1,139 @@
1
+ import { type CodexOnlyHookEvent, type HookEvent } from '../hook/contract.js';
2
+ /** One Codex hook event, as the binary spells it in all three notations. */
3
+ export interface CodexHookEventSpec {
4
+ /** The `hook_event_name` value Codex puts in the payload and reads back. */
5
+ readonly pascal: string;
6
+ /** The kebab-case subcommand this runtime accepts for the event. */
7
+ readonly kebab: string;
8
+ /** The `harness-reflex hook <subcommand>` token for the event. */
9
+ readonly subcommand: string;
10
+ /**
11
+ * The canonical event this maps to, or `null` when the runtime has no
12
+ * capability for it and must answer `{}`.
13
+ */
14
+ readonly canonical: HookEvent | null;
15
+ /**
16
+ * The Codex-only event, when {@link canonical} is `null` and the event is
17
+ * still recognized. `null` on both means a genuinely unsupported event.
18
+ */
19
+ readonly codexOnly: CodexOnlyHookEvent | null;
20
+ /** Handler timeout in seconds, kept inside both budgets. */
21
+ readonly timeoutSec: number;
22
+ }
23
+ /** The SessionEnd timeout Codex clamps to, discovered from its own warning. */
24
+ export declare const CODEX_SESSION_END_TIMEOUT_SEC = 3;
25
+ /**
26
+ * The twelve Codex hook events and what this runtime does with each.
27
+ *
28
+ * Order follows the binary so a diff against `command_runner.rs` is readable.
29
+ */
30
+ export declare const CODEX_HOOK_EVENTS: readonly CodexHookEventSpec[];
31
+ /**
32
+ * Resolve a Codex event from any spelling: PascalCase, kebab-case, snake_case,
33
+ * the hook subcommand, or the canonical name.
34
+ * @param raw - the event name to resolve.
35
+ * @returns the matching spec, or `undefined` for an unsupported name.
36
+ */
37
+ export declare function parseCodexHookEvent(raw: string | undefined): CodexHookEventSpec | undefined;
38
+ /** The spec for one canonical event, for tests and for the reverse mapping. */
39
+ export declare function codexSpecForCanonical(event: HookEvent): CodexHookEventSpec | undefined;
40
+ /** Every Codex-only event the runtime recognizes but cannot decide. */
41
+ export declare function codexOnlyEvents(): readonly CodexOnlyHookEvent[];
42
+ /**
43
+ * Render the whole command Codex should run for one event.
44
+ *
45
+ * Codex does not forward handler `args`, so the event is part of the command
46
+ * string. Two shapes are supported and distinguished by the entry itself:
47
+ *
48
+ * - a **script path** (`/x/dist/cli/index.js`, `./cli.js`) runs under this Node
49
+ * binary, because Codex spawns the command without knowing it is JS;
50
+ * - a **command name** (`harness-reflex`, the installed bin) runs as-is.
51
+ *
52
+ * Anything that looks like a path is quoted, so a directory with spaces works.
53
+ * @param entry - an absolute script path or an installed command name.
54
+ * @param spec - the event to wire.
55
+ * @returns the command string for `hooks.json`.
56
+ */
57
+ export declare function renderCodexHookCommand(entry: string, spec: CodexHookEventSpec): string;
58
+ /** One matcher group of a Codex `hooks.json` event. */
59
+ export interface CodexHookMatcherGroup {
60
+ matcher?: string;
61
+ hooks: {
62
+ type: 'command';
63
+ command: string;
64
+ timeout: number;
65
+ }[];
66
+ }
67
+ /** The `hooks.json` document Codex loads from `$CODEX_HOME/hooks.json`. */
68
+ export interface CodexHooksConfig {
69
+ hooks: Record<string, CodexHookMatcherGroup[]>;
70
+ }
71
+ /**
72
+ * Build the `hooks.json` document for this runtime.
73
+ *
74
+ * `PreToolUse` and `PostToolUse` get a `matcher` that covers both the built-in
75
+ * shell tools and any MCP tool, because the probe showed `matcher: ".*"` is
76
+ * honored and a matcher that only names MCP tools would miss every shell call.
77
+ * @param entryScript - absolute path to `dist/cli/index.js`.
78
+ * @param options - `events` narrows the wired set; `matcher` overrides the tool
79
+ * matcher for the tool-scoped events.
80
+ * @returns the document, ready to serialize.
81
+ */
82
+ export declare function buildCodexHooksConfig(entryScript: string, options?: {
83
+ events?: readonly CodexHookEventSpec[];
84
+ matcher?: string;
85
+ }): CodexHooksConfig;
86
+ /**
87
+ * Build the `config.toml` fragment that registers the MCP server.
88
+ *
89
+ * Codex reads MCP servers from `config.toml` (`[mcp_servers.<name>]`), which
90
+ * `codex mcp list --json` reports back and which the probe confirmed. The
91
+ * `.codex/config.json` file this repository wrote before that is kept for
92
+ * backwards compatibility but is not what Codex reads.
93
+ * @param entryScript - absolute path to `dist/cli/index.js`.
94
+ * @param options - `name` overrides the server name; `env` overrides the
95
+ * environment table (empty values are dropped, an empty object emits no table).
96
+ * @returns the TOML fragment, without the surrounding config.
97
+ */
98
+ export declare function renderCodexMcpToml(entryScript: string, options?: {
99
+ name?: string;
100
+ env?: Record<string, string>;
101
+ }): string;
102
+ /** What one Codex configuration run wrote. */
103
+ export interface CodexSetupResult {
104
+ /** `.codex/config.json` — the legacy MCP block, kept for compatibility. */
105
+ configPath: string;
106
+ /** `.codex/hooks.json` — the hook wiring Codex actually loads. */
107
+ hooksPath: string;
108
+ /** `.codex/config.toml` — the MCP block Codex actually reads. */
109
+ tomlPath: string;
110
+ created: boolean;
111
+ }
112
+ export declare class CodexAdapter {
113
+ /**
114
+ * Generates or updates Codex CLI configuration: MCP (both files) and hooks.
115
+ *
116
+ * Codex reads MCP servers from `config.toml`, not `config.json` — the latter
117
+ * is what this repository wrote before and is kept so existing setups keep
118
+ * working. Hooks come from `$CODEX_HOME/hooks.json`, so the same directory is
119
+ * written here; a user who points `CODEX_HOME` at `<workspace>/.codex` gets a
120
+ * complete setup.
121
+ * @param workspaceDir - the directory that holds `.codex/`.
122
+ * @param binaryPath - absolute path to `dist/cli/index.js`.
123
+ */
124
+ static configureCodex(workspaceDir: string, binaryPath: string): CodexSetupResult;
125
+ /**
126
+ * Write only the hook wiring, leaving any MCP configuration alone.
127
+ * @param workspaceDir - the directory that holds `.codex/`.
128
+ * @param binaryPath - absolute path to `dist/cli/index.js`.
129
+ */
130
+ static configureCodexHooks(workspaceDir: string, binaryPath: string): {
131
+ hooksPath: string;
132
+ };
133
+ /**
134
+ * The `hooks.json` document for every Codex event.
135
+ * @param binaryPath - absolute path to `dist/cli/index.js`.
136
+ */
137
+ static buildHooksConfig(binaryPath: string): CodexHooksConfig;
138
+ static getCodexInstructions(): string;
139
+ }
@@ -0,0 +1,368 @@
1
+ /**
2
+ * The Codex adapter: event table, `hooks.json`, `config.toml`, and the setup entry
3
+ * point.
4
+ *
5
+ * Everything here is grounded in codex-cli 0.163.0 rather than in its
6
+ * documentation, because the documentation does not cover hooks yet. The event
7
+ * table was read out of the binary (`hooks/src/engine/command_runner.rs`) and
8
+ * then confirmed by running a real `codex exec` against a probe hook:
9
+ *
10
+ * - **Twelve events**, not ten. `Stop` and `Interrupt` are in the binary's
11
+ * normalized list and `Stop` fires on every completed turn.
12
+ * - **`args` is not passed to the hook process.** A handler declared as
13
+ * `{command: "/path/hook.sh", args: ["session-start"]}` runs with `argv = []`.
14
+ * The event therefore has to ride in the command string itself.
15
+ * - **Codex clamps the SessionEnd timeout to 3 s** and warns when `hooks.json`
16
+ * asks for more, so the table stays under 3.
17
+ * - **The event name is in the payload** (`hook_event_name`, PascalCase), which
18
+ * is what the probe records and what the normalizer trusts over `argv`.
19
+ *
20
+ * The payload normalizer itself lives in `hook/payload` because it describes the
21
+ * stdin shape of every host; an adapter that imported another adapter would
22
+ * break the dependency fence this repository tests.
23
+ *
24
+ * @module adapters/codex
25
+ */
26
+ import * as fs from 'fs';
27
+ import * as path from 'path';
28
+ import { CODEX_ONLY_HOOK_EVENTS, EVENT_BUDGETS } from '../hook/contract.js';
29
+ /** The SessionEnd timeout Codex clamps to, discovered from its own warning. */
30
+ export const CODEX_SESSION_END_TIMEOUT_SEC = 3;
31
+ /**
32
+ * Convert a host timeout in milliseconds to the whole seconds `hooks.json` takes.
33
+ *
34
+ * Rounded **up**: the host timeout must never be shorter than the internal
35
+ * decision budget, or a decision that would have finished is killed by the host
36
+ * and the event silently fails open.
37
+ */
38
+ function toHostSeconds(ms) {
39
+ return Math.max(1, Math.ceil(ms / 1000));
40
+ }
41
+ /**
42
+ * The twelve Codex hook events and what this runtime does with each.
43
+ *
44
+ * Order follows the binary so a diff against `command_runner.rs` is readable.
45
+ */
46
+ export const CODEX_HOOK_EVENTS = [
47
+ {
48
+ pascal: 'PreToolUse',
49
+ kebab: 'pre-tool-use',
50
+ subcommand: 'pretooluse',
51
+ canonical: 'pretooluse',
52
+ codexOnly: null,
53
+ timeoutSec: toHostSeconds(EVENT_BUDGETS.pretooluse.hookTimeoutMs)
54
+ },
55
+ {
56
+ pascal: 'PermissionRequest',
57
+ kebab: 'permission-request',
58
+ subcommand: 'permissionrequest',
59
+ canonical: null,
60
+ codexOnly: 'permissionrequest',
61
+ timeoutSec: 1
62
+ },
63
+ {
64
+ pascal: 'PostToolUse',
65
+ kebab: 'post-tool-use',
66
+ subcommand: 'posttooluse',
67
+ canonical: 'posttooluse',
68
+ codexOnly: null,
69
+ timeoutSec: toHostSeconds(EVENT_BUDGETS.posttooluse.hookTimeoutMs)
70
+ },
71
+ {
72
+ pascal: 'PreCompact',
73
+ kebab: 'pre-compact',
74
+ subcommand: 'precompact',
75
+ canonical: null,
76
+ codexOnly: 'precompact',
77
+ timeoutSec: 1
78
+ },
79
+ {
80
+ pascal: 'PostCompact',
81
+ kebab: 'post-compact',
82
+ subcommand: 'postcompact',
83
+ canonical: null,
84
+ codexOnly: 'postcompact',
85
+ timeoutSec: 1
86
+ },
87
+ {
88
+ pascal: 'SessionStart',
89
+ kebab: 'session-start',
90
+ subcommand: 'sessionstart',
91
+ canonical: 'sessionstart',
92
+ codexOnly: null,
93
+ timeoutSec: toHostSeconds(EVENT_BUDGETS.sessionstart.hookTimeoutMs)
94
+ },
95
+ {
96
+ pascal: 'SessionEnd',
97
+ kebab: 'session-end',
98
+ subcommand: 'sessionend',
99
+ canonical: 'sessionend',
100
+ codexOnly: null,
101
+ // Codex clamps this one to 3 s and warns, so ask for 3 and stay quiet.
102
+ timeoutSec: Math.min(CODEX_SESSION_END_TIMEOUT_SEC, toHostSeconds(EVENT_BUDGETS.sessionend.hookTimeoutMs))
103
+ },
104
+ {
105
+ pascal: 'UserPromptSubmit',
106
+ kebab: 'user-prompt-submit',
107
+ subcommand: 'userpromptsubmit',
108
+ canonical: null,
109
+ codexOnly: 'userpromptsubmit',
110
+ timeoutSec: 1
111
+ },
112
+ {
113
+ pascal: 'SubagentStart',
114
+ kebab: 'subagent-start',
115
+ subcommand: 'subagentstart',
116
+ canonical: null,
117
+ codexOnly: 'subagentstart',
118
+ timeoutSec: 1
119
+ },
120
+ {
121
+ pascal: 'SubagentStop',
122
+ kebab: 'subagent-stop',
123
+ subcommand: 'substop',
124
+ canonical: 'substop',
125
+ codexOnly: null,
126
+ timeoutSec: toHostSeconds(EVENT_BUDGETS.substop.hookTimeoutMs)
127
+ },
128
+ {
129
+ pascal: 'Stop',
130
+ kebab: 'stop',
131
+ subcommand: 'stop',
132
+ canonical: 'stop',
133
+ codexOnly: null,
134
+ timeoutSec: toHostSeconds(EVENT_BUDGETS.stop.hookTimeoutMs)
135
+ },
136
+ {
137
+ pascal: 'Interrupt',
138
+ kebab: 'interrupt',
139
+ subcommand: 'interrupt',
140
+ canonical: null,
141
+ codexOnly: 'interrupt',
142
+ timeoutSec: 1
143
+ }
144
+ ];
145
+ /** Normalize any spelling of a Codex event to its spec. */
146
+ function normalizeName(raw) {
147
+ return raw.trim().toLowerCase().replace(/[-_\s]/g, '');
148
+ }
149
+ /**
150
+ * Resolve a Codex event from any spelling: PascalCase, kebab-case, snake_case,
151
+ * the hook subcommand, or the canonical name.
152
+ * @param raw - the event name to resolve.
153
+ * @returns the matching spec, or `undefined` for an unsupported name.
154
+ */
155
+ export function parseCodexHookEvent(raw) {
156
+ if (!raw)
157
+ return undefined;
158
+ const wanted = normalizeName(raw);
159
+ for (const spec of CODEX_HOOK_EVENTS) {
160
+ if (normalizeName(spec.pascal) === wanted ||
161
+ normalizeName(spec.kebab) === wanted ||
162
+ normalizeName(spec.subcommand) === wanted) {
163
+ return spec;
164
+ }
165
+ }
166
+ return undefined;
167
+ }
168
+ /** The spec for one canonical event, for tests and for the reverse mapping. */
169
+ export function codexSpecForCanonical(event) {
170
+ return CODEX_HOOK_EVENTS.find((spec) => spec.canonical === event);
171
+ }
172
+ /** Every Codex-only event the runtime recognizes but cannot decide. */
173
+ export function codexOnlyEvents() {
174
+ return CODEX_ONLY_HOOK_EVENTS;
175
+ }
176
+ /**
177
+ * Render the whole command Codex should run for one event.
178
+ *
179
+ * Codex does not forward handler `args`, so the event is part of the command
180
+ * string. Two shapes are supported and distinguished by the entry itself:
181
+ *
182
+ * - a **script path** (`/x/dist/cli/index.js`, `./cli.js`) runs under this Node
183
+ * binary, because Codex spawns the command without knowing it is JS;
184
+ * - a **command name** (`harness-reflex`, the installed bin) runs as-is.
185
+ *
186
+ * Anything that looks like a path is quoted, so a directory with spaces works.
187
+ * @param entry - an absolute script path or an installed command name.
188
+ * @param spec - the event to wire.
189
+ * @returns the command string for `hooks.json`.
190
+ */
191
+ export function renderCodexHookCommand(entry, spec) {
192
+ const looksLikeScript = entry.includes('/') || entry.includes('\\') || /\.(?:js|mjs|cjs)$/.test(entry);
193
+ const program = looksLikeScript ? `node ${quote(entry)}` : entry;
194
+ return `${program} hook ${spec.subcommand}`;
195
+ }
196
+ /** Quote one shell word when it contains anything a shell would split on. */
197
+ function quote(word) {
198
+ return /^[A-Za-z0-9_./:@%+-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, '\\$1')}"`;
199
+ }
200
+ /**
201
+ * Build the `hooks.json` document for this runtime.
202
+ *
203
+ * `PreToolUse` and `PostToolUse` get a `matcher` that covers both the built-in
204
+ * shell tools and any MCP tool, because the probe showed `matcher: ".*"` is
205
+ * honored and a matcher that only names MCP tools would miss every shell call.
206
+ * @param entryScript - absolute path to `dist/cli/index.js`.
207
+ * @param options - `events` narrows the wired set; `matcher` overrides the tool
208
+ * matcher for the tool-scoped events.
209
+ * @returns the document, ready to serialize.
210
+ */
211
+ export function buildCodexHooksConfig(entryScript, options = {}) {
212
+ const events = options.events ?? CODEX_HOOK_EVENTS;
213
+ // `.*` is what was verified against a real exec run; it covers exec_command,
214
+ // apply_patch, and mcp__* alike.
215
+ const matcher = options.matcher ?? '.*';
216
+ const hooks = {};
217
+ for (const spec of events) {
218
+ const handler = {
219
+ type: 'command',
220
+ command: renderCodexHookCommand(entryScript, spec),
221
+ timeout: spec.timeoutSec
222
+ };
223
+ hooks[spec.pascal] =
224
+ spec.pascal === 'PreToolUse' || spec.pascal === 'PostToolUse'
225
+ ? [{ matcher, hooks: [handler] }]
226
+ : [{ hooks: [handler] }];
227
+ }
228
+ return { hooks };
229
+ }
230
+ /**
231
+ * Build the `config.toml` fragment that registers the MCP server.
232
+ *
233
+ * Codex reads MCP servers from `config.toml` (`[mcp_servers.<name>]`), which
234
+ * `codex mcp list --json` reports back and which the probe confirmed. The
235
+ * `.codex/config.json` file this repository wrote before that is kept for
236
+ * backwards compatibility but is not what Codex reads.
237
+ * @param entryScript - absolute path to `dist/cli/index.js`.
238
+ * @param options - `name` overrides the server name; `env` overrides the
239
+ * environment table (empty values are dropped, an empty object emits no table).
240
+ * @returns the TOML fragment, without the surrounding config.
241
+ */
242
+ export function renderCodexMcpToml(entryScript, options = {}) {
243
+ const name = options.name ?? 'harness-reflex';
244
+ const env = options.env ?? {
245
+ SYSTEM_ONE_BACKEND: process.env.SYSTEM_ONE_BACKEND || process.env.REFLEX_BACKEND || 'mock',
246
+ SYSTEM_ONE_API_KEY: process.env.SYSTEM_ONE_API_KEY || process.env.JEV_API_KEY || '',
247
+ SYSTEM_ONE_BASE_URL: process.env.SYSTEM_ONE_BASE_URL || process.env.JEV_BASE_URL || ''
248
+ };
249
+ const lines = [
250
+ `[mcp_servers.${name}]`,
251
+ 'command = "node"',
252
+ `args = [${JSON.stringify(entryScript)}, "mcp"]`,
253
+ 'startup_timeout_sec = 20'
254
+ ];
255
+ // Emit the env table only when there is at least one non-empty value.
256
+ const entries = Object.entries(env).filter(([, value]) => value !== '');
257
+ if (entries.length > 0) {
258
+ lines.push('');
259
+ lines.push(`[mcp_servers.${name}.env]`);
260
+ for (const [key, value] of entries)
261
+ lines.push(`${key} = ${JSON.stringify(value)}`);
262
+ }
263
+ return `${lines.join('\n')}\n`;
264
+ }
265
+ export class CodexAdapter {
266
+ /**
267
+ * Generates or updates Codex CLI configuration: MCP (both files) and hooks.
268
+ *
269
+ * Codex reads MCP servers from `config.toml`, not `config.json` — the latter
270
+ * is what this repository wrote before and is kept so existing setups keep
271
+ * working. Hooks come from `$CODEX_HOME/hooks.json`, so the same directory is
272
+ * written here; a user who points `CODEX_HOME` at `<workspace>/.codex` gets a
273
+ * complete setup.
274
+ * @param workspaceDir - the directory that holds `.codex/`.
275
+ * @param binaryPath - absolute path to `dist/cli/index.js`.
276
+ */
277
+ static configureCodex(workspaceDir, binaryPath) {
278
+ const codexConfigDir = path.join(workspaceDir, '.codex');
279
+ if (!fs.existsSync(codexConfigDir)) {
280
+ fs.mkdirSync(codexConfigDir, { recursive: true });
281
+ }
282
+ const configPath = path.join(codexConfigDir, 'config.json');
283
+ let config = { mcpServers: {} };
284
+ if (fs.existsSync(configPath)) {
285
+ try {
286
+ config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
287
+ if (!config.mcpServers)
288
+ config.mcpServers = {};
289
+ }
290
+ catch {
291
+ config = { mcpServers: {} };
292
+ }
293
+ }
294
+ config.mcpServers['harness-reflex'] = {
295
+ command: 'node',
296
+ args: [binaryPath, 'mcp'],
297
+ env: {
298
+ SYSTEM_ONE_BACKEND: process.env.SYSTEM_ONE_BACKEND || process.env.REFLEX_BACKEND || 'mock',
299
+ SYSTEM_ONE_API_KEY: process.env.SYSTEM_ONE_API_KEY || process.env.JEV_API_KEY || '',
300
+ SYSTEM_ONE_BASE_URL: process.env.SYSTEM_ONE_BASE_URL || process.env.JEV_BASE_URL || ''
301
+ }
302
+ };
303
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
304
+ // `config.toml` is the file Codex actually reads for MCP servers. Merge the
305
+ // managed block in without touching whatever else the user keeps there.
306
+ const tomlPath = path.join(codexConfigDir, 'config.toml');
307
+ const block = renderCodexMcpToml(binaryPath);
308
+ writeManagedTomlBlock(tomlPath, block);
309
+ const hooks = CodexAdapter.buildHooksConfig(binaryPath);
310
+ const hooksPath = path.join(codexConfigDir, 'hooks.json');
311
+ fs.writeFileSync(hooksPath, `${JSON.stringify(hooks, null, 2)}\n`, 'utf8');
312
+ return { configPath, hooksPath, tomlPath, created: true };
313
+ }
314
+ /**
315
+ * Write only the hook wiring, leaving any MCP configuration alone.
316
+ * @param workspaceDir - the directory that holds `.codex/`.
317
+ * @param binaryPath - absolute path to `dist/cli/index.js`.
318
+ */
319
+ static configureCodexHooks(workspaceDir, binaryPath) {
320
+ const codexConfigDir = path.join(workspaceDir, '.codex');
321
+ fs.mkdirSync(codexConfigDir, { recursive: true });
322
+ const hooksPath = path.join(codexConfigDir, 'hooks.json');
323
+ fs.writeFileSync(hooksPath, `${JSON.stringify(CodexAdapter.buildHooksConfig(binaryPath), null, 2)}\n`, 'utf8');
324
+ return { hooksPath };
325
+ }
326
+ /**
327
+ * The `hooks.json` document for every Codex event.
328
+ * @param binaryPath - absolute path to `dist/cli/index.js`.
329
+ */
330
+ static buildHooksConfig(binaryPath) {
331
+ return buildCodexHooksConfig(binaryPath, { events: CODEX_HOOK_EVENTS });
332
+ }
333
+ static getCodexInstructions() {
334
+ return `
335
+ # Codex Harness Reflex Rules
336
+ 1. **Pre-flight & Post-flight Gate**: Do not submit PR or mark goal done without passing \`reflex_gate\`.
337
+ 2. **Context Pruning**: Use \`reflex_prune\` on command stdout exceeding 1000 characters.
338
+ 3. **Loop Breaker**: When hitting repeated bash exit code > 0, check \`reflex_detect_stagnation\`.
339
+ `;
340
+ }
341
+ }
342
+ /** The marker that delimits the block this adapter owns inside `config.toml`. */
343
+ const TOML_BLOCK_START = '# >>> harness-reflex (managed) >>>';
344
+ const TOML_BLOCK_END = '# <<< harness-reflex (managed) <<<';
345
+ /**
346
+ * Replace the managed block in a TOML file, leaving every other byte alone.
347
+ * @param tomlPath - the file to update; created when missing.
348
+ * @param block - the block body, without markers.
349
+ */
350
+ function writeManagedTomlBlock(tomlPath, block) {
351
+ const managed = `${TOML_BLOCK_START}\n${block.trimEnd()}\n${TOML_BLOCK_END}`;
352
+ let existing = '';
353
+ if (fs.existsSync(tomlPath)) {
354
+ existing = fs.readFileSync(tomlPath, 'utf8');
355
+ }
356
+ const start = existing.indexOf(TOML_BLOCK_START);
357
+ const end = existing.indexOf(TOML_BLOCK_END);
358
+ let next;
359
+ if (start >= 0 && end > start) {
360
+ next = `${existing.slice(0, start)}${managed}${existing.slice(end + TOML_BLOCK_END.length)}`;
361
+ }
362
+ else {
363
+ const separator = existing.length === 0 || existing.endsWith('\n\n') ? '' : existing.endsWith('\n') ? '\n' : '\n\n';
364
+ next = `${existing}${separator}${managed}\n`;
365
+ }
366
+ fs.writeFileSync(tomlPath, next, 'utf8');
367
+ }
368
+ //# sourceMappingURL=codex.js.map