@ornexus/neocortex 4.60.68 → 4.60.70

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 (232) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +3 -3
  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 +3 -290
  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.d.ts +6 -0
  38. package/packages/client/dist/commands/invoke.js +142 -7140
  39. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  40. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  41. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  42. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  43. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  44. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  45. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  46. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  47. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  48. package/packages/client/dist/commands/mutation-qa.js +1 -220
  49. package/packages/client/dist/commands/native-agent.js +2 -136
  50. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  51. package/packages/client/dist/commands/planning-generation.js +1 -53
  52. package/packages/client/dist/commands/planning-memory.js +1 -40
  53. package/packages/client/dist/commands/planning-research.js +1 -42
  54. package/packages/client/dist/commands/private-session.js +1 -75
  55. package/packages/client/dist/commands/property-qa.js +1 -139
  56. package/packages/client/dist/commands/qa-control.js +1 -16
  57. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  58. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  59. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  60. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  61. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  62. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  63. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  64. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  65. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  66. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  67. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  68. package/packages/client/dist/commands/refactor-commit.js +13 -399
  69. package/packages/client/dist/commands/refactor-control.js +3 -142
  70. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  71. package/packages/client/dist/commands/refactor-review.js +5 -283
  72. package/packages/client/dist/commands/refactor-root.js +7 -588
  73. package/packages/client/dist/commands/refresh-memory.js +3 -156
  74. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  76. package/packages/client/dist/config/profile-directory.js +1 -13
  77. package/packages/client/dist/config/resolver-selection.js +1 -278
  78. package/packages/client/dist/config/secure-config.js +12 -281
  79. package/packages/client/dist/config.js +2 -223
  80. package/packages/client/dist/constants.js +1 -25
  81. package/packages/client/dist/context/context-collector.js +2 -222
  82. package/packages/client/dist/context/context-sanitizer.js +1 -145
  83. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  84. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  85. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  86. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  87. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  88. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  89. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  90. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  91. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  92. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  93. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  94. package/packages/client/dist/continuity/outbox.js +1 -117
  95. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  96. package/packages/client/dist/continuity/sqlite-store.js +81 -2536
  97. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  98. package/packages/client/dist/errors/error-messages.js +2 -228
  99. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  100. package/packages/client/dist/evidence/collector.js +1 -347
  101. package/packages/client/dist/evidence/index.js +1 -1
  102. package/packages/client/dist/evidence/types.js +0 -2
  103. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  104. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  105. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  106. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  107. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  108. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  109. package/packages/client/dist/git/git-lifecycle-store.js +9 -1938
  110. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  111. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  112. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  113. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  114. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  115. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  116. package/packages/client/dist/i18n/first-run.js +2 -60
  117. package/packages/client/dist/index.js +1 -47
  118. package/packages/client/dist/invocation/invoke-input.js +1 -24
  119. package/packages/client/dist/license/index.js +1 -5
  120. package/packages/client/dist/license/license-client.js +1 -304
  121. package/packages/client/dist/machine/fingerprint.js +2 -163
  122. package/packages/client/dist/machine/index.js +1 -5
  123. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  124. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  125. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  126. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  127. package/packages/client/dist/migrations/project-identity.js +7 -493
  128. package/packages/client/dist/migrations/state-json.js +4 -344
  129. package/packages/client/dist/policy/architecture-policy.js +2 -184
  130. package/packages/client/dist/policy/index.js +1 -7
  131. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  132. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  133. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  134. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  135. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  136. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  137. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  138. package/packages/client/dist/private-execution/delivery.js +13 -410
  139. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  140. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  141. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  142. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  143. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  144. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  145. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  146. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  147. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  148. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  149. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  150. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  151. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  152. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  153. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  154. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  155. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  156. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  157. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  158. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  159. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  160. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  161. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  162. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  163. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  164. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  165. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  166. package/packages/client/dist/private-execution/session-lease.js +1 -63
  167. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  168. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  169. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  170. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  171. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  172. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  173. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  174. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  175. package/packages/client/dist/resilience/index.js +1 -8
  176. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  177. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  178. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  179. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  180. package/packages/client/dist/runner/binary.js +1 -404
  181. package/packages/client/dist/runner/cli.js +17 -1571
  182. package/packages/client/dist/runner/headless/adapters.js +1 -49
  183. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  184. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  185. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  186. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  187. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +8 -1236
  188. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  189. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  190. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  191. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  192. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  193. package/packages/client/dist/runner/headless/resolver.js +1 -231
  194. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  195. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  196. package/packages/client/dist/runner/headless/types.js +2 -574
  197. package/packages/client/dist/runner/local-console.js +13 -396
  198. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  199. package/packages/client/dist/runner/project-identity.js +1 -106
  200. package/packages/client/dist/runner/scheduler.js +7 -995
  201. package/packages/client/dist/runner-cli.js +2 -18
  202. package/packages/client/dist/state/invocation-shape.js +1 -13
  203. package/packages/client/dist/state/project-state-snapshot.js +1 -1677
  204. package/packages/client/dist/state/state-json-repair.js +3 -785
  205. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  206. package/packages/client/dist/telemetry/index.js +1 -5
  207. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  208. package/packages/client/dist/tier/index.js +1 -5
  209. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  210. package/packages/client/dist/types/index.js +1 -38
  211. package/packages/client/dist/version.js +1 -27
  212. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  213. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  214. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -185
  215. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  216. package/packages/client/dist/yoloop/index.js +1 -8
  217. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  218. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  219. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  220. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  221. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1723
  222. package/targets-stubs/antigravity/gemini.md +1 -1
  223. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  224. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  225. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  226. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  227. package/targets-stubs/claude-code/neocortex.md +2 -2
  228. package/targets-stubs/codex/AGENTS.md +1 -1
  229. package/targets-stubs/cursor/agent.md +2 -2
  230. package/targets-stubs/gemini-cli/agent.md +2 -2
  231. package/targets-stubs/opencode/neocortex-root.md +1 -1
  232. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,785 +1,3 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * Client-owned `.neocortex/state.json` automatic repair helpers.
