@ornexus/neocortex 4.61.5 → 4.61.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -220
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -260
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -364
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +148 -7822
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -174
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  76. package/packages/client/dist/commands/story-worktree.js +5 -258
  77. package/packages/client/dist/config/host-auth-broker.js +1 -60
  78. package/packages/client/dist/config/host-auth-reference.js +1 -93
  79. package/packages/client/dist/config/profile-directory.js +1 -13
  80. package/packages/client/dist/config/resolver-selection.js +1 -278
  81. package/packages/client/dist/config/secure-config.js +12 -281
  82. package/packages/client/dist/config.js +2 -224
  83. package/packages/client/dist/constants.js +1 -25
  84. package/packages/client/dist/context/context-collector.js +2 -222
  85. package/packages/client/dist/context/context-sanitizer.js +1 -145
  86. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  87. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  88. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  89. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  90. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  91. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  92. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  93. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  94. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  95. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  96. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  97. package/packages/client/dist/continuity/outbox.js +1 -117
  98. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  99. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  100. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  101. package/packages/client/dist/errors/error-messages.js +2 -258
  102. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  103. package/packages/client/dist/evidence/collector.js +1 -347
  104. package/packages/client/dist/evidence/index.js +1 -1
  105. package/packages/client/dist/evidence/types.js +0 -2
  106. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  107. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  108. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  109. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  110. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +70 -0
  111. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1592
  112. package/packages/client/dist/git/epic-operational-state.js +2 -672
  113. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  114. package/packages/client/dist/git/git-lifecycle-store.d.ts +22 -0
  115. package/packages/client/dist/git/git-lifecycle-store.js +8 -2529
  116. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  117. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  118. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  119. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  120. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  121. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  122. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  123. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  124. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  125. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  126. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  127. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  128. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  129. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  130. package/packages/client/dist/i18n/first-run.js +2 -60
  131. package/packages/client/dist/index.js +1 -50
  132. package/packages/client/dist/invocation/invoke-input.js +1 -24
  133. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  134. package/packages/client/dist/license/index.js +1 -5
  135. package/packages/client/dist/license/license-client.js +1 -337
  136. package/packages/client/dist/machine/fingerprint.js +2 -163
  137. package/packages/client/dist/machine/index.js +1 -5
  138. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  139. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  140. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  141. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  142. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  143. package/packages/client/dist/migrations/project-identity.js +7 -493
  144. package/packages/client/dist/migrations/state-json.js +4 -393
  145. package/packages/client/dist/policy/architecture-policy.js +2 -184
  146. package/packages/client/dist/policy/index.js +1 -7
  147. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  148. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  149. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  150. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  151. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  152. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  153. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  154. package/packages/client/dist/private-execution/delivery.js +13 -410
  155. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  156. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  157. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  158. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  159. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  160. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  161. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  162. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  163. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  164. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  165. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  166. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  167. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  168. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  169. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  170. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  171. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  172. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  173. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  174. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  175. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  176. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  177. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  178. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  179. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  180. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  181. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  182. package/packages/client/dist/private-execution/session-lease.js +1 -63
  183. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  184. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  185. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  186. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  187. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  188. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  189. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  190. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  191. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  192. package/packages/client/dist/resilience/index.js +1 -8
  193. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  194. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  195. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  196. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  197. package/packages/client/dist/runner/binary.js +1 -404
  198. package/packages/client/dist/runner/cli.js +17 -1571
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.js +1 -85
  202. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  203. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  204. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  205. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  206. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  207. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  208. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  209. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  210. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  211. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  212. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  213. package/packages/client/dist/runner/headless/resolver.js +1 -231
  214. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  215. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  216. package/packages/client/dist/runner/headless/types.js +2 -575
  217. package/packages/client/dist/runner/host-capacity.js +1 -59
  218. package/packages/client/dist/runner/local-console.js +13 -396
  219. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  220. package/packages/client/dist/runner/project-identity.js +1 -106
  221. package/packages/client/dist/runner/scheduler.js +7 -995
  222. package/packages/client/dist/runner-cli.js +2 -18
  223. package/packages/client/dist/state/invocation-shape.js +1 -13
  224. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  225. package/packages/client/dist/state/state-json-repair.js +3 -785
  226. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  227. package/packages/client/dist/telemetry/index.js +1 -5
  228. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  229. package/packages/client/dist/tier/index.js +1 -5
  230. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  231. package/packages/client/dist/types/index.js +1 -38
  232. package/packages/client/dist/version.js +1 -27
  233. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  234. package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
  235. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  236. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  237. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  238. package/packages/client/dist/yoloop/index.js +1 -8
  239. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  240. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  241. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  242. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  243. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  244. package/targets-stubs/antigravity/gemini.md +1 -1
  245. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  246. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  247. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  248. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  249. package/targets-stubs/claude-code/neocortex.md +2 -2
  250. package/targets-stubs/codex/AGENTS.md +1 -1
  251. package/targets-stubs/cursor/agent.md +2 -2
  252. package/targets-stubs/gemini-cli/agent.md +2 -2
  253. package/targets-stubs/opencode/neocortex-root.md +1 -1
  254. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,262 +1 @@
