@ornexus/neocortex 4.60.73 → 4.60.74

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 (241) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1216 -1210
  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 -212
  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 -417
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -251
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -108
  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 -358
  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 +143 -7200
  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 -156
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  75. package/packages/client/dist/config/profile-directory.js +1 -13
  76. package/packages/client/dist/config/resolver-selection.js +1 -278
  77. package/packages/client/dist/config/secure-config.js +12 -281
  78. package/packages/client/dist/config.js +2 -223
  79. package/packages/client/dist/constants.js +1 -25
  80. package/packages/client/dist/context/context-collector.js +2 -222
  81. package/packages/client/dist/context/context-sanitizer.js +1 -145
  82. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  83. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  84. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  85. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  86. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  87. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  88. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  89. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  90. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  91. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  92. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  93. package/packages/client/dist/continuity/outbox.js +1 -117
  94. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  95. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  96. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  97. package/packages/client/dist/errors/error-messages.js +2 -228
  98. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  99. package/packages/client/dist/evidence/collector.js +1 -347
  100. package/packages/client/dist/evidence/index.js +1 -1
  101. package/packages/client/dist/evidence/types.js +0 -2
  102. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  103. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  104. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  105. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  106. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  107. package/packages/client/dist/git/epic-operational-state.js +2 -672
  108. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  109. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  110. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  113. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  117. package/packages/client/dist/i18n/first-run.js +2 -60
  118. package/packages/client/dist/index.js +1 -47
  119. package/packages/client/dist/invocation/invoke-input.js +1 -24
  120. package/packages/client/dist/license/index.js +1 -5
  121. package/packages/client/dist/license/license-client.js +1 -304
  122. package/packages/client/dist/machine/fingerprint.js +2 -163
  123. package/packages/client/dist/machine/index.js +1 -5
  124. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  125. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  126. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  127. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  128. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  129. package/packages/client/dist/migrations/project-identity.js +7 -493
  130. package/packages/client/dist/migrations/state-json.js +4 -393
  131. package/packages/client/dist/policy/architecture-policy.js +2 -184
  132. package/packages/client/dist/policy/index.js +1 -7
  133. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  134. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  135. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  136. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  137. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  138. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  139. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  140. package/packages/client/dist/private-execution/delivery.js +13 -410
  141. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  142. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  143. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  144. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  145. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  146. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  147. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  148. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  149. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  150. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  151. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  152. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  153. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  154. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  155. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  156. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  157. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  158. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  159. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  160. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  161. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  162. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  163. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  164. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  165. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  166. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  167. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  168. package/packages/client/dist/private-execution/session-lease.js +1 -63
  169. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  170. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  171. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  172. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  173. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  174. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  175. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  176. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  177. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  178. package/packages/client/dist/resilience/index.js +1 -8
  179. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  180. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  181. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  182. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  183. package/packages/client/dist/runner/binary.js +1 -404
  184. package/packages/client/dist/runner/cli.js +17 -1571
  185. package/packages/client/dist/runner/headless/adapters.js +1 -49
  186. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  187. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  188. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  189. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  190. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  191. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  192. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  193. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +18 -2
  194. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  195. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  196. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  197. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  198. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  199. package/packages/client/dist/runner/headless/resolver.js +1 -231
  200. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  201. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  202. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  203. package/packages/client/dist/runner/headless/types.js +2 -574
  204. package/packages/client/dist/runner/local-console.js +13 -396
  205. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  206. package/packages/client/dist/runner/project-identity.js +1 -106
  207. package/packages/client/dist/runner/scheduler.js +7 -995
  208. package/packages/client/dist/runner-cli.js +2 -18
  209. package/packages/client/dist/state/invocation-shape.js +1 -13
  210. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  211. package/packages/client/dist/state/state-json-repair.js +3 -785
  212. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  213. package/packages/client/dist/telemetry/index.js +1 -5
  214. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  215. package/packages/client/dist/tier/index.js +1 -5
  216. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  217. package/packages/client/dist/types/index.js +1 -38
  218. package/packages/client/dist/version.js +1 -27
  219. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  220. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  221. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  222. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  223. package/packages/client/dist/yoloop/index.js +1 -8
  224. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  225. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  226. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  227. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  228. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  229. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  230. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  231. package/targets-stubs/antigravity/gemini.md +1 -1
  232. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  233. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  234. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  235. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  236. package/targets-stubs/claude-code/neocortex.md +2 -2
  237. package/targets-stubs/codex/AGENTS.md +1 -1
  238. package/targets-stubs/cursor/agent.md +2 -2
  239. package/targets-stubs/gemini-cli/agent.md +2 -2
  240. package/targets-stubs/opencode/neocortex-root.md +1 -1
  241. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,669 +1,12 @@
