@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,399 +1,13 @@
1
- /** Root-owned, two-phase Git checkpoint for an accepted characterized refactor. */
2
- import { createHash } from 'node:crypto';
3
- import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
4
- import { join, resolve } from 'node:path';
5
- import { mutationQaGit } from './mutation-qa-git.js';
6
- import { privateRefactorDirectory, readPrivateRefactorAdmission, refactorSidecarDigest, verifyRootRefactor } from './refactor-root.js';
7
- import { readRootRefactorSemanticReview } from './refactor-review.js';
8
- const SHA256 = /^[a-f0-9]{64}$/;
9
- const GIT_SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
10
- function sha(value) {
11
- return createHash('sha256').update(value).digest('hex');
12
- }
13
- function git(root, args) {
14
- return mutationQaGit(root, args).toString('utf8').trim();
15
- }
16
- function names(root, args) {
17
- return mutationQaGit(root, args).toString('utf8').split('\0').filter(Boolean);
18
- }
19
- function ordered(paths) {
20
- return [...paths].sort((a, b) => Buffer.from(a).compare(Buffer.from(b)));
21
- }
22
- function exact(value, keys) {
23
- return value !== null && typeof value === 'object' && !Array.isArray(value)
24
- && Object.keys(value).sort().join('\0') === [...keys].sort().join('\0');
25
- }
26
- function physical(root, path) {
27
- const target = join(root, path);
28
- const stat = lstatSync(target);
29
- if (!stat.isFile() || stat.isSymbolicLink() || realpathSync(target) !== target
30
- || stat.size < 1 || stat.size > 8 * 1024 * 1024) {
31
- throw new Error('refactor-root-commit-physical-drift');
32
- }
33
- const bytes = readFileSync(target);
34
- if (bytes.length !== stat.size)
35
- throw new Error('refactor-root-commit-physical-drift');
36
- return Object.freeze({ sha256: sha(bytes), mode: stat.mode & 0o777 });
37
- }
38
- function planPath(root, planSha256) {
39
- if (!SHA256.test(planSha256))
40
- throw new Error('refactor-root-commit-plan-invalid');
41
- return join(privateRefactorDirectory(root), `commit-plan-${planSha256}.json`);
42
- }
43
- function checkpointPath(root, planSha256) {
44
- if (!SHA256.test(planSha256))
45
- throw new Error('refactor-root-commit-plan-invalid');
46
- return join(privateRefactorDirectory(root), `commit-checkpoint-${planSha256}.json`);
47
- }
48
- function privateBytes(path, maximum) {
49
- const stat = lstatSync(path);
50
- if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
51
- || (stat.mode & 0o077) !== 0 || stat.size < 100 || stat.size > maximum) {
52
- throw new Error('refactor-root-commit-plan-invalid');
53
- }
54
- const bytes = readFileSync(path);
55
- if (bytes.length !== stat.size)
56
- throw new Error('refactor-root-commit-plan-invalid');
57
- return bytes;
58
- }
59
- function persist(root, path, bytes) {
60
- if (existsSync(path)) {
61
- if (!privateBytes(path, 128 * 1024).equals(bytes)) {
62
- throw new Error('refactor-root-commit-plan-conflict');
63
- }
64
- return;
65
- }
66
- const handle = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL
67
- | (constants.O_NOFOLLOW ?? 0), 0o600);
68
- try {
69
- writeFileSync(handle, bytes);
70
- fsyncSync(handle);
71
- }
72
- finally {
73
- closeSync(handle);
74
- }
75
- const directory = openSync(privateRefactorDirectory(root), constants.O_RDONLY
76
- | (constants.O_DIRECTORY ?? 0));
77
- try {
78
- fsyncSync(directory);
79
- }
80
- finally {
81
- closeSync(directory);
82
- }
83
- }
84
- function readPlan(root, planSha256) {
85
- const raw = privateBytes(planPath(root, planSha256), 128 * 1024);
86
- let parsed;
87
- try {
88
- parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
89
- }
90
- catch {
91
- throw new Error('refactor-root-commit-plan-invalid');
92
- }
93
- if (!exact(parsed, ['schemaVersion', 'kind', 'storyId', 'baseHead', 'branchRef',
94
- 'admissionSha256', 'baselineSha256', 'candidateSha256', 'reviewSha256',
95
- 'reviewRecordSha256', 'sidecarSha256', 'files', 'planSha256'])
96
- || parsed.schemaVersion !== 1 || parsed.kind !== 'private-root-refactor-commit-plan'
97
- || typeof parsed.storyId !== 'string' || !/^P[0-9]+(?:\.[0-9]+)+$/.test(parsed.storyId)
98
- || typeof parsed.baseHead !== 'string' || !GIT_SHA.test(parsed.baseHead)
99
- || typeof parsed.branchRef !== 'string'
100
- || ![`refs/heads/epic/${parsed.storyId.split('.')[0]}`,
101
- `refs/heads/story/${parsed.storyId.split('.')[0]}/${parsed.storyId}`].includes(parsed.branchRef)
102
- || ![parsed.admissionSha256, parsed.baselineSha256, parsed.candidateSha256,
103
- parsed.reviewSha256, parsed.reviewRecordSha256, parsed.sidecarSha256]
104
- .every((value) => typeof value === 'string' && SHA256.test(value))
105
- || !Array.isArray(parsed.files) || parsed.files.length < 2 || parsed.files.length > 256
106
- || !parsed.files.every((file) => exact(file, ['path', 'sha256', 'mode'])
107
- && typeof file.path === 'string' && /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(file.path)
108
- && typeof file.sha256 === 'string' && SHA256.test(file.sha256)
109
- && Number.isSafeInteger(file.mode) && Number(file.mode) >= 0 && Number(file.mode) <= 0o777)
110
- || parsed.files.map((file) => file.path).join('\0')
111
- !== ordered(parsed.files.map((file) => file.path)).join('\0')
112
- || new Set(parsed.files.map((file) => file.path)).size !== parsed.files.length
113
- || parsed.planSha256 !== planSha256) {
114
- throw new Error('refactor-root-commit-plan-invalid');
115
- }
116
- const { planSha256: _digest, ...body } = parsed;
117
- if (sha(JSON.stringify(body)) !== planSha256
118
- || !raw.equals(Buffer.from(`${JSON.stringify(parsed)}\n`))) {
119
- throw new Error('refactor-root-commit-plan-invalid');
120
- }
121
- const admission = readPrivateRefactorAdmission(root, parsed.admissionSha256);
122
- const admitted = new Set([...admission.files.map((file) => file.path),
123
- ...(admission.schemaVersion === 2 ? admission.newFiles.map((file) => file.path) : [])]);
124
- if (admission.storyId !== parsed.storyId || admission.sourceHead !== parsed.baseHead
125
- || admission.sidecarSha256 !== parsed.sidecarSha256
126
- || parsed.files.some((file) => !admitted.has(file.path))) {
127
- throw new Error('refactor-root-commit-plan-invalid');
128
- }
129
- return parsed;
130
- }
131
- function reviewRecordPath(root, plan) {
132
- return join(privateRefactorDirectory(root), `review-${plan.admissionSha256}-${plan.candidateSha256}.json`);
133
- }
134
- function commitSubject(storyId) {
135
- return `refactor(${storyId}): characterized change`;
136
- }
137
- function commitTrailer(planSha256) {
138
- return `Neocortex-Refactor-Plan: ${planSha256}`;
139
- }
140
- function branch(root) {
141
- return git(root, ['symbolic-ref', '-q', 'HEAD']);
142
- }
143
- function allowedDirty(root) {
144
- return names(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])
145
- .every((entry) => entry.length >= 4 && entry[2] === ' ' && entry.slice(3).startsWith('.neocortex/'));
146
- }
147
- export function prepareRootRefactorCommit(projectRoot, admissionSha256, baselineSha256, authorizeRootPlan) {
148
- if (!authorizeRootPlan)
149
- throw new Error('refactor-root-commit-authorization-required');
150
- try {
151
- const root = resolve(projectRoot);
152
- const accepted = readRootRefactorSemanticReview(root, admissionSha256, baselineSha256);
153
- const admission = readPrivateRefactorAdmission(root, admissionSha256);
154
- const containment = verifyRootRefactor(root, admissionSha256);
155
- const branchRef = branch(root);
156
- const epicId = admission.storyId.split('.')[0];
157
- if (![`refs/heads/epic/${epicId}`,
158
- `refs/heads/story/${epicId}/${admission.storyId}`].includes(branchRef)) {
159
- throw new Error('refactor-root-commit-branch-invalid');
160
- }
161
- const tracked = names(root, ['diff', '--name-only', '-z', '--no-ext-diff', '--no-textconv']);
162
- const untracked = names(root, ['ls-files', '--others', '--exclude-standard', '-z']);
163
- const paths = ordered([...tracked, ...untracked].filter((path) => !path.startsWith('.neocortex/')));
164
- const admitted = new Set([...admission.files.map((file) => file.path),
165
- ...(admission.schemaVersion === 2 ? admission.newFiles.map((file) => file.path) : [])]);
166
- if (paths.length !== containment.changedFileCount || paths.some((path) => !admitted.has(path))) {
167
- throw new Error('refactor-root-commit-delta-invalid');
168
- }
169
- const files = paths.map((path) => Object.freeze({ path, ...physical(root, path) }));
170
- const reviewRecordSha256 = sha(privateBytes(reviewRecordPath(root, {
171
- admissionSha256, candidateSha256: accepted.candidateSha256,
172
- }), 128 * 1024));
173
- const body = { schemaVersion: 1, kind: 'private-root-refactor-commit-plan',
174
- storyId: admission.storyId, baseHead: admission.sourceHead, branchRef,
175
- admissionSha256, baselineSha256, candidateSha256: accepted.candidateSha256,
176
- reviewSha256: accepted.reviewSha256, reviewRecordSha256,
177
- sidecarSha256: admission.sidecarSha256, files };
178
- const planSha256 = sha(JSON.stringify(body));
179
- const record = { ...body, planSha256 };
180
- if (git(root, ['rev-parse', '--verify', 'HEAD']) !== admission.sourceHead
181
- || refactorSidecarDigest(root) !== admission.sidecarSha256
182
- || files.some((file) => {
183
- const current = physical(root, file.path);
184
- return current.sha256 !== file.sha256 || current.mode !== file.mode;
185
- })) {
186
- throw new Error('refactor-root-commit-physical-drift');
187
- }
188
- persist(root, planPath(root, planSha256), Buffer.from(`${JSON.stringify(record)}\n`));
189
- readPlan(root, planSha256);
190
- return Object.freeze({ schemaVersion: 1, kind: 'root-refactor-commit-plan',
191
- storyId: admission.storyId, baseHead: admission.sourceHead, branchRef,
192
- planSha256, fileCount: files.length, commitSubject: commitSubject(admission.storyId),
193
- commitTrailer: commitTrailer(planSha256), gitCommitAuthorized: false,
194
- checkpointAccepted: false, publicSafe: true });
195
- }
196
- catch (error) {
197
- if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
198
- throw error;
199
- throw new Error('refactor-root-commit-unverified');
200
- }
201
- }
202
- export function verifyRootRefactorStaged(projectRoot, planSha256) {
203
- try {
204
- const root = resolve(projectRoot);
205
- const plan = readPlan(root, planSha256);
206
- if (branch(root) !== plan.branchRef || git(root, ['rev-parse', '--verify', 'HEAD']) !== plan.baseHead
207
- || refactorSidecarDigest(root) !== plan.sidecarSha256
208
- || sha(privateBytes(reviewRecordPath(root, plan), 128 * 1024)) !== plan.reviewRecordSha256) {
209
- throw new Error('refactor-root-commit-physical-drift');
210
- }
211
- const staged = ordered(names(root, ['diff', '--cached', '--name-only', '-z', '--no-renames']));
212
- const expected = plan.files.map((file) => file.path);
213
- const unstaged = names(root, ['diff', '--name-only', '-z', '--no-renames'])
214
- .filter((path) => !path.startsWith('.neocortex/'));
215
- const untracked = names(root, ['ls-files', '--others', '--exclude-standard', '-z'])
216
- .filter((path) => !path.startsWith('.neocortex/'));
217
- if (staged.join('\0') !== expected.join('\0') || unstaged.length || untracked.length) {
218
- throw new Error('refactor-root-commit-staged-invalid');
219
- }
220
- for (const file of plan.files) {
221
- const index = mutationQaGit(root, ['ls-files', '--stage', '-z', '--', file.path]).toString('utf8');
222
- const match = index.match(/^(100644|100755) [a-f0-9]{40,64} 0\t([^\0]+)\0$/);
223
- if (!match || match[2] !== file.path
224
- || match[1] !== ((file.mode & 0o111) ? '100755' : '100644')
225
- || sha(mutationQaGit(root, ['show', `:${file.path}`])) !== file.sha256
226
- || physical(root, file.path).sha256 !== file.sha256
227
- || physical(root, file.path).mode !== file.mode) {
228
- throw new Error('refactor-root-commit-staged-invalid');
229
- }
230
- }
231
- if (branch(root) !== plan.branchRef || git(root, ['rev-parse', '--verify', 'HEAD']) !== plan.baseHead
232
- || refactorSidecarDigest(root) !== plan.sidecarSha256) {
233
- throw new Error('refactor-root-commit-physical-drift');
234
- }
235
- return Object.freeze({ schemaVersion: 1, kind: 'root-refactor-staged-verification',
236
- planSha256, baseHead: plan.baseHead, fileCount: plan.files.length,
237
- stagedWriteSetSha256: sha(JSON.stringify(plan.files)), gitCommitAuthorized: true,
238
- checkpointAccepted: false, publicSafe: true });
239
- }
240
- catch (error) {
241
- if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
242
- throw error;
243
- throw new Error('refactor-root-commit-unverified');
244
- }
245
- }
246
- function physicalCommit(root, plan) {
247
- const head = git(root, ['rev-parse', '--verify', 'HEAD']);
248
- const parents = git(root, ['show', '-s', '--format=%P', head]);
249
- const object = mutationQaGit(root, ['cat-file', 'commit', head]);
250
- const bodyOffset = object.indexOf(Buffer.from('\n\n'));
251
- const message = bodyOffset < 0 ? Buffer.alloc(0) : object.subarray(bodyOffset + 2);
252
- const expectedMessage = Buffer.from(`${commitSubject(plan.storyId)}\n\n${commitTrailer(plan.planSha256)}\n`);
253
- if (!GIT_SHA.test(head) || parents !== plan.baseHead || !message.equals(expectedMessage)
254
- || branch(root) !== plan.branchRef || !allowedDirty(root)
255
- || refactorSidecarDigest(root) !== plan.sidecarSha256
256
- || sha(privateBytes(reviewRecordPath(root, plan), 128 * 1024)) !== plan.reviewRecordSha256) {
257
- throw new Error('refactor-root-commit-physical-drift');
258
- }
259
- const changed = ordered(names(root, ['diff-tree', '--no-commit-id', '--name-only',
260
- '--no-renames', '-r', '-z', head]));
261
- if (changed.join('\0') !== plan.files.map((file) => file.path).join('\0')) {
262
- throw new Error('refactor-root-commit-physical-drift');
263
- }
264
- for (const file of plan.files) {
265
- const entry = mutationQaGit(root, ['ls-tree', '-z', head, '--', file.path]).toString('utf8');
266
- const match = entry.match(/^(100644|100755) blob [a-f0-9]{40,64}\t([^\0]+)\0$/);
267
- if (!match || match[2] !== file.path
268
- || match[1] !== ((file.mode & 0o111) ? '100755' : '100644')
269
- || sha(mutationQaGit(root, ['show', `${head}:${file.path}`])) !== file.sha256
270
- || physical(root, file.path).sha256 !== file.sha256
271
- || physical(root, file.path).mode !== file.mode) {
272
- throw new Error('refactor-root-commit-physical-drift');
273
- }
274
- }
275
- if (git(root, ['rev-parse', '--verify', 'HEAD']) !== head || branch(root) !== plan.branchRef) {
276
- throw new Error('refactor-root-commit-physical-drift');
277
- }
278
- return head;
279
- }
280
- export function sealRootRefactorCommit(projectRoot, planSha256, authorizeRootSeal) {
281
- if (!authorizeRootSeal)
282
- throw new Error('refactor-root-commit-authorization-required');
283
- try {
284
- const root = resolve(projectRoot);
285
- const plan = readPlan(root, planSha256);
286
- const commitSha = physicalCommit(root, plan);
287
- const receipt = Object.freeze({ schemaVersion: 1,
288
- kind: 'root-refactor-commit-checkpoint', storyId: plan.storyId,
289
- baseHead: plan.baseHead, commitSha, branchRef: plan.branchRef,
290
- planSha256, candidateSha256: plan.candidateSha256, reviewSha256: plan.reviewSha256,
291
- fileCount: plan.files.length, checkpointAccepted: true,
292
- graphExecution: 'NOT_RUN', publicSafe: true });
293
- persist(root, checkpointPath(root, planSha256), Buffer.from(`${JSON.stringify(receipt)}\n`));
294
- if (!privateBytes(checkpointPath(root, planSha256), 8 * 1024)
295
- .equals(Buffer.from(`${JSON.stringify(receipt)}\n`))) {
296
- throw new Error('refactor-root-commit-checkpoint-invalid');
297
- }
298
- return receipt;
299
- }
300
- catch (error) {
301
- if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
302
- throw error;
303
- throw new Error('refactor-root-commit-unverified');
304
- }
305
- }
306
- export function readRootRefactorCommitCheckpoint(projectRoot, planSha256) {
307
- try {
308
- const root = resolve(projectRoot);
309
- const plan = readPlan(root, planSha256);
310
- const commitSha = physicalCommit(root, plan);
311
- const bytes = privateBytes(checkpointPath(root, planSha256), 8 * 1024);
312
- const receipt = JSON.parse(bytes.toString('utf8'));
313
- if (!exact(receipt, ['schemaVersion', 'kind', 'storyId', 'baseHead', 'commitSha',
314
- 'branchRef', 'planSha256', 'candidateSha256', 'reviewSha256', 'fileCount',
315
- 'checkpointAccepted', 'graphExecution', 'publicSafe'])
316
- || receipt.schemaVersion !== 1 || receipt.kind !== 'root-refactor-commit-checkpoint'
317
- || receipt.commitSha !== commitSha || receipt.planSha256 !== planSha256
318
- || receipt.storyId !== plan.storyId || receipt.baseHead !== plan.baseHead
319
- || receipt.branchRef !== plan.branchRef || receipt.candidateSha256 !== plan.candidateSha256
320
- || receipt.reviewSha256 !== plan.reviewSha256 || receipt.fileCount !== plan.files.length
321
- || receipt.checkpointAccepted !== true || receipt.graphExecution !== 'NOT_RUN'
322
- || receipt.publicSafe !== true || !bytes.equals(Buffer.from(`${JSON.stringify(receipt)}\n`))) {
323
- throw new Error('refactor-root-commit-checkpoint-invalid');
324
- }
325
- return receipt;
326
- }
327
- catch {
328
- throw new Error('refactor-root-commit-checkpoint-invalid');
329
- }
330
- }
331
- export function refactorCommitCliHandler(args) {
332
- const action = args[0];
333
- let projectRoot = '';
334
- let admissionSha256 = '';
335
- let baselineSha256 = '';
336
- let planSha256 = '';
337
- let authorizeRun = false;
338
- let authorizePlan = false;
339
- let authorizeSeal = false;
340
- let format = 'plain';
341
- const seen = new Set();
342
- try {
343
- if (!['commit-plan', 'commit-staged', 'commit-seal', 'commit-status'].includes(action ?? '')) {
344
- throw new Error('refactor-root-commit-arguments-invalid');
345
- }
346
- for (let index = 1; index < args.length; index++) {
347
- const token = args[index];
348
- if (seen.has(token))
349
- throw new Error('refactor-root-commit-arguments-invalid');
350
- seen.add(token);
351
- const next = () => {
352
- const value = args[++index];
353
- if (!value || value.startsWith('--'))
354
- throw new Error('refactor-root-commit-arguments-invalid');
355
- return value;
356
- };
357
- if (token === '--project-root')
358
- projectRoot = next();
359
- else if (token === '--admission-sha')
360
- admissionSha256 = next();
361
- else if (token === '--baseline-sha')
362
- baselineSha256 = next();
363
- else if (token === '--plan-sha')
364
- planSha256 = next();
365
- else if (token === '--authorize-run')
366
- authorizeRun = true;
367
- else if (token === '--authorize-root-commit-plan')
368
- authorizePlan = true;
369
- else if (token === '--authorize-root-seal')
370
- authorizeSeal = true;
371
- else if (token === '--format')
372
- format = next();
373
- else
374
- throw new Error('refactor-root-commit-arguments-invalid');
375
- }
376
- if (!projectRoot || !['plain', 'json'].includes(format)
377
- || (action === 'commit-plan' && (!SHA256.test(admissionSha256)
378
- || !SHA256.test(baselineSha256) || planSha256 || !authorizeRun
379
- || !authorizePlan || authorizeSeal))
380
- || (action !== 'commit-plan' && (!SHA256.test(planSha256)
381
- || admissionSha256 || baselineSha256 || authorizeRun || authorizePlan
382
- || authorizeSeal !== (action === 'commit-seal')))) {
383
- throw new Error('refactor-root-commit-arguments-invalid');
384
- }
385
- const result = action === 'commit-plan'
386
- ? prepareRootRefactorCommit(projectRoot, admissionSha256, baselineSha256, authorizePlan)
387
- : action === 'commit-staged' ? verifyRootRefactorStaged(projectRoot, planSha256)
388
- : action === 'commit-seal' ? sealRootRefactorCommit(projectRoot, planSha256, authorizeSeal)
389
- : readRootRefactorCommitCheckpoint(projectRoot, planSha256);
390
- process.stdout.write(`${JSON.stringify({ ok: true, result })}\n`);
391
- return 0;
392
- }
393
- catch (error) {
394
- const reasonCode = error instanceof Error && /^refactor-root-[a-z-]+$/.test(error.message)
395
- ? error.message : 'refactor-root-commit-unverified';
396
- process.stdout.write(`${JSON.stringify({ ok: false, reasonCode })}\n`);
397
- return 1;
398
- }
399
- }
1
+ import{createHash as Q}from"node:crypto";import{closeSync as _,constants as E,existsSync as X,fsyncSync as W,lstatSync as V,openSync as P,readFileSync as q,realpathSync as K,writeFileSync as tt}from"node:fs";import{join as $,resolve as H}from"node:path";import{mutationQaGit as y}from"./mutation-qa-git.js";import{privateRefactorDirectory as x,readPrivateRefactorAdmission as F,refactorSidecarDigest as j,verifyRootRefactor as et}from"./refactor-root.js";import{readRootRefactorSemanticReview as rt}from"./refactor-review.js";const S=/^[a-f0-9]{64}$/,T=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;function w(o){return Q("sha256").update(o).digest("hex")}function g(o,e){return y(o,e).toString("utf8").trim()}function b(o,e){return y(o,e).toString("utf8").split("\0").filter(Boolean)}function I(o){return[...o].sort((e,r)=>Buffer.from(e).compare(Buffer.from(r)))}function N(o,e){return o!==null&&typeof o=="object"&&!Array.isArray(o)&&Object.keys(o).sort().join("\0")===[...e].sort().join("\0")}function R(o,e){const r=$(o,e),t=V(r);if(!t.isFile()||t.isSymbolicLink()||K(r)!==r||t.size<1||t.size>8*1024*1024)throw new Error("refactor-root-commit-physical-drift");const n=q(r);if(n.length!==t.size)throw new Error("refactor-root-commit-physical-drift");return Object.freeze({sha256:w(n),mode:t.mode&511})}function L(o,e){if(!S.test(e))throw new Error("refactor-root-commit-plan-invalid");return $(x(o),`commit-plan-${e}.json`)}function C(o,e){if(!S.test(e))throw new Error("refactor-root-commit-plan-invalid");return $(x(o),`commit-checkpoint-${e}.json`)}function v(o,e){const r=V(o);if(!r.isFile()||r.isSymbolicLink()||r.uid!==process.getuid?.()||(r.mode&63)!==0||r.size<100||r.size>e)throw new Error("refactor-root-commit-plan-invalid");const t=q(o);if(t.length!==r.size)throw new Error("refactor-root-commit-plan-invalid");return t}function Y(o,e,r){if(X(e)){if(!v(e,128*1024).equals(r))throw new Error("refactor-root-commit-plan-conflict");return}const t=P(e,E.O_WRONLY|E.O_CREAT|E.O_EXCL|(E.O_NOFOLLOW??0),384);try{tt(t,r),W(t)}finally{_(t)}const n=P(x(o),E.O_RDONLY|(E.O_DIRECTORY??0));try{W(n)}finally{_(n)}}function A(o,e){const r=v(L(o,e),131072);let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new Error("refactor-root-commit-plan-invalid")}if(!N(t,["schemaVersion","kind","storyId","baseHead","branchRef","admissionSha256","baselineSha256","candidateSha256","reviewSha256","reviewRecordSha256","sidecarSha256","files","planSha256"])||t.schemaVersion!==1||t.kind!=="private-root-refactor-commit-plan"||typeof t.storyId!="string"||!/^P[0-9]+(?:\.[0-9]+)+$/.test(t.storyId)||typeof t.baseHead!="string"||!T.test(t.baseHead)||typeof t.branchRef!="string"||![`refs/heads/epic/${t.storyId.split(".")[0]}`,`refs/heads/story/${t.storyId.split(".")[0]}/${t.storyId}`].includes(t.branchRef)||![t.admissionSha256,t.baselineSha256,t.candidateSha256,t.reviewSha256,t.reviewRecordSha256,t.sidecarSha256].every(a=>typeof a=="string"&&S.test(a))||!Array.isArray(t.files)||t.files.length<2||t.files.length>256||!t.files.every(a=>N(a,["path","sha256","mode"])&&typeof a.path=="string"&&/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(a.path)&&typeof a.sha256=="string"&&S.test(a.sha256)&&Number.isSafeInteger(a.mode)&&Number(a.mode)>=0&&Number(a.mode)<=511)||t.files.map(a=>a.path).join("\0")!==I(t.files.map(a=>a.path)).join("\0")||new Set(t.files.map(a=>a.path)).size!==t.files.length||t.planSha256!==e)throw new Error("refactor-root-commit-plan-invalid");const{planSha256:n,...c}=t;if(w(JSON.stringify(c))!==e||!r.equals(Buffer.from(`${JSON.stringify(t)}
2
+ `)))throw new Error("refactor-root-commit-plan-invalid");const i=F(o,t.admissionSha256),m=new Set([...i.files.map(a=>a.path),...i.schemaVersion===2?i.newFiles.map(a=>a.path):[]]);if(i.storyId!==t.storyId||i.sourceHead!==t.baseHead||i.sidecarSha256!==t.sidecarSha256||t.files.some(a=>!m.has(a.path)))throw new Error("refactor-root-commit-plan-invalid");return t}function B(o,e){return $(x(o),`review-${e.admissionSha256}-${e.candidateSha256}.json`)}function G(o){return`refactor(${o}): characterized change`}function U(o){return`Neocortex-Refactor-Plan: ${o}`}function k(o){return g(o,["symbolic-ref","-q","HEAD"])}function ot(o){return b(o,["status","--porcelain=v1","-z","--untracked-files=all"]).every(e=>e.length>=4&&e[2]===" "&&e.slice(3).startsWith(".neocortex/"))}function it(o,e,r,t){if(!t)throw new Error("refactor-root-commit-authorization-required");try{const n=H(o),c=rt(n,e,r),i=F(n,e),m=et(n,e),a=k(n),s=i.storyId.split(".")[0];if(![`refs/heads/epic/${s}`,`refs/heads/story/${s}/${i.storyId}`].includes(a))throw new Error("refactor-root-commit-branch-invalid");const u=b(n,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]),d=b(n,["ls-files","--others","--exclude-standard","-z"]),l=I([...u,...d].filter(f=>!f.startsWith(".neocortex/"))),h=new Set([...i.files.map(f=>f.path),...i.schemaVersion===2?i.newFiles.map(f=>f.path):[]]);if(l.length!==m.changedFileCount||l.some(f=>!h.has(f)))throw new Error("refactor-root-commit-delta-invalid");const p=l.map(f=>Object.freeze({path:f,...R(n,f)})),z=w(v(B(n,{admissionSha256:e,candidateSha256:c.candidateSha256}),128*1024)),D={schemaVersion:1,kind:"private-root-refactor-commit-plan",storyId:i.storyId,baseHead:i.sourceHead,branchRef:a,admissionSha256:e,baselineSha256:r,candidateSha256:c.candidateSha256,reviewSha256:c.reviewSha256,reviewRecordSha256:z,sidecarSha256:i.sidecarSha256,files:p},O=w(JSON.stringify(D)),M={...D,planSha256:O};if(g(n,["rev-parse","--verify","HEAD"])!==i.sourceHead||j(n)!==i.sidecarSha256||p.some(f=>{const J=R(n,f.path);return J.sha256!==f.sha256||J.mode!==f.mode}))throw new Error("refactor-root-commit-physical-drift");return Y(n,L(n,O),Buffer.from(`${JSON.stringify(M)}
3
+ `)),A(n,O),Object.freeze({schemaVersion:1,kind:"root-refactor-commit-plan",storyId:i.storyId,baseHead:i.sourceHead,branchRef:a,planSha256:O,fileCount:p.length,commitSubject:G(i.storyId),commitTrailer:U(O),gitCommitAuthorized:!1,checkpointAccepted:!1,publicSafe:!0})}catch(n){throw n instanceof Error&&n.message.startsWith("refactor-root-commit-")?n:new Error("refactor-root-commit-unverified")}}function at(o,e){try{const r=H(o),t=A(r,e);if(k(r)!==t.branchRef||g(r,["rev-parse","--verify","HEAD"])!==t.baseHead||j(r)!==t.sidecarSha256||w(v(B(r,t),128*1024))!==t.reviewRecordSha256)throw new Error("refactor-root-commit-physical-drift");const n=I(b(r,["diff","--cached","--name-only","-z","--no-renames"])),c=t.files.map(a=>a.path),i=b(r,["diff","--name-only","-z","--no-renames"]).filter(a=>!a.startsWith(".neocortex/")),m=b(r,["ls-files","--others","--exclude-standard","-z"]).filter(a=>!a.startsWith(".neocortex/"));if(n.join("\0")!==c.join("\0")||i.length||m.length)throw new Error("refactor-root-commit-staged-invalid");for(const a of t.files){const u=y(r,["ls-files","--stage","-z","--",a.path]).toString("utf8").match(/^(100644|100755) [a-f0-9]{40,64} 0\t([^\0]+)\0$/);if(!u||u[2]!==a.path||u[1]!==(a.mode&73?"100755":"100644")||w(y(r,["show",`:${a.path}`]))!==a.sha256||R(r,a.path).sha256!==a.sha256||R(r,a.path).mode!==a.mode)throw new Error("refactor-root-commit-staged-invalid")}if(k(r)!==t.branchRef||g(r,["rev-parse","--verify","HEAD"])!==t.baseHead||j(r)!==t.sidecarSha256)throw new Error("refactor-root-commit-physical-drift");return Object.freeze({schemaVersion:1,kind:"root-refactor-staged-verification",planSha256:e,baseHead:t.baseHead,fileCount:t.files.length,stagedWriteSetSha256:w(JSON.stringify(t.files)),gitCommitAuthorized:!0,checkpointAccepted:!1,publicSafe:!0})}catch(r){throw r instanceof Error&&r.message.startsWith("refactor-root-commit-")?r:new Error("refactor-root-commit-unverified")}}function Z(o,e){const r=g(o,["rev-parse","--verify","HEAD"]),t=g(o,["show","-s","--format=%P",r]),n=y(o,["cat-file","commit",r]),c=n.indexOf(Buffer.from(`
4
+
5
+ `)),i=c<0?Buffer.alloc(0):n.subarray(c+2),m=Buffer.from(`${G(e.storyId)}
6
+
7
+ ${U(e.planSha256)}
8
+ `);if(!T.test(r)||t!==e.baseHead||!i.equals(m)||k(o)!==e.branchRef||!ot(o)||j(o)!==e.sidecarSha256||w(v(B(o,e),128*1024))!==e.reviewRecordSha256)throw new Error("refactor-root-commit-physical-drift");if(I(b(o,["diff-tree","--no-commit-id","--name-only","--no-renames","-r","-z",r])).join("\0")!==e.files.map(s=>s.path).join("\0"))throw new Error("refactor-root-commit-physical-drift");for(const s of e.files){const d=y(o,["ls-tree","-z",r,"--",s.path]).toString("utf8").match(/^(100644|100755) blob [a-f0-9]{40,64}\t([^\0]+)\0$/);if(!d||d[2]!==s.path||d[1]!==(s.mode&73?"100755":"100644")||w(y(o,["show",`${r}:${s.path}`]))!==s.sha256||R(o,s.path).sha256!==s.sha256||R(o,s.path).mode!==s.mode)throw new Error("refactor-root-commit-physical-drift")}if(g(o,["rev-parse","--verify","HEAD"])!==r||k(o)!==e.branchRef)throw new Error("refactor-root-commit-physical-drift");return r}function nt(o,e,r){if(!r)throw new Error("refactor-root-commit-authorization-required");try{const t=H(o),n=A(t,e),c=Z(t,n),i=Object.freeze({schemaVersion:1,kind:"root-refactor-commit-checkpoint",storyId:n.storyId,baseHead:n.baseHead,commitSha:c,branchRef:n.branchRef,planSha256:e,candidateSha256:n.candidateSha256,reviewSha256:n.reviewSha256,fileCount:n.files.length,checkpointAccepted:!0,graphExecution:"NOT_RUN",publicSafe:!0});if(Y(t,C(t,e),Buffer.from(`${JSON.stringify(i)}
9
+ `)),!v(C(t,e),8*1024).equals(Buffer.from(`${JSON.stringify(i)}
10
+ `)))throw new Error("refactor-root-commit-checkpoint-invalid");return i}catch(t){throw t instanceof Error&&t.message.startsWith("refactor-root-commit-")?t:new Error("refactor-root-commit-unverified")}}function ct(o,e){try{const r=H(o),t=A(r,e),n=Z(r,t),c=v(C(r,e),8*1024),i=JSON.parse(c.toString("utf8"));if(!N(i,["schemaVersion","kind","storyId","baseHead","commitSha","branchRef","planSha256","candidateSha256","reviewSha256","fileCount","checkpointAccepted","graphExecution","publicSafe"])||i.schemaVersion!==1||i.kind!=="root-refactor-commit-checkpoint"||i.commitSha!==n||i.planSha256!==e||i.storyId!==t.storyId||i.baseHead!==t.baseHead||i.branchRef!==t.branchRef||i.candidateSha256!==t.candidateSha256||i.reviewSha256!==t.reviewSha256||i.fileCount!==t.files.length||i.checkpointAccepted!==!0||i.graphExecution!=="NOT_RUN"||i.publicSafe!==!0||!c.equals(Buffer.from(`${JSON.stringify(i)}
11
+ `)))throw new Error("refactor-root-commit-checkpoint-invalid");return i}catch{throw new Error("refactor-root-commit-checkpoint-invalid")}}function ut(o){const e=o[0];let r="",t="",n="",c="",i=!1,m=!1,a=!1,s="plain";const u=new Set;try{if(!["commit-plan","commit-staged","commit-seal","commit-status"].includes(e??""))throw new Error("refactor-root-commit-arguments-invalid");for(let l=1;l<o.length;l++){const h=o[l];if(u.has(h))throw new Error("refactor-root-commit-arguments-invalid");u.add(h);const p=()=>{const z=o[++l];if(!z||z.startsWith("--"))throw new Error("refactor-root-commit-arguments-invalid");return z};if(h==="--project-root")r=p();else if(h==="--admission-sha")t=p();else if(h==="--baseline-sha")n=p();else if(h==="--plan-sha")c=p();else if(h==="--authorize-run")i=!0;else if(h==="--authorize-root-commit-plan")m=!0;else if(h==="--authorize-root-seal")a=!0;else if(h==="--format")s=p();else throw new Error("refactor-root-commit-arguments-invalid")}if(!r||!["plain","json"].includes(s)||e==="commit-plan"&&(!S.test(t)||!S.test(n)||c||!i||!m||a)||e!=="commit-plan"&&(!S.test(c)||t||n||i||m||a!==(e==="commit-seal")))throw new Error("refactor-root-commit-arguments-invalid");const d=e==="commit-plan"?it(r,t,n,m):e==="commit-staged"?at(r,c):e==="commit-seal"?nt(r,c,a):ct(r,c);return process.stdout.write(`${JSON.stringify({ok:!0,result:d})}
12
+ `),0}catch(d){const l=d instanceof Error&&/^refactor-root-[a-z-]+$/.test(d.message)?d.message:"refactor-root-commit-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:l})}
13
+ `),1}}export{it as prepareRootRefactorCommit,ct as readRootRefactorCommitCheckpoint,ut as refactorCommitCliHandler,nt as sealRootRefactorCommit,at as verifyRootRefactorStaged};
@@ -1,142 +1,3 @@
1
- /** Mechanical authenticated control transport; workflow decisions stay server-side. */
2
- import { lstatSync, readFileSync, realpathSync } from 'node:fs';
3
- import { join, resolve } from 'node:path';
4
- import { signNxInvokeRequest } from '../../../shared/dist/nx-invoke-signature.js';
5
- import { COMMAND_REGISTRY_VERSION, COMMAND_REGISTRY_CHECKSUM } from '../generated/command-registry.generated.js';
6
- import { CLIENT_VERSION } from '../version.js';
7
- import { loadSecureConfig } from '../config/secure-config.js';
8
- import { neocortexProfileDirectory } from '../config/profile-directory.js';
9
- import { EncryptedCache } from '../cache/encrypted-cache.js';
10
- import { LicenseClient } from '../license/license-client.js';
11
- import { detectPlatform } from '../adapters/platform-detector.js';
12
- const CONTROL_ERRORS = new Set([
13
- 'refactor-control-input-invalid', 'refactor-control-auth-required',
14
- 'refactor-control-tier-required', 'refactor-control-read-only',
15
- 'refactor-control-signature-required', 'refactor-control-client-unsupported',
16
- 'refactor-control-registry-mismatch', 'refactor-control-executor-unavailable',
17
- ]);
18
- const CLIENT_CONTROL_ERRORS = new Set(['arguments-invalid', 'authorization-required', 'host-unsupported',
19
- 'project-unbound', 'auth-required', 'response-invalid', 'request-refused', 'outcome-unknown']
20
- .map(code => `refactor-root-control-${code}`));
21
- /** Enforce the byte budget while receiving; do not buffer an unbounded body. */
22
- async function readControlResponse(response) {
23
- const reader = response.body?.getReader();
24
- if (!reader)
25
- throw new Error('refactor-root-control-response-invalid');
26
- let complete = false;
27
- try {
28
- const chunks = [];
29
- let size = 0;
30
- for (;;) {
31
- const next = await reader.read();
32
- if (next.done) {
33
- complete = true;
34
- break;
35
- }
36
- size += next.value.byteLength;
37
- if (size > 16384)
38
- throw new Error('refactor-root-control-response-invalid');
39
- chunks.push(Buffer.from(next.value));
40
- }
41
- return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)));
42
- }
43
- catch {
44
- throw new Error('refactor-root-control-response-invalid');
45
- }
46
- finally {
47
- if (!complete)
48
- await reader.cancel().catch(() => undefined);
49
- reader.releaseLock();
50
- }
51
- }
52
- export async function requestRootControl(family, input, fetchFn = fetch) {
53
- if (family !== 'refactor' && family !== 'qa')
54
- throw new Error('refactor-root-control-arguments-invalid');
55
- const target = `/api/v1/invoke/${family}/control`;
56
- const attempt = signNxInvokeRequest({ method: 'POST', target,
57
- body: Buffer.from(JSON.stringify({ projectId: input.projectId, storyId: input.storyId,
58
- platformTarget: input.platformTarget, registryVersion: COMMAND_REGISTRY_VERSION, registryChecksum: COMMAND_REGISTRY_CHECKSUM })),
59
- bearerToken: input.token, clientVersion: CLIENT_VERSION });
60
- const response = await fetchFn(`${input.serverUrl.replace(/\/+$/, '')}${target}`, {
61
- method: 'POST', redirect: 'error', signal: AbortSignal.timeout(200000),
62
- headers: { ...attempt.headers, Authorization: `Bearer ${input.token}` }, body: attempt.body,
63
- });
64
- const value = await readControlResponse(response);
65
- if (!response.ok)
66
- throw new Error(typeof value?.error_code === 'string'
67
- && CONTROL_ERRORS.has(value.error_code.replace(/^qa-/, 'refactor-')) && value.error_code.startsWith(`${family}-`) ? value.error_code : 'refactor-root-control-request-refused');
68
- const keys = ['schemaVersion', 'kind', 'status', 'completedStages', 'authority', 'qaAccepted', 'gitAuthority', 'billingAuthority', 'publicSafe'];
69
- if (!value || typeof value !== 'object' || Array.isArray(value)
70
- || Object.keys(value).some(key => !keys.includes(key))
71
- || value.schemaVersion !== 1 || value.kind !== `root-${family}-control`
72
- || typeof value.status !== 'string' || !['advanced', 'waiting', 'blocked', 'candidate-ready', ...(family === 'qa' ? ['debt'] : [])].includes(value.status)
73
- || value.authority !== (family === 'qa' ? 'LOCAL_ROOT_QA_CANDIDATE_ONLY' : 'LOCAL_ROOT_CANDIDATE_ONLY') || value.qaAccepted !== false
74
- || value.gitAuthority !== 'NONE' || value.billingAuthority !== 'NONE' || value.publicSafe !== true
75
- || value.completedStages !== undefined && (typeof value.completedStages !== 'number' || !Number.isInteger(value.completedStages)
76
- || value.completedStages < 0 || value.completedStages > (family === 'qa' ? 3 : 7))) {
77
- throw new Error('refactor-root-control-response-invalid');
78
- }
79
- return value;
80
- }
81
- export async function requestRefactorControl(input, fetchFn = fetch) {
82
- return requestRootControl('refactor', input, fetchFn);
83
- }
84
- export async function refactorControlCliHandler(args, family = 'refactor') {
85
- try {
86
- let root = '';
87
- let storyId = '';
88
- let authorized = false;
89
- let format = 'json';
90
- const tokens = [...args];
91
- if (tokens.shift() !== 'control')
92
- throw new Error('refactor-root-control-arguments-invalid');
93
- for (let i = 0; i < tokens.length; i++) {
94
- const token = tokens[i];
95
- if (token === '--authorize-root-control')
96
- authorized = true;
97
- else if (token === '--project-root')
98
- root = tokens[++i] ?? '';
99
- else if (token === '--story')
100
- storyId = tokens[++i] ?? '';
101
- else if (token === '--format')
102
- format = tokens[++i] ?? '';
103
- else
104
- throw new Error('refactor-root-control-arguments-invalid');
105
- }
106
- if (!authorized || !root || format !== 'json' || !/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/.test(storyId)) {
107
- throw new Error('refactor-root-control-authorization-required');
108
- }
109
- const platformTarget = detectPlatform({ cwd: resolve(root), env: process.env }).targetId;
110
- if (platformTarget !== 'codex')
111
- throw new Error('refactor-root-control-host-unsupported');
112
- const path = join(resolve(root), '.neocortex', 'state.json');
113
- const stat = lstatSync(path);
114
- if (!stat.isFile() || stat.isSymbolicLink() || realpathSync(path) !== path || stat.size > 16 * 1024 * 1024) {
115
- throw new Error('refactor-root-control-project-unbound');
116
- }
117
- const projectId = JSON.parse(readFileSync(path, 'utf8')).config?.project_id;
118
- if (typeof projectId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/.test(projectId)) {
119
- throw new Error('refactor-root-control-project-unbound');
120
- }
121
- const config = loadSecureConfig({ strictReadOnly: true });
122
- if (!config?.licenseKey)
123
- throw new Error('refactor-root-control-auth-required');
124
- const serverUrl = process.env.NEOCORTEX_SERVER_URL ?? config.serverUrl;
125
- if (!serverUrl)
126
- throw new Error('refactor-root-control-auth-required');
127
- const token = await new LicenseClient({ serverUrl, licenseKey: config.licenseKey,
128
- cacheProvider: new EncryptedCache({ cacheDir: join(neocortexProfileDirectory(), 'cache'), passphrase: config.licenseKey }) }).getToken();
129
- if (!token)
130
- throw new Error('refactor-root-control-auth-required');
131
- const result = await requestRootControl(family, { serverUrl, token, projectId, storyId, platformTarget });
132
- process.stdout.write(`${JSON.stringify({ ok: true, control: result })}\n`);
133
- return 0;
134
- }
135
- catch (error) {
136
- const message = error instanceof Error ? error.message.replace(/^qa-/, 'refactor-') : '';
137
- const reasonCode = CLIENT_CONTROL_ERRORS.has(message) || CONTROL_ERRORS.has(message)
138
- ? message : 'refactor-root-control-outcome-unknown';
139
- process.stdout.write(`${JSON.stringify({ ok: false, reasonCode: family === 'qa' ? reasonCode.replace(/^refactor-/, 'qa-') : reasonCode })}\n`);
140
- return 1;
141
- }
142
- }
1
+ import{lstatSync as S,readFileSync as v,realpathSync as R}from"node:fs";import{join as w,resolve as g}from"node:path";import{signNxInvokeRequest as k}from"../../../shared/dist/nx-invoke-signature.js";import{COMMAND_REGISTRY_VERSION as q,COMMAND_REGISTRY_CHECKSUM as C}from"../generated/command-registry.generated.js";import{CLIENT_VERSION as N}from"../version.js";import{loadSecureConfig as b}from"../config/secure-config.js";import{neocortexProfileDirectory as _}from"../config/profile-directory.js";import{EncryptedCache as A}from"../cache/encrypted-cache.js";import{LicenseClient as T}from"../license/license-client.js";import{detectPlatform as I}from"../adapters/platform-detector.js";const y=new Set(["refactor-control-input-invalid","refactor-control-auth-required","refactor-control-tier-required","refactor-control-read-only","refactor-control-signature-required","refactor-control-client-unsupported","refactor-control-registry-mismatch","refactor-control-executor-unavailable"]),L=new Set(["arguments-invalid","authorization-required","host-unsupported","project-unbound","auth-required","response-invalid","request-refused","outcome-unknown"].map(e=>`refactor-root-control-${e}`));async function j(e){const o=e.body?.getReader();if(!o)throw new Error("refactor-root-control-response-invalid");let n=!1;try{const t=[];let c=0;for(;;){const a=await o.read();if(a.done){n=!0;break}if(c+=a.value.byteLength,c>16384)throw new Error("refactor-root-control-response-invalid");t.push(Buffer.from(a.value))}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(t,c)))}catch{throw new Error("refactor-root-control-response-invalid")}finally{n||await o.cancel().catch(()=>{}),o.releaseLock()}}async function E(e,o,n=fetch){if(e!=="refactor"&&e!=="qa")throw new Error("refactor-root-control-arguments-invalid");const t=`/api/v1/invoke/${e}/control`,c=k({method:"POST",target:t,body:Buffer.from(JSON.stringify({projectId:o.projectId,storyId:o.storyId,platformTarget:o.platformTarget,registryVersion:q,registryChecksum:C})),bearerToken:o.token,clientVersion:N}),a=await n(`${o.serverUrl.replace(/\/+$/,"")}${t}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(2e5),headers:{...c.headers,Authorization:`Bearer ${o.token}`},body:c.body}),r=await j(a);if(!a.ok)throw new Error(typeof r?.error_code=="string"&&y.has(r.error_code.replace(/^qa-/,"refactor-"))&&r.error_code.startsWith(`${e}-`)?r.error_code:"refactor-root-control-request-refused");const l=["schemaVersion","kind","status","completedStages","authority","qaAccepted","gitAuthority","billingAuthority","publicSafe"];if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(s=>!l.includes(s))||r.schemaVersion!==1||r.kind!==`root-${e}-control`||typeof r.status!="string"||!["advanced","waiting","blocked","candidate-ready",...e==="qa"?["debt"]:[]].includes(r.status)||r.authority!==(e==="qa"?"LOCAL_ROOT_QA_CANDIDATE_ONLY":"LOCAL_ROOT_CANDIDATE_ONLY")||r.qaAccepted!==!1||r.gitAuthority!=="NONE"||r.billingAuthority!=="NONE"||r.publicSafe!==!0||r.completedStages!==void 0&&(typeof r.completedStages!="number"||!Number.isInteger(r.completedStages)||r.completedStages<0||r.completedStages>(e==="qa"?3:7)))throw new Error("refactor-root-control-response-invalid");return r}async function B(e,o=fetch){return E("refactor",e,o)}async function Y(e,o="refactor"){try{let n="",t="",c=!1,a="json";const r=[...e];if(r.shift()!=="control")throw new Error("refactor-root-control-arguments-invalid");for(let i=0;i<r.length;i++){const d=r[i];if(d==="--authorize-root-control")c=!0;else if(d==="--project-root")n=r[++i]??"";else if(d==="--story")t=r[++i]??"";else if(d==="--format")a=r[++i]??"";else throw new Error("refactor-root-control-arguments-invalid")}if(!c||!n||a!=="json"||!/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/.test(t))throw new Error("refactor-root-control-authorization-required");const l=I({cwd:g(n),env:process.env}).targetId;if(l!=="codex")throw new Error("refactor-root-control-host-unsupported");const s=w(g(n),".neocortex","state.json"),u=S(s);if(!u.isFile()||u.isSymbolicLink()||R(s)!==s||u.size>16*1024*1024)throw new Error("refactor-root-control-project-unbound");const p=JSON.parse(v(s,"utf8")).config?.project_id;if(typeof p!="string"||!/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/.test(p))throw new Error("refactor-root-control-project-unbound");const f=b({strictReadOnly:!0});if(!f?.licenseKey)throw new Error("refactor-root-control-auth-required");const h=process.env.NEOCORTEX_SERVER_URL??f.serverUrl;if(!h)throw new Error("refactor-root-control-auth-required");const m=await new T({serverUrl:h,licenseKey:f.licenseKey,cacheProvider:new A({cacheDir:w(_(),"cache"),passphrase:f.licenseKey})}).getToken();if(!m)throw new Error("refactor-root-control-auth-required");const O=await E(o,{serverUrl:h,token:m,projectId:p,storyId:t,platformTarget:l});return process.stdout.write(`${JSON.stringify({ok:!0,control:O})}
2
+ `),0}catch(n){const t=n instanceof Error?n.message.replace(/^qa-/,"refactor-"):"",c=L.has(t)||y.has(t)?t:"refactor-root-control-outcome-unknown";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:o==="qa"?c.replace(/^refactor-/,"qa-"):c})}
3
+ `),1}}export{Y as refactorControlCliHandler,B as requestRefactorControl,E as requestRootControl};