@ornexus/neocortex 4.61.5 → 4.61.6

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 (254) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -220
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -260
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -364
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +148 -7822
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -174
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  76. package/packages/client/dist/commands/story-worktree.js +5 -258
  77. package/packages/client/dist/config/host-auth-broker.js +1 -60
  78. package/packages/client/dist/config/host-auth-reference.js +1 -93
  79. package/packages/client/dist/config/profile-directory.js +1 -13
  80. package/packages/client/dist/config/resolver-selection.js +1 -278
  81. package/packages/client/dist/config/secure-config.js +12 -281
  82. package/packages/client/dist/config.js +2 -224
  83. package/packages/client/dist/constants.js +1 -25
  84. package/packages/client/dist/context/context-collector.js +2 -222
  85. package/packages/client/dist/context/context-sanitizer.js +1 -145
  86. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  87. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  88. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  89. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  90. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  91. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  92. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  93. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  94. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  95. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  96. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  97. package/packages/client/dist/continuity/outbox.js +1 -117
  98. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  99. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  100. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  101. package/packages/client/dist/errors/error-messages.js +2 -258
  102. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  103. package/packages/client/dist/evidence/collector.js +1 -347
  104. package/packages/client/dist/evidence/index.js +1 -1
  105. package/packages/client/dist/evidence/types.js +0 -2
  106. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  107. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  108. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  109. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  110. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +70 -0
  111. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1592
  112. package/packages/client/dist/git/epic-operational-state.js +2 -672
  113. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  114. package/packages/client/dist/git/git-lifecycle-store.d.ts +22 -0
  115. package/packages/client/dist/git/git-lifecycle-store.js +8 -2529
  116. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  117. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  118. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  119. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  120. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  121. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  122. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  123. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  124. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  125. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  126. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  127. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  128. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  129. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  130. package/packages/client/dist/i18n/first-run.js +2 -60
  131. package/packages/client/dist/index.js +1 -50
  132. package/packages/client/dist/invocation/invoke-input.js +1 -24
  133. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  134. package/packages/client/dist/license/index.js +1 -5
  135. package/packages/client/dist/license/license-client.js +1 -337
  136. package/packages/client/dist/machine/fingerprint.js +2 -163
  137. package/packages/client/dist/machine/index.js +1 -5
  138. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  139. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  140. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  141. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  142. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  143. package/packages/client/dist/migrations/project-identity.js +7 -493
  144. package/packages/client/dist/migrations/state-json.js +4 -393
  145. package/packages/client/dist/policy/architecture-policy.js +2 -184
  146. package/packages/client/dist/policy/index.js +1 -7
  147. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  148. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  149. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  150. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  151. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  152. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  153. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  154. package/packages/client/dist/private-execution/delivery.js +13 -410
  155. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  156. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  157. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  158. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  159. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  160. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  161. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  162. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  163. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  164. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  165. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  166. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  167. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  168. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  169. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  170. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  171. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  172. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  173. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  174. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  175. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  176. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  177. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  178. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  179. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  180. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  181. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  182. package/packages/client/dist/private-execution/session-lease.js +1 -63
  183. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  184. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  185. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  186. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  187. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  188. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  189. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  190. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  191. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  192. package/packages/client/dist/resilience/index.js +1 -8
  193. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  194. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  195. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  196. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  197. package/packages/client/dist/runner/binary.js +1 -404
  198. package/packages/client/dist/runner/cli.js +17 -1571
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.js +1 -85
  202. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  203. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  204. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  205. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  206. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  207. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  208. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  209. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  210. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  211. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  212. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  213. package/packages/client/dist/runner/headless/resolver.js +1 -231
  214. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  215. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  216. package/packages/client/dist/runner/headless/types.js +2 -575
  217. package/packages/client/dist/runner/host-capacity.js +1 -59
  218. package/packages/client/dist/runner/local-console.js +13 -396
  219. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  220. package/packages/client/dist/runner/project-identity.js +1 -106
  221. package/packages/client/dist/runner/scheduler.js +7 -995
  222. package/packages/client/dist/runner-cli.js +2 -18
  223. package/packages/client/dist/state/invocation-shape.js +1 -13
  224. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  225. package/packages/client/dist/state/state-json-repair.js +3 -785
  226. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  227. package/packages/client/dist/telemetry/index.js +1 -5
  228. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  229. package/packages/client/dist/tier/index.js +1 -5
  230. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  231. package/packages/client/dist/types/index.js +1 -38
  232. package/packages/client/dist/version.js +1 -27
  233. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  234. package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
  235. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  236. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  237. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  238. package/packages/client/dist/yoloop/index.js +1 -8
  239. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  240. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  241. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  242. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  243. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  244. package/targets-stubs/antigravity/gemini.md +1 -1
  245. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  246. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  247. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  248. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  249. package/targets-stubs/claude-code/neocortex.md +2 -2
  250. package/targets-stubs/codex/AGENTS.md +1 -1
  251. package/targets-stubs/cursor/agent.md +2 -2
  252. package/targets-stubs/gemini-cli/agent.md +2 -2
  253. package/targets-stubs/opencode/neocortex-root.md +1 -1
  254. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,274 +1 @@