1
- /**
2
- * Epic P101.07 -- invoke.ts hooks for yoloop state persistence.
3
- *
4
- * Two hooks:
5
- * - `readYoloopForRequest(args, projectRoot)` — pre-request; returns
6
- * `YoloopPersistedState | undefined` to embed in stateSnapshot.yoloop.
7
- * Returns undefined (no-op) for non-yoloop invocations to avoid I/O.
8
- * - `persistYoloopFromResponse(metadata, projectRoot)` — post-response;
9
- * if the server returned `yoloopStateUpdate`, apply operations locally.
10
- * Authoritative rollover/successor-transition failures are returned to the invoke boundary;
11
- * auxiliary legacy updates retain bounded fail-soft compatibility.
12
- *
13
- * Trigger detection is regex-based over the first token of `args`, aligned
14
- * with the P96.01 TRIGGER_ALIASES set for yoloop. Cheap enough to run on
15
- * every invoke.
16
- */
17
- import { statSync } from 'node:fs';
18
- import { join } from 'node:path';
19
- import { YoloopClientStateStore } from './yoloop-client-state-store.js';
20
- import { isYoloopInvocation } from './target-normalization.js';
21
- import { applyStateMigration, StateMigrationApplyError } from '../migrations/state-json.js';
22
- /**
23
- * Detect whether an args string is a yoloop invocation (including aliases).
24
- * Matches: `*yoloop`, `yoloop`, `*auto-yolo`, `*epic-runner`, `*story-runner`,
25
- * `*loop-yolo`, `*auto-epic` (case-insensitive, with optional leading whitespace
26
- * and optional `*` prefix).
27
- */
28
- export function isYoloopTrigger(args) {
29
- return isYoloopInvocation(args);
30
- }
31
- export const YOLOOP_PERSISTENCE_REASON_CODES = Object.freeze({
32
- stateReadFailed: 'YOLOOP_STATE_READ_FAILED',
33
- authoritativeWritebackFailed: 'YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED',
34
- auxiliaryWritebackFailed: 'YOLOOP_AUXILIARY_WRITEBACK_FAILED',
35
- });
36
- export class YoloopStateReadError extends Error {
37
- reasonCode;
38
- constructor(reasonCode) {
39
- super(reasonCode);
40
- this.reasonCode = reasonCode;
41
- this.name = 'YoloopStateReadError';
42
- }
43
- }
44
- function publicPersistenceReason(error, fallback) {
45
- const message = error instanceof Error ? error.message : String(error);
46
- return message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0] ?? fallback;
47
- }
48
- const RECOVERABLE_AUTHORITATIVE_WRITE_CODES = new Set([
49
- 'YOLOOP_RUN_REVISION_CONFLICT',
50
- 'YOLOOP_RUN_SNAPSHOT_CONFLICT',
51
- 'YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT',
52
- 'EAGAIN',
53
- 'EBUSY',
54
- 'EMFILE',
55
- 'ENFILE',
56
- ]);
57
- function shouldRetryAuthoritativeWrite(error) {
58
- const reason = publicPersistenceReason(error, '');
59
- if (RECOVERABLE_AUTHORITATIVE_WRITE_CODES.has(reason))
60
- return true;
61
- const code = error?.code;
62
- return typeof code === 'string' && RECOVERABLE_AUTHORITATIVE_WRITE_CODES.has(code);
63
- }
64
- // =====================================================================
65
- // P121.05 -- Zero-config *yoloop auto-resolve
66
- // =====================================================================
67
- /**
68
- * P121.05: Yoloop trigger regex (mirror of `isYoloopTrigger` predicate, but
69
- * exposes capture group + match index for token-aware rewrites).
70
- */
71
- const YOLOOP_TRIGGER_TOKEN_RE = /^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;
72
- /**
73
- * P121.05 -- Zero-config `*yoloop`. When the user types `*yoloop` (or any
74
- * alias) with no args, auto-resolve to `<projectRoot>/docs/epics/` if that
75
- * directory exists.
76
- *
77
- * Behavior:
78
- * - Yoloop trigger detection: same regex as P101.07 / P120.04.
79
- * - Args-empty detection: trigger token + optional whitespace; remainder
80
- * `=== ''` after `.trim()`.
81
- * - Directory existence: synchronous `fs.statSync(...).isDirectory()`,
82
- * wrapped in try/catch.
83
- * - Rewrite: appends ` @docs/epics/` to the matched trigger token,
84
- * preserving the original token (canonical or alias) and any leading
85
- * `*` prefix.
86
- * - Fail-soft: any error -> `ctx.logger.warn` + return unchanged args.
87
- *
88
- * Mutates `ctx.args` in place when auto-resolve fires. Caller (invoke.ts)
89
- * propagates the new value via the InvokeOptions immutable update pattern.
90
- *
91
- * AC1, AC2, AC3, AC4, AC5, AC6, AC7, AC8, AC13.
92
- */
93
- export function maybeAutoResolveYoloopArgs(ctx) {
94
- // Defensive: defensive types -- unexpected non-strings get a no-op.
95
- if (typeof ctx.args !== 'string' || ctx.args.length === 0) {
96
- return;
97
- }
98
- // 1. Match yoloop trigger token (with optional `*` prefix).
99
- const match = ctx.args.match(YOLOOP_TRIGGER_TOKEN_RE);
100
- if (!match) {
101
- // Not a yoloop trigger -> nothing to do.
102
- return;
103
- }
104
- // 2. Strip the matched trigger from `args` and check the remainder.
105
- // `match[0]` is the matched substring including any leading whitespace
106
- // and the optional `*` prefix and the trigger token. Anything after
107
- // the trigger token (and any trailing whitespace) is the explicit args.
108
- const matchedToken = match[0]; // e.g., "*yoloop" or " yoloop"
109
- const remainder = ctx.args.slice(matchedToken.length).trim();
110
- if (remainder !== '') {
111
- // Explicit args present -> never rewrite (AC6, backward compat).
112
- return;
113
- }
114
- // 3. Check whether `<projectRoot>/docs/epics/` exists and is a directory.
115
- // Wrapped in try/catch so any fs error (permission denied, ENOENT,
116
- // unexpected errors from `node:fs`) is swallowed -> args unchanged.
117
- let isDir = false;
118
- try {
119
- const target = join(ctx.projectRoot, 'docs', 'epics');
120
- const stat = statSync(target);
121
- isDir = stat.isDirectory();
122
- }
123
- catch (err) {
124
- // Fail-soft: log warn + bail. Args remain unchanged. Server emits the
125
- // existing `INVALID_YOLOOP_TARGET` error if/when the request reaches it.
126
- const msg = err instanceof Error ? err.message : String(err);
127
- ctx.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${msg}. Proceeding with raw args.`);
128
- return;
129
- }
130
- if (!isDir) {
131
- // Directory does not exist (or `docs/epics` is a file) -> args unchanged.
132
- return;
133
- }
134
- // 4. Rewrite: preserve the matched trigger token and append ` @docs/epics/`.
135
- // Canonical examples:
136
- // `*yoloop` -> `*yoloop @docs/epics/`
137
- // `*auto-yolo` -> `*auto-yolo @docs/epics/`
138
- // ` yoloop ` -> ` yoloop @docs/epics/`
139
- ctx.args = `${matchedToken} @docs/epics/`;
140
- // 5. Surface the auto-resolution at info level so operators see the
141
- // transformation in stderr without being noisy on every invoke.
142
- ctx.logger?.info?.(`[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/`);
143
- }
144
- /**
145
- * Pre-request hook: read client-side yoloop state for the given project.
146
- * Returns undefined for non-yoloop invocations (no I/O). A yoloop read or
147
- * recovery failure is authoritative and fails closed so the server can never
148
- * reinterpret corrupt/unavailable persisted state as a fresh session.
149
- */
150
- export async function readYoloopForRequest(args, projectRoot, nowIso) {
151
- if (!isYoloopTrigger(args))
152
- return undefined;
153
- try {
154
- const store = new YoloopClientStateStore(projectRoot);
155
- return await store.readAll(nowIso);
156
- }
157
- catch (err) {
158
- const reasonCode = publicPersistenceReason(err, YOLOOP_PERSISTENCE_REASON_CODES.stateReadFailed);
159
- process.stderr.write(`[yoloop] ${reasonCode}. Local yoloop authority was not read; no request was sent.\n`);
160
- throw new YoloopStateReadError(reasonCode);
161
- }
162
- }
163
- /**
164
- * Post-response hook: apply server-provided operations to local state.
165
- * Safe to call for any response — no-op if no yoloopStateUpdate present.
166
- * A `rollover_session` or `commit_successor_transition` update is
167
- * authoritative: failure is returned to the caller so instructions cannot be
168
- * released before durable state exists.
169
- * Non-rollover legacy operations retain fail-soft compatibility.
170
- */
171
- export async function persistYoloopFromResponse(metadata, projectRoot, nowIso) {
172
- if (!metadata)
173
- return { ok: true, authoritative: false, reasonCodes: [] };
174
- const update = metadata.yoloopStateUpdate;
175
- if (!update || !Array.isArray(update.operations) || update.operations.length === 0) {
176
- return { ok: true, authoritative: false, reasonCodes: [] };
177
- }
178
- const authoritative = update.operations.some((operation) => operation.type === 'rollover_session'
179
- || operation.type === 'commit_successor_transition');
180
- let lastError;
181
- const attempts = authoritative ? 3 : 1;
182
- for (let attempt = 0; attempt < attempts; attempt += 1) {
183
- try {
184
- const store = new YoloopClientStateStore(projectRoot);
185
- await store.applyUpdate(update, nowIso);
186
- return { ok: true, authoritative, reasonCodes: [] };
187
- }
188
- catch (error) {
189
- lastError = error;
190
- if (!authoritative || attempt + 1 >= attempts || !shouldRetryAuthoritativeWrite(error))
191
- break;
192
- // A fresh store rereads and recovers any prepared manifest. These
193
- // bounded internal attempts do not create a new server run, dispatch,
194
- // entitlement charge, strike or cooldown.
195
- }
196
- }
197
- {
198
- const err = lastError;
199
- const reasonCode = publicPersistenceReason(err, authoritative
200
- ? YOLOOP_PERSISTENCE_REASON_CODES.authoritativeWritebackFailed
201
- : YOLOOP_PERSISTENCE_REASON_CODES.auxiliaryWritebackFailed);
202
- if (authoritative) {
203
- process.stderr.write(`[yoloop] ${reasonCode}. Authoritative yoloop transition was not persisted; no continuation instructions were released.\n`);
204
- return { ok: false, authoritative: true, reasonCodes: [reasonCode] };
205
- }
206
- process.stderr.write(`[yoloop] ${reasonCode}. Auxiliary state update was not persisted; retry the same command.\n`);
207
- return { ok: true, authoritative: false, reasonCodes: [reasonCode] };
208
- }
209
- }
210
- function isPlainRecord(value) {
211
- return typeof value === 'object' && value !== null && !Array.isArray(value);
212
- }
213
- function boundedPublicStrings(value, max) {
214
- return Array.isArray(value)
215
- && value.length <= max
216
- && value.every((entry) => typeof entry === 'string' && entry.length > 0 && entry.length <= 160 && /^[A-Za-z0-9_.:+-]+$/.test(entry));
217
- }
218
- function projectedOrPartialState(value) {
219
- if (!isPlainRecord(value.scope))
220
- return false;
221
- return value.scope.kind === 'projected'
222
- || (typeof value.scope.omittedStoryCount === 'number' && value.scope.omittedStoryCount > 0)
223
- || (typeof value.scope.omittedEpicCount === 'number' && value.scope.omittedEpicCount > 0);
224
- }
225
- function stripRequestOnlyStateFields(value) {
226
- const canonical = { ...value };
227
- delete canonical.scope;
228
- delete canonical.stateSummary;
229
- delete canonical.graphRetrieval;
230
- delete canonical.runnerBootstrap;
231
- delete canonical.projectEvidence;
232
- delete canonical.continuity;
233
- delete canonical.implementCheckpoint;
234
- return canonical;
235
- }
236
- function doneLikeStatus(value) {
237
- return typeof value === 'string' && ['done', 'completed', 'merged'].includes(value.trim().toLowerCase());
238
- }
239
- function safeInlineYoloBranch(value) {
240
- return /^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(value)
241
- && !value.includes('..')
242
- && !value.includes('//')
243
- && !value.includes('@{')
244
- && !value.endsWith('/')
245
- && !value.endsWith('.')
246
- && !value.endsWith('.lock');
247
- }
248
- async function persistInlineYoloMaterialization(metadata, projectRoot) {
249
- const syntheticStory = metadata.syntheticStory;
250
- if (!isPlainRecord(syntheticStory)) {
251
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-mutation-missing' };
252
- }
253
- const schemaVersion = syntheticStory.schemaVersion;
254
- const epicId = syntheticStory.epicId;
255
- const storyId = syntheticStory.storyId;
256
- const storyPath = syntheticStory.storyPath;
257
- const deterministicKey = syntheticStory.deterministicKey;
258
- const storyContent = syntheticStory.storyContent;
259
- const storyContentSha256 = syntheticStory.storyContentSha256;
260
- const lifecycle = syntheticStory.lifecycle;
261
- if (schemaVersion !== 2
262
- || typeof epicId !== 'string' || !/^P9\d{18}$/.test(epicId)
263
- || typeof storyId !== 'string' || storyId !== `${epicId}.01.000001`
264
- || typeof storyPath !== 'string' || storyPath !== `docs/stories/${storyId}.story.md`
265
- || typeof deterministicKey !== 'string' || !/^[a-f0-9]{16}$/.test(deterministicKey)
266
- || typeof storyContentSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(storyContentSha256)
267
- || typeof storyContent !== 'string' || storyContent.length === 0 || storyContent.length > 131_072
268
- || !isPlainRecord(lifecycle)
269
- || lifecycle.branchMode !== 'epic'
270
- || lifecycle.executionBranch !== `epic/${epicId}`
271
- || typeof lifecycle.originBranch !== 'string'
272
- || !safeInlineYoloBranch(lifecycle.originBranch)
273
- || typeof lifecycle.graphRevision !== 'string' || !/^[a-f0-9]{64}$/.test(lifecycle.graphRevision)
274
- || lifecycle.isolatedSyntheticEpic !== true
275
- || syntheticStory.publicSafe !== true || syntheticStory.sanitized !== true) {
276
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-mutation-invalid' };
277
- }
278
- const fs = await import('node:fs/promises');
279
- const path = await import('node:path');
280
- const crypto = await import('node:crypto');
281
- if (crypto.createHash('sha256').update(storyContent).digest('hex') !== storyContentSha256) {
282
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-story-content-integrity-invalid' };
283
- }
284
- const stateDir = path.join(projectRoot, '.neocortex');
285
- const statePath = path.join(stateDir, 'state.json');
286
- const absoluteStoryPath = path.join(projectRoot, ...storyPath.split('/'));
287
- let rawState;
288
- try {
289
- rawState = await fs.readFile(statePath, 'utf8');
290
- }
291
- catch {
292
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-state-missing' };
293
- }
294
- const sourceStateSha256 = crypto.createHash('sha256').update(rawState).digest('hex');
295
- let parsedState;
296
- try {
297
- parsedState = JSON.parse(rawState);
298
- }
299
- catch {
300
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-state-corrupt' };
301
- }
302
- if (!isPlainRecord(parsedState) || !isPlainRecord(parsedState.stories) || !isPlainRecord(parsedState.epics)
303
- || projectedOrPartialState(parsedState)) {
304
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-state-not-full' };
305
- }
306
- if (!isPlainRecord(parsedState.config) || parsedState.config.default_branch !== lifecycle.originBranch) {
307
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-origin-branch-conflict' };
308
- }
309
- const previousStory = parsedState.stories[storyId];
310
- if (previousStory !== undefined && (!isPlainRecord(previousStory)
311
- || previousStory.epic_id !== epicId
312
- || previousStory.story_file !== storyPath
313
- || !isPlainRecord(previousStory.inlineYolo)
314
- || previousStory.inlineYolo.deterministicKey !== deterministicKey)) {
315
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-story-conflict' };
316
- }
317
- const previousEpic = parsedState.epics[epicId];
318
- if (previousEpic !== undefined && (!isPlainRecord(previousEpic)
319
- || previousEpic.id !== epicId
320
- || previousEpic.source !== 'inline-yolo-materialization'
321
- || previousEpic.branch_mode !== 'epic'
322
- || previousEpic.execution_branch !== lifecycle.executionBranch
323
- || previousEpic.origin_branch !== lifecycle.originBranch
324
- || previousEpic.graph_revision !== lifecycle.graphRevision
325
- || !isPlainRecord(previousEpic.inlineYoloLifecycle)
326
- || previousEpic.inlineYoloLifecycle.deterministicKey !== deterministicKey
327
- || previousEpic.inlineYoloLifecycle.isolatedSyntheticEpic !== true
328
- || !Array.isArray(previousEpic.stories))) {
329
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-epic-conflict' };
330
- }
331
- const epic = isPlainRecord(previousEpic) ? previousEpic : {};
332
- const previousStoryIds = Array.isArray(epic.stories) ? epic.stories : [];
333
- if (previousStoryIds.some((entry) => typeof entry !== 'string') || new Set(previousStoryIds).size !== previousStoryIds.length) {
334
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-epic-story-list-invalid' };
335
- }
336
- for (const existingId of previousStoryIds) {
337
- const existingStory = parsedState.stories[existingId];
338
- if (!isPlainRecord(existingStory) || existingStory.id !== existingId || existingStory.epic_id !== epicId) {
339
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-epic-ownership-conflict' };
340
- }
341
- }
342
- try {
343
- const existingContent = await fs.readFile(absoluteStoryPath, 'utf8');
344
- const materializationIdentityPreserved = existingContent.includes(`id: ${storyId}`)
345
- && existingContent.includes(`synthetic_key: ${deterministicKey}`);
346
- if (existingContent !== storyContent && !materializationIdentityPreserved) {
347
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-story-file-conflict' };
348
- }
349
- }
350
- catch (error) {
351
- if (error.code !== 'ENOENT') {
352
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-story-file-unreadable' };
353
- }
354
- }
355
- const storyIds = previousStoryIds.includes(storyId)
356
- ? [...previousStoryIds]
357
- : [...previousStoryIds, storyId];
358
- const stories = {
359
- ...parsedState.stories,
360
- [storyId]: {
361
- ...(isPlainRecord(previousStory) ? previousStory : {}),
362
- id: storyId,
363
- epic_id: epicId,
364
- title: 'Synthetic inline USER STORY for yolo',
365
- status: isPlainRecord(previousStory) && typeof previousStory.status === 'string' ? previousStory.status : 'backlog',
366
- steps_completed: isPlainRecord(previousStory) && Array.isArray(previousStory.steps_completed) ? previousStory.steps_completed : [],
367
- last_step: isPlainRecord(previousStory) ? previousStory.last_step ?? null : null,
368
- branch_name: isPlainRecord(previousStory) ? previousStory.branch_name ?? null : null,
369
- story_file: storyPath,
370
- source: 'inline-yolo-materialization',
371
- inlineYolo: {
372
- ...(isPlainRecord(previousStory) && isPlainRecord(previousStory.inlineYolo) ? previousStory.inlineYolo : {}),
373
- schemaVersion: 2,
374
- deterministicKey,
375
- publicSafe: true,
376
- sanitized: true,
377
- materializedBeforeExecution: true,
378
- ephemeralExecutionForbidden: true,
379
- },
380
- },
381
- };
382
- const completedStories = storyIds.filter((id) => isPlainRecord(stories[id]) && doneLikeStatus(stories[id].status)).length;
383
- const previousInlineYolo = isPlainRecord(parsedState.inlineYolo) ? parsedState.inlineYolo : {};
384
- const previousMaterializations = isPlainRecord(previousInlineYolo.materializations)
385
- ? previousInlineYolo.materializations : {};
386
- const nextState = stripRequestOnlyStateFields({
387
- ...parsedState,
388
- stories,
389
- epics: {
390
- ...parsedState.epics,
391
- [epicId]: {
392
- ...epic,
393
- id: epicId,
394
- title: typeof epic.title === 'string' ? epic.title : 'Isolated synthetic inline yolo lifecycle',
395
- status: completedStories === storyIds.length && storyIds.length > 0 ? 'done' : 'in-progress',
396
- source: 'inline-yolo-materialization',
397
- branch_mode: 'epic',
398
- execution_branch: lifecycle.executionBranch,
399
- origin_branch: lifecycle.originBranch,
400
- graph_revision: lifecycle.graphRevision,
401
- stories: storyIds,
402
- total_stories: storyIds.length,
403
- completed_stories: completedStories,
404
- ...(completedStories === storyIds.length && storyIds.length > 0 ? {} : { completed_at: null }),
405
- inlineYoloLifecycle: {
406
- schemaVersion: 2,
407
- deterministicKey,
408
- isolatedSyntheticEpic: true,
409
- },
410
- },
411
- },
412
- inlineYolo: {
413
- ...previousInlineYolo,
414
- schemaVersion: 2,
415
- materializations: {
416
- ...previousMaterializations,
417
- [storyId]: {
418
- schemaVersion: 2,
419
- epicId,
420
- storyId,
421
- storyPath,
422
- deterministicKey,
423
- storyContentSha256,
424
- sourceStateSha256,
425
- lifecycle,
426
- publicSafe: true,
427
- sanitized: true,
428
- materializedBeforeExecution: true,
429
- ephemeralExecutionForbidden: true,
430
- pipelineTrigger: `*yolo @${storyPath}`,
431
- reasonCodes: Array.isArray(syntheticStory.reasonCodes) ? syntheticStory.reasonCodes : [],
432
- },
433
- },
434
- },
435
- last_updated: new Date().toISOString(),
436
- });
437
- const suffix = `${Date.now()}-${crypto.randomBytes(6).toString('hex')}`;
438
- const stateTmpPath = path.join(stateDir, `state.json.tmp.${suffix}`);
439
- const storyTmpPath = `${absoluteStoryPath}.tmp.${suffix}`;
440
- const backupPath = path.join(stateDir, `state.json.backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
441
- const lockPath = path.join(stateDir, 'state.json.inline-yolo.lock');
442
- let storyCreated = false;
443
- let lockHandle;
444
- const syncDirectory = async (directory) => {
445
- let handle;
446
- try {
447
- handle = await fs.open(directory, 'r');
448
- await handle.sync();
449
- }
450
- catch (error) {
451
- const code = error.code;
452
- if (!['EINVAL', 'ENOTSUP', 'EPERM', 'EISDIR'].includes(code ?? ''))
453
- throw error;
454
- }
455
- finally {
456
- await handle?.close().catch(() => undefined);
457
- }
458
- };
459
- const durableExclusiveWrite = async (temporaryPath, content) => {
460
- const handle = await fs.open(temporaryPath, 'wx', 0o600);
461
- try {
462
- await handle.writeFile(content, 'utf8');
463
- await handle.sync();
464
- }
465
- finally {
466
- await handle.close();
467
- }
468
- };
469
- try {
470
- await fs.mkdir(stateDir, { recursive: true });
471
- await fs.mkdir(path.dirname(absoluteStoryPath), { recursive: true });
472
- try {
473
- lockHandle = await fs.open(lockPath, 'wx', 0o600);
474
- await lockHandle.writeFile(`${process.pid}\n${sourceStateSha256}\n`, 'utf8');
475
- await lockHandle.sync();
476
- }
477
- catch (error) {
478
- if (error.code === 'EEXIST') {
479
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-writeback-locked' };
480
- }
481
- throw error;
482
- }
483
- // Compare-and-swap under the cooperative lock. A stale response may never
484
- // replace state that changed after it was read and validated above.
485
- const currentRawState = await fs.readFile(statePath, 'utf8');
486
- const currentStateSha256 = crypto.createHash('sha256').update(currentRawState).digest('hex');
487
- if (currentStateSha256 !== sourceStateSha256) {
488
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-state-cas-conflict' };
489
- }
490
- try {
491
- await fs.access(absoluteStoryPath);
492
- }
493
- catch {
494
- await durableExclusiveWrite(storyTmpPath, storyContent);
495
- await fs.rename(storyTmpPath, absoluteStoryPath);
496
- await syncDirectory(path.dirname(absoluteStoryPath));
497
- storyCreated = true;
498
- }
499
- await fs.copyFile(statePath, backupPath);
500
- const backupHandle = await fs.open(backupPath, 'r');
501
- try {
502
- await backupHandle.sync();
503
- }
504
- finally {
505
- await backupHandle.close();
506
- }
507
- await durableExclusiveWrite(stateTmpPath, JSON.stringify(nextState, null, 2));
508
- await fs.rename(stateTmpPath, statePath);
509
- await syncDirectory(stateDir);
510
- process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${storyId}; backup=${path.basename(backupPath)}.\n`);
511
- return { applied: true, blocking: false, reasonCode: 'inline-yolo-materialized' };
512
- }
513
- catch (error) {
514
- await Promise.allSettled([fs.unlink(stateTmpPath), fs.unlink(storyTmpPath)]);
515
- if (storyCreated) {
516
- const currentStory = await fs.readFile(absoluteStoryPath, 'utf8').catch(() => undefined);
517
- if (currentStory === storyContent)
518
- await fs.unlink(absoluteStoryPath).catch(() => undefined);
519
- }
520
- const message = error.message ?? String(error);
521
- process.stderr.write(`[Neocortex] inline yolo materialization failed: ${message}.\n`);
522
- return { applied: false, blocking: true, reasonCode: 'inline-yolo-persistence-failed' };
523
- }
524
- finally {
525
- await lockHandle?.close().catch(() => undefined);
526
- if (lockHandle)
527
- await fs.unlink(lockPath).catch(() => undefined);
528
- }
529
- }
530
- export async function persistMigratedStateFromResponse(metadata, projectRoot) {
531
- if (!metadata || metadata.stateMutated !== true) {
532
- return { applied: false, blocking: false, reasonCode: 'state-writeback-not-requested' };
533
- }
534
- if (metadata.stateMutationStrategy === 'merge-inline-yolo-v2'
535
- || metadata.stateMutationReason === 'inline-yolo-materialized-synthetic-story') {
536
- return persistInlineYoloMaterialization(metadata, projectRoot);
537
- }
538
- if (metadata.stateMutationStrategy === 'state-migration-v1' || metadata.stateMigrationPlan !== undefined) {
539
- const rawPlan = metadata.stateMigrationPlan;
540
- const directiveKeys = new Set([
541
- 'schemaVersion', 'operationId', 'sourceSchemaVersion', 'targetSchemaVersion',
542
- 'sourceCanonicalHash', 'targetCanonicalHash', 'steps', 'migratedEpicIds',
543
- 'migratedStoryIds', 'preservedUnknownFieldCount', 'reasonCodes', 'sourceByteDigest',
544
- ]);
545
- if (!isPlainRecord(rawPlan)
546
- || Object.keys(rawPlan).some((key) => !directiveKeys.has(key))
547
- || rawPlan.schemaVersion !== 'StateMigrationPlan/1.0'
548
- || typeof rawPlan.operationId !== 'string' || !/^smig_[a-f0-9]{32}$/.test(rawPlan.operationId)
549
- || typeof rawPlan.sourceCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(rawPlan.sourceCanonicalHash)
550
- || typeof rawPlan.targetCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(rawPlan.targetCanonicalHash)
551
- || typeof rawPlan.sourceByteDigest !== 'string' || !/^[a-f0-9]{64}$/.test(rawPlan.sourceByteDigest)
552
- || ![0, 1, 'absent'].includes(rawPlan.sourceSchemaVersion)
553
- || rawPlan.targetSchemaVersion !== 1
554
- || !Array.isArray(rawPlan.steps) || rawPlan.steps.length > 8192
555
- || rawPlan.steps.some((step) => !isPlainRecord(step)
556
- || Object.keys(step).some((key) => !['kind', 'source', 'target'].includes(key))
557
- || !['initialize-collection', 'merge-epic', 'merge-story', 'preserve-legacy', 'remove-legacy', 'set-schema-version'].includes(String(step.kind))
558
- || typeof step.target !== 'string' || step.target.length > 512 || !/^[A-Za-z0-9_.:[\]-]+$/.test(step.target)
559
- || (step.source !== undefined && (typeof step.source !== 'string' || step.source.length > 512 || !/^[A-Za-z0-9_.:[\]-]+$/.test(step.source))))
560
- || !boundedPublicStrings(rawPlan.migratedEpicIds, 4096)
561
- || !boundedPublicStrings(rawPlan.migratedStoryIds, 4096)
562
- || !boundedPublicStrings(rawPlan.reasonCodes, 32)
563
- || !Number.isSafeInteger(rawPlan.preservedUnknownFieldCount) || rawPlan.preservedUnknownFieldCount < 0) {
564
- return { applied: false, blocking: true, reasonCode: 'state-migration-plan-missing-or-invalid' };
565
- }
566
- try {
567
- const migrationReceipt = applyStateMigration(projectRoot, rawPlan);
568
- const backupPath = `.neocortex/state.json.migration-backup-${migrationReceipt.operationId}`;
569
- process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${migrationReceipt.outcome}; operation=${migrationReceipt.operationId}; backup=${migrationReceipt.backupHash ? backupPath : 'none'}.\n`);
570
- return {
571
- applied: migrationReceipt.outcome === 'applied',
572
- blocking: false,
573
- reasonCode: migrationReceipt.outcome === 'applied' ? 'state-migration-applied' : 'state-migration-replay-verified',
574
- };
575
- }
576
- catch (error) {
577
- const reasonCode = error instanceof StateMigrationApplyError ? error.reasonCode : 'state-migration-apply-failed';
578
- process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${reasonCode}.\n`);
579
- return { applied: false, blocking: true, reasonCode };
580
- }
581
- }
582
- const migratedState = metadata.migratedState;
583
- if (!migratedState || typeof migratedState !== 'object' || Array.isArray(migratedState)) {
584
- return { applied: false, blocking: true, reasonCode: 'state-writeback-payload-missing' };
585
- }
586
- if (projectedOrPartialState(migratedState)) {
587
- process.stderr.write('[Neocortex] Refused projected/partial state replacement; canonical state was not modified.\n');
588
- return { applied: false, blocking: true, reasonCode: 'state-writeback-partial-rejected' };
589
- }
590
- process.stderr.write('[P220-EV-STATE-MIGRATION] blocked=state-migration-plan-missing-or-invalid; canonical state was not modified.\n');
591
- return { applied: false, blocking: true, reasonCode: 'state-migration-plan-missing-or-invalid' };
592
- }
593
- // =====================================================================
594
- // P120.04 -- Discovery hook integration
595
- // =====================================================================
596
- /**
597
- * P120.04: lazy-loaded discovery hook wrapper.
598
- *
599
- * Short-circuits BEFORE the dynamic import when `featureFlag` is off, so
600
- * clients with `YOLOOP_AUTO_DISCOVERY` unset (default) never load the
601
- * discovery-hook module. ESM tree-shakers can prune the entire module +
602
- * its `shared-discover-epics.ts` mirror in production builds.
603
- *
604
- * Defensive try/catch around the dynamic import handles the
605
- * (vanishingly unlikely) case where the hook module is missing or the
606
- * dynamic import itself throws -- never blocks the invoke flow.
607
- *
608
- * Caller (invoke.ts) is expected to ALSO wrap this in a try/catch as
609
- * belt-and-suspenders.
610
- */
611
- export async function maybeRunDiscoveryHook(ctx) {
612
- // Flag-off short-circuit -- preserves tree-shaking + zero overhead.
613
- if (!ctx.featureFlag) {
614
- return {
615
- applied: false,
616
- added: Object.freeze([]),
617
- skipped: Object.freeze([]),
618
- storiesAdded: 0,
619
- reason: 'flag off',
620
- };
621
- }
622
- try {
623
- const mod = await import('./discovery-hook.js');
624
- return await mod.runDiscoveryHook(ctx);
625
- }
626
- catch (err) {
627
- const msg = err instanceof Error ? err.message : String(err);
628
- ctx.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${msg}. Proceeding without enrichment.`);
629
- return {
630
- applied: false,
631
- added: Object.freeze([]),
632
- skipped: Object.freeze([]),
633
- storiesAdded: 0,
634
- reason: `lazy load error: ${msg}`,
635
- };
636
- }
637
- }
638
- // =====================================================================
639
- // P158.06 -- Pre-command graph retrieval hook integration
640
- // =====================================================================
641
- /**
642
- * P158.06 / P198.02: lazy-loaded graph retrieval wrapper.
643
- *
644
- * Short-circuits before dynamic import when the feature flag is off. When on,
645
- * command eligibility, profiles and budgets are resolved by the public command
646
- * context policy shadow. Runtime errors are public-warning/fail-soft and never
647
- * block invoke.
648
- */
649
- export async function maybeRunGraphRetrievalHook(ctx) {
650
- if (!ctx.featureFlag) {
651
- return {
652
- applied: false,
653
- reason: 'flag_off',
654
- };
655
- }
656
- try {
657
- const mod = await import('../graph-retrieval/pre-command-hook.js');
658
- return await mod.runGraphRetrievalHook(ctx);
659
- }
660
- catch (err) {
661
- const msg = err instanceof Error ? err.message : String(err);
662
- ctx.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${msg}. Proceeding without enrichment.`);
663
- return {
664
- applied: false,
665
- reason: 'hook_error',
666
- warning: msg,
667
- };
668
- }
669
- }
1
+ import{statSync as q}from"node:fs";import{join as J}from"node:path";import{YoloopClientStateStore as U}from"./yoloop-client-state-store.js";import{isYoloopInvocation as X}from"./target-normalization.js";import{applyStateMigration as Q,StateMigrationApplyError as ee}from"../migrations/state-json.js";function te(e){return X(e)}const N=Object.freeze({stateReadFailed:"YOLOOP_STATE_READ_FAILED",authoritativeWritebackFailed:"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED",auxiliaryWritebackFailed:"YOLOOP_AUXILIARY_WRITEBACK_FAILED"});class oe extends Error{reasonCode;constructor(o){super(o),this.reasonCode=o,this.name="YoloopStateReadError"}}function L(e,o){return(e instanceof Error?e.message:String(e)).match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??o}const W=new Set(["YOLOOP_RUN_REVISION_CONFLICT","YOLOOP_RUN_SNAPSHOT_CONFLICT","YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT","EAGAIN","EBUSY","EMFILE","ENFILE"]);function re(e){const o=L(e,"");if(W.has(o))return!0;const r=e?.code;return typeof r=="string"&&W.has(r)}const ie=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function fe(e){if(typeof e.args!="string"||e.args.length===0)return;const o=e.args.match(ie);if(!o)return;const r=o[0];if(e.args.slice(r.length).trim()!=="")return;let n=!1;try{const t=J(e.projectRoot,"docs","epics");n=q(t).isDirectory()}catch(t){const l=t instanceof Error?t.message:String(t);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${l}. Proceeding with raw args.`);return}n&&(e.args=`${r} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function ge(e,o,r){if(te(e))try{return await new U(o).readAll(r)}catch(i){const n=L(i,N.stateReadFailed);throw process.stderr.write(`[yoloop] ${n}. Local yoloop authority was not read; no request was sent.
2
+ `),new oe(n)}}async function he(e,o,r){if(!e)return{ok:!0,authoritative:!1,reasonCodes:[]};const i=e.yoloopStateUpdate;if(!i||!Array.isArray(i.operations)||i.operations.length===0)return{ok:!0,authoritative:!1,reasonCodes:[]};const n=i.operations.some(p=>p.type==="rollover_session"||p.type==="commit_successor_transition");let t;const l=n?3:1;for(let p=0;p<l;p+=1)try{return await new U(o).applyUpdate(i,r),{ok:!0,authoritative:n,reasonCodes:[]}}catch(u){if(t=u,!n||p+1>=l||!re(u))break}{const u=L(t,n?N.authoritativeWritebackFailed:N.auxiliaryWritebackFailed);return n?(process.stderr.write(`[yoloop] ${u}. Authoritative yoloop transition was not persisted; no continuation instructions were released.
3
+ `),{ok:!1,authoritative:!0,reasonCodes:[u]}):(process.stderr.write(`[yoloop] ${u}. Auxiliary state update was not persisted; retry the same command.
4
+ `),{ok:!0,authoritative:!1,reasonCodes:[u]})}}function a(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function j(e,o){return Array.isArray(e)&&e.length<=o&&e.every(r=>typeof r=="string"&&r.length>0&&r.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(r))}function G(e){return a(e.scope)?e.scope.kind==="projected"||typeof e.scope.omittedStoryCount=="number"&&e.scope.omittedStoryCount>0||typeof e.scope.omittedEpicCount=="number"&&e.scope.omittedEpicCount>0:!1}function ne(e){const o={...e};return delete o.scope,delete o.stateSummary,delete o.graphRetrieval,delete o.runnerBootstrap,delete o.projectEvidence,delete o.continuity,delete o.implementCheckpoint,o}function ae(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}function se(e){return/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(e)&&!e.includes("..")&&!e.includes("//")&&!e.includes("@{")&&!e.endsWith("/")&&!e.endsWith(".")&&!e.endsWith(".lock")}async function ce(e,o){const r=e.syntheticStory;if(!a(r))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const i=r.schemaVersion,n=r.epicId,t=r.storyId,l=r.storyPath,p=r.deterministicKey,u=r.storyContent,A=r.storyContentSha256,y=r.lifecycle;if(i!==2||typeof n!="string"||!/^P9\d{18}$/.test(n)||typeof t!="string"||t!==`${n}.01.000001`||typeof l!="string"||l!==`docs/stories/${t}.story.md`||typeof p!="string"||!/^[a-f0-9]{16}$/.test(p)||typeof A!="string"||!/^[a-f0-9]{64}$/.test(A)||typeof u!="string"||u.length===0||u.length>131072||!a(y)||y.branchMode!=="epic"||y.executionBranch!==`epic/${n}`||typeof y.originBranch!="string"||!se(y.originBranch)||typeof y.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(y.graphRevision)||y.isolatedSyntheticEpic!==!0||r.publicSafe!==!0||r.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const d=await import("node:fs/promises"),S=await import("node:path"),O=await import("node:crypto");if(O.createHash("sha256").update(u).digest("hex")!==A)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-content-integrity-invalid"};const C=S.join(o,".neocortex"),I=S.join(C,"state.json"),w=S.join(o,...l.split("/"));let $;try{$=await d.readFile(I,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}const P=O.createHash("sha256").update($).digest("hex");let f;try{f=JSON.parse($)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!a(f)||!a(f.stories)||!a(f.epics)||G(f))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};if(!a(f.config)||f.config.default_branch!==y.originBranch)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-origin-branch-conflict"};const c=f.stories[t];if(c!==void 0&&(!a(c)||c.epic_id!==n||c.story_file!==l||!a(c.inlineYolo)||c.inlineYolo.deterministicKey!==p))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const g=f.epics[n];if(g!==void 0&&(!a(g)||g.id!==n||g.source!=="inline-yolo-materialization"||g.branch_mode!=="epic"||g.execution_branch!==y.executionBranch||g.origin_branch!==y.originBranch||g.graph_revision!==y.graphRevision||!a(g.inlineYoloLifecycle)||g.inlineYoloLifecycle.deterministicKey!==p||g.inlineYoloLifecycle.isolatedSyntheticEpic!==!0||!Array.isArray(g.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const E=a(g)?g:{},b=Array.isArray(E.stories)?E.stories:[];if(b.some(s=>typeof s!="string")||new Set(b).size!==b.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const s of b){const h=f.stories[s];if(!a(h)||h.id!==s||h.epic_id!==n)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const s=await d.readFile(w,"utf8"),h=s.includes(`id: ${t}`)&&s.includes(`synthetic_key: ${p}`);if(s!==u&&!h)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-conflict"}}catch(s){if(s.code!=="ENOENT")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-unreadable"}}const k=b.includes(t)?[...b]:[...b,t],T={...f.stories,[t]:{...a(c)?c:{},id:t,epic_id:n,title:"Synthetic inline USER STORY for yolo",status:a(c)&&typeof c.status=="string"?c.status:"backlog",steps_completed:a(c)&&Array.isArray(c.steps_completed)?c.steps_completed:[],last_step:a(c)?c.last_step??null:null,branch_name:a(c)?c.branch_name??null:null,story_file:l,source:"inline-yolo-materialization",inlineYolo:{...a(c)&&a(c.inlineYolo)?c.inlineYolo:{},schemaVersion:2,deterministicKey:p,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},v=k.filter(s=>a(T[s])&&ae(T[s].status)).length,Y=a(f.inlineYolo)?f.inlineYolo:{},K=a(Y.materializations)?Y.materializations:{},Z=ne({...f,stories:T,epics:{...f.epics,[n]:{...E,id:n,title:typeof E.title=="string"?E.title:"Isolated synthetic inline yolo lifecycle",status:v===k.length&&k.length>0?"done":"in-progress",source:"inline-yolo-materialization",branch_mode:"epic",execution_branch:y.executionBranch,origin_branch:y.originBranch,graph_revision:y.graphRevision,stories:k,total_stories:k.length,completed_stories:v,...v===k.length&&k.length>0?{}:{completed_at:null},inlineYoloLifecycle:{schemaVersion:2,deterministicKey:p,isolatedSyntheticEpic:!0}}},inlineYolo:{...Y,schemaVersion:2,materializations:{...K,[t]:{schemaVersion:2,epicId:n,storyId:t,storyPath:l,deterministicKey:p,storyContentSha256:A,sourceStateSha256:P,lifecycle:y,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${l}`,reasonCodes:Array.isArray(r.reasonCodes)?r.reasonCodes:[]}}},last_updated:new Date().toISOString()}),B=`${Date.now()}-${O.randomBytes(6).toString("hex")}`,z=S.join(C,`state.json.tmp.${B}`),x=`${w}.tmp.${B}`,F=S.join(C,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),V=S.join(C,"state.json.inline-yolo.lock");let D=!1,_;const H=async s=>{let h;try{h=await d.open(s,"r"),await h.sync()}catch(m){const R=m.code;if(!["EINVAL","ENOTSUP","EPERM","EISDIR"].includes(R??""))throw m}finally{await h?.close().catch(()=>{})}},M=async(s,h)=>{const m=await d.open(s,"wx",384);try{await m.writeFile(h,"utf8"),await m.sync()}finally{await m.close()}};try{await d.mkdir(C,{recursive:!0}),await d.mkdir(S.dirname(w),{recursive:!0});try{_=await d.open(V,"wx",384),await _.writeFile(`${process.pid}
5
+ ${P}
6
+ `,"utf8"),await _.sync()}catch(R){if(R.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw R}const s=await d.readFile(I,"utf8");if(O.createHash("sha256").update(s).digest("hex")!==P)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await d.access(w)}catch{await M(x,u),await d.rename(x,w),await H(S.dirname(w)),D=!0}await d.copyFile(I,F);const m=await d.open(F,"r");try{await m.sync()}finally{await m.close()}return await M(z,JSON.stringify(Z,null,2)),await d.rename(z,I),await H(C),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${t}; backup=${S.basename(F)}.
7
+ `),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(s){await Promise.allSettled([d.unlink(z),d.unlink(x)]),D&&await d.readFile(w,"utf8").catch(()=>{})===u&&await d.unlink(w).catch(()=>{});const h=s.message??String(s);return process.stderr.write(`[Neocortex] inline yolo materialization failed: ${h}.
8
+ `),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await _?.close().catch(()=>{}),_&&await d.unlink(V).catch(()=>{})}}async function me(e,o){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return ce(e,o);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const i=e.stateMigrationPlan,n=new Set(["schemaVersion","operationId","sourceSchemaVersion","targetSchemaVersion","sourceCanonicalHash","targetCanonicalHash","steps","migratedEpicIds","migratedStoryIds","preservedUnknownFieldCount","reasonCodes","sourceByteDigest"]);if(!a(i)||Object.keys(i).some(t=>!n.has(t))||i.schemaVersion!=="StateMigrationPlan/1.0"||typeof i.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(i.operationId)||typeof i.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.sourceCanonicalHash)||typeof i.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.targetCanonicalHash)||typeof i.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(i.sourceByteDigest)||![0,1,"absent"].includes(i.sourceSchemaVersion)||i.targetSchemaVersion!==1||!Array.isArray(i.steps)||i.steps.length>8192||i.steps.some(t=>!a(t)||Object.keys(t).some(l=>!["kind","source","target"].includes(l))||!["initialize-collection","merge-epic","merge-story","preserve-legacy","remove-legacy","set-schema-version"].includes(String(t.kind))||typeof t.target!="string"||t.target.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(t.target)||t.source!==void 0&&(typeof t.source!="string"||t.source.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(t.source)))||!j(i.migratedEpicIds,4096)||!j(i.migratedStoryIds,4096)||!j(i.reasonCodes,32)||!Number.isSafeInteger(i.preservedUnknownFieldCount)||i.preservedUnknownFieldCount<0)return{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"};try{const t=Q(o,i),l=`.neocortex/state.json.migration-backup-${t.operationId}`;return process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${t.outcome}; operation=${t.operationId}; backup=${t.backupHash?l:"none"}.
9
+ `),{applied:t.outcome==="applied",blocking:!1,reasonCode:t.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(t){const l=t instanceof ee?t.reasonCode:"state-migration-apply-failed";return process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${l}.
10
+ `),{applied:!1,blocking:!0,reasonCode:l}}}const r=e.migratedState;return!r||typeof r!="object"||Array.isArray(r)?{applied:!1,blocking:!0,reasonCode:"state-writeback-payload-missing"}:G(r)?(process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
11
+ `),{applied:!1,blocking:!0,reasonCode:"state-writeback-partial-rejected"}):(process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=state-migration-plan-missing-or-invalid; canonical state was not modified.
12
+ `),{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"})}async function Se(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await(await import("./discovery-hook.js")).runDiscoveryHook(e)}catch(o){const r=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${r}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`lazy load error: ${r}`}}}async function we(e){if(!e.featureFlag)return{applied:!1,reason:"flag_off"};try{return await(await import("../graph-retrieval/pre-command-hook.js")).runGraphRetrievalHook(e)}catch(o){const r=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${r}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",warning:r}}}export{N as YOLOOP_PERSISTENCE_REASON_CODES,oe as YoloopStateReadError,te as isYoloopTrigger,fe as maybeAutoResolveYoloopArgs,Se as maybeRunDiscoveryHook,we as maybeRunGraphRetrievalHook,me as persistMigratedStateFromResponse,he as persistYoloopFromResponse,ge as readYoloopForRequest};