6
- */
7
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, copyFileSync, } from 'node:fs';
8
- import { join } from 'node:path';
9
- import { randomBytes } from 'node:crypto';
10
- import { planStateMigration, StateMigrationHardStopError, } from '../../../shared/dist/state/index.js';
11
- import { applyStateMigration, previewStateMigration, StateMigrationApplyError, } from '../migrations/state-json.js';
12
- import { readGitLifecycleRuntimeSync, verifyAcceptedGitLifecycleStoryCheckpointSync, } from '../git/git-lifecycle-store.js';
13
- export class StateRepairHardStopError extends Error {
14
- reasonCode;
15
- constructor(message, reasonCode) {
16
- super(message);
17
- this.reasonCode = reasonCode;
18
- this.name = 'StateRepairHardStopError';
19
- }
20
- }
21
- export const P189_STATE_SHAPE_GAP_CODE = 'P189-GAP-STATE-SHAPE';
22
- export const EPIC_AGGREGATE_REASON_CODES = {
23
- reconciled: 'epic_aggregate_reconciled',
24
- totalRecounted: 'epic_total_stories_recounted',
25
- completedRecounted: 'epic_completed_stories_recounted',
26
- statusPromotedDone: 'epic_status_promoted_done',
27
- completedAtSet: 'epic_completed_at_set',
28
- stateNotObject: 'epic_aggregate_state_not_object',
29
- epicsNotObject: 'epic_aggregate_epics_not_object',
30
- storiesNotObject: 'epic_aggregate_stories_not_object',
31
- scopeProjected: 'epic_aggregate_scope_projected',
32
- epicNotObject: 'epic_aggregate_epic_not_object',
33
- epicIdConflict: 'epic_aggregate_epic_id_conflict',
34
- storyListNotArray: 'epic_aggregate_story_list_not_array',
35
- storyRefInvalid: 'epic_aggregate_story_ref_invalid',
36
- storyRefDuplicate: 'epic_aggregate_story_ref_duplicate',
37
- storyMissing: 'epic_aggregate_story_missing',
38
- storyNotObject: 'epic_aggregate_story_not_object',
39
- storyIdConflict: 'epic_aggregate_story_id_conflict',
40
- storyEpicConflict: 'epic_aggregate_story_epic_conflict',
41
- terminalIncompleteConflict: 'epic_aggregate_terminal_incomplete_conflict',
42
- };
43
- const STORY_AGGREGATE_TARGET_TRIGGERS = new Set([
44
- 'yolo',
45
- 'implement',
46
- 'diagnose',
47
- 'research',
48
- 'write-spec',
49
- 'create-tasks',
50
- 'refactor-suggest',
51
- 'property-tests',
52
- 'validate-tests',
53
- 'qa-gate',
54
- 'update-project-memory',
55
- 'commit-push',
56
- 'sync-main',
57
- 'create-pr',
58
- 'review-pr',
59
- 'merge-pr',
60
- 'review',
61
- ]);
62
- const EPIC_AGGREGATE_TARGET_TRIGGERS = new Set([
63
- 'yoloop',
64
- 'auto-yolo',
65
- 'epic-runner',
66
- 'story-runner',
67
- 'loop-yolo',
68
- 'auto-epic',
69
- ]);
70
- function isPlainObject(value) {
71
- return value !== null && typeof value === 'object' && !Array.isArray(value);
72
- }
73
- function nowIso() {
74
- return new Date().toISOString();
75
- }
76
- function backupTimestamp() {
77
- return nowIso().replace(/[:.]/g, '-');
78
- }
79
- function sortedStringArray(value) {
80
- if (!Array.isArray(value))
81
- return [];
82
- return value.filter((entry) => typeof entry === 'string' && entry.length > 0);
83
- }
84
- function normalizeAggregateRepairTrigger(args) {
85
- const [firstToken] = args.trim().split(/\s+/, 1);
86
- if (!firstToken)
87
- return null;
88
- return firstToken.replace(/^@?\*/, '').replace(/^@/, '').toLowerCase();
89
- }
90
- function firstTokenIsStoryReference(args) {
91
- const [firstToken] = args.trim().split(/\s+/, 1);
92
- if (!firstToken)
93
- return false;
94
- const normalized = firstToken.replace(/^@/, '');
95
- return /^[A-Z]?\d+(?:\.\d+)+$/i.test(normalized)
96
- || /(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(normalized);
97
- }
98
- function extractStoryIdFromArgs(args) {
99
- const storyFileMatch = args.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);
100
- if (storyFileMatch?.[1])
101
- return storyFileMatch[1];
102
- const storyIdMatch = args.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i);
103
- return storyIdMatch?.[1] ?? null;
104
- }
105
- /** Materialization has no story/epic acceptance authority to replay or repair. */
106
- export function isInlineYoloMaterialization(args, canonicalCommandId) {
107
- if (typeof args !== 'string')
108
- return false;
109
- const command = canonicalCommandId ?? normalizeAggregateRepairTrigger(args);
110
- return (command === 'yolo' || command === 'yolo-inline')
111
- && triggerRemainder(args).length > 0 && extractStoryIdFromArgs(args) === null;
112
- }
113
- function triggerRemainder(args) {
114
- const trimmed = args.trim();
115
- const firstWhitespace = trimmed.search(/\s/);
116
- return firstWhitespace === -1 ? '' : trimmed.slice(firstWhitespace).trim();
117
- }
118
- function firstPositionalArg(args) {
119
- const positional = triggerRemainder(args)
120
- .split(/\s+/)
121
- .find((token) => token.length > 0 && !token.startsWith('-'));
122
- return positional ? positional.replace(/^@/, '').replace(/^['"]|['"]$/g, '') : null;
123
- }
124
- function resolveEpicId(candidate, epicsMap) {
125
- const normalized = candidate.replace(/^@/, '').replace(/^epic-/i, '');
126
- const withoutExtension = normalized.replace(/\.md$/i, '');
127
- const candidates = [
128
- withoutExtension,
129
- withoutExtension.toUpperCase(),
130
- /^p\d+$/i.test(withoutExtension)
131
- ? `P${withoutExtension.replace(/^p/i, '')}`
132
- : null,
133
- /^\d+$/.test(withoutExtension) ? `P${withoutExtension}` : null,
134
- ].filter((entry) => typeof entry === 'string' && entry.length > 0);
135
- for (const entry of candidates) {
136
- if (isPlainObject(epicsMap[entry]))
137
- return entry;
138
- }
139
- return null;
140
- }
141
- function extractEpicIdFromCanonicalFile(args, epicsMap) {
142
- const match = args.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);
143
- if (!match?.[1])
144
- return null;
145
- return resolveEpicId(match[1], epicsMap);
146
- }
147
- function inferAggregateRepairTargetEpicId(state, args, canonicalCommandId) {
148
- if (typeof args !== 'string' || args.trim().length === 0)
149
- return undefined;
150
- if (!isPlainObject(state.epics) || !isPlainObject(state.stories))
151
- return undefined;
152
- const trigger = args.trim();
153
- const normalizedTrigger = canonicalCommandId ?? normalizeAggregateRepairTrigger(trigger);
154
- const mayTargetStory = (normalizedTrigger !== null && STORY_AGGREGATE_TARGET_TRIGGERS.has(normalizedTrigger))
155
- || firstTokenIsStoryReference(trigger);
156
- if (mayTargetStory) {
157
- const storyId = extractStoryIdFromArgs(trigger);
158
- const story = storyId ? state.stories[storyId] : undefined;
159
- if (isPlainObject(story) && typeof story.epic_id === 'string' && isPlainObject(state.epics[story.epic_id])) {
160
- return story.epic_id;
161
- }
162
- // Inline *yolo materializes the story only after admission. The explicit
163
- // canonical ID still provides a safe existing-epic scope; never fall back
164
- // to reconciling unrelated epics merely because the story shell is absent.
165
- const inlineEpicId = storyId?.split('.')[0];
166
- if (inlineEpicId && isPlainObject(state.epics[inlineEpicId]))
167
- return inlineEpicId;
168
- }
169
- if (normalizedTrigger !== null && EPIC_AGGREGATE_TARGET_TRIGGERS.has(normalizedTrigger)) {
170
- const fromFile = extractEpicIdFromCanonicalFile(trigger, state.epics);
171
- if (fromFile)
172
- return fromFile;
173
- const targetArg = firstPositionalArg(trigger);
174
- if (targetArg) {
175
- const fromArg = resolveEpicId(targetArg, state.epics);
176
- if (fromArg)
177
- return fromArg;
178
- }
179
- }
180
- return undefined;
181
- }
182
- const COMPLETION_RECONCILIATION_REASON = 'pr_merged_issue_closed_reconciled';
183
- const INVALID_WORKFLOW_ISSUE_REASON = 'invalid_workflow_issue_removed';
184
- function normalizePublicStatus(value) {
185
- return typeof value === 'string' ? value.trim().toLowerCase().replace(/[_\s]+/g, '-') : '';
186
- }
187
- const DONE_LIKE_STORY_STATUSES = new Set(['done', 'completed', 'merged']);
188
- const TERMINAL_EPIC_STATUSES = new Set(['done', 'completed', 'merged']);
189
- export function isP189DoneLikeStoryStatus(value) {
190
- return DONE_LIKE_STORY_STATUSES.has(normalizePublicStatus(value));
191
- }
192
- function isP189TerminalEpicStatus(value) {
193
- return TERMINAL_EPIC_STATUSES.has(normalizePublicStatus(value));
194
- }
195
- function throwEpicAggregateHardStop(reasonCode, message) {
196
- throw new StateRepairHardStopError(`${message} (${P189_STATE_SHAPE_GAP_CODE} if this shape is intentionally new).`, reasonCode);
197
- }
198
- function cloneJsonState(state) {
199
- return JSON.parse(JSON.stringify(state));
200
- }
201
- function assertFullAggregateCoverage(state, options) {
202
- const scope = options.scope ?? state.scope;
203
- if (!isPlainObject(scope))
204
- return;
205
- const kind = typeof scope.kind === 'string' ? scope.kind : null;
206
- const omittedStoryCount = typeof scope.omittedStoryCount === 'number' ? scope.omittedStoryCount : 0;
207
- const omittedEpicCount = typeof scope.omittedEpicCount === 'number' ? scope.omittedEpicCount : 0;
208
- if (kind === 'projected' || omittedStoryCount > 0 || omittedEpicCount > 0) {
209
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.scopeProjected, '[Neocortex] state.json aggregate reconciliation stopped: projected or partial state coverage cannot prove epic aggregates.');
210
- }
211
- }
212
- function validateEpicAggregateStoryIds(epicId, storyRefs) {
213
- const storyIds = [];
214
- const seen = new Set();
215
- for (const storyRef of storyRefs) {
216
- if (typeof storyRef !== 'string' || storyRef.length === 0) {
217
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.storyRefInvalid, `[Neocortex] state.json aggregate reconciliation stopped: epic "${sanitizePublicId(epicId)}" has a non-string or empty story reference.`);
218
- }
219
- if (seen.has(storyRef)) {
220
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.storyRefDuplicate, `[Neocortex] state.json aggregate reconciliation stopped: epic "${sanitizePublicId(epicId)}" lists story "${sanitizePublicId(storyRef)}" more than once.`);
221
- }
222
- seen.add(storyRef);
223
- storyIds.push(storyRef);
224
- }
225
- return storyIds;
226
- }
227
- function validateListedStoryForEpic(epicId, storyId, storiesMap) {
228
- const story = storiesMap[storyId];
229
- if (story === undefined) {
230
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.storyMissing, `[Neocortex] state.json aggregate reconciliation stopped: epic "${sanitizePublicId(epicId)}" references missing story "${sanitizePublicId(storyId)}".`);
231
- }
232
- if (!isPlainObject(story)) {
233
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.storyNotObject, `[Neocortex] state.json aggregate reconciliation stopped: story "${sanitizePublicId(storyId)}" is not an object.`);
234
- }
235
- if (story.id !== storyId) {
236
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.storyIdConflict, `[Neocortex] state.json aggregate reconciliation stopped: story key "${sanitizePublicId(storyId)}" conflicts with its id field.`);
237
- }
238
- if (story.epic_id !== epicId) {
239
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.storyEpicConflict, `[Neocortex] state.json aggregate reconciliation stopped: story "${sanitizePublicId(storyId)}" does not belong to epic "${sanitizePublicId(epicId)}".`);
240
- }
241
- return story;
242
- }
243
- function addAggregateReason(reasonCodes, reasonCode) {
244
- if (!reasonCodes.includes(reasonCode))
245
- reasonCodes.push(reasonCode);
246
- }
247
- export function reconcileEpicAggregatesInState(input, options = {}) {
248
- if (!isPlainObject(input)) {
249
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.stateNotObject, '[Neocortex] state.json aggregate reconciliation stopped: top-level state must be an object.');
250
- }
251
- if (!isPlainObject(input.epics)) {
252
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.epicsNotObject, '[Neocortex] state.json aggregate reconciliation stopped: `epics` must be an object before counts are authoritative.');
253
- }
254
- if (!isPlainObject(input.stories)) {
255
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.storiesNotObject, '[Neocortex] state.json aggregate reconciliation stopped: `stories` must be an object before counts are authoritative.');
256
- }
257
- assertFullAggregateCoverage(input, options);
258
- const migrated = cloneJsonState(input);
259
- const epicsMap = migrated.epics;
260
- const storiesMap = migrated.stories;
261
- const allReasonCodes = [];
262
- const changes = [];
263
- const effectiveDoneStoryIds = new Set(options.effectiveDoneStoryIds ?? []);
264
- for (const [epicId, epic] of Object.entries(epicsMap)) {
265
- if (options.targetEpicId && epicId !== options.targetEpicId)
266
- continue;
267
- if (!isPlainObject(epic)) {
268
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.epicNotObject, `[Neocortex] state.json aggregate reconciliation stopped: epic "${sanitizePublicId(epicId)}" is not an object.`);
269
- }
270
- if (epic.id !== epicId) {
271
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.epicIdConflict, `[Neocortex] state.json aggregate reconciliation stopped: epic key "${sanitizePublicId(epicId)}" conflicts with its id field.`);
272
- }
273
- if (!Array.isArray(epic.stories)) {
274
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.storyListNotArray, `[Neocortex] state.json aggregate reconciliation stopped: epic "${sanitizePublicId(epicId)}" has non-array stories.`);
275
- }
276
- const storyIds = validateEpicAggregateStoryIds(epicId, epic.stories);
277
- const totalStories = storyIds.length;
278
- const completedStories = storyIds.filter((storyId) => {
279
- const story = validateListedStoryForEpic(epicId, storyId, storiesMap);
280
- return isP189DoneLikeStoryStatus(story.status) || effectiveDoneStoryIds.has(storyId);
281
- }).length;
282
- const allListedStoriesDoneLike = totalStories > 0 && completedStories === totalStories;
283
- if (isP189TerminalEpicStatus(epic.status) && !allListedStoriesDoneLike && totalStories > 0) {
284
- throwEpicAggregateHardStop(EPIC_AGGREGATE_REASON_CODES.terminalIncompleteConflict, `[Neocortex] state.json aggregate reconciliation stopped: terminal epic "${sanitizePublicId(epicId)}" has incomplete listed stories.`);
285
- }
286
- // Derived counts/status must not dirty the epic branch after its atomic story
287
- // commit. Keep all ownership/coverage/terminal-conflict validation above;
288
- // the verified runtime overlay and server projection own effective counts.
289
- if (options.preserveGitLifecycleAggregates
290
- && (epic.branch_mode === 'epic' || typeof epic.execution_branch === 'string'))
291
- continue;
292
- const perEpicReasons = [];
293
- const previous = {
294
- total_stories: epic.total_stories,
295
- completed_stories: epic.completed_stories,
296
- status: epic.status,
297
- completed_at: epic.completed_at,
298
- };
299
- if (epic.total_stories !== totalStories) {
300
- epic.total_stories = totalStories;
301
- addAggregateReason(perEpicReasons, EPIC_AGGREGATE_REASON_CODES.totalRecounted);
302
- }
303
- if (epic.completed_stories !== completedStories) {
304
- epic.completed_stories = completedStories;
305
- addAggregateReason(perEpicReasons, EPIC_AGGREGATE_REASON_CODES.completedRecounted);
306
- }
307
- const shouldPromote = !isP189TerminalEpicStatus(epic.status) && allListedStoriesDoneLike;
308
- if (shouldPromote) {
309
- epic.status = 'done';
310
- addAggregateReason(perEpicReasons, EPIC_AGGREGATE_REASON_CODES.statusPromotedDone);
311
- if (epic.completed_at === undefined || epic.completed_at === null) {
312
- epic.completed_at = options.nowIso ?? nowIso();
313
- addAggregateReason(perEpicReasons, EPIC_AGGREGATE_REASON_CODES.completedAtSet);
314
- }
315
- }
316
- if (perEpicReasons.length > 0) {
317
- addAggregateReason(perEpicReasons, EPIC_AGGREGATE_REASON_CODES.reconciled);
318
- for (const reasonCode of perEpicReasons)
319
- addAggregateReason(allReasonCodes, reasonCode);
320
- changes.push({
321
- epicId,
322
- reasonCodes: perEpicReasons,
323
- previous,
324
- next: {
325
- total_stories: totalStories,
326
- completed_stories: completedStories,
327
- status: epic.status,
328
- completed_at: epic.completed_at,
329
- },
330
- });
331
- }
332
- }
333
- return {
334
- mutated: JSON.stringify(migrated) !== JSON.stringify(input),
335
- state: migrated,
336
- reasonCodes: allReasonCodes,
337
- changes,
338
- };
339
- }
340
- function nestedRecord(input, key) {
341
- const value = input[key];
342
- return isPlainObject(value) ? value : null;
343
- }
344
- function hasIssueClosedEvidence(story) {
345
- const audit = nestedRecord(story, 'issueCloseAudit') ?? nestedRecord(story, 'issue_close_audit');
346
- if (audit) {
347
- const event = normalizePublicStatus(audit.event).replace(/-/g, '_');
348
- const publicSafe = audit.publicSafe === true || audit.public_safe === true;
349
- const rawLogForbidden = audit.rawLogStorage === 'forbidden' || audit.raw_log_storage === 'forbidden';
350
- if (event === 'story_issue_closed' && publicSafe && rawLogForbidden)
351
- return true;
352
- }
353
- const completion = nestedRecord(story, 'completionEvidence') ?? nestedRecord(story, 'completion_evidence');
354
- const completionIssueState = normalizePublicStatus(completion?.issueState ?? completion?.issue_state ?? completion?.state);
355
- return story.issue_closed === true
356
- || normalizePublicStatus(story.issue_state ?? story.issueState ?? story.workflow_issue_state) === 'closed'
357
- || completionIssueState === 'closed';
358
- }
359
- function hasPrMergedEvidence(story) {
360
- const completion = nestedRecord(story, 'completionEvidence') ?? nestedRecord(story, 'completion_evidence');
361
- const scopedCi = nestedRecord(story, 'scopedCiEvidence') ?? nestedRecord(story, 'scoped_ci_evidence');
362
- const states = [
363
- story.physicalMergeStatus,
364
- story.pr_state,
365
- story.prState,
366
- story.pull_request_state,
367
- story.pullRequestState,
368
- completion?.prState,
369
- completion?.pr_state,
370
- completion?.pullRequestState,
371
- scopedCi?.prState,
372
- ].map(normalizePublicStatus);
373
- return story.merged === true
374
- || states.includes('merged')
375
- || normalizePublicStatus(scopedCi?.finalState) === 'can-merge' && story.merged === true;
376
- }
377
- function hasConflictingCompletionEvidence(story) {
378
- const completion = nestedRecord(story, 'completionEvidence') ?? nestedRecord(story, 'completion_evidence');
379
- const states = [
380
- story.pr_state,
381
- story.prState,
382
- story.pull_request_state,
383
- story.pullRequestState,
384
- completion?.prState,
385
- completion?.pr_state,
386
- completion?.pullRequestState,
387
- ].map(normalizePublicStatus);
388
- const mergedSignal = hasPrMergedEvidence(story);
389
- const deniedSignal = ['denied-external-gate', 'denied-local-or-repo', 'not-attempted'].includes(normalizePublicStatus(story.physicalMergeStatus));
390
- const closedWithoutMergeSignal = states.includes('closed') || states.includes('closed-unmerged');
391
- return (mergedSignal && (story.merged === false || deniedSignal || closedWithoutMergeSignal))
392
- || (story.merged === true && deniedSignal);
393
- }
394
- function upsertCompletionDebt(existing, storyId, reconciledAt) {
395
- const id = `state-completion-reconciliation:${sanitizePublicId(storyId)}`;
396
- const next = existing.filter(isPlainObject).map((entry) => ({ ...entry }));
397
- const incoming = {
398
- id,
399
- status: 'open',
400
- reason: 'stale_state_completion_evidence_observed',
401
- reason_codes: [COMPLETION_RECONCILIATION_REASON],
402
- category: 'state/completion-reconciliation',
403
- story_id: sanitizePublicId(storyId),
404
- public_safe: true,
405
- raw_log_storage: 'forbidden',
406
- created_at: reconciledAt,
407
- last_seen_at: reconciledAt,
408
- occurrences: 1,
409
- };
410
- const index = next.findIndex((entry) => entry.id === id);
411
- if (index < 0)
412
- return [...next, incoming];
413
- const current = next[index];
414
- next[index] = {
415
- ...current,
416
- ...incoming,
417
- created_at: typeof current.created_at === 'string' ? current.created_at : reconciledAt,
418
- occurrences: Math.max(1, typeof current.occurrences === 'number' ? current.occurrences : 1) + 1,
419
- };
420
- return next;
421
- }
422
- function reconcileCompletionEvidence(migrated, changes, reasonCodes, targetEpicId) {
423
- const storiesMap = isPlainObject(migrated.stories) ? migrated.stories : null;
424
- if (!storiesMap)
425
- return;
426
- const reconciliations = [];
427
- const reconciledAt = nowIso();
428
- for (const [storyId, story] of Object.entries(storiesMap)) {
429
- if (!isPlainObject(story))
430
- continue;
431
- const storyEpicId = typeof story.epic_id === 'string' ? story.epic_id : storyId.split('.')[0];
432
- if (targetEpicId && storyEpicId !== targetEpicId)
433
- continue;
434
- const status = normalizePublicStatus(story.status);
435
- if (hasConflictingCompletionEvidence(story)) {
436
- throw new StateRepairHardStopError(`[Neocortex] state.json repair stopped: story "${storyId}" has conflicting PR merge completion evidence. ` +
437
- 'Resolve .neocortex/state.json manually before invoking Neocortex.', 'conflicting_completion_evidence');
438
- }
439
- if (status !== 'pr-reviewed')
440
- continue;
441
- if (!hasPrMergedEvidence(story) || !hasIssueClosedEvidence(story))
442
- continue;
443
- const previousStatus = typeof story.status === 'string' ? story.status : status;
444
- const stepsCompleted = sortedStringArray(story.steps_completed);
445
- story.status = 'done';
446
- story.last_step = 'step-c-12-merge-pr';
447
- story.steps_completed = Array.from(new Set([...stepsCompleted, 'step-c-12-merge-pr']));
448
- story.merged = true;
449
- story.physicalMergeStatus = 'merged';
450
- story.completion_reconciled_at = reconciledAt;
451
- changes.push(`reconciled completion evidence for story ${storyId}`);
452
- reasonCodes.push(COMPLETION_RECONCILIATION_REASON);
453
- reconciliations.push({
454
- schemaVersion: 1,
455
- publicSafe: true,
456
- rawLogStorage: 'forbidden',
457
- storyId: sanitizePublicId(storyId),
458
- previousStatus,
459
- nextStatus: 'done',
460
- reasonCodes: [COMPLETION_RECONCILIATION_REASON],
461
- reconciledAt,
462
- });
463
- migrated.state_repair_debt = upsertCompletionDebt(Array.isArray(migrated.state_repair_debt) ? migrated.state_repair_debt : [], storyId, reconciledAt);
464
- }
465
- if (reconciliations.length > 0) {
466
- migrated.state_completion_reconciliations = [
467
- ...(Array.isArray(migrated.state_completion_reconciliations) ? migrated.state_completion_reconciliations.filter(isPlainObject) : []),
468
- ...reconciliations,
469
- ];
470
- }
471
- }
472
- function removeInvalidWorkflowIssues(migrated, changes, reasonCodes) {
473
- const storiesMap = isPlainObject(migrated.stories) ? migrated.stories : null;
474
- if (!storiesMap)
475
- return;
476
- for (const [storyId, story] of Object.entries(storiesMap)) {
477
- if (!isPlainObject(story) || !Object.prototype.hasOwnProperty.call(story, 'workflow_issue'))
478
- continue;
479
- if (typeof story.workflow_issue === 'number' && Number.isFinite(story.workflow_issue))
480
- continue;
481
- delete story.workflow_issue;
482
- changes.push(`removed invalid workflow_issue from story ${sanitizePublicId(storyId)}`);
483
- reasonCodes.push(INVALID_WORKFLOW_ISSUE_REASON);
484
- }
485
- }
486
- function repairStateObject(input, options = {}) {
487
- if (Array.isArray(input.stories)) {
488
- throw new StateRepairHardStopError('[Neocortex] state.json repair stopped: `stories` is an Array. Convert it to an object keyed by story ID or run `*migrate-state --preview` for guidance.', 'stories_array_ambiguous');
489
- }
490
- if (isPlainObject(input.epics)) {
491
- for (const [epicId, epic] of Object.entries(input.epics)) {
492
- if (isPlainObject(epic) && epic.stories !== undefined && !Array.isArray(epic.stories)) {
493
- throw new StateRepairHardStopError(`[Neocortex] state.json repair stopped: epic "${epicId}" has non-array \`stories\`. Repair this ambiguous shape manually before invoking Neocortex.`, 'epic_stories_not_array');
494
- }
495
- }
496
- }
497
- if (input.schema_version !== undefined && input.schema_version !== 0 && input.schema_version !== 1) {
498
- throw new StateRepairHardStopError(`[Neocortex] state.json repair stopped: schema_version=${String(input.schema_version)} is not a safe automatic downgrade target. ` +
499
- 'Run `*migrate-state --preview` or repair the schema version manually.', 'unsupported_schema_version');
500
- }
501
- // Preserve the complete tracked state during targetless materialization.
502
- // Structural corruption above still fails closed; targeted execution keeps
503
- // its normal repair and physical checkpoint validation below.
504
- if (isInlineYoloMaterialization(options.args, options.canonicalCommandId)) {
505
- // No historical reconciliation here, but appending a new story must not
506
- // reinterpret a malformed map or overwrite a record with conflicting ID.
507
- for (const key of ['epics', 'stories']) {
508
- const collection = input[key];
509
- if (collection === undefined)
510
- continue;
511
- if (!isPlainObject(collection))
512
- throw new StateRepairHardStopError('[Neocortex] inline materialization stopped: invalid state collection.', 'inline_state_collection_invalid');
513
- for (const [id, record] of Object.entries(collection)) {
514
- if (!isPlainObject(record))
515
- throw new StateRepairHardStopError('[Neocortex] inline materialization stopped: invalid state record.', 'inline_state_record_invalid');
516
- if (record.id !== undefined && record.id !== id)
517
- throw new StateRepairHardStopError('[Neocortex] inline materialization stopped: conflicting state identity.', 'inline_state_identity_conflict');
518
- }
519
- }
520
- return { mutated: false, state: input, reasonCodes: [], changes: [] };
521
- }
522
- let migrationDecision;
523
- try {
524
- migrationDecision = planStateMigration(input);
525
- }
526
- catch (error) {
527
- if (error instanceof StateMigrationHardStopError) {
528
- throw new StateRepairHardStopError(`[Neocortex] state.json repair stopped by shared migration planner: ${error.message}`, error.reasonCode);
529
- }
530
- throw error;
531
- }
532
- let migrated = JSON.parse(JSON.stringify(migrationDecision.kind === 'migrate' ? migrationDecision.plan.targetState : input));
533
- const changes = migrationDecision.kind === 'migrate'
534
- ? migrationDecision.plan.steps.map((operation) => `shared migration ${operation.kind}: ${operation.target}`)
535
- : [];
536
- const reasonCodes = migrationDecision.kind === 'migrate' ? ['state_migration_shared_plan'] : [];
537
- let aggregateChanges = [];
538
- const targetEpicId = inferAggregateRepairTargetEpicId(migrated, options.args, options.canonicalCommandId);
539
- removeInvalidWorkflowIssues(migrated, changes, reasonCodes);
540
- reconcileCompletionEvidence(migrated, changes, reasonCodes, targetEpicId);
541
- if (typeof options.args === 'string') {
542
- const aggregateRepair = reconcileEpicAggregatesInState(migrated, {
543
- nowIso: options.nowIso,
544
- targetEpicId,
545
- effectiveDoneStoryIds: options.effectiveDoneStoryIds,
546
- preserveGitLifecycleAggregates: true,
547
- });
548
- if (aggregateRepair.mutated) {
549
- migrated = aggregateRepair.state;
550
- aggregateChanges = aggregateRepair.changes;
551
- for (const reasonCode of aggregateRepair.reasonCodes)
552
- reasonCodes.push(reasonCode);
553
- for (const change of aggregateRepair.changes) {
554
- changes.push(`reconciled aggregate for epic ${sanitizePublicId(change.epicId)}`);
555
- }
556
- }
557
- }
558
- const mutated = JSON.stringify(migrated) !== JSON.stringify(input);
559
- if (mutated) {
560
- const repairedAt = options.nowIso ?? nowIso();
561
- const uniqueReasonCodes = Array.from(new Set(reasonCodes));
562
- if (aggregateChanges.length > 0) {
563
- appendAggregateReconciliationAudit(migrated, aggregateChanges, repairedAt);
564
- }
565
- migrated.last_updated = repairedAt;
566
- migrated.state_migration_repairs = [
567
- ...(Array.isArray(migrated.state_migration_repairs) ? migrated.state_migration_repairs : []),
568
- {
569
- schemaVersion: 1,
570
- action: 'client_auto_repair',
571
- reasonCodes: uniqueReasonCodes,
572
- repairedAt,
573
- },
574
- ];
575
- migrated.state_repair_debt = upsertStateRepairDebt(Array.isArray(migrated.state_repair_debt) ? migrated.state_repair_debt : [], uniqueReasonCodes, repairedAt);
576
- }
577
- return {
578
- mutated,
579
- state: migrated,
580
- reasonCodes: Array.from(new Set(reasonCodes)),
581
- changes,
582
- };
583
- }
584
- function safeAggregateCount(value) {
585
- return typeof value === 'number' && Number.isFinite(value) ? value : null;
586
- }
587
- function safeAggregateStatus(value) {
588
- const normalized = normalizePublicStatus(value);
589
- return normalized.length > 0 ? sanitizePublicText(normalized).slice(0, 80) : null;
590
- }
591
- function aggregateAuditEntry(change, repairedAt) {
592
- return {
593
- schemaVersion: 1,
594
- publicSafe: true,
595
- epicId: sanitizePublicId(change.epicId),
596
- reasonCodes: change.reasonCodes.map(sanitizePublicText).filter(Boolean),
597
- previous: {
598
- total_stories: safeAggregateCount(change.previous.total_stories),
599
- completed_stories: safeAggregateCount(change.previous.completed_stories),
600
- status: safeAggregateStatus(change.previous.status),
601
- completed_at_present: typeof change.previous.completed_at === 'string' && change.previous.completed_at.length > 0,
602
- },
603
- next: {
604
- total_stories: change.next.total_stories,
605
- completed_stories: change.next.completed_stories,
606
- status: safeAggregateStatus(change.next.status),
607
- completed_at_present: typeof change.next.completed_at === 'string' && change.next.completed_at.length > 0,
608
- },
609
- repairedAt,
610
- };
611
- }
612
- function upsertAggregateRepairDebt(existing, changes, repairedAt) {
613
- let next = existing
614
- .filter(isPlainObject)
615
- .map((entry) => ({ ...entry }));
616
- for (const change of changes) {
617
- const epicId = sanitizePublicId(change.epicId);
618
- const reasonCodes = Array.from(new Set(change.reasonCodes.map(sanitizePublicText).filter(Boolean))).sort();
619
- const id = `state-aggregate-reconciliation:${epicId}`;
620
- const incoming = {
621
- id,
622
- status: 'open',
623
- reason: 'epic_aggregate_reconciled',
624
- reason_codes: reasonCodes,
625
- category: 'state/epic-aggregate-reconciliation',
626
- epic_id: epicId,
627
- created_at: repairedAt,
628
- last_seen_at: repairedAt,
629
- occurrences: 1,
630
- };
631
- const index = next.findIndex((entry) => entry.id === id);
632
- if (index < 0) {
633
- next = [...next, incoming];
634
- continue;
635
- }
636
- const current = next[index];
637
- next[index] = {
638
- ...current,
639
- ...incoming,
640
- created_at: typeof current.created_at === 'string' ? current.created_at : repairedAt,
641
- occurrences: Math.max(1, typeof current.occurrences === 'number' ? current.occurrences : 1) + 1,
642
- };
643
- }
644
- return next;
645
- }
646
- function appendAggregateReconciliationAudit(migrated, changes, repairedAt) {
647
- migrated.state_aggregate_reconciliations = [
648
- ...(Array.isArray(migrated.state_aggregate_reconciliations)
649
- ? migrated.state_aggregate_reconciliations.filter(isPlainObject)
650
- : []),
651
- ...changes.map((change) => aggregateAuditEntry(change, repairedAt)),
652
- ];
653
- migrated.state_repair_debt = upsertAggregateRepairDebt(Array.isArray(migrated.state_repair_debt) ? migrated.state_repair_debt : [], changes, repairedAt);
654
- }
655
- function upsertStateRepairDebt(existing, reasonCodes, repairedAt) {
656
- const safeCodes = Array.from(new Set(reasonCodes.map(sanitizePublicText).filter(Boolean))).sort();
657
- const id = `state-drift-repair:${safeCodes.join('+') || 'unknown'}`;
658
- const next = existing
659
- .filter(isPlainObject)
660
- .map((entry) => ({ ...entry }));
661
- const incoming = {
662
- id,
663
- status: 'open',
664
- reason: 'state_json_drift_repaired',
665
- reason_codes: safeCodes,
666
- category: 'state/drift-repair',
667
- created_at: repairedAt,
668
- last_seen_at: repairedAt,
669
- occurrences: 1,
670
- };
671
- const index = next.findIndex((entry) => entry.id === id);
672
- if (index < 0)
673
- return [...next, incoming];
674
- const current = next[index];
675
- next[index] = {
676
- ...current,
677
- ...incoming,
678
- created_at: typeof current.created_at === 'string' ? current.created_at : repairedAt,
679
- occurrences: Math.max(1, typeof current.occurrences === 'number' ? current.occurrences : 1) + 1,
680
- };
681
- return next;
682
- }
683
- function sanitizePublicText(value) {
684
- return value
685
- .replace(/\b(sk|ghp|gho|github_pat|xoxb|AKIA)[A-Za-z0-9_-]{8,}\b/g, '[redacted]')
686
- .replace(/(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^,\s)]+/gi, '$1=[redacted]')
687
- .replace(/https?:\/\/[^\s)]+/gi, '[url-redacted]')
688
- .replace(/[^a-z0-9_+-]+/gi, '_')
689
- .replace(/^_+|_+$/g, '')
690
- .slice(0, 120);
691
- }
692
- function sanitizePublicId(value) {
693
- return value.replace(/[^a-z0-9_.:-]+/gi, '_').replace(/^_+|_+$/g, '').slice(0, 120) || 'unknown';
694
- }
695
- export function maybeRepairStateJsonBeforeInvoke(projectRoot, options = {}) {
696
- const stateDir = join(projectRoot, '.neocortex');
697
- const statePath = join(stateDir, 'state.json');
698
- if (!existsSync(statePath)) {
699
- return { repaired: false, reasonCodes: [], changes: [] };
700
- }
701
- let migrationReceipt;
702
- if (!isInlineYoloMaterialization(options.args, options.canonicalCommandId)) {
703
- try {
704
- const plan = previewStateMigration(projectRoot);
705
- if (plan)
706
- migrationReceipt = applyStateMigration(projectRoot, plan);
707
- }
708
- catch (error) {
709
- const reasonCode = error instanceof StateMigrationApplyError ? error.reasonCode : 'state_migration_apply_failed';
710
- throw new StateRepairHardStopError(`[Neocortex] state.json migration stopped before invoke: ${error instanceof Error ? error.message : String(error)}. No unverified state was used.`, reasonCode);
711
- }
712
- }
713
- let parsed;
714
- try {
715
- parsed = JSON.parse(readFileSync(statePath, 'utf8'));
716
- }
717
- catch (err) {
718
- const msg = err instanceof Error ? err.message : String(err);
719
- throw new StateRepairHardStopError(`[Neocortex] state.json repair stopped: invalid JSON in .neocortex/state.json (${msg}). No files were overwritten. Fix the JSON or restore a backup, then rerun.`, 'invalid_json');
720
- }
721
- if (!isPlainObject(parsed)) {
722
- throw new StateRepairHardStopError('[Neocortex] state.json repair stopped: top-level state must be a JSON object. Restore a valid .neocortex/state.json before invoking Neocortex.', 'state_not_object');
723
- }
724
- const targetEpicId = inferAggregateRepairTargetEpicId(parsed, options.args, options.canonicalCommandId);
725
- const effectiveDoneStoryIds = isInlineYoloMaterialization(options.args, options.canonicalCommandId)
726
- ? [] : collectPhysicallyVerifiedRuntimeDoneStories(projectRoot, parsed, targetEpicId);
727
- const repair = repairStateObject(parsed, { ...options, effectiveDoneStoryIds });
728
- if (!repair.mutated) {
729
- if (!migrationReceipt)
730
- return { repaired: false, reasonCodes: [], changes: [] };
731
- return {
732
- repaired: true,
733
- reasonCodes: ['state_migration_transaction_applied'],
734
- backupPath: migrationReceipt.backupHash
735
- ? `.neocortex/state.json.migration-backup-${migrationReceipt.operationId}`
736
- : undefined,
737
- changes: [`shared state migration ${migrationReceipt.outcome}`],
738
- };
739
- }
740
- mkdirSync(stateDir, { recursive: true });
741
- const ts = backupTimestamp();
742
- const backupPath = join(stateDir, `state.json.backup-${ts}`);
743
- const tmpPath = join(stateDir, `state.json.tmp.${randomBytes(6).toString('hex')}`);
744
- copyFileSync(statePath, backupPath);
745
- writeFileSync(tmpPath, `${JSON.stringify(repair.state, null, 2)}\n`, 'utf8');
746
- renameSync(tmpPath, statePath);
747
- const publicBackupPath = `.neocortex/state.json.backup-${ts}`;
748
- process.stderr.write(`[Neocortex P156.05] state.json auto-repaired before invoke; backup=${publicBackupPath}; reasonCodes=${repair.reasonCodes.join(',')}; changes=${repair.changes.join('; ')}\n`);
749
- return {
750
- repaired: true,
751
- reasonCodes: repair.reasonCodes,
752
- backupPath: publicBackupPath,
753
- changes: repair.changes,
754
- };
755
- }
756
- /**
757
- * The tracked file cannot contain post-commit checkpoint truth without changing
758
- * the commit it proves. Count only sidecar `done` overlays whose checkpoint can
759
- * be recomputed from the current repository, and never copy that overlay into
760
- * the tracked story document.
761
- */
762
- function collectPhysicallyVerifiedRuntimeDoneStories(projectRoot, tracked, targetEpicId) {
763
- const runtime = readGitLifecycleRuntimeSync(projectRoot);
764
- const trackedEpics = isPlainObject(tracked.epics) ? tracked.epics : {};
765
- const trackedStories = isPlainObject(tracked.stories) ? tracked.stories : {};
766
- const verified = [];
767
- for (const [storyId, overlay] of Object.entries(runtime.stories)) {
768
- if (!isPlainObject(overlay) || !isP189DoneLikeStoryStatus(overlay.status) || !overlay.checkpoint)
769
- continue;
770
- const story = isPlainObject(trackedStories[storyId]) ? trackedStories[storyId] : null;
771
- const epicId = typeof story?.epic_id === 'string' ? story.epic_id : storyId.split('.')[0];
772
- if (!epicId || targetEpicId && epicId !== targetEpicId)
773
- continue;
774
- const trackedEpic = isPlainObject(trackedEpics[epicId]) ? trackedEpics[epicId] : null;
775
- const runtimeEpic = isPlainObject(runtime.epics[epicId]) ? runtime.epics[epicId] : null;
776
- const branchMode = runtimeEpic?.branch_mode ?? trackedEpic?.branch_mode;
777
- const executionBranch = runtimeEpic?.execution_branch ?? trackedEpic?.execution_branch;
778
- if (branchMode !== 'epic' || typeof executionBranch !== 'string')
779
- continue;
780
- const receipt = verifyAcceptedGitLifecycleStoryCheckpointSync(projectRoot, overlay.checkpoint, storyId, epicId, executionBranch);
781
- if (receipt.verdict === 'verified')
782
- verified.push(storyId);
783
- }
784
- return verified.sort();
785
- }
1
+ import{existsSync as F,mkdirSync as J,readFileSync as q,renameSync as B,writeFileSync as H,copyFileSync as W}from"node:fs";import{join as x}from"node:path";import{randomBytes as V}from"node:crypto";import{planStateMigration as Z,StateMigrationHardStopError as U}from"../../../shared/dist/state/index.js";import{applyStateMigration as K,previewStateMigration as Y,StateMigrationApplyError as Q}from"../migrations/state-json.js";import{readGitLifecycleRuntimeSync as X,verifyAcceptedGitLifecycleStoryCheckpointSync as ee}from"../git/git-lifecycle-store.js";class S extends Error{reasonCode;constructor(t,o){super(t),this.reasonCode=o,this.name="StateRepairHardStopError"}}const te="P189-GAP-STATE-SHAPE",f={reconciled:"epic_aggregate_reconciled",totalRecounted:"epic_total_stories_recounted",completedRecounted:"epic_completed_stories_recounted",statusPromotedDone:"epic_status_promoted_done",completedAtSet:"epic_completed_at_set",stateNotObject:"epic_aggregate_state_not_object",epicsNotObject:"epic_aggregate_epics_not_object",storiesNotObject:"epic_aggregate_stories_not_object",scopeProjected:"epic_aggregate_scope_projected",epicNotObject:"epic_aggregate_epic_not_object",epicIdConflict:"epic_aggregate_epic_id_conflict",storyListNotArray:"epic_aggregate_story_list_not_array",storyRefInvalid:"epic_aggregate_story_ref_invalid",storyRefDuplicate:"epic_aggregate_story_ref_duplicate",storyMissing:"epic_aggregate_story_missing",storyNotObject:"epic_aggregate_story_not_object",storyIdConflict:"epic_aggregate_story_id_conflict",storyEpicConflict:"epic_aggregate_story_epic_conflict",terminalIncompleteConflict:"epic_aggregate_terminal_incomplete_conflict"},oe=new Set(["yolo","implement","diagnose","research","write-spec","create-tasks","refactor-suggest","property-tests","validate-tests","qa-gate","update-project-memory","commit-push","sync-main","create-pr","review-pr","merge-pr","review"]),re=new Set(["yoloop","auto-yolo","epic-runner","story-runner","loop-yolo","auto-epic"]);function d(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function j(){return new Date().toISOString()}function ne(){return j().replace(/[:.]/g,"-")}function ie(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function k(e){const[t]=e.trim().split(/\s+/,1);return t?t.replace(/^@?\*/,"").replace(/^@/,"").toLowerCase():null}function se(e){const[t]=e.trim().split(/\s+/,1);if(!t)return!1;const o=t.replace(/^@/,"");return/^[A-Z]?\d+(?:\.\d+)+$/i.test(o)||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(o)}function R(e){const t=e.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return t?.[1]?t[1]:e.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function I(e,t){if(typeof e!="string")return!1;const o=t??k(e);return(o==="yolo"||o==="yolo-inline")&&$(e).length>0&&R(e)===null}function $(e){const t=e.trim(),o=t.search(/\s/);return o===-1?"":t.slice(o).trim()}function ce(e){const t=$(e).split(/\s+/).find(o=>o.length>0&&!o.startsWith("-"));return t?t.replace(/^@/,"").replace(/^['"]|['"]$/g,""):null}function O(e,t){const r=e.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),s=[r,r.toUpperCase(),/^p\d+$/i.test(r)?`P${r.replace(/^p/i,"")}`:null,/^\d+$/.test(r)?`P${r}`:null].filter(c=>typeof c=="string"&&c.length>0);for(const c of s)if(d(t[c]))return c;return null}function ae(e,t){const o=e.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return o?.[1]?O(o[1],t):null}function P(e,t,o){if(typeof t!="string"||t.trim().length===0||!d(e.epics)||!d(e.stories))return;const r=t.trim(),s=o??k(r);if(s!==null&&oe.has(s)||se(r)){const l=R(r),a=l?e.stories[l]:void 0;if(d(a)&&typeof a.epic_id=="string"&&d(e.epics[a.epic_id]))return a.epic_id;const n=l?.split(".")[0];if(n&&d(e.epics[n]))return n}if(s!==null&&re.has(s)){const l=ae(r,e.epics);if(l)return l;const a=ce(r);if(a){const n=O(a,e.epics);if(n)return n}}}const E="pr_merged_issue_closed_reconciled",pe="invalid_workflow_issue_removed";function b(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}const le=new Set(["done","completed","merged"]),de=new Set(["done","completed","merged"]);function T(e){return le.has(b(e))}function M(e){return de.has(b(e))}function h(e,t){throw new S(`${t} (${te} if this shape is intentionally new).`,e)}function ue(e){return JSON.parse(JSON.stringify(e))}function fe(e,t){const o=t.scope??e.scope;if(!d(o))return;const r=typeof o.kind=="string"?o.kind:null,s=typeof o.omittedStoryCount=="number"?o.omittedStoryCount:0,c=typeof o.omittedEpicCount=="number"?o.omittedEpicCount:0;(r==="projected"||s>0||c>0)&&h(f.scopeProjected,"[Neocortex] state.json aggregate reconciliation stopped: projected or partial state coverage cannot prove epic aggregates.")}function ge(e,t){const o=[],r=new Set;for(const s of t)(typeof s!="string"||s.length===0)&&h(f.storyRefInvalid,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" has a non-string or empty story reference.`),r.has(s)&&h(f.storyRefDuplicate,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" lists story "${u(s)}" more than once.`),r.add(s),o.push(s);return o}function _e(e,t,o){const r=o[t];return r===void 0&&h(f.storyMissing,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" references missing story "${u(t)}".`),d(r)||h(f.storyNotObject,`[Neocortex] state.json aggregate reconciliation stopped: story "${u(t)}" is not an object.`),r.id!==t&&h(f.storyIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: story key "${u(t)}" conflicts with its id field.`),r.epic_id!==e&&h(f.storyEpicConflict,`[Neocortex] state.json aggregate reconciliation stopped: story "${u(t)}" does not belong to epic "${u(e)}".`),r}function v(e,t){e.includes(t)||e.push(t)}function me(e,t={}){d(e)||h(f.stateNotObject,"[Neocortex] state.json aggregate reconciliation stopped: top-level state must be an object."),d(e.epics)||h(f.epicsNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `epics` must be an object before counts are authoritative."),d(e.stories)||h(f.storiesNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `stories` must be an object before counts are authoritative."),fe(e,t);const o=ue(e),r=o.epics,s=o.stories,c=[],l=[],a=new Set(t.effectiveDoneStoryIds??[]);for(const[n,i]of Object.entries(r)){if(t.targetEpicId&&n!==t.targetEpicId)continue;d(i)||h(f.epicNotObject,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(n)}" is not an object.`),i.id!==n&&h(f.epicIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: epic key "${u(n)}" conflicts with its id field.`),Array.isArray(i.stories)||h(f.storyListNotArray,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(n)}" has non-array stories.`);const p=ge(n,i.stories),g=p.length,m=p.filter(A=>{const z=_e(n,A,s);return T(z.status)||a.has(A)}).length,_=g>0&&m===g;if(M(i.status)&&!_&&g>0&&h(f.terminalIncompleteConflict,`[Neocortex] state.json aggregate reconciliation stopped: terminal epic "${u(n)}" has incomplete listed stories.`),t.preserveGitLifecycleAggregates&&(i.branch_mode==="epic"||typeof i.execution_branch=="string"))continue;const y=[],N={total_stories:i.total_stories,completed_stories:i.completed_stories,status:i.status,completed_at:i.completed_at};if(i.total_stories!==g&&(i.total_stories=g,v(y,f.totalRecounted)),i.completed_stories!==m&&(i.completed_stories=m,v(y,f.completedRecounted)),!M(i.status)&&_&&(i.status="done",v(y,f.statusPromotedDone),(i.completed_at===void 0||i.completed_at===null)&&(i.completed_at=t.nowIso??j(),v(y,f.completedAtSet))),y.length>0){v(y,f.reconciled);for(const A of y)v(c,A);l.push({epicId:n,reasonCodes:y,previous:N,next:{total_stories:g,completed_stories:m,status:i.status,completed_at:i.completed_at}})}}return{mutated:JSON.stringify(o)!==JSON.stringify(e),state:o,reasonCodes:c,changes:l}}function w(e,t){const o=e[t];return d(o)?o:null}function ye(e){const t=w(e,"issueCloseAudit")??w(e,"issue_close_audit");if(t){const s=b(t.event).replace(/-/g,"_"),c=t.publicSafe===!0||t.public_safe===!0,l=t.rawLogStorage==="forbidden"||t.raw_log_storage==="forbidden";if(s==="story_issue_closed"&&c&&l)return!0}const o=w(e,"completionEvidence")??w(e,"completion_evidence"),r=b(o?.issueState??o?.issue_state??o?.state);return e.issue_closed===!0||b(e.issue_state??e.issueState??e.workflow_issue_state)==="closed"||r==="closed"}function D(e){const t=w(e,"completionEvidence")??w(e,"completion_evidence"),o=w(e,"scopedCiEvidence")??w(e,"scoped_ci_evidence"),r=[e.physicalMergeStatus,e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,t?.prState,t?.pr_state,t?.pullRequestState,o?.prState].map(b);return e.merged===!0||r.includes("merged")||b(o?.finalState)==="can-merge"&&e.merged===!0}function he(e){const t=w(e,"completionEvidence")??w(e,"completion_evidence"),o=[e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,t?.prState,t?.pr_state,t?.pullRequestState].map(b),r=D(e),s=["denied-external-gate","denied-local-or-repo","not-attempted"].includes(b(e.physicalMergeStatus)),c=o.includes("closed")||o.includes("closed-unmerged");return r&&(e.merged===!1||s||c)||e.merged===!0&&s}function Se(e,t,o){const r=`state-completion-reconciliation:${u(t)}`,s=e.filter(d).map(n=>({...n})),c={id:r,status:"open",reason:"stale_state_completion_evidence_observed",reason_codes:[E],category:"state/completion-reconciliation",story_id:u(t),public_safe:!0,raw_log_storage:"forbidden",created_at:o,last_seen_at:o,occurrences:1},l=s.findIndex(n=>n.id===r);if(l<0)return[...s,c];const a=s[l];return s[l]={...a,...c,created_at:typeof a.created_at=="string"?a.created_at:o,occurrences:Math.max(1,typeof a.occurrences=="number"?a.occurrences:1)+1},s}function be(e,t,o,r){const s=d(e.stories)?e.stories:null;if(!s)return;const c=[],l=j();for(const[a,n]of Object.entries(s)){if(!d(n))continue;const i=typeof n.epic_id=="string"?n.epic_id:a.split(".")[0];if(r&&i!==r)continue;const p=b(n.status);if(he(n))throw new S(`[Neocortex] state.json repair stopped: story "${a}" has conflicting PR merge completion evidence. Resolve .neocortex/state.json manually before invoking Neocortex.`,"conflicting_completion_evidence");if(p!=="pr-reviewed"||!D(n)||!ye(n))continue;const g=typeof n.status=="string"?n.status:p,m=ie(n.steps_completed);n.status="done",n.last_step="step-c-12-merge-pr",n.steps_completed=Array.from(new Set([...m,"step-c-12-merge-pr"])),n.merged=!0,n.physicalMergeStatus="merged",n.completion_reconciled_at=l,t.push(`reconciled completion evidence for story ${a}`),o.push(E),c.push({schemaVersion:1,publicSafe:!0,rawLogStorage:"forbidden",storyId:u(a),previousStatus:g,nextStatus:"done",reasonCodes:[E],reconciledAt:l}),e.state_repair_debt=Se(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],a,l)}c.length>0&&(e.state_completion_reconciliations=[...Array.isArray(e.state_completion_reconciliations)?e.state_completion_reconciliations.filter(d):[],...c])}function we(e,t,o){const r=d(e.stories)?e.stories:null;if(r)for(const[s,c]of Object.entries(r))!d(c)||!Object.prototype.hasOwnProperty.call(c,"workflow_issue")||typeof c.workflow_issue=="number"&&Number.isFinite(c.workflow_issue)||(delete c.workflow_issue,t.push(`removed invalid workflow_issue from story ${u(s)}`),o.push(pe))}function ve(e,t={}){if(Array.isArray(e.stories))throw new S("[Neocortex] state.json repair stopped: `stories` is an Array. Convert it to an object keyed by story ID or run `*migrate-state --preview` for guidance.","stories_array_ambiguous");if(d(e.epics)){for(const[i,p]of Object.entries(e.epics))if(d(p)&&p.stories!==void 0&&!Array.isArray(p.stories))throw new S(`[Neocortex] state.json repair stopped: epic "${i}" has non-array \`stories\`. Repair this ambiguous shape manually before invoking Neocortex.`,"epic_stories_not_array")}if(e.schema_version!==void 0&&e.schema_version!==0&&e.schema_version!==1)throw new S(`[Neocortex] state.json repair stopped: schema_version=${String(e.schema_version)} is not a safe automatic downgrade target. Run \`*migrate-state --preview\` or repair the schema version manually.`,"unsupported_schema_version");if(I(t.args,t.canonicalCommandId)){for(const i of["epics","stories"]){const p=e[i];if(p!==void 0){if(!d(p))throw new S("[Neocortex] inline materialization stopped: invalid state collection.","inline_state_collection_invalid");for(const[g,m]of Object.entries(p)){if(!d(m))throw new S("[Neocortex] inline materialization stopped: invalid state record.","inline_state_record_invalid");if(m.id!==void 0&&m.id!==g)throw new S("[Neocortex] inline materialization stopped: conflicting state identity.","inline_state_identity_conflict")}}}return{mutated:!1,state:e,reasonCodes:[],changes:[]}}let o;try{o=Z(e)}catch(i){throw i instanceof U?new S(`[Neocortex] state.json repair stopped by shared migration planner: ${i.message}`,i.reasonCode):i}let r=JSON.parse(JSON.stringify(o.kind==="migrate"?o.plan.targetState:e));const s=o.kind==="migrate"?o.plan.steps.map(i=>`shared migration ${i.kind}: ${i.target}`):[],c=o.kind==="migrate"?["state_migration_shared_plan"]:[];let l=[];const a=P(r,t.args,t.canonicalCommandId);if(we(r,s,c),be(r,s,c,a),typeof t.args=="string"){const i=me(r,{nowIso:t.nowIso,targetEpicId:a,effectiveDoneStoryIds:t.effectiveDoneStoryIds,preserveGitLifecycleAggregates:!0});if(i.mutated){r=i.state,l=i.changes;for(const p of i.reasonCodes)c.push(p);for(const p of i.changes)s.push(`reconciled aggregate for epic ${u(p.epicId)}`)}}const n=JSON.stringify(r)!==JSON.stringify(e);if(n){const i=t.nowIso??j(),p=Array.from(new Set(c));l.length>0&&je(r,l,i),r.last_updated=i,r.state_migration_repairs=[...Array.isArray(r.state_migration_repairs)?r.state_migration_repairs:[],{schemaVersion:1,action:"client_auto_repair",reasonCodes:p,repairedAt:i}],r.state_repair_debt=Ce(Array.isArray(r.state_repair_debt)?r.state_repair_debt:[],p,i)}return{mutated:n,state:r,reasonCodes:Array.from(new Set(c)),changes:s}}function G(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function L(e){const t=b(e);return t.length>0?C(t).slice(0,80):null}function Ae(e,t){return{schemaVersion:1,publicSafe:!0,epicId:u(e.epicId),reasonCodes:e.reasonCodes.map(C).filter(Boolean),previous:{total_stories:G(e.previous.total_stories),completed_stories:G(e.previous.completed_stories),status:L(e.previous.status),completed_at_present:typeof e.previous.completed_at=="string"&&e.previous.completed_at.length>0},next:{total_stories:e.next.total_stories,completed_stories:e.next.completed_stories,status:L(e.next.status),completed_at_present:typeof e.next.completed_at=="string"&&e.next.completed_at.length>0},repairedAt:t}}function xe(e,t,o){let r=e.filter(d).map(s=>({...s}));for(const s of t){const c=u(s.epicId),l=Array.from(new Set(s.reasonCodes.map(C).filter(Boolean))).sort(),a=`state-aggregate-reconciliation:${c}`,n={id:a,status:"open",reason:"epic_aggregate_reconciled",reason_codes:l,category:"state/epic-aggregate-reconciliation",epic_id:c,created_at:o,last_seen_at:o,occurrences:1},i=r.findIndex(g=>g.id===a);if(i<0){r=[...r,n];continue}const p=r[i];r[i]={...p,...n,created_at:typeof p.created_at=="string"?p.created_at:o,occurrences:Math.max(1,typeof p.occurrences=="number"?p.occurrences:1)+1}}return r}function je(e,t,o){e.state_aggregate_reconciliations=[...Array.isArray(e.state_aggregate_reconciliations)?e.state_aggregate_reconciliations.filter(d):[],...t.map(r=>Ae(r,o))],e.state_repair_debt=xe(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],t,o)}function Ce(e,t,o){const r=Array.from(new Set(t.map(C).filter(Boolean))).sort(),s=`state-drift-repair:${r.join("+")||"unknown"}`,c=e.filter(d).map(i=>({...i})),l={id:s,status:"open",reason:"state_json_drift_repaired",reason_codes:r,category:"state/drift-repair",created_at:o,last_seen_at:o,occurrences:1},a=c.findIndex(i=>i.id===s);if(a<0)return[...c,l];const n=c[a];return c[a]={...n,...l,created_at:typeof n.created_at=="string"?n.created_at:o,occurrences:Math.max(1,typeof n.occurrences=="number"?n.occurrences:1)+1},c}function C(e){return e.replace(/\b(sk|ghp|gho|github_pat|xoxb|AKIA)[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^,\s)]+/gi,"$1=[redacted]").replace(/https?:\/\/[^\s)]+/gi,"[url-redacted]").replace(/[^a-z0-9_+-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)}function u(e){return e.replace(/[^a-z0-9_.:-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)||"unknown"}function Te(e,t={}){const o=x(e,".neocortex"),r=x(o,"state.json");if(!F(r))return{repaired:!1,reasonCodes:[],changes:[]};let s;if(!I(t.args,t.canonicalCommandId))try{const _=Y(e);_&&(s=K(e,_))}catch(_){const y=_ instanceof Q?_.reasonCode:"state_migration_apply_failed";throw new S(`[Neocortex] state.json migration stopped before invoke: ${_ instanceof Error?_.message:String(_)}. No unverified state was used.`,y)}let c;try{c=JSON.parse(q(r,"utf8"))}catch(_){const y=_ instanceof Error?_.message:String(_);throw new S(`[Neocortex] state.json repair stopped: invalid JSON in .neocortex/state.json (${y}). No files were overwritten. Fix the JSON or restore a backup, then rerun.`,"invalid_json")}if(!d(c))throw new S("[Neocortex] state.json repair stopped: top-level state must be a JSON object. Restore a valid .neocortex/state.json before invoking Neocortex.","state_not_object");const l=P(c,t.args,t.canonicalCommandId),a=I(t.args,t.canonicalCommandId)?[]:Ie(e,c,l),n=ve(c,{...t,effectiveDoneStoryIds:a});if(!n.mutated)return s?{repaired:!0,reasonCodes:["state_migration_transaction_applied"],backupPath:s.backupHash?`.neocortex/state.json.migration-backup-${s.operationId}`:void 0,changes:[`shared state migration ${s.outcome}`]}:{repaired:!1,reasonCodes:[],changes:[]};J(o,{recursive:!0});const i=ne(),p=x(o,`state.json.backup-${i}`),g=x(o,`state.json.tmp.${V(6).toString("hex")}`);W(r,p),H(g,`${JSON.stringify(n.state,null,2)}
2
+ `,"utf8"),B(g,r);const m=`.neocortex/state.json.backup-${i}`;return process.stderr.write(`[Neocortex P156.05] state.json auto-repaired before invoke; backup=${m}; reasonCodes=${n.reasonCodes.join(",")}; changes=${n.changes.join("; ")}
3
+ `),{repaired:!0,reasonCodes:n.reasonCodes,backupPath:m,changes:n.changes}}function Ie(e,t,o){const r=X(e),s=d(t.epics)?t.epics:{},c=d(t.stories)?t.stories:{},l=[];for(const[a,n]of Object.entries(r.stories)){if(!d(n)||!T(n.status)||!n.checkpoint)continue;const i=d(c[a])?c[a]:null,p=typeof i?.epic_id=="string"?i.epic_id:a.split(".")[0];if(!p||o&&p!==o)continue;const g=d(s[p])?s[p]:null,m=d(r.epics[p])?r.epics[p]:null,_=m?.branch_mode??g?.branch_mode,y=m?.execution_branch??g?.execution_branch;if(_!=="epic"||typeof y!="string")continue;ee(e,n.checkpoint,a,p,y).verdict==="verified"&&l.push(a)}return l.sort()}export{f as EPIC_AGGREGATE_REASON_CODES,te as P189_STATE_SHAPE_GAP_CODE,S as StateRepairHardStopError,I as isInlineYoloMaterialization,T as isP189DoneLikeStoryStatus,Te as maybeRepairStateJsonBeforeInvoke,me as reconcileEpicAggregatesInState};