1
- /**
2
- * P224.05 -- fail-closed cleanup of explicitly managed temporary resources.
3
- *
4
- * This module owns policy and replay ordering only. Concrete host, process and
5
- * interface effects stay behind an injected adapter. Production callers that
6
- * do not have a supported adapter preserve resources as pending.
7
- */
8
- import { createHash } from 'node:crypto';
9
- const EFFECT_KIND = {
10
- remove_managed_worktree: 'worktree',
11
- stop_owned_process: 'process',
12
- remove_interface_entry: 'interface_entry',
13
- };
14
- /** Reconcile durable evidence before any new effect, then apply at most once. */
15
- export async function executeManagedEnvironmentCleanup(requests, adapter, now) {
16
- const receipts = [];
17
- const reasonCodes = [];
18
- const seen = new Set();
19
- let pending = false;
20
- let failed = false;
21
- for (const request of requests) {
22
- const key = `${request.resourceId}\0${request.effect}`;
23
- if (seen.has(key)) {
24
- const current = failedReceipt(request, managedEnvironmentCleanupIdempotencyKey(request), 'managed-environment-request-duplicate', now());
25
- receipts.push(current);
26
- reasonCodes.push(...current.reasonCodes);
27
- pending = true;
28
- failed = true;
29
- continue;
30
- }
31
- seen.add(key);
32
- const requestReason = validateRequest(request);
33
- if (requestReason) {
34
- const current = failedReceipt(request, managedEnvironmentCleanupIdempotencyKey(request), requestReason, now());
35
- receipts.push(current);
36
- reasonCodes.push(requestReason);
37
- pending = true;
38
- failed = true;
39
- continue;
40
- }
41
- const idempotencyKey = managedEnvironmentCleanupIdempotencyKey(request);
42
- if (!adapter) {
43
- const current = createReceipt(request, idempotencyKey, 'preserved', ['managed-environment-capability-unsupported'], now());
44
- receipts.push(current);
45
- reasonCodes.push(...current.reasonCodes);
46
- pending = true;
47
- continue;
48
- }
49
- if (request.existingReceipt) {
50
- if (!receiptMatchesRequest(request.existingReceipt, request)
51
- || request.existingReceipt.idempotencyKey !== idempotencyKey) {
52
- const current = failedReceipt(request, idempotencyKey, 'managed-environment-receipt-binding-mismatch', now());
53
- receipts.push(current);
54
- reasonCodes.push(...current.reasonCodes);
55
- pending = true;
56
- failed = true;
57
- continue;
58
- }
59
- const reconciled = await adapter.reconcile({ request, receipt: request.existingReceipt });
60
- if (!reconciled.ok || !receiptMatchesRequest(reconciled.receipt, request)
61
- || reconciled.receipt.idempotencyKey !== idempotencyKey) {
62
- const reason = reconciled.ok
63
- ? 'managed-environment-receipt-binding-mismatch'
64
- : reconciled.reasonCode;
65
- const current = failedReceipt(request, idempotencyKey, reason, now());
66
- receipts.push(current);
67
- reasonCodes.push(reason);
68
- pending = true;
69
- failed = true;
70
- continue;
71
- }
72
- const disposition = receiptDisposition(reconciled.receipt);
73
- if (disposition.failed || !disposition.pending) {
74
- receipts.push(reconciled.receipt);
75
- reasonCodes.push(...reconciled.receipt.reasonCodes);
76
- pending ||= disposition.pending;
77
- failed ||= disposition.failed;
78
- continue;
79
- }
80
- // A pending preservation receipt (for example, capability unavailable)
81
- // is observation history, not permanent authority to skip a newly safe
82
- // effect. Reconciliation happened first; fresh inspection may now retry.
83
- }
84
- const inspected = await adapter.inspect(request);
85
- if (!inspected.ok) {
86
- const current = failedReceipt(request, idempotencyKey, inspected.reasonCode, now());
87
- receipts.push(current);
88
- reasonCodes.push(inspected.reasonCode);
89
- pending = true;
90
- failed = true;
91
- continue;
92
- }
93
- const classification = classifyManagedEnvironmentSnapshot(request, inspected.snapshot);
94
- reasonCodes.push(...classification.reasonCodes);
95
- if (classification.action === 'preserve') {
96
- receipts.push(createReceipt(request, idempotencyKey, 'preserved', classification.reasonCodes, now()));
97
- pending ||= classification.pending;
98
- continue;
99
- }
100
- if (classification.action === 'already_absent') {
101
- receipts.push(createReceipt(request, idempotencyKey, 'already_absent', classification.reasonCodes, now()));
102
- continue;
103
- }
104
- const applied = await adapter.apply({ request, snapshot: inspected.snapshot, effect: request.effect, idempotencyKey });
105
- if (!applied.ok || !receiptMatchesRequest(applied.receipt, request)
106
- || applied.receipt.idempotencyKey !== idempotencyKey) {
107
- const reason = applied.ok
108
- ? 'managed-environment-receipt-binding-mismatch'
109
- : applied.reasonCode;
110
- const current = failedReceipt(request, idempotencyKey, reason, now());
111
- receipts.push(current);
112
- reasonCodes.push(reason);
113
- pending = true;
114
- failed = true;
115
- continue;
116
- }
117
- const reconciled = await adapter.reconcile({ request, receipt: applied.receipt });
118
- if (!reconciled.ok || !receiptMatchesRequest(reconciled.receipt, request)
119
- || reconciled.receipt.idempotencyKey !== idempotencyKey) {
120
- const reason = reconciled.ok
121
- ? 'managed-environment-receipt-binding-mismatch'
122
- : reconciled.reasonCode;
123
- const current = failedReceipt(request, idempotencyKey, reason, now());
124
- receipts.push(current);
125
- reasonCodes.push(reason);
126
- pending = true;
127
- failed = true;
128
- continue;
129
- }
130
- receipts.push(reconciled.receipt);
131
- reasonCodes.push(...reconciled.receipt.reasonCodes);
132
- const disposition = receiptDisposition(reconciled.receipt);
133
- pending ||= disposition.pending;
134
- failed ||= disposition.failed;
135
- }
136
- return {
137
- ok: !failed && !pending,
138
- pending,
139
- receipts,
140
- reasonCodes: unique(reasonCodes),
141
- publicSafe: true,
142
- };
143
- }
144
- export function classifyManagedEnvironmentSnapshot(request, snapshot) {
145
- if (!snapshotShapeValid(snapshot)) {
146
- return preserve(true, 'managed-environment-snapshot-invalid');
147
- }
148
- if (snapshot.resourceId !== request.resourceId || snapshot.epicId !== request.epicId) {
149
- return preserve(false, 'managed-environment-identity-mismatch');
150
- }
151
- if (snapshot.kind !== request.expectedKind || EFFECT_KIND[request.effect] !== snapshot.kind) {
152
- return preserve(false, 'managed-environment-kind-mismatch');
153
- }
154
- if (!snapshot.managed)
155
- return preserve(false, 'managed-environment-ownership-unproven');
156
- if (snapshot.ownerDigest !== request.expectedOwnerDigest)
157
- return preserve(false, 'managed-environment-owner-replaced');
158
- if (snapshot.revision !== request.expectedRevision)
159
- return preserve(false, 'managed-environment-revision-stale');
160
- if (snapshot.presence === 'absent') {
161
- return { action: 'already_absent', pending: false, reasonCodes: ['managed-environment-already-absent'] };
162
- }
163
- if (snapshot.presence !== 'present')
164
- return preserve(true, 'managed-environment-presence-unknown');
165
- if (snapshot.capability !== 'supported')
166
- return preserve(true, 'managed-environment-capability-unsupported');
167
- if (snapshot.primary)
168
- return preserve(true, 'managed-environment-primary-preserved');
169
- if (snapshot.protected)
170
- return preserve(true, 'managed-environment-protected');
171
- if (snapshot.active)
172
- return preserve(true, 'managed-environment-active');
173
- if (snapshot.locked)
174
- return preserve(true, 'managed-environment-locked');
175
- if (snapshot.submoduleActive)
176
- return preserve(true, 'managed-environment-submodule-active');
177
- if (snapshot.clean === 'unknown')
178
- return preserve(true, 'managed-environment-cleanliness-unknown');
179
- if (!snapshot.clean)
180
- return preserve(true, 'managed-environment-dirty');
181
- if (snapshot.preservableIgnored)
182
- return preserve(true, 'managed-environment-preservable-ignored');
183
- if (!snapshot.integrated)
184
- return preserve(true, 'managed-environment-integration-unproven');
185
- return { action: 'apply', pending: false, reasonCodes: [] };
186
- }
187
- export function managedEnvironmentCleanupIdempotencyKey(request) {
188
- return `environment-cleanup:v1:${createHash('sha256').update([
189
- request.resourceId,
190
- request.effect,
191
- request.expectedOwnerDigest,
192
- request.expectedRevision,
193
- ].join('\0')).digest('hex')}`;
194
- }
195
- function validateRequest(request) {
196
- if (request.schemaVersion !== 1 || request.publicSafe !== true
197
- || !safeToken(request.resourceId) || !safeToken(request.epicId)
198
- || !isHash(request.expectedOwnerDigest) || !isHash(request.expectedRevision)
199
- || EFFECT_KIND[request.effect] !== request.expectedKind) {
200
- return 'managed-environment-request-invalid';
201
- }
202
- return null;
203
- }
204
- function snapshotShapeValid(snapshot) {
205
- return snapshot.schemaVersion === 1 && snapshot.publicSafe === true
206
- && safeToken(snapshot.resourceId) && safeToken(snapshot.epicId)
207
- && isHash(snapshot.ownerDigest) && isHash(snapshot.revision)
208
- && ['worktree', 'process', 'interface_entry'].includes(snapshot.kind)
209
- && ['present', 'absent', 'unknown'].includes(snapshot.presence)
210
- && ['supported', 'unsupported'].includes(snapshot.capability)
211
- && (typeof snapshot.clean === 'boolean' || snapshot.clean === 'unknown')
212
- && [snapshot.managed, snapshot.active, snapshot.integrated, snapshot.protected,
213
- snapshot.primary, snapshot.locked, snapshot.submoduleActive, snapshot.preservableIgnored]
214
- .every((value) => typeof value === 'boolean');
215
- }
216
- function receiptMatchesRequest(receipt, request) {
217
- return receipt.schemaVersion === 1 && receipt.publicSafe === true
218
- && receipt.resourceId === request.resourceId
219
- && receipt.effect === request.effect
220
- && receipt.expectedOwnerDigest === request.expectedOwnerDigest
221
- && receipt.expectedRevision === request.expectedRevision
222
- && ['applied', 'already_absent', 'preserved', 'failed'].includes(receipt.outcome)
223
- && safeToken(receipt.idempotencyKey)
224
- && receipt.reasonCodes.length <= 128 && receipt.reasonCodes.every(safeToken)
225
- && isIso(receipt.checkedAt) && isIso(receipt.recordedAt);
226
- }
227
- function receiptDisposition(receipt) {
228
- if (receipt.outcome === 'failed')
229
- return { pending: true, failed: true };
230
- if (receipt.outcome !== 'preserved')
231
- return { pending: false, failed: false };
232
- const terminalNonOwned = receipt.reasonCodes.every((reason) => [
233
- 'managed-environment-ownership-unproven',
234
- 'managed-environment-owner-replaced',
235
- 'managed-environment-revision-stale',
236
- 'managed-environment-kind-mismatch',
237
- 'managed-environment-identity-mismatch',
238
- ].includes(reason));
239
- return { pending: !terminalNonOwned, failed: false };
240
- }
241
- function preserve(pending, reasonCode) {
242
- return { action: 'preserve', pending, reasonCodes: [reasonCode] };
243
- }
244
- function createReceipt(request, idempotencyKey, outcome, reasonCodes, timestamp) {
245
- return {
246
- schemaVersion: 1,
247
- resourceId: request.resourceId,
248
- effect: request.effect,
249
- outcome,
250
- expectedOwnerDigest: request.expectedOwnerDigest,
251
- expectedRevision: request.expectedRevision,
252
- idempotencyKey,
253
- reasonCodes: unique(reasonCodes),
254
- checkedAt: timestamp,
255
- recordedAt: timestamp,
256
- publicSafe: true,
257
- };
258
- }
259
- function failedReceipt(request, idempotencyKey, reasonCode, timestamp) {
260
- return createReceipt(request, idempotencyKey, 'failed', [reasonCode], timestamp);
261
- }
262
- function safeToken(value) {
263
- return typeof value === 'string' && value.length > 0 && value.length <= 240
264
- && /^[A-Za-z0-9._:/@#-]+$/.test(value);
265
- }
266
- function isHash(value) {
267
- return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
268
- }
269
- function isIso(value) {
270
- return typeof value === 'string' && Number.isFinite(Date.parse(value));
271
- }
272
- function unique(values) {
273
- return [...new Set(values)];
274
- }
1
+ import{createHash as E}from"node:crypto";const D={remove_managed_worktree:"worktree",stop_owned_process:"process",remove_interface_entry:"interface_entry"};async function M(e,n,c){const t=[],a=[],h=new Set;let d=!1,s=!1;for(const r of e){const R=`${r.resourceId}\0${r.effect}`;if(h.has(R)){const i=m(r,I(r),"managed-environment-request-duplicate",c());t.push(i),a.push(...i.reasonCodes),d=!0,s=!0;continue}h.add(R);const w=$(r);if(w){const i=m(r,I(r),w,c());t.push(i),a.push(w),d=!0,s=!0;continue}const u=I(r);if(!n){const i=x(r,u,"preserved",["managed-environment-capability-unsupported"],c());t.push(i),a.push(...i.reasonCodes),d=!0;continue}if(r.existingReceipt){if(!k(r.existingReceipt,r)||r.existingReceipt.idempotencyKey!==u){const b=m(r,u,"managed-environment-receipt-binding-mismatch",c());t.push(b),a.push(...b.reasonCodes),d=!0,s=!0;continue}const i=await n.reconcile({request:r,receipt:r.existingReceipt});if(!i.ok||!k(i.receipt,r)||i.receipt.idempotencyKey!==u){const b=i.ok?"managed-environment-receipt-binding-mismatch":i.reasonCode,A=m(r,u,b,c());t.push(A),a.push(b),d=!0,s=!0;continue}const f=K(i.receipt);if(f.failed||!f.pending){t.push(i.receipt),a.push(...i.receipt.reasonCodes),d||=f.pending,s||=f.failed;continue}}const y=await n.inspect(r);if(!y.ok){const i=m(r,u,y.reasonCode,c());t.push(i),a.push(y.reasonCode),d=!0,s=!0;continue}const l=V(r,y.snapshot);if(a.push(...l.reasonCodes),l.action==="preserve"){t.push(x(r,u,"preserved",l.reasonCodes,c())),d||=l.pending;continue}if(l.action==="already_absent"){t.push(x(r,u,"already_absent",l.reasonCodes,c()));continue}const g=await n.apply({request:r,snapshot:y.snapshot,effect:r.effect,idempotencyKey:u});if(!g.ok||!k(g.receipt,r)||g.receipt.idempotencyKey!==u){const i=g.ok?"managed-environment-receipt-binding-mismatch":g.reasonCode,f=m(r,u,i,c());t.push(f),a.push(i),d=!0,s=!0;continue}const p=await n.reconcile({request:r,receipt:g.receipt});if(!p.ok||!k(p.receipt,r)||p.receipt.idempotencyKey!==u){const i=p.ok?"managed-environment-receipt-binding-mismatch":p.reasonCode,f=m(r,u,i,c());t.push(f),a.push(i),d=!0,s=!0;continue}t.push(p.receipt),a.push(...p.receipt.reasonCodes);const _=K(p.receipt);d||=_.pending,s||=_.failed}return{ok:!s&&!d,pending:d,receipts:t,reasonCodes:S(a),publicSafe:!0}}function V(e,n){return N(n)?n.resourceId!==e.resourceId||n.epicId!==e.epicId?o(!1,"managed-environment-identity-mismatch"):n.kind!==e.expectedKind||D[e.effect]!==n.kind?o(!1,"managed-environment-kind-mismatch"):n.managed?n.ownerDigest!==e.expectedOwnerDigest?o(!1,"managed-environment-owner-replaced"):n.revision!==e.expectedRevision?o(!1,"managed-environment-revision-stale"):n.presence==="absent"?{action:"already_absent",pending:!1,reasonCodes:["managed-environment-already-absent"]}:n.presence!=="present"?o(!0,"managed-environment-presence-unknown"):n.capability!=="supported"?o(!0,"managed-environment-capability-unsupported"):n.primary?o(!0,"managed-environment-primary-preserved"):n.protected?o(!0,"managed-environment-protected"):n.active?o(!0,"managed-environment-active"):n.locked?o(!0,"managed-environment-locked"):n.submoduleActive?o(!0,"managed-environment-submodule-active"):n.clean==="unknown"?o(!0,"managed-environment-cleanliness-unknown"):n.clean?n.preservableIgnored?o(!0,"managed-environment-preservable-ignored"):n.integrated?{action:"apply",pending:!1,reasonCodes:[]}:o(!0,"managed-environment-integration-unproven"):o(!0,"managed-environment-dirty"):o(!1,"managed-environment-ownership-unproven"):o(!0,"managed-environment-snapshot-invalid")}function I(e){return`environment-cleanup:v1:${E("sha256").update([e.resourceId,e.effect,e.expectedOwnerDigest,e.expectedRevision].join("\0")).digest("hex")}`}function $(e){return e.schemaVersion!==1||e.publicSafe!==!0||!v(e.resourceId)||!v(e.epicId)||!C(e.expectedOwnerDigest)||!C(e.expectedRevision)||D[e.effect]!==e.expectedKind?"managed-environment-request-invalid":null}function N(e){return e.schemaVersion===1&&e.publicSafe===!0&&v(e.resourceId)&&v(e.epicId)&&C(e.ownerDigest)&&C(e.revision)&&["worktree","process","interface_entry"].includes(e.kind)&&["present","absent","unknown"].includes(e.presence)&&["supported","unsupported"].includes(e.capability)&&(typeof e.clean=="boolean"||e.clean==="unknown")&&[e.managed,e.active,e.integrated,e.protected,e.primary,e.locked,e.submoduleActive,e.preservableIgnored].every(n=>typeof n=="boolean")}function k(e,n){return e.schemaVersion===1&&e.publicSafe===!0&&e.resourceId===n.resourceId&&e.effect===n.effect&&e.expectedOwnerDigest===n.expectedOwnerDigest&&e.expectedRevision===n.expectedRevision&&["applied","already_absent","preserved","failed"].includes(e.outcome)&&v(e.idempotencyKey)&&e.reasonCodes.length<=128&&e.reasonCodes.every(v)&&O(e.checkedAt)&&O(e.recordedAt)}function K(e){return e.outcome==="failed"?{pending:!0,failed:!0}:e.outcome!=="preserved"?{pending:!1,failed:!1}:{pending:!e.reasonCodes.every(c=>["managed-environment-ownership-unproven","managed-environment-owner-replaced","managed-environment-revision-stale","managed-environment-kind-mismatch","managed-environment-identity-mismatch"].includes(c)),failed:!1}}function o(e,n){return{action:"preserve",pending:e,reasonCodes:[n]}}function x(e,n,c,t,a){return{schemaVersion:1,resourceId:e.resourceId,effect:e.effect,outcome:c,expectedOwnerDigest:e.expectedOwnerDigest,expectedRevision:e.expectedRevision,idempotencyKey:n,reasonCodes:S(t),checkedAt:a,recordedAt:a,publicSafe:!0}}function m(e,n,c,t){return x(e,n,"failed",[c],t)}function v(e){return typeof e=="string"&&e.length>0&&e.length<=240&&/^[A-Za-z0-9._:/@#-]+$/.test(e)}function C(e){return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)}function O(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function S(e){return[...new Set(e)]}export{V as classifyManagedEnvironmentSnapshot,M as executeManagedEnvironmentCleanup,I as managedEnvironmentCleanupIdempotencyKey};
@@ -1,149 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P201.12 -- fixed-path managed profile and effective policy preflight.
6
- */
7
- import { lstatSync, readFileSync } from 'node:fs';
8
- import { homedir } from 'node:os';
9
- import { join } from 'node:path';
10
- import { getSubagentApprovalPolicy } from '../../config.js';
11
- import { HEADLESS_REASON_CODES, boundPublicSummary, hashPublicValue, redaction, } from './types.js';
12
- export const GOVERNED_HEADLESS_EVIDENCE = '[P201-EV-HEADLESS]';
13
- const MAX_PROFILE_BYTES = 96 * 1024;
14
- const PARALLEL_DELEGATION_MARKER = '## Parallel Delegation Contract';
15
- export function preflightManagedHeadlessProfile(adapterId, options) {
16
- const candidates = managedProfileCandidates(adapterId, options);
17
- for (const candidate of candidates) {
18
- let stat;
19
- try {
20
- stat = lstatSync(candidate);
21
- }
22
- catch (error) {
23
- if (error.code === 'ENOENT')
24
- continue;
25
- return invalidProfile();
26
- }
27
- if (stat.isSymbolicLink() || !stat.isFile() || stat.size <= 0 || stat.size > MAX_PROFILE_BYTES) {
28
- return invalidProfile();
29
- }
30
- try {
31
- const content = readFileSync(candidate, 'utf8');
32
- if (!isGovernedProfile(adapterId, content))
33
- return invalidProfile();
34
- return validateEffectiveApprovalPolicy(adapterId, options);
35
- }
36
- catch {
37
- return invalidProfile();
38
- }
39
- }
40
- return failure(HEADLESS_REASON_CODES.MANAGED_PROFILE_MISSING, 'Managed neocortex profile was not found in a trusted host location.');
41
- }
42
- export function governedPreflightFailureResult(adapterId, input, preflight) {
43
- return {
44
- status: 'failed',
45
- adapterId,
46
- runtimeId: input.runtimeId,
47
- ...(input.modelId ? { modelId: input.modelId } : {}),
48
- ...(input.runtimeSource ? { runtimeSource: input.runtimeSource } : {}),
49
- reasonCode: preflight.reasonCode,
50
- reasonCodes: [preflight.reasonCode, HEADLESS_REASON_CODES.RECEIPT_REDACTED],
51
- durationMs: 0,
52
- counts: { governedPreflightDenials: 1 },
53
- hashes: { governanceEvidence: hashPublicValue(GOVERNED_HEADLESS_EVIDENCE) },
54
- publicSummary: preflight.publicSummary,
55
- redactionSummary: [redaction('managedProfile', 'managed_profile', 'value-denied')],
56
- relativePaths: [input.targetRef],
57
- ...(input.receipt ? { receipt: input.receipt } : {}),
58
- publicSafe: true,
59
- };
60
- }
61
- export function withGovernedHeadlessEvidence(result) {
62
- return {
63
- ...result,
64
- counts: { ...result.counts, governedPreflightPasses: 1 },
65
- hashes: { ...result.hashes, governanceEvidence: hashPublicValue(GOVERNED_HEADLESS_EVIDENCE) },
66
- publicSummary: boundPublicSummary(`${result.publicSummary} ${GOVERNED_HEADLESS_EVIDENCE}`),
67
- };
68
- }
69
- function managedProfileCandidates(adapterId, options) {
70
- const candidates = [];
71
- const home = trustedHome(options.env);
72
- if (adapterId === 'claude-code') {
73
- // Claude Code only discovers top-level `agents/*.md`; the nested
74
- // `agents/neocortex/neocortex.md` location is a legacy fallback.
75
- const roots = [options.cwd, home].filter((root) => Boolean(root));
76
- for (const root of roots)
77
- candidates.push(join(root, '.claude', 'agents', 'neocortex.md'));
78
- for (const root of roots)
79
- candidates.push(join(root, '.claude', 'agents', 'neocortex', 'neocortex.md'));
80
- return Array.from(new Set(candidates));
81
- }
82
- if (options.cwd) {
83
- candidates.push(join(options.cwd, '.opencode', 'agents', 'neocortex.md'));
84
- }
85
- if (!home)
86
- return candidates;
87
- {
88
- const configHome = options.env?.OPENCODE_HOME
89
- || join(options.env?.XDG_CONFIG_HOME || join(home, '.config'), 'opencode');
90
- candidates.push(join(configHome, 'agents', 'neocortex.md'));
91
- candidates.push(join(home, '.opencode', 'agents', 'neocortex.md'));
92
- }
93
- return Array.from(new Set(candidates));
94
- }
95
- function trustedHome(env) {
96
- const candidate = env ? env.HOME || env.USERPROFILE : homedir();
97
- return candidate && !/[\r\n\0]/.test(candidate) ? candidate : undefined;
98
- }
99
- function isGovernedProfile(adapterId, content) {
100
- if (Buffer.byteLength(content) > MAX_PROFILE_BYTES)
101
- return false;
102
- const front = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(content)?.[1];
103
- if (front === undefined)
104
- return false;
105
- // Parallel delegation is the default: a managed profile must not deny the
106
- // host delegation primitive, and must carry the parallel delegation contract.
107
- if (!content.includes('Never pass the original root invocation')
108
- || !content.includes(PARALLEL_DELEGATION_MARKER))
109
- return false;
110
- if (adapterId === 'claude-code') {
111
- return /^name:\s*neocortex\s*$/m.test(front)
112
- && /^permissionMode:\s*bypassPermissions\s*$/m.test(front)
113
- && !/^disallowedTools:.*\b(?:Agent|Task)\b/m.test(front)
114
- && /^\s*-\s*Agent\s*$/m.test(front);
115
- }
116
- return /^name:\s*neocortex\s*$/m.test(front)
117
- && /^mode:\s*subagent\s*$/m.test(front)
118
- && /^\s+"\*":\s*allow\s*$/m.test(front)
119
- && !/^\s+task:\s*deny\s*$/m.test(front)
120
- && content.includes('root OpenCode agent remains the yoloop owner');
121
- }
122
- function validateEffectiveApprovalPolicy(adapterId, options) {
123
- try {
124
- const home = trustedHome(options.env);
125
- const resolution = getSubagentApprovalPolicy({
126
- ...(home ? { configFilePath: join(home, '.neocortex', 'config.json') } : {}),
127
- platformTarget: adapterId,
128
- hostPolicy: options.approvalHostPolicy,
129
- }).resolution;
130
- if (resolution.requestedMode !== 'max' || resolution.effectiveMode !== 'max') {
131
- return failure(HEADLESS_REASON_CODES.APPROVAL_POLICY_MISMATCH, 'Managed max profile did not match the effective subagent approval policy.');
132
- }
133
- return { ok: true, publicSafe: true };
134
- }
135
- catch {
136
- return failure(HEADLESS_REASON_CODES.APPROVAL_POLICY_INVALID, 'Managed subagent approval policy could not be validated safely.');
137
- }
138
- }
139
- function failure(reasonCode, summary) {
140
- return {
141
- ok: false,
142
- reasonCode,
143
- publicSummary: boundPublicSummary(`${summary} ${GOVERNED_HEADLESS_EVIDENCE}`),
144
- publicSafe: true,
145
- };
146
- }
147
- function invalidProfile() {
148
- return failure(HEADLESS_REASON_CODES.MANAGED_PROFILE_INVALID, 'Managed neocortex profile failed bounded identity, approval, or isolation validation.');
149
- }
1
+ import{lstatSync as g,readFileSync as p}from"node:fs";import{homedir as P}from"node:os";import{join as s}from"node:path";import{getSubagentApprovalPolicy as S}from"../../config.js";import{HEADLESS_REASON_CODES as i,boundPublicSummary as l,hashPublicValue as f,redaction as h}from"./types.js";const c="[P201-EV-HEADLESS]",m=96*1024,v="## Parallel Delegation Contract";function M(r,e){const o=y(r,e);for(const t of o){let n;try{n=g(t)}catch(a){if(a.code==="ENOENT")continue;return u()}if(n.isSymbolicLink()||!n.isFile()||n.size<=0||n.size>m)return u();try{const a=p(t,"utf8");return A(r,a)?b(r,e):u()}catch{return u()}}return d(i.MANAGED_PROFILE_MISSING,"Managed neocortex profile was not found in a trusted host location.")}function D(r,e,o){return{status:"failed",adapterId:r,runtimeId:e.runtimeId,...e.modelId?{modelId:e.modelId}:{},...e.runtimeSource?{runtimeSource:e.runtimeSource}:{},reasonCode:o.reasonCode,reasonCodes:[o.reasonCode,i.RECEIPT_REDACTED],durationMs:0,counts:{governedPreflightDenials:1},hashes:{governanceEvidence:f(c)},publicSummary:o.publicSummary,redactionSummary:[h("managedProfile","managed_profile","value-denied")],relativePaths:[e.targetRef],...e.receipt?{receipt:e.receipt}:{},publicSafe:!0}}function C(r){return{...r,counts:{...r.counts,governedPreflightPasses:1},hashes:{...r.hashes,governanceEvidence:f(c)},publicSummary:l(`${r.publicSummary} ${c}`)}}function y(r,e){const o=[],t=E(e.env);if(r==="claude-code"){const n=[e.cwd,t].filter(a=>!!a);for(const a of n)o.push(s(a,".claude","agents","neocortex.md"));for(const a of n)o.push(s(a,".claude","agents","neocortex","neocortex.md"));return Array.from(new Set(o))}if(e.cwd&&o.push(s(e.cwd,".opencode","agents","neocortex.md")),!t)return o;{const n=e.env?.OPENCODE_HOME||s(e.env?.XDG_CONFIG_HOME||s(t,".config"),"opencode");o.push(s(n,"agents","neocortex.md")),o.push(s(t,".opencode","agents","neocortex.md"))}return Array.from(new Set(o))}function E(r){const e=r?r.HOME||r.USERPROFILE:P();return e&&!/[\r\n\0]/.test(e)?e:void 0}function A(r,e){if(Buffer.byteLength(e)>m)return!1;const o=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(e)?.[1];return o===void 0||!e.includes("Never pass the original root invocation")||!e.includes(v)?!1:r==="claude-code"?/^name:\s*neocortex\s*$/m.test(o)&&/^permissionMode:\s*bypassPermissions\s*$/m.test(o)&&!/^disallowedTools:.*\b(?:Agent|Task)\b/m.test(o)&&/^\s*-\s*Agent\s*$/m.test(o):/^name:\s*neocortex\s*$/m.test(o)&&/^mode:\s*subagent\s*$/m.test(o)&&/^\s+"\*":\s*allow\s*$/m.test(o)&&!/^\s+task:\s*deny\s*$/m.test(o)&&e.includes("root OpenCode agent remains the yoloop owner")}function b(r,e){try{const o=E(e.env),t=S({...o?{configFilePath:s(o,".neocortex","config.json")}:{},platformTarget:r,hostPolicy:e.approvalHostPolicy}).resolution;return t.requestedMode!=="max"||t.effectiveMode!=="max"?d(i.APPROVAL_POLICY_MISMATCH,"Managed max profile did not match the effective subagent approval policy."):{ok:!0,publicSafe:!0}}catch{return d(i.APPROVAL_POLICY_INVALID,"Managed subagent approval policy could not be validated safely.")}}function d(r,e){return{ok:!1,reasonCode:r,publicSummary:l(`${e} ${c}`),publicSafe:!0}}function u(){return d(i.MANAGED_PROFILE_INVALID,"Managed neocortex profile failed bounded identity, approval, or isolation validation.")}export{c as GOVERNED_HEADLESS_EVIDENCE,D as governedPreflightFailureResult,M as preflightManagedHeadlessProfile,C as withGovernedHeadlessEvidence};
@@ -1,145 +1,2 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P190.04 -- trusted OpenCode headless adapter interface.
6
- */
7
- import { checkTrustedHeadlessRuntimeBinary } from '../binary.js';
8
- import { HEADLESS_REASON_CODES, adapterAvailabilityFailure, adapterAvailabilitySuccess, createRejectedExecutionResult, createUnavailableExecutionResult, hashPublicValue, normalizeHeadlessCommandResult, redaction, runHeadlessCommand, validateHeadlessAdapterExecutionInput, } from './types.js';
9
- import { governedPreflightFailureResult, preflightManagedHeadlessProfile, withGovernedHeadlessEvidence, } from './managed-profile.js';
10
- const OPENCODE_ADAPTER_ID = 'opencode';
11
- const OPENCODE_COMMAND = 'opencode';
12
- const OPENCODE_AGENT_PROFILE = 'neocortex';
13
- const VERSION_EVIDENCE_MAX_CHARS = 2_000;
14
- const VERSION_EVIDENCE_MAX_BYTES = 2_000;
15
- const UNSAFE_VERSION_EVIDENCE_PATTERN = /(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|\bPRIVATE\b)/i;
16
- const CLAUDE_CODE_PRODUCT_PATTERN = /\b(?:Claude\s+Code|claude-code|@anthropic-ai\/claude-code)\b/i;
17
- const VERSION_SEMVER_PATTERN = /\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?\b/;
18
- export function createOpenCodeHeadlessAdapter() {
19
- return {
20
- id: OPENCODE_ADAPTER_ID,
21
- displayName: 'OpenCode Headless Adapter',
22
- async checkAvailability(options = {}) {
23
- return checkRuntimeAvailability(OPENCODE_ADAPTER_ID, OPENCODE_COMMAND, options, {
24
- realpathBasenamePolicy: 'opencode-npm-native',
25
- });
26
- },
27
- buildInvocation(input) {
28
- const validation = validateHeadlessAdapterExecutionInput(input, OPENCODE_ADAPTER_ID);
29
- if (!validation.ok)
30
- return validation;
31
- return {
32
- ok: true,
33
- invocation: {
34
- adapterId: OPENCODE_ADAPTER_ID,
35
- commandName: OPENCODE_COMMAND,
36
- args: buildOpenCodeArgs(validation.prompt, validation.input.modelId),
37
- promptHash: validation.promptHash,
38
- ...(validation.input.modelId ? { modelId: validation.input.modelId } : {}),
39
- timeoutMs: validation.input.timeoutMs ?? 10 * 60 * 1000,
40
- publicSafe: true,
41
- },
42
- publicSafe: true,
43
- };
44
- },
45
- async execute(input, options = {}) {
46
- const validation = validateHeadlessAdapterExecutionInput(input, OPENCODE_ADAPTER_ID);
47
- if (!validation.ok)
48
- return createRejectedExecutionResult(OPENCODE_ADAPTER_ID, OPENCODE_ADAPTER_ID, validation);
49
- const preflight = preflightManagedHeadlessProfile(OPENCODE_ADAPTER_ID, options);
50
- if (!preflight.ok)
51
- return governedPreflightFailureResult(OPENCODE_ADAPTER_ID, validation.input, preflight);
52
- if (options.signal?.aborted) {
53
- return withGovernedHeadlessEvidence(normalizeHeadlessCommandResult(OPENCODE_ADAPTER_ID, validation.input, {
54
- exitCode: null, signal: 'SIGTERM', timedOut: false, cancelled: true, durationMs: 0,
55
- stdout: '', stderr: '', stdoutBytes: 0, stderrBytes: 0,
56
- }));
57
- }
58
- const availability = await this.checkAvailability(options);
59
- if (!availability.ok)
60
- return withGovernedHeadlessEvidence(createUnavailableExecutionResult(OPENCODE_ADAPTER_ID, validation.input, availability));
61
- const invocation = this.buildInvocation(validation.input);
62
- if (!invocation.ok)
63
- return createRejectedExecutionResult(OPENCODE_ADAPTER_ID, OPENCODE_ADAPTER_ID, invocation);
64
- const runner = options.commandRunner ?? runHeadlessCommand;
65
- const result = await runner(availability.executablePath ?? OPENCODE_COMMAND, invocation.invocation.args, {
66
- cwd: options.cwd,
67
- env: options.env,
68
- timeoutMs: invocation.invocation.timeoutMs,
69
- maxOutputBytes: options.maxOutputBytes,
70
- signal: options.signal,
71
- ...(validation.input.receipt?.jobId ? { localConsole: { projectRoot: options.cwd, jobId: validation.input.receipt.jobId, attemptId: validation.input.receipt.attemptId, executionId: validation.input.receipt.executionId, publicSafe: true } } : {}),
72
- });
73
- return withGovernedHeadlessEvidence(normalizeHeadlessCommandResult(OPENCODE_ADAPTER_ID, validation.input, result));
74
- },
75
- };
76
- }
77
- export async function checkRuntimeAvailability(adapterId, commandName, options, policy = {}) {
78
- const trust = checkTrustedHeadlessRuntimeBinary({
79
- commandName,
80
- env: options.env,
81
- platform: options.platform,
82
- commandLocator: options.commandLocator,
83
- realpathBasenamePolicy: policy.realpathBasenamePolicy,
84
- });
85
- if (!trust.ok) {
86
- return adapterAvailabilityFailure(adapterId, commandName, trust.reasonCode === HEADLESS_REASON_CODES.ADAPTER_UNAVAILABLE
87
- ? HEADLESS_REASON_CODES.ADAPTER_UNAVAILABLE
88
- : HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED, trust.publicSummary, trust.redactionSummary);
89
- }
90
- const runner = options.versionRunner ?? options.commandRunner ?? runHeadlessCommand;
91
- const version = await runner(trust.executablePath, ['--version'], {
92
- env: options.env,
93
- timeoutMs: 5_000,
94
- maxOutputBytes: 2_000,
95
- });
96
- const evidence = validateRuntimeVersionEvidence(version, policy.versionEvidence ?? 'generic-public');
97
- if (!evidence.ok) {
98
- return adapterAvailabilityFailure(adapterId, commandName, HEADLESS_REASON_CODES.ADAPTER_UNAVAILABLE, evidence.publicSummary, evidence.redactionSummary);
99
- }
100
- return adapterAvailabilitySuccess(adapterId, commandName, trustedAvailabilitySummary(commandName, policy.versionEvidence), {
101
- executablePath: trust.executablePath,
102
- versionText: evidence.versionText,
103
- });
104
- }
105
- function validateRuntimeVersionEvidence(version, requirement) {
106
- const versionText = normalizeVersionEvidenceText(`${version.stdout}\n${version.stderr}`.trim());
107
- const redactionSummary = versionText
108
- ? [redaction('runtimeVersion', 'raw_log', hashPublicValue(versionText))]
109
- : [redaction('runtimeVersion', 'missing', 'value-denied')];
110
- if (version.timedOut
111
- || version.exitCode !== 0
112
- || versionText.length === 0
113
- || versionText.length > VERSION_EVIDENCE_MAX_CHARS
114
- || version.stdoutBytes + version.stderrBytes > VERSION_EVIDENCE_MAX_BYTES
115
- || UNSAFE_VERSION_EVIDENCE_PATTERN.test(versionText)) {
116
- return {
117
- ok: false,
118
- publicSummary: 'Headless runtime version check did not return a bounded public result.',
119
- redactionSummary,
120
- };
121
- }
122
- if (requirement === 'claude-code' && (!CLAUDE_CODE_PRODUCT_PATTERN.test(versionText) || !VERSION_SEMVER_PATTERN.test(versionText))) {
123
- return {
124
- ok: false,
125
- publicSummary: 'Headless runtime version check did not return bounded Claude Code product/version evidence.',
126
- redactionSummary,
127
- };
128
- }
129
- return { ok: true, versionText };
130
- }
131
- function normalizeVersionEvidenceText(value) {
132
- return value.replace(/\s+/g, ' ').trim();
133
- }
134
- function trustedAvailabilitySummary(commandName, requirement) {
135
- if (requirement === 'claude-code')
136
- return `Trusted ${commandName} runtime is available with bounded Claude Code version evidence.`;
137
- return `Trusted ${commandName} runtime is available.`;
138
- }
139
- function buildOpenCodeArgs(prompt, modelId) {
140
- const args = ['run', '--standalone', '--agent', OPENCODE_AGENT_PROFILE, '--auto'];
141
- if (modelId)
142
- args.push('--model', modelId);
143
- args.push('--', prompt);
144
- return args;
145
- }
1
+ import{checkTrustedHeadlessRuntimeBinary as _}from"../binary.js";import{HEADLESS_REASON_CODES as s,adapterAvailabilityFailure as m,adapterAvailabilitySuccess as R,createRejectedExecutionResult as p,createUnavailableExecutionResult as I,hashPublicValue as f,normalizeHeadlessCommandResult as E,redaction as A,runHeadlessCommand as v,validateHeadlessAdapterExecutionInput as b}from"./types.js";import{governedPreflightFailureResult as h,preflightManagedHeadlessProfile as y,withGovernedHeadlessEvidence as c}from"./managed-profile.js";const r="opencode",d="opencode",S="neocortex",T=2e3,C=2e3,P=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|\bPRIVATE\b)/i,O=/\b(?:Claude\s+Code|claude-code|@anthropic-ai\/claude-code)\b/i,k=/\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?\b/;function w(){return{id:r,displayName:"OpenCode Headless Adapter",async checkAvailability(n={}){return N(r,d,n,{realpathBasenamePolicy:"opencode-npm-native"})},buildInvocation(n){const e=b(n,r);return e.ok?{ok:!0,invocation:{adapterId:r,commandName:d,args:V(e.prompt,e.input.modelId),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(n,e={}){const t=b(n,r);if(!t.ok)return p(r,r,t);const a=y(r,e);if(!a.ok)return h(r,t.input,a);if(e.signal?.aborted)return c(E(r,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const i=await this.checkAvailability(e);if(!i.ok)return c(I(r,t.input,i));const o=this.buildInvocation(t.input);if(!o.ok)return p(r,r,o);const u=await(e.commandRunner??v)(i.executablePath??d,o.invocation.args,{cwd:e.cwd,env:e.env,timeoutMs:o.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return c(E(r,t.input,u))}}}async function N(n,e,t,a={}){const i=_({commandName:e,env:t.env,platform:t.platform,commandLocator:t.commandLocator,realpathBasenamePolicy:a.realpathBasenamePolicy});if(!i.ok)return m(n,e,i.reasonCode===s.ADAPTER_UNAVAILABLE?s.ADAPTER_UNAVAILABLE:s.RUNTIME_UNTRUSTED,i.publicSummary,i.redactionSummary);const l=await(t.versionRunner??t.commandRunner??v)(i.executablePath,["--version"],{env:t.env,timeoutMs:5e3,maxOutputBytes:2e3}),u=g(l,a.versionEvidence??"generic-public");return u.ok?R(n,e,D(e,a.versionEvidence),{executablePath:i.executablePath,versionText:u.versionText}):m(n,e,s.ADAPTER_UNAVAILABLE,u.publicSummary,u.redactionSummary)}function g(n,e){const t=x(`${n.stdout}
2
+ ${n.stderr}`.trim()),a=t?[A("runtimeVersion","raw_log",f(t))]:[A("runtimeVersion","missing","value-denied")];return n.timedOut||n.exitCode!==0||t.length===0||t.length>T||n.stdoutBytes+n.stderrBytes>C||P.test(t)?{ok:!1,publicSummary:"Headless runtime version check did not return a bounded public result.",redactionSummary:a}:e==="claude-code"&&(!O.test(t)||!k.test(t))?{ok:!1,publicSummary:"Headless runtime version check did not return bounded Claude Code product/version evidence.",redactionSummary:a}:{ok:!0,versionText:t}}function x(n){return n.replace(/\s+/g," ").trim()}function D(n,e){return e==="claude-code"?`Trusted ${n} runtime is available with bounded Claude Code version evidence.`:`Trusted ${n} runtime is available.`}function V(n,e){const t=["run","--standalone","--agent",S,"--auto"];return e&&t.push("--model",e),t.push("--",n),t}export{N as checkRuntimeAvailability,w as createOpenCodeHeadlessAdapter};
@@ -1,43 +1 @@
1
- /** P208.05 -- client enforcement for phased plans and branchless bundles. */
2
- import { createHash } from 'node:crypto';
3
- import { validateYoloopPreparationBundle } from '../../../../shared/dist/yoloop/wave-decision-receipt.js';
4
- export function validatePhasedYoloopPlan(plan) {
5
- const errors = [];
6
- const phases = Array.isArray(plan.phases) ? plan.phases.filter(isRecord) : [];
7
- const budgets = isRecord(plan.budgets) ? plan.budgets : {};
8
- if (plan.version !== 2 || !isHash(plan.graphRevision))
9
- errors.push('phased-plan-invalid');
10
- if (budgets.maxWriteConcurrency !== 1)
11
- errors.push('writer-concurrency-invalid');
12
- for (const phase of phases) {
13
- if (!Number.isInteger(phase.maxConcurrency) || Number(phase.maxConcurrency) < 1)
14
- errors.push('phase-concurrency-invalid');
15
- const mutatesEpicCheckout = phase.mutatesEpicCheckout === true || phase.mutatesEpicWorktree === true;
16
- if (mutatesEpicCheckout && (phase.maxConcurrency !== 1 || !['epic-writer-lease', 'commit-range'].includes(String(phase.isolation))))
17
- errors.push('mutating-phase-not-serialized');
18
- }
19
- const required = ['read-only-analysis', 'isolated-build-test', 'patch-preparation', 'single-writer-integration', 'story-checkpoint-review'];
20
- if (required.some((kind) => !phases.some((phase) => phase.kind === kind)))
21
- errors.push('phase-missing');
22
- const receiptIds = Array.isArray(plan.decisionReceiptIds) ? plan.decisionReceiptIds : [];
23
- if (receiptIds.length === 0 || receiptIds.some((id) => !isHash(id)))
24
- errors.push('decision-receipt-invalid');
25
- const preparationConcurrency = Math.max(1, ...phases.filter((phase) => phase.mutatesEpicCheckout !== true && phase.mutatesEpicWorktree !== true).map((phase) => Number(phase.maxConcurrency) || 1));
26
- return { ok: errors.length === 0, preparationConcurrency, childExecutionConcurrency: 1, reasonCodes: [...new Set(errors)].sort() };
27
- }
28
- export function admitPreparedStoryBundle(input) {
29
- const errors = [...validateYoloopPreparationBundle(input.bundle, input.expected)];
30
- if (input.bundle.claimRevision !== input.expected.claimRevision)
31
- errors.push('bundle-claims-stale');
32
- if (!sameStrings(input.bundle.authorizedWriteSet, input.expected.authorizedWriteSet ?? []))
33
- errors.push('bundle-write-set-stale');
34
- const digest = createHash('sha256').update(input.payload).digest('hex');
35
- if (digest !== input.bundle.bundleDigest)
36
- errors.push('bundle-payload-digest-mismatch');
37
- if (!input.writerLease || input.writerLease.ownerStoryId !== input.bundle.storyId || input.writerLease.expiresAt <= input.expected.nowIso)
38
- errors.push('bundle-writer-lease-missing');
39
- return [...new Set(errors)].sort();
40
- }
41
- function isRecord(value) { return Boolean(value) && typeof value === 'object' && !Array.isArray(value); }
42
- function isHash(value) { return typeof value === 'string' && /^[a-f0-9]{40,64}$/.test(value); }
43
- function sameStrings(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); }
1
+ import{createHash as u}from"node:crypto";import{validateYoloopPreparationBundle as h}from"../../../../shared/dist/yoloop/wave-decision-receipt.js";function f(e){const r=[],s=Array.isArray(e.phases)?e.phases.filter(a):[],i=a(e.budgets)?e.budgets:{};(e.version!==2||!c(e.graphRevision))&&r.push("phased-plan-invalid"),i.maxWriteConcurrency!==1&&r.push("writer-concurrency-invalid");for(const t of s)(!Number.isInteger(t.maxConcurrency)||Number(t.maxConcurrency)<1)&&r.push("phase-concurrency-invalid"),(t.mutatesEpicCheckout===!0||t.mutatesEpicWorktree===!0)&&(t.maxConcurrency!==1||!["epic-writer-lease","commit-range"].includes(String(t.isolation)))&&r.push("mutating-phase-not-serialized");["read-only-analysis","isolated-build-test","patch-preparation","single-writer-integration","story-checkpoint-review"].some(t=>!s.some(n=>n.kind===t))&&r.push("phase-missing");const o=Array.isArray(e.decisionReceiptIds)?e.decisionReceiptIds:[];(o.length===0||o.some(t=>!c(t)))&&r.push("decision-receipt-invalid");const d=Math.max(1,...s.filter(t=>t.mutatesEpicCheckout!==!0&&t.mutatesEpicWorktree!==!0).map(t=>Number(t.maxConcurrency)||1));return{ok:r.length===0,preparationConcurrency:d,childExecutionConcurrency:1,reasonCodes:[...new Set(r)].sort()}}function g(e){const r=[...h(e.bundle,e.expected)];return e.bundle.claimRevision!==e.expected.claimRevision&&r.push("bundle-claims-stale"),l(e.bundle.authorizedWriteSet,e.expected.authorizedWriteSet??[])||r.push("bundle-write-set-stale"),u("sha256").update(e.payload).digest("hex")!==e.bundle.bundleDigest&&r.push("bundle-payload-digest-mismatch"),(!e.writerLease||e.writerLease.ownerStoryId!==e.bundle.storyId||e.writerLease.expiresAt<=e.expected.nowIso)&&r.push("bundle-writer-lease-missing"),[...new Set(r)].sort()}function a(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function c(e){return typeof e=="string"&&/^[a-f0-9]{40,64}$/.test(e)}function l(e,r){return e.length===r.length&&e.every((s,i)=>s===r[i])}export{g as admitPreparedStoryBundle,f as validatePhasedYoloopPlan};