1
- import { execFileSync, spawnSync } from 'node:child_process';
2
- import { realpathSync } from 'node:fs';
3
- import { createYoloChangeEvidence } from '../../../shared/dist/yolo/change-evidence.js';
4
- import { readGitLifecycleRuntimeSync } from '../git/git-lifecycle-store.js';
5
- export class YoloChangeEvidenceUnavailableError extends Error {
6
- diagnostic;
7
- constructor(diagnostic) {
8
- super('yolo-change-evidence-unavailable');
9
- this.name = 'YoloChangeEvidenceUnavailableError';
10
- this.diagnostic = Object.freeze({ ...diagnostic });
11
- }
12
- }
13
- export function yoloChangeEvidenceDiagnostic(error) {
14
- return error instanceof YoloChangeEvidenceUnavailableError ? error.diagnostic : undefined;
15
- }
16
- const NO_REPAIR = Object.freeze({
17
- repair: 'not-attempted', recollectionCount: 0,
18
- });
19
- function fallbackAction(reason) {
20
- if (reason === 'lease-owner-mismatch' || reason === 'lease-invalid-or-nonsetup'
21
- || reason === 'direct-yolo-writer-active')
22
- return 'resolve-lease-conflict';
23
- if (reason === 'base-ref-missing' || reason === 'base-observation-unavailable'
24
- || reason === 'base-observation-timeout' || reason === 'base-object-missing' || reason === 'base-not-ancestor'
25
- || reason === 'diff-read-unavailable')
26
- return 'restore-verified-base-evidence';
27
- if (reason === 'execution-branch-mismatch'
28
- || reason.startsWith('direct-yolo-'))
29
- return 'inspect-repository-binding';
30
- return 'none';
31
- }
32
- function unavailable(reason, baseSource, reconciliation = NO_REPAIR, repair = reconciliation.repair) {
33
- throw new YoloChangeEvidenceUnavailableError({
34
- reason,
35
- baseSource,
36
- repair,
37
- recollectionCount: reconciliation.recollectionCount,
38
- fallbackAction: fallbackAction(reason),
39
- publicSafe: true,
40
- });
41
- }
42
- /** Reacquire only an expired setup lease for this exact story through P207's CAS boundary. */
43
- export async function reconcileYoloChangeEvidenceLease(options) {
44
- let runtime;
45
- try {
46
- runtime = readGitLifecycleRuntimeSync(options.projectRoot, { required: true });
47
- }
48
- catch (error) {
49
- // C01 can legitimately precede first-use sidecar materialization. Only
50
- // that exact absence falls through to the existing remote/base evidence.
51
- if (error instanceof Error && error.message === 'git-lifecycle-runtime-missing')
52
- return NO_REPAIR;
53
- unavailable('runtime-state-unavailable', 'none');
54
- }
55
- const lease = runtime.epics[options.epicId]?.branch_lease;
56
- if (lease === null || lease === undefined)
57
- return NO_REPAIR;
58
- if (typeof lease !== 'object' || Array.isArray(lease)) {
59
- unavailable('lease-invalid-or-nonsetup', 'active-story-lease', NO_REPAIR, 'not-eligible');
60
- }
61
- if (lease.ownerStoryId !== options.storyId) {
62
- unavailable('lease-owner-mismatch', 'active-story-lease', NO_REPAIR, 'not-eligible');
63
- }
64
- if (typeof lease.expiresAt !== 'string') {
65
- unavailable('lease-invalid-or-nonsetup', 'active-story-lease', NO_REPAIR, 'not-eligible');
66
- }
67
- const expiry = Date.parse(lease.expiresAt);
68
- if (!Number.isFinite(expiry)) {
69
- unavailable('lease-invalid-or-nonsetup', 'active-story-lease', NO_REPAIR, 'not-eligible');
70
- }
71
- if (expiry > Date.now())
72
- return NO_REPAIR;
73
- if (typeof lease.sessionId !== 'string'
74
- || !/^setup-[a-f0-9]{64}$/.test(lease.sessionId)
75
- || lease.idempotencyKey !== lease.sessionId) {
76
- unavailable('lease-invalid-or-nonsetup', 'active-story-lease', NO_REPAIR, 'not-eligible');
77
- }
78
- const { prepareDirectYoloSetup } = await import('../git/direct-yolo-checkpoint.js');
79
- const result = await prepareDirectYoloSetup({
80
- ...options,
81
- expiredSetupRecovery: {
82
- schemaVersion: 1,
83
- expectedRuntimeRevision: runtime.revision,
84
- expectedLease: Object.freeze({ ...lease }),
85
- },
86
- });
87
- if (!result.ok) {
88
- unavailable(result.reasonCode, 'active-story-lease', NO_REPAIR, 'not-eligible');
89
- }
90
- if (result.value.storyId !== options.storyId
91
- || result.value.epicId !== options.epicId
92
- || Date.parse(result.value.leaseExpiresAt) <= Date.now()) {
93
- unavailable('lease-invalid-or-nonsetup', 'active-story-lease', NO_REPAIR, 'not-eligible');
94
- }
95
- return Object.freeze({ repair: 'applied', recollectionCount: 1 });
96
- }
97
- function git(root, args, reason, baseSource, reconciliation) {
98
- try {
99
- return execFileSync('git', ['-C', root, ...args], {
100
- encoding: 'utf8', timeout: 3_000, maxBuffer: 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'],
101
- });
102
- }
103
- catch {
104
- unavailable(reason, baseSource, reconciliation);
105
- }
106
- }
107
- // Remote observation crosses the network: local Git reads keep the 3 s bound,
108
- // but `ls-remote` gets a longer bound and one retry, and a timeout is reported
109
- // distinctly so a slow network is never mistaken for missing base evidence.
110
- const REMOTE_OBSERVATION_TIMEOUT_MS = 15_000;
111
- const REMOTE_OBSERVATION_ATTEMPTS = 2;
112
- function gitRemote(root, args, baseSource, reconciliation) {
113
- let timedOut = false;
114
- for (let attempt = 0; attempt < REMOTE_OBSERVATION_ATTEMPTS; attempt += 1) {
115
- try {
116
- return execFileSync('git', ['-C', root, ...args], {
117
- encoding: 'utf8', timeout: REMOTE_OBSERVATION_TIMEOUT_MS, maxBuffer: 1024 * 1024,
118
- stdio: ['ignore', 'pipe', 'ignore'],
119
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
120
- });
121
- }
122
- catch (error) {
123
- const code = error.code;
124
- const signal = error.signal;
125
- timedOut = code === 'ETIMEDOUT' || signal === 'SIGTERM';
126
- }
127
- }
128
- unavailable(timedOut ? 'base-observation-timeout' : 'base-observation-unavailable', baseSource, reconciliation);
129
- }
130
- function gitRefExists(root, ref, reconciliation) {
131
- const result = spawnSync('git', ['-C', root, 'show-ref', '--verify', '--quiet', ref], {
132
- timeout: 3_000, stdio: 'ignore',
133
- });
134
- if (result.status === 0)
135
- return true;
136
- if (result.status === 1)
137
- return false;
138
- unavailable('base-observation-unavailable', 'none', reconciliation);
139
- }
140
- function gitObjectExists(root, object, source, reconciliation) {
141
- const result = spawnSync('git', ['-C', root, 'cat-file', '-e', `${object}^{commit}`], {
142
- timeout: 3_000, stdio: 'ignore',
143
- });
144
- if (result.status === 0)
145
- return true;
146
- if (result.status === 1 || result.status === 128)
147
- return false;
148
- unavailable('base-observation-unavailable', source, reconciliation);
149
- }
150
- export function collectYoloChangeEvidence(options) {
151
- const reconciliation = options.reconciliation ?? NO_REPAIR;
152
- if (!/^[A-Za-z0-9][A-Za-z0-9_./-]{0,119}$/.test(options.defaultBranch)
153
- || options.defaultBranch.includes('..'))
154
- unavailable('invalid-default-branch', 'none', reconciliation);
155
- let repositoryRoot;
156
- try {
157
- repositoryRoot = git(options.projectRoot, ['rev-parse', '--show-toplevel'], 'repository-root-mismatch', 'none', reconciliation).trim();
158
- if (realpathSync(repositoryRoot) !== realpathSync(options.projectRoot)) {
159
- unavailable('repository-root-mismatch', 'none', reconciliation);
160
- }
161
- }
162
- catch (error) {
163
- if (error instanceof YoloChangeEvidenceUnavailableError)
164
- throw error;
165
- unavailable('repository-root-mismatch', 'none', reconciliation);
166
- }
167
- const headSha = git(options.projectRoot, ['rev-parse', 'HEAD'], 'base-observation-unavailable', 'none', reconciliation).trim();
168
- if (headSha !== options.expectedHeadSha)
169
- throw new Error('yolo-change-evidence-stale');
170
- let baseSha;
171
- let baseSource = 'none';
172
- let activeStoryLease = false;
173
- let executionBranch = null;
174
- if (options.storyId && options.epicId) {
175
- let runtime;
176
- try {
177
- runtime = readGitLifecycleRuntimeSync(options.projectRoot);
178
- }
179
- catch {
180
- unavailable('runtime-state-unavailable', 'none', reconciliation);
181
- }
182
- const epic = runtime.epics[options.epicId];
183
- // 4.61.5: inside a P225 story worktree the epic writer lease belongs to the
184
- // root integration, not to this story; isolation comes from the story
185
- // worktree lease, so the epic lease is not consulted here.
186
- const lease = isActiveStoryWorktree(options.projectRoot, runtime, options.storyId) ? undefined : epic?.branch_lease;
187
- const currentBranch = git(options.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD'], 'execution-branch-mismatch', 'none', reconciliation).trim();
188
- if (epic?.branch_mode === 'epic' && epic.execution_branch === currentBranch)
189
- executionBranch = currentBranch;
190
- if (lease && typeof lease === 'object' && !Array.isArray(lease)) {
191
- const item = lease;
192
- if (item.ownerStoryId !== options.storyId) {
193
- unavailable('lease-owner-mismatch', 'active-story-lease', reconciliation, 'not-eligible');
194
- }
195
- if (typeof item.expiresAt !== 'string' || !Number.isFinite(Date.parse(item.expiresAt))
196
- || Date.parse(item.expiresAt) <= Date.now()) {
197
- unavailable('lease-invalid-or-nonsetup', 'active-story-lease', reconciliation, 'not-eligible');
198
- }
199
- if (executionBranch === null) {
200
- unavailable('execution-branch-mismatch', 'active-story-lease', reconciliation, 'not-eligible');
201
- }
202
- activeStoryLease = true;
203
- }
204
- }
205
- if (activeStoryLease) {
206
- // The live setup lease explicitly scopes evidence to current story bytes.
207
- baseSha = headSha;
208
- baseSource = 'active-story-lease';
209
- }
210
- else {
211
- const remoteLine = executionBranch === null ? '' : gitRemote(options.projectRoot, [
212
- 'ls-remote', '--heads', 'origin', `refs/heads/${executionBranch}`,
213
- ], 'published-execution-branch', reconciliation).trim();
214
- if (remoteLine) {
215
- baseSource = 'published-execution-branch';
216
- const match = /^([a-f0-9]{40})\trefs\/heads\/([^\n]+)$/.exec(remoteLine);
217
- if (!match || match[2] !== executionBranch) {
218
- unavailable('base-observation-unavailable', baseSource, reconciliation);
219
- }
220
- if (!gitObjectExists(options.projectRoot, match[1], baseSource, reconciliation)) {
221
- unavailable('base-object-missing', baseSource, reconciliation);
222
- }
223
- const ancestor = spawnSync('git', ['-C', options.projectRoot,
224
- 'merge-base', '--is-ancestor', match[1], 'HEAD'], { timeout: 3_000, stdio: 'ignore' });
225
- if (ancestor.status !== 0)
226
- unavailable('base-not-ancestor', baseSource, reconciliation);
227
- baseSha = match[1];
228
- }
229
- else {
230
- const localRef = `refs/heads/${options.defaultBranch}`;
231
- const remoteRef = `refs/remotes/origin/${options.defaultBranch}`;
232
- const selectedRef = gitRefExists(options.projectRoot, localRef, reconciliation)
233
- ? localRef
234
- : gitRefExists(options.projectRoot, remoteRef, reconciliation) ? remoteRef : null;
235
- if (!selectedRef)
236
- unavailable('base-ref-missing', 'none', reconciliation);
237
- baseSource = selectedRef === localRef ? 'local-default-branch' : 'remote-default-branch';
238
- baseSha = git(options.projectRoot, ['merge-base', 'HEAD', selectedRef], 'base-not-ancestor', baseSource, reconciliation).trim();
239
- }
240
- }
241
- const tracked = git(options.projectRoot, ['diff', '--name-only', '-z', baseSha, '--'], 'diff-read-unavailable', baseSource, reconciliation).split('\0').filter(Boolean);
242
- const untracked = git(options.projectRoot, ['ls-files', '--others', '--exclude-standard', '-z'], 'diff-read-unavailable', baseSource, reconciliation).split('\0').filter(Boolean);
243
- const evidence = createYoloChangeEvidence({ baseSha, headSha, changedPaths: [...tracked, ...untracked] });
244
- if (git(options.projectRoot, ['rev-parse', 'HEAD'], 'base-observation-unavailable', baseSource, reconciliation).trim() !== headSha) {
245
- throw new Error('yolo-change-evidence-stale');
246
- }
247
- return evidence;
248
- }
249
- /** True when `projectRoot` is the registered, active story worktree of `storyId`. */
250
- function isActiveStoryWorktree(projectRoot, runtime, storyId) {
251
- const toplevel = spawnSync('git', ['-C', projectRoot, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 3_000 });
252
- if (toplevel.status !== 0)
253
- return false;
254
- let root;
255
- try {
256
- root = realpathSync(toplevel.stdout.trim());
257
- }
258
- catch {
259
- return false;
260
- }
261
- return Object.values(runtime.storyWorktrees?.entries ?? {}).some((entry) => entry.storyId === storyId && entry.state === 'active' && entry.worktreePath === root);
262
- }
1
+ import{execFileSync as w,spawnSync as m}from"node:child_process";import{realpathSync as I}from"node:fs";import{createYoloChangeEvidence as A}from"../../../shared/dist/yolo/change-evidence.js";import{readGitLifecycleRuntimeSync as R}from"../git/git-lifecycle-store.js";class E extends Error{diagnostic;constructor(t){super("yolo-change-evidence-unavailable"),this.name="YoloChangeEvidenceUnavailableError",this.diagnostic=Object.freeze({...t})}}function P(e){return e instanceof E?e.diagnostic:void 0}const u=Object.freeze({repair:"not-attempted",recollectionCount:0});function _(e){return e==="lease-owner-mismatch"||e==="lease-invalid-or-nonsetup"||e==="direct-yolo-writer-active"?"resolve-lease-conflict":e==="base-ref-missing"||e==="base-observation-unavailable"||e==="base-observation-timeout"||e==="base-object-missing"||e==="base-not-ancestor"||e==="diff-read-unavailable"?"restore-verified-base-evidence":e==="execution-branch-mismatch"||e.startsWith("direct-yolo-")?"inspect-repository-binding":"none"}function i(e,t,n=u,r=n.repair){throw new E({reason:e,baseSource:t,repair:r,recollectionCount:n.recollectionCount,fallbackAction:_(e),publicSafe:!0})}async function $(e){let t;try{t=R(e.projectRoot,{required:!0})}catch(d){if(d instanceof Error&&d.message==="git-lifecycle-runtime-missing")return u;i("runtime-state-unavailable","none")}const n=await T(e.projectRoot,t,e.storyId,e.epicId);if(n)return Object.freeze({...u,storyWorktree:n});const r=t.epics[e.epicId]?.branch_lease;if(r==null)return u;(typeof r!="object"||Array.isArray(r))&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),r.ownerStoryId!==e.storyId&&i("lease-owner-mismatch","active-story-lease",u,"not-eligible"),typeof r.expiresAt!="string"&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const a=Date.parse(r.expiresAt);if(Number.isFinite(a)||i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),a>Date.now())return u;(typeof r.sessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.sessionId)||r.idempotencyKey!==r.sessionId)&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const{prepareDirectYoloSetup:o}=await import("../git/direct-yolo-checkpoint.js"),s=await o({...e,expiredSetupRecovery:{schemaVersion:1,expectedRuntimeRevision:t.revision,expectedLease:Object.freeze({...r})}});return s.ok||i(s.reasonCode,"active-story-lease",u,"not-eligible"),(s.value.storyId!==e.storyId||s.value.epicId!==e.epicId||Date.parse(s.value.leaseExpiresAt)<=Date.now())&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),Object.freeze({repair:"applied",recollectionCount:1})}function h(e,t,n,r,a){try{return w("git",["-C",e,...t],{encoding:"utf8",timeout:3e3,maxBuffer:1024*1024,stdio:["ignore","pipe","ignore"]})}catch{i(n,r,a)}}const C=15e3,O=2;function k(e,t,n,r){let a=!1;for(let o=0;o<O;o+=1)try{return w("git",["-C",e,...t],{encoding:"utf8",timeout:C,maxBuffer:1024*1024,stdio:["ignore","pipe","ignore"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}catch(s){const d=s.code,b=s.signal;a=d==="ETIMEDOUT"||b==="SIGTERM"}i(a?"base-observation-timeout":"base-observation-unavailable",n,r)}function x(e,t,n){const r=m("git",["-C",e,"show-ref","--verify","--quiet",t],{timeout:3e3,stdio:"ignore"});if(r.status===0)return!0;if(r.status===1)return!1;i("base-observation-unavailable","none",n)}function D(e,t,n,r){const a=m("git",["-C",e,"cat-file","-e",`${t}^{commit}`],{timeout:3e3,stdio:"ignore"});if(a.status===0)return!0;if(a.status===1||a.status===128)return!1;i("base-observation-unavailable",n,r)}function L(e){const t=e.reconciliation??u;(!/^[A-Za-z0-9][A-Za-z0-9_./-]{0,119}$/.test(e.defaultBranch)||e.defaultBranch.includes(".."))&&i("invalid-default-branch","none",t);let n;try{n=h(e.projectRoot,["rev-parse","--show-toplevel"],"repository-root-mismatch","none",t).trim(),I(n)!==I(e.projectRoot)&&i("repository-root-mismatch","none",t)}catch(f){if(f instanceof E)throw f;i("repository-root-mismatch","none",t)}const r=h(e.projectRoot,["rev-parse","HEAD"],"base-observation-unavailable","none",t).trim();if(r!==e.expectedHeadSha)throw new Error("yolo-change-evidence-stale");let a,o="none",s=!1,d,b=null;if(e.storyId&&e.epicId&&t.storyWorktree){let f;try{f=R(e.projectRoot,{required:!0})}catch{i("runtime-state-unavailable","none",t)}const c=t.storyWorktree,l=f.storyWorktrees?.entries[c.leaseId];(!l||l.storyId!==e.storyId||l.epicId!==e.epicId||l.state!=="active"||l.worktreePath!==S(e.projectRoot)||(l.syncedSha??l.baseSha)!==c.baseSha)&&i("lease-invalid-or-nonsetup","active-story-lease",t,"not-eligible"),m("git",["-C",e.projectRoot,"merge-base","--is-ancestor",c.baseSha,"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor","active-story-lease",t,"not-eligible"),d=c.baseSha}else if(e.storyId&&e.epicId){let f;try{f=R(e.projectRoot)}catch{i("runtime-state-unavailable","none",t)}const c=f.epics[e.epicId],l=B(e.projectRoot,f,e.storyId)?void 0:c?.branch_lease,v=h(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"],"execution-branch-mismatch","none",t).trim();if(c?.branch_mode==="epic"&&c.execution_branch===v&&(b=v),l&&typeof l=="object"&&!Array.isArray(l)){const g=l;g.ownerStoryId!==e.storyId&&i("lease-owner-mismatch","active-story-lease",t,"not-eligible"),(typeof g.expiresAt!="string"||!Number.isFinite(Date.parse(g.expiresAt))||Date.parse(g.expiresAt)<=Date.now())&&i("lease-invalid-or-nonsetup","active-story-lease",t,"not-eligible"),b===null&&i("execution-branch-mismatch","active-story-lease",t,"not-eligible"),s=!0}}if(d)a=d,o="active-story-lease";else if(s)a=r,o="active-story-lease";else{const f=b===null?"":k(e.projectRoot,["ls-remote","--heads","origin",`refs/heads/${b}`],"published-execution-branch",t).trim();if(f){o="published-execution-branch";const c=/^([a-f0-9]{40})\trefs\/heads\/([^\n]+)$/.exec(f);(!c||c[2]!==b)&&i("base-observation-unavailable",o,t),D(e.projectRoot,c[1],o,t)||i("base-object-missing",o,t),m("git",["-C",e.projectRoot,"merge-base","--is-ancestor",c[1],"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor",o,t),a=c[1]}else{const c=`refs/heads/${e.defaultBranch}`,l=`refs/remotes/origin/${e.defaultBranch}`,v=x(e.projectRoot,c,t)?c:x(e.projectRoot,l,t)?l:null;v||i("base-ref-missing","none",t),o=v===c?"local-default-branch":"remote-default-branch",a=h(e.projectRoot,["merge-base","HEAD",v],"base-not-ancestor",o,t).trim()}}const y=h(e.projectRoot,["diff","--name-only","-z",a,"--"],"diff-read-unavailable",o,t).split("\0").filter(Boolean),j=h(e.projectRoot,["ls-files","--others","--exclude-standard","-z"],"diff-read-unavailable",o,t).split("\0").filter(Boolean),p=A({baseSha:a,headSha:r,changedPaths:[...y,...j]});if(h(e.projectRoot,["rev-parse","HEAD"],"base-observation-unavailable",o,t).trim()!==r)throw new Error("yolo-change-evidence-stale");return p}function S(e){const t=m("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",timeout:3e3});if(t.status===0)try{return I(t.stdout.trim())}catch{return}}async function T(e,t,n,r){const a=S(e);if(!a)return;const o=Object.values(t.storyWorktrees?.entries??{}).filter(p=>p.storyId===n&&p.worktreePath===a);if(o.length===0)return;const s=o[0];(o.length>1||s.state!=="active"||s.epicId!==r)&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const{StoryWorktreeManager:d}=await import("../git/story-worktree-manager.js"),b=await new d({projectRoot:e}).probe(s.leaseId);(!b.ok||b.value.ownership!=="proven")&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const y=s.syncedSha??s.baseSha;return m("git",["-C",e,"merge-base","--is-ancestor",y,"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor","active-story-lease",u,"not-eligible"),Object.freeze({leaseId:s.leaseId,baseSha:y})}function B(e,t,n){const r=m("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",timeout:3e3});if(r.status!==0)return!1;let a;try{a=I(r.stdout.trim())}catch{return!1}return Object.values(t.storyWorktrees?.entries??{}).some(o=>o.storyId===n&&o.state==="active"&&o.worktreePath===a)}export{E as YoloChangeEvidenceUnavailableError,L as collectYoloChangeEvidence,$ as reconcileYoloChangeEvidenceLease,P as yoloChangeEvidenceDiagnostic};
@@ -1,65 +1 @@
1
- import { YOLO_INVOKE_ENVELOPE_CAPABILITY } from '../../../shared/dist/yolo/spec-envelope.js';
2
- const MAX_CAPABILITY_RESPONSE_BYTES = 16 * 1024;
3
- const PUBLIC_VERSION = /^[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}(?:-[A-Za-z0-9.-]{1,40})?$/;
4
- function result(supported, reason, serverVersion) {
5
- return Object.freeze({
6
- supported,
7
- capability: YOLO_INVOKE_ENVELOPE_CAPABILITY,
8
- reason,
9
- ...(serverVersion && PUBLIC_VERSION.test(serverVersion) ? { serverVersion } : {}),
10
- publicSafe: true,
11
- });
12
- }
13
- /**
14
- * Non-mutating, fail-closed compatibility probe for targeted YOLO requests.
15
- * Older strict servers must be rejected before local release-gate execution.
16
- */
17
- export async function probeYoloInvokeEnvelopeCapability(serverUrl, fetcher = globalThis.fetch) {
18
- if (!fetcher)
19
- return result(false, 'fetch-unavailable');
20
- const controller = new AbortController();
21
- const timeout = setTimeout(() => controller.abort(), 5_000);
22
- timeout.unref?.();
23
- try {
24
- // `/health` serves the same handler as `/api/v1/health` but is exempt from
25
- // the API rate limit, so parallel story-worktree children cannot turn a
26
- // 429 into a false `capability-missing`.
27
- const response = await fetcher(`${serverUrl.replace(/\/+$/, '')}/health`, {
28
- method: 'GET',
29
- headers: { accept: 'application/json' },
30
- signal: controller.signal,
31
- });
32
- if (!response.ok)
33
- return result(false, 'http-rejected');
34
- const raw = await response.text();
35
- if (Buffer.byteLength(raw, 'utf8') > MAX_CAPABILITY_RESPONSE_BYTES) {
36
- return result(false, 'response-too-large');
37
- }
38
- let parsed;
39
- try {
40
- parsed = JSON.parse(raw);
41
- }
42
- catch {
43
- return result(false, 'response-invalid');
44
- }
45
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
46
- return result(false, 'response-invalid');
47
- }
48
- const record = parsed;
49
- const capabilities = record.capabilities;
50
- const serverVersion = typeof record.version === 'string' ? record.version : undefined;
51
- if (!Array.isArray(capabilities)
52
- || capabilities.some((value) => typeof value !== 'string' || value.length > 80)) {
53
- return result(false, 'response-invalid', serverVersion);
54
- }
55
- return capabilities.includes(YOLO_INVOKE_ENVELOPE_CAPABILITY)
56
- ? result(true, 'supported', serverVersion)
57
- : result(false, 'capability-missing', serverVersion);
58
- }
59
- catch {
60
- return result(false, 'request-failed');
61
- }
62
- finally {
63
- clearTimeout(timeout);
64
- }
65
- }
1
+ import{YOLO_INVOKE_ENVELOPE_CAPABILITY as u}from"../../../shared/dist/yolo/spec-envelope.js";const y=16*1024,b=/^[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}(?:-[A-Za-z0-9.-]{1,40})?$/;function e(n,a,t){return Object.freeze({supported:n,capability:u,reason:a,...t&&b.test(t)?{serverVersion:t}:{},publicSafe:!0})}async function h(n,a=globalThis.fetch){if(!a)return e(!1,"fetch-unavailable");const t=new AbortController,l=setTimeout(()=>t.abort(),5e3);l.unref?.();try{const c=await a(`${n.replace(/\/+$/,"")}/health`,{method:"GET",headers:{accept:"application/json"},signal:t.signal});if(!c.ok)return e(!1,"http-rejected");const f=await c.text();if(Buffer.byteLength(f,"utf8")>y)return e(!1,"response-too-large");let r;try{r=JSON.parse(f)}catch{return e(!1,"response-invalid")}if(!r||typeof r!="object"||Array.isArray(r))return e(!1,"response-invalid");const s=r,i=s.capabilities,o=typeof s.version=="string"?s.version:void 0;return!Array.isArray(i)||i.some(p=>typeof p!="string"||p.length>80)?e(!1,"response-invalid",o):i.includes(u)?e(!0,"supported",o):e(!1,"capability-missing",o)}catch{return e(!1,"request-failed")}finally{clearTimeout(l)}}export{h as probeYoloInvokeEnvelopeCapability};
@@ -1,184 +1,5 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
- import { join, sep } from 'node:path';
4
- import { createYoloSpecEnvelopeV1, YOLO_SPEC_MAX_ARTIFACTS, } from '../../../shared/dist/yolo/spec-envelope.js';
5
- import { inspectFrontmatterContext } from '../../../shared/dist/frontmatter-context-contract.js';
6
- const TEMPLATE_PATHS = [
7
- 'core/templates/specs/feature-spec-template.md',
8
- 'core/templates/specs/architecture-spec-template.md',
9
- 'core/templates/specs/contract-spec-template.md',
10
- 'core/templates/specs/story-spec-template.md',
11
- 'core/templates/specs/traceability-matrix-template.md',
12
- ];
13
- const REFERENCE_PATH = /(?:^|[\s([`'";])((?:docs\/(?:stories|epics|specs|architecture|examples)\/|core\/templates\/specs\/)[A-Za-z0-9_./-]+\.(?:md|mdx|feature))(?:$|[\s)\]`'",;])/gm;
14
- const STORY_ID = /^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)+$/;
15
- // Resource-safety stop only. Ordinary envelope sizing belongs to the existing
16
- // invoke request guardrail, not to a smaller 64/128 KiB document policy.
17
- const YOLO_SPEC_LOCAL_SOURCE_SAFETY_LIMIT_BYTES = 16 * 1024 * 1024;
18
- /** Resolve only an explicit story target. Inline YOLO text intentionally has no match. */
19
- export function extractTargetedYoloStoryId(args) {
20
- const pathMatches = [...args.matchAll(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)+)\.story\.md(?=\s|$)/g)]
21
- .map((match) => match[1]);
22
- const tokenMatches = args.trim().split(/\s+/).slice(1)
23
- .map((token) => token.replace(/^@/, ''))
24
- .filter((token) => STORY_ID.test(token));
25
- const matches = [...new Set([...pathMatches, ...tokenMatches])];
26
- return matches.length === 1 ? matches[0] : null;
27
- }
28
- function artifactKind(path) {
29
- if (path.startsWith('core/templates/'))
30
- return 'template';
31
- if (path.startsWith('docs/epics/'))
32
- return 'epic';
33
- if (path.startsWith('docs/stories/') && path.endsWith('.story.md'))
34
- return 'story';
35
- if (path.endsWith('.rtm.md'))
36
- return 'traceability';
37
- if (path.toLowerCase().includes('adr'))
38
- return 'adr';
39
- if (path.toLowerCase().includes('contract'))
40
- return 'contract';
41
- if (path.toLowerCase().includes('nfr'))
42
- return 'nfr';
43
- if (path.endsWith('.feature'))
44
- return 'bdd';
45
- if (path.toLowerCase().includes('traceability'))
46
- return 'traceability';
47
- if (path.startsWith('docs/examples/'))
48
- return 'example';
49
- return 'spec';
50
- }
51
- function selectedReferencePaths(story) {
52
- return [...new Set([...story.matchAll(REFERENCE_PATH)].map((match) => match[1]).filter((path) => Boolean(path)))].sort();
53
- }
54
- function safeSource(root, path) {
55
- const rootReal = realpathSync(root);
56
- let fileReal;
57
- try {
58
- fileReal = realpathSync(join(rootReal, path));
59
- }
60
- catch {
61
- throw new Error('yolo-spec-envelope-required');
62
- }
63
- if (!fileReal.startsWith(`${rootReal}${sep}`))
64
- throw new Error('yolo-spec-envelope-path-out-of-scope');
65
- const sourceStat = statSync(fileReal);
66
- if (!sourceStat.isFile())
67
- throw new Error('yolo-spec-envelope-unsafe');
68
- if (sourceStat.size > YOLO_SPEC_LOCAL_SOURCE_SAFETY_LIMIT_BYTES)
69
- throw new Error('yolo-spec-envelope-too-large');
70
- return readFileSync(fileReal, 'utf8');
71
- }
72
- function publicMarkdown(source, kind) {
73
- const context = kind === 'story' ? 'story-target' : 'epic-target';
74
- const inspected = inspectFrontmatterContext(source, { context, explicitlySelected: true });
75
- if (inspected.status === 'malformed' || inspected.status === 'oversized')
76
- throw new Error('yolo-spec-envelope-unsafe');
77
- if (inspected.status === 'absent')
78
- return source;
79
- const match = source.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);
80
- if (!match)
81
- throw new Error('yolo-spec-envelope-unsafe');
82
- const fields = Object.entries(inspected.metadata).map(([key, value]) => `${key}: ${JSON.stringify(value)}`);
83
- return `---\n${fields.join('\n')}\n---\n${source.slice(match[0].length)}`;
84
- }
85
- function readHeadSha(root) {
86
- try {
87
- return execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], {
88
- encoding: 'utf8', timeout: 2_000, stdio: ['ignore', 'pipe', 'ignore'],
89
- }).trim();
90
- }
91
- catch {
92
- throw new Error('yolo-spec-envelope-stale');
93
- }
94
- }
95
- export function collectYoloSpecEnvelope(options) {
96
- const targetPath = `docs/stories/${options.storyId}.story.md`;
97
- const epicPath = `docs/epics/epic-${options.epicId}.md`;
98
- const initialHead = options.headSha ?? readHeadSha(options.projectRoot);
99
- const story = publicMarkdown(safeSource(options.projectRoot, targetPath), 'story');
100
- const epic = publicMarkdown(safeSource(options.projectRoot, epicPath), 'epic');
101
- const artifacts = [
102
- { kind: 'story', path: targetPath, content: story },
103
- { kind: 'epic', path: epicPath, content: epic },
104
- ];
105
- const coreStoryReferences = new Set([
106
- `docs/stories/${options.storyId}.spec.md`,
107
- `docs/stories/${options.storyId}.tasks.md`,
108
- `docs/stories/${options.storyId}.rtm.md`,
109
- ]);
110
- // Older stories may not link to their own SDD files. Bind physically present
111
- // siblings to the same HEAD/content checks as explicitly referenced files.
112
- const selectedReferences = [...new Set([
113
- ...selectedReferencePaths(story),
114
- ...[...coreStoryReferences].filter((path) => existsSync(join(options.projectRoot, path))),
115
- ])].sort();
116
- const prioritizedReferences = [
117
- ...selectedReferences.filter((path) => coreStoryReferences.has(path)),
118
- ...selectedReferences.filter((path) => !coreStoryReferences.has(path)),
119
- ];
120
- let omittedReferences = 0;
121
- for (const path of prioritizedReferences) {
122
- if (path === targetPath || path === epicPath || !existsSync(join(options.projectRoot, path)))
123
- continue;
124
- // A foreign story/epic is a target conflict, never optional context. The
125
- // byte budget must not turn a prior target-mismatch denial into admission.
126
- if ((path.startsWith('docs/stories/') && path.endsWith('.story.md'))
127
- || path.startsWith('docs/epics/'))
128
- throw new Error('yolo-spec-envelope-target-mismatch');
129
- const content = safeSource(options.projectRoot, path);
130
- if (artifacts.length >= YOLO_SPEC_MAX_ARTIFACTS) {
131
- if (coreStoryReferences.has(path))
132
- throw new Error('yolo-spec-envelope-too-large');
133
- omittedReferences += 1;
134
- continue;
135
- }
136
- artifacts.push({ kind: artifactKind(path), path, content });
137
- }
138
- // Templates and non-core references are supporting context. Preserve the
139
- // story's own SDD artifacts and signal omissions without exposing paths.
140
- if (omittedReferences)
141
- options.onOmittedReferences?.(omittedReferences);
142
- for (const path of TEMPLATE_PATHS) {
143
- if (path === targetPath || path === epicPath || selectedReferences.includes(path)
144
- || !existsSync(join(options.projectRoot, path)))
145
- continue;
146
- const content = safeSource(options.projectRoot, path);
147
- if (artifacts.length >= YOLO_SPEC_MAX_ARTIFACTS)
148
- continue;
149
- artifacts.push({ kind: artifactKind(path), path, content });
150
- }
151
- const envelope = createYoloSpecEnvelopeV1({
152
- storyId: options.storyId,
153
- epicId: options.epicId,
154
- targetPath,
155
- inputSha256: options.inputSha256,
156
- headSha: initialHead,
157
- collectedAt: options.collectedAt ?? new Date().toISOString(),
158
- artifacts,
159
- });
160
- const finalHead = options.headSha ?? readHeadSha(options.projectRoot);
161
- if (initialHead !== finalHead
162
- || publicMarkdown(safeSource(options.projectRoot, targetPath), 'story') !== story
163
- || publicMarkdown(safeSource(options.projectRoot, epicPath), 'epic') !== epic
164
- || artifacts.some((artifact) => artifact.kind !== 'story' && artifact.kind !== 'epic'
165
- && safeSource(options.projectRoot, artifact.path) !== artifact.content)) {
166
- throw new Error('yolo-spec-envelope-stale');
167
- }
168
- return envelope;
169
- }
170
- /**
171
- * Reissue a precollected physical snapshot with a fresh bounded transport time.
172
- * The caller still performs the final disk/HEAD collection and digest comparison.
173
- */
174
- export function refreshPrecollectedYoloSpecEnvelope(envelope, collectedAt = new Date().toISOString()) {
175
- return createYoloSpecEnvelopeV1({
176
- storyId: envelope.storyId,
177
- epicId: envelope.epicId,
178
- targetPath: envelope.targetPath,
179
- inputSha256: envelope.inputSha256,
180
- headSha: envelope.sourceRevision.headSha,
181
- collectedAt,
182
- artifacts: envelope.artifacts.map(({ kind, path, content }) => ({ kind, path, content })),
183
- });
184
- }
1
+ import{execFileSync as _}from"node:child_process";import{existsSync as u,readFileSync as j,realpathSync as y,statSync as x}from"node:fs";import{join as l,sep as $}from"node:path";import{createYoloSpecEnvelopeV1 as S,YOLO_SPEC_MAX_ARTIFACTS as w}from"../../../shared/dist/yolo/spec-envelope.js";import{inspectFrontmatterContext as v}from"../../../shared/dist/frontmatter-context-contract.js";const C=["core/templates/specs/feature-spec-template.md","core/templates/specs/architecture-spec-template.md","core/templates/specs/contract-spec-template.md","core/templates/specs/story-spec-template.md","core/templates/specs/traceability-matrix-template.md"],O=/(?:^|[\s([`'";])((?:docs\/(?:stories|epics|specs|architecture|examples)\/|core\/templates\/specs\/)[A-Za-z0-9_./-]+\.(?:md|mdx|feature))(?:$|[\s)\]`'",;])/gm,P=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)+$/,T=16*1024*1024;function F(e){const r=[...e.matchAll(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)+)\.story\.md(?=\s|$)/g)].map(c=>c[1]),s=e.trim().split(/\s+/).slice(1).map(c=>c.replace(/^@/,"")).filter(c=>P.test(c)),o=[...new Set([...r,...s])];return o.length===1?o[0]:null}function R(e){return e.startsWith("core/templates/")?"template":e.startsWith("docs/epics/")?"epic":e.startsWith("docs/stories/")&&e.endsWith(".story.md")?"story":e.endsWith(".rtm.md")?"traceability":e.toLowerCase().includes("adr")?"adr":e.toLowerCase().includes("contract")?"contract":e.toLowerCase().includes("nfr")?"nfr":e.endsWith(".feature")?"bdd":e.toLowerCase().includes("traceability")?"traceability":e.startsWith("docs/examples/")?"example":"spec"}function W(e){return[...new Set([...e.matchAll(O)].map(r=>r[1]).filter(r=>!!r))].sort()}function a(e,r){const s=y(e);let o;try{o=y(l(s,r))}catch{throw new Error("yolo-spec-envelope-required")}if(!o.startsWith(`${s}${$}`))throw new Error("yolo-spec-envelope-path-out-of-scope");const c=x(o);if(!c.isFile())throw new Error("yolo-spec-envelope-unsafe");if(c.size>T)throw new Error("yolo-spec-envelope-too-large");return j(o,"utf8")}function d(e,r){const o=v(e,{context:r==="story"?"story-target":"epic-target",explicitlySelected:!0});if(o.status==="malformed"||o.status==="oversized")throw new Error("yolo-spec-envelope-unsafe");if(o.status==="absent")return e;const c=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);if(!c)throw new Error("yolo-spec-envelope-unsafe");return`---
2
+ ${Object.entries(o.metadata).map(([n,i])=>`${n}: ${JSON.stringify(i)}`).join(`
3
+ `)}
4
+ ---
5
+ ${e.slice(c[0].length)}`}function E(e){try{return _("git",["-C",e,"rev-parse","HEAD"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("yolo-spec-envelope-stale")}}function Z(e){const r=`docs/stories/${e.storyId}.story.md`,s=`docs/epics/epic-${e.epicId}.md`,o=e.headSha??E(e.projectRoot),c=d(a(e.projectRoot,r),"story"),p=d(a(e.projectRoot,s),"epic"),n=[{kind:"story",path:r,content:c},{kind:"epic",path:s,content:p}],i=new Set([`docs/stories/${e.storyId}.spec.md`,`docs/stories/${e.storyId}.tasks.md`,`docs/stories/${e.storyId}.rtm.md`]),f=[...new Set([...W(c),...[...i].filter(t=>u(l(e.projectRoot,t)))])].sort(),g=[...f.filter(t=>i.has(t)),...f.filter(t=>!i.has(t))];let m=0;for(const t of g){if(t===r||t===s||!u(l(e.projectRoot,t)))continue;if(t.startsWith("docs/stories/")&&t.endsWith(".story.md")||t.startsWith("docs/epics/"))throw new Error("yolo-spec-envelope-target-mismatch");const h=a(e.projectRoot,t);if(n.length>=w){if(i.has(t))throw new Error("yolo-spec-envelope-too-large");m+=1;continue}n.push({kind:R(t),path:t,content:h})}m&&e.onOmittedReferences?.(m);for(const t of C){if(t===r||t===s||f.includes(t)||!u(l(e.projectRoot,t)))continue;const h=a(e.projectRoot,t);n.length>=w||n.push({kind:R(t),path:t,content:h})}const A=S({storyId:e.storyId,epicId:e.epicId,targetPath:r,inputSha256:e.inputSha256,headSha:o,collectedAt:e.collectedAt??new Date().toISOString(),artifacts:n}),I=e.headSha??E(e.projectRoot);if(o!==I||d(a(e.projectRoot,r),"story")!==c||d(a(e.projectRoot,s),"epic")!==p||n.some(t=>t.kind!=="story"&&t.kind!=="epic"&&a(e.projectRoot,t.path)!==t.content))throw new Error("yolo-spec-envelope-stale");return A}function H(e,r=new Date().toISOString()){return S({storyId:e.storyId,epicId:e.epicId,targetPath:e.targetPath,inputSha256:e.inputSha256,headSha:e.sourceRevision.headSha,collectedAt:r,artifacts:e.artifacts.map(({kind:s,path:o,content:c})=>({kind:s,path:o,content:c}))})}export{Z as collectYoloSpecEnvelope,F as extractTargetedYoloStoryId,H as refreshPrecollectedYoloSpecEnvelope};