@ornexus/neocortex 4.61.6 → 4.64.0

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 (99) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +28 -5
  5. package/package.json +6 -4
  6. package/packages/client/dist/agent/refresh-stubs.d.ts +6 -0
  7. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  8. package/packages/client/dist/agent/update-description.d.ts +8 -1
  9. package/packages/client/dist/agent/update-description.js +2 -1
  10. package/packages/client/dist/commands/invoke.d.ts +24 -0
  11. package/packages/client/dist/commands/invoke.js +73 -73
  12. package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
  13. package/packages/client/dist/commands/refresh-memory.js +5 -3
  14. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  15. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
  16. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +110 -10
  17. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -4
  18. package/packages/client/dist/git/git-lifecycle-store.d.ts +96 -2
  19. package/packages/client/dist/git/git-lifecycle-store.js +8 -7
  20. package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
  21. package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
  22. package/packages/client/dist/git/release-gate-env.d.ts +23 -0
  23. package/packages/client/dist/git/release-gate-env.js +1 -0
  24. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  25. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -9
  26. package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
  27. package/packages/client/dist/git/state-json-field-merge.js +2 -0
  28. package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
  29. package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
  30. package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
  31. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  32. package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
  33. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  34. package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
  35. package/packages/client/dist/git/story-worktree-paths.js +1 -1
  36. package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
  37. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  38. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  39. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  40. package/packages/client/dist/runner/headless/child-env.js +1 -0
  41. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -11
  42. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +31 -0
  43. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -10
  44. package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
  45. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  46. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  47. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  48. package/packages/client/dist/runner/headless/types.d.ts +9 -1
  49. package/packages/client/dist/runner/headless/types.js +2 -2
  50. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  51. package/packages/client/dist/state/state-json-repair.d.ts +23 -0
  52. package/packages/client/dist/state/state-json-repair.js +4 -3
  53. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  54. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  55. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -1
  56. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  57. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  58. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  59. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  60. package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
  61. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  62. package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
  63. package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
  64. package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
  65. package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
  66. package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
  67. package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
  68. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +62 -1
  69. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  70. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
  71. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  72. package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +92 -0
  73. package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
  74. package/packages/shared/dist/compatibility/index.js +6 -0
  75. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  76. package/packages/shared/dist/project-manifest-projection.js +202 -0
  77. package/packages/shared/dist/project-validation-commands.js +14 -6
  78. package/packages/shared/dist/release-gate-env-contract.js +129 -0
  79. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  80. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  81. package/packages/shared/dist/yoloop/branch-unit.js +119 -3
  82. package/packages/shared/dist/yoloop/epic-terminal-git.js +98 -6
  83. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  84. package/targets-stubs/antigravity/gemini.md +1 -1
  85. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  86. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  87. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  88. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  89. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  90. package/targets-stubs/claude-code/neocortex.md +5 -5
  91. package/targets-stubs/codex/AGENTS.md +1 -1
  92. package/targets-stubs/codex/install-codex.sh +12 -4
  93. package/targets-stubs/cursor/agent.md +2 -2
  94. package/targets-stubs/gemini-cli/agent.md +2 -2
  95. package/targets-stubs/lib/managed-config-merge.js +459 -5
  96. package/targets-stubs/lib/managed-profile.sh +54 -7
  97. package/targets-stubs/opencode/neocortex-root.md +1 -1
  98. package/targets-stubs/vscode/install-vscode.sh +21 -0
  99. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -0,0 +1,129 @@
1
+ /**
2
+ * P226.01 — `P205-CI-02-ENV` v1: versioned environment contract of the Local
3
+ * YOLO/TDD Release Gate.
4
+ *
5
+ * The contract lives in `config/release-gates.env.v1.json`, a sibling of the
6
+ * P205 manifest (`config/release-gates.v2.json`), whose closed key set is not
7
+ * changed. It declares variable NAMES only; values never appear in the file,
8
+ * reason codes, receipts, state, evidence or logs. Rejected names are never
9
+ * echoed.
10
+ *
11
+ * Everything here is pure: the parent environment and platform are injected.
12
+ * Single implementation (P227.13, D-001 paid): the published client re-exports
13
+ * the compiled module from `packages/client/src/git/release-gate-env.ts`, which
14
+ * keeps only the bounded file reader. Identity and parity are enforced by
15
+ * `packages/client/src/__tests__/release-gate-env.test.ts`.
16
+ */
17
+ export const RELEASE_GATE_ENV_CONTRACT_ID = 'P205-CI-02-ENV';
18
+ export const RELEASE_GATE_ENV_CONTRACT_PATH = 'config/release-gates.env.v1.json';
19
+ export const RELEASE_GATE_ENV_CONTRACT_MAX_BYTES = 16 * 1024;
20
+ export const RELEASE_GATE_ENV_MAX_NAMES_PER_LIST = 64;
21
+ export const RELEASE_GATE_ENV_NAME_PATTERN = /^[A-Z][A-Za-z0-9_]{0,63}$/;
22
+ /** Closed, cross-OS minimal environment always forwarded when present. */
23
+ export const RELEASE_GATE_MINIMAL_ENV = Object.freeze([
24
+ 'PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'ComSpec', 'PATHEXT',
25
+ 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL', 'TZ', 'CI',
26
+ ]);
27
+ export const P205_GATE_ENV_CONTRACT_INVALID = 'p205-gate-env-contract-invalid';
28
+ export const P205_GATE_ENV_CONTRACT_UNDECLARED = 'p205-gate-env-contract-undeclared';
29
+ export const P205_DATASOURCE_MISSING_PREFIX = 'p205-datasource-missing:';
30
+ const CONTRACT_KEYS = Object.freeze(['contract', 'optional', 'required', 'schemaVersion']);
31
+ const INVALID = Object.freeze({
32
+ ok: false,
33
+ reason: P205_GATE_ENV_CONTRACT_INVALID,
34
+ });
35
+ function validNameList(value) {
36
+ if (!Array.isArray(value) || value.length > RELEASE_GATE_ENV_MAX_NAMES_PER_LIST)
37
+ return false;
38
+ return value.every((name) => typeof name === 'string' && RELEASE_GATE_ENV_NAME_PATTERN.test(name));
39
+ }
40
+ /** Closed validator. Any defect yields one fixed reason code; nothing is echoed. */
41
+ export function validateReleaseGateEnvContract(value) {
42
+ if (!value || typeof value !== 'object' || Array.isArray(value))
43
+ return INVALID;
44
+ const record = value;
45
+ const keys = Object.keys(record).sort();
46
+ if (keys.length !== CONTRACT_KEYS.length || keys.some((key, index) => key !== CONTRACT_KEYS[index])) {
47
+ return INVALID;
48
+ }
49
+ if (record.schemaVersion !== 1 || record.contract !== RELEASE_GATE_ENV_CONTRACT_ID)
50
+ return INVALID;
51
+ if (!validNameList(record.required) || !validNameList(record.optional))
52
+ return INVALID;
53
+ // P227.13 D4: the contract file is shared by every OS and win32 env names
54
+ // are case-insensitive, so names that differ only in case are duplicates.
55
+ const all = [...record.required, ...record.optional].map((name) => name.toUpperCase());
56
+ if (new Set(all).size !== all.length)
57
+ return INVALID;
58
+ return Object.freeze({
59
+ ok: true,
60
+ contract: Object.freeze({
61
+ schemaVersion: 1,
62
+ contract: RELEASE_GATE_ENV_CONTRACT_ID,
63
+ required: Object.freeze([...record.required]),
64
+ optional: Object.freeze([...record.optional]),
65
+ }),
66
+ });
67
+ }
68
+ /** Parses UTF-8 contract text; malformed JSON is `p205-gate-env-contract-invalid`. */
69
+ export function parseReleaseGateEnvContract(text) {
70
+ let parsed;
71
+ try {
72
+ parsed = JSON.parse(text);
73
+ }
74
+ catch {
75
+ return INVALID;
76
+ }
77
+ return validateReleaseGateEnvContract(parsed);
78
+ }
79
+ function lookup(parentEnv, name, caseInsensitive) {
80
+ const direct = parentEnv[name];
81
+ if (direct !== undefined || !caseInsensitive)
82
+ return direct;
83
+ const upper = name.toUpperCase();
84
+ const match = Object.keys(parentEnv).sort().find((key) => key.toUpperCase() === upper);
85
+ return match === undefined ? undefined : parentEnv[match];
86
+ }
87
+ /**
88
+ * Projects the gate environment: present minimal names ∪ present declared names.
89
+ * Undeclared variables are dropped. A missing `required` name fails before any
90
+ * spawn with `p205-datasource-missing:<NAME>` (first missing in declared order).
91
+ */
92
+ export function projectReleaseGateEnv(input) {
93
+ const caseInsensitive = input.platform === 'win32';
94
+ const contract = input.contract;
95
+ if (contract) {
96
+ const missing = contract.required.filter((name) => lookup(input.parentEnv, name, caseInsensitive) === undefined);
97
+ if (missing.length > 0) {
98
+ return Object.freeze({
99
+ ok: false,
100
+ reason: `${P205_DATASOURCE_MISSING_PREFIX}${missing[0]}`,
101
+ missing: Object.freeze(missing),
102
+ });
103
+ }
104
+ }
105
+ const names = [];
106
+ const seen = new Set();
107
+ for (const name of [...RELEASE_GATE_MINIMAL_ENV, ...(contract?.required ?? []), ...(contract?.optional ?? [])]) {
108
+ const key = caseInsensitive ? name.toUpperCase() : name;
109
+ if (seen.has(key))
110
+ continue;
111
+ seen.add(key);
112
+ names.push(name);
113
+ }
114
+ const env = {};
115
+ const forwardedNames = [];
116
+ for (const name of names) {
117
+ const value = lookup(input.parentEnv, name, caseInsensitive);
118
+ if (value === undefined)
119
+ continue;
120
+ env[name] = value;
121
+ forwardedNames.push(name);
122
+ }
123
+ return Object.freeze({
124
+ ok: true,
125
+ env: Object.freeze(env),
126
+ forwardedNames: Object.freeze(forwardedNames),
127
+ debt: Object.freeze(contract ? [] : [P205_GATE_ENV_CONTRACT_UNDECLARED]),
128
+ });
129
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * P226.06 named content rules for the YOLO spec envelope.
3
+ *
4
+ * Each rule keeps the exact body and flags of the former single
5
+ * `PROHIBITED_CONTENT` alternative, so every previously blocked input stays
6
+ * blocked. The only exception is an `inline-credential-assignment` whose whole
7
+ * value is a strict placeholder. Findings expose a rule id and a 1-based line,
8
+ * never the matched text.
9
+ */
10
+ export const YOLO_SPEC_ENVELOPE_RULE_IDS = [
11
+ 'private-key-pem',
12
+ 'inline-credential-assignment',
13
+ 'email-address',
14
+ 'vendor-key-prefix',
15
+ 'absolute-home-path',
16
+ ];
17
+ const RULES = [
18
+ { id: 'private-key-pem', source: '-----BEGIN [A-Z ]*PRIVATE KEY-----', priority: 0 },
19
+ { id: 'vendor-key-prefix', source: '\\b(?:sk-|ghp_|github_pat_|npm_)[A-Za-z0-9_-]{12,}\\b', priority: 1 },
20
+ { id: 'inline-credential-assignment', source: '\\b(?:bearer|token|password|secret|api[_-]?key)\\s*[:=]\\s*(\\S+)', priority: 2 },
21
+ { id: 'email-address', source: '\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b', priority: 3 },
22
+ { id: 'absolute-home-path', source: '(?:^|[\\s"\'(])\\/(?:home|media|root|etc|var|Users)\\/', priority: 4 },
23
+ ];
24
+ /**
25
+ * A whole value that is exactly `<UPPER_SNAKE>`, `${UPPER_SNAKE}` or
26
+ * `{{ identifier }}`, optionally wrapped by one identical pair of quotes or
27
+ * backticks and followed by at most one closing delimiter. Case-sensitive.
28
+ */
29
+ const STRICT_PLACEHOLDER_VALUE = /^(["'`]?)(?:<[A-Z][A-Z0-9_]*>|\$\{[A-Z][A-Z0-9_]*\}|\{\{[ \t]*[A-Za-z_][A-Za-z0-9_.-]*[ \t]*\}\})\1[`"'),;.]?(?=[ \t]|$)/;
30
+ /** True only when the value (rest of its line) starts with a strict placeholder token. */
31
+ export function isStrictYoloSpecPlaceholder(value) {
32
+ const line = value.split('\n', 1)[0] ?? '';
33
+ return STRICT_PLACEHOLDER_VALUE.test(line);
34
+ }
35
+ function lineAt(content, index) {
36
+ let line = 1;
37
+ for (let cursor = content.indexOf('\n'); cursor !== -1 && cursor < index; cursor = content.indexOf('\n', cursor + 1)) {
38
+ line += 1;
39
+ }
40
+ return line;
41
+ }
42
+ function firstFindingIndex(rule, content) {
43
+ const pattern = new RegExp(rule.source, 'gim');
44
+ for (let match = pattern.exec(content); match; match = pattern.exec(content)) {
45
+ if (rule.id === 'inline-credential-assignment') {
46
+ const value = match[1] ?? '';
47
+ const valueStart = match.index + match[0].length - value.length;
48
+ if (isStrictYoloSpecPlaceholder(content.slice(valueStart))) {
49
+ // Re-scan from the next character so an overlapping assignment is never hidden.
50
+ pattern.lastIndex = match.index + 1;
51
+ continue;
52
+ }
53
+ }
54
+ const leading = /^\s*/.exec(match[0])?.[0].length ?? 0;
55
+ return match.index + leading;
56
+ }
57
+ return null;
58
+ }
59
+ /**
60
+ * Return the reported prohibited-content finding for normalized content, or
61
+ * `null`. Lowest line wins; same-line ties follow rule priority.
62
+ */
63
+ export function findYoloSpecProhibitedContent(content) {
64
+ let best = null;
65
+ for (const rule of RULES) {
66
+ const index = firstFindingIndex(rule, content);
67
+ if (index === null)
68
+ continue;
69
+ const line = lineAt(content, index);
70
+ if (!best || line < best.line || (line === best.line && rule.priority < best.priority)) {
71
+ best = { ruleId: rule.id, line, priority: rule.priority };
72
+ }
73
+ }
74
+ return best ? { ruleId: best.ruleId, line: best.line } : null;
75
+ }
76
+ const UNSAFE_REASON_CODE = new RegExp(`^yolo-spec-envelope-unsafe:(?:${YOLO_SPEC_ENVELOPE_RULE_IDS.join('|')}):[A-Za-z0-9_./-]{1,240}:[1-9][0-9]{0,8}$`);
77
+ /** `yolo-spec-envelope-unsafe:<rule>:<path>:<line>`; callers pass an allow-listed relative path. */
78
+ export function yoloSpecEnvelopeUnsafeReasonCode(ruleId, path, line) {
79
+ const code = `yolo-spec-envelope-unsafe:${ruleId}:${path}:${line}`;
80
+ return UNSAFE_REASON_CODE.test(code) ? code : 'yolo-spec-envelope-unsafe';
81
+ }
82
+ /** Strict recognizer for the qualified unsafe reason code. */
83
+ export function isYoloSpecEnvelopeUnsafeReasonCode(value) {
84
+ return typeof value === 'string' && UNSAFE_REASON_CODE.test(value);
85
+ }
@@ -1,21 +1,26 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { posix } from 'node:path';
3
3
  import { inspectFrontmatterContext } from '../frontmatter-context-contract.js';
4
+ import { findYoloSpecProhibitedContent, yoloSpecEnvelopeUnsafeReasonCode } from './spec-envelope-rules.js';
5
+ export { findYoloSpecProhibitedContent, isStrictYoloSpecPlaceholder, isYoloSpecEnvelopeUnsafeReasonCode, YOLO_SPEC_ENVELOPE_RULE_IDS, yoloSpecEnvelopeUnsafeReasonCode, } from './spec-envelope-rules.js';
4
6
  // Artifact bytes are intentionally not capped here. The invoke transport owns
5
7
  // the request-level byte guardrail; this contract owns count, shape, content,
6
8
  // target, freshness and digest integrity without a smaller duplicate ceiling.
7
9
  export const YOLO_SPEC_MAX_ARTIFACTS = 12;
8
10
  export const YOLO_SPEC_MAX_AGE_MS = 120_000;
9
11
  export const YOLO_SPEC_FUTURE_SKEW_MS = 30_000;
12
+ /** P226.07: cited foreign stories/epics are public IDs only, never content. */
13
+ export const YOLO_SPEC_MAX_REFERENCED_STORIES = 32;
10
14
  /** Public server capability for both mandatory top-level YOLO invoke fields. */
11
15
  export const YOLO_INVOKE_ENVELOPE_CAPABILITY = 'yolo-invoke-envelope-v1';
12
16
  const HASH = /^[a-f0-9]{64}$/;
13
17
  const HEAD = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
14
18
  const STORY_ID = /^[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+$/;
15
19
  const EPIC_ID = /^[A-Za-z0-9]+$/;
20
+ const REFERENCED_ID = /^[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)*$/;
21
+ const ENVELOPE_KEYS = ['schemaVersion', 'storyId', 'epicId', 'targetPath', 'inputSha256', 'sourceRevision', 'collectedAt', 'artifacts', 'envelopeSha256'];
16
22
  const KINDS = ['story', 'epic', 'spec', 'contract', 'adr', 'nfr', 'example', 'bdd', 'traceability', 'template'];
17
23
  const ALLOWED_PATH = /^(?:docs\/(?:stories|epics|specs|architecture|examples)\/|core\/templates\/specs\/)[A-Za-z0-9_./-]+$/;
18
- const PROHIBITED_CONTENT = /(?:-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:bearer|token|password|secret|api[_-]?key)\s*[:=]\s*\S+|\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b|\b(?:sk-|ghp_|github_pat_|npm_)[A-Za-z0-9_-]{12,}\b|(?:^|[\s"'(])\/(?:home|media|root|etc|var|Users)\/)/im;
19
24
  function deny(code) {
20
25
  throw new Error(code);
21
26
  }
@@ -37,12 +42,18 @@ function validPath(value) {
37
42
  && !value.includes('\\') && !value.split('/').includes('..')
38
43
  && posix.normalize(value) === value;
39
44
  }
40
- function normalizeContent(content) {
45
+ /**
46
+ * P226.06: named rules replace the former single regex. `path` is already
47
+ * allow-listed by `validPath`; the reason code carries rule/path/line only and
48
+ * never the matched text.
49
+ */
50
+ function normalizeContent(content, path) {
41
51
  if (content.includes('\0') || /\r(?!\n)/.test(content))
42
52
  deny('yolo-spec-envelope-unsafe');
43
53
  const normalized = content.replaceAll('\r\n', '\n');
44
- if (PROHIBITED_CONTENT.test(normalized))
45
- deny('yolo-spec-envelope-unsafe');
54
+ const finding = findYoloSpecProhibitedContent(normalized);
55
+ if (finding)
56
+ deny(yoloSpecEnvelopeUnsafeReasonCode(finding.ruleId, path, finding.line));
46
57
  return normalized;
47
58
  }
48
59
  function artifactManifestSha256(artifacts) {
@@ -51,6 +62,14 @@ function artifactManifestSha256(artifacts) {
51
62
  function unsignedEnvelopeSha256(value) {
52
63
  return sha256(JSON.stringify(value));
53
64
  }
65
+ function checkReferencedStories(value, storyId, epicId) {
66
+ if (!Array.isArray(value) || value.length < 1 || value.length > YOLO_SPEC_MAX_REFERENCED_STORIES
67
+ || value.some((id, index) => typeof id !== 'string' || id.length > 80 || !REFERENCED_ID.test(id)
68
+ || (index > 0 && !(String(value[index - 1]) < id))))
69
+ deny('yolo-spec-envelope-unsafe');
70
+ if (value.includes(storyId) || value.includes(epicId))
71
+ deny('yolo-spec-envelope-target-mismatch');
72
+ }
54
73
  function checkArtifact(value) {
55
74
  if (!isRecord(value) || !hasExactKeys(value, ['kind', 'path', 'content', 'byteLength', 'sha256'])
56
75
  || !KINDS.includes(String(value.kind)) || !validPath(value.path))
@@ -58,7 +77,7 @@ function checkArtifact(value) {
58
77
  if (typeof value.content !== 'string' || !Number.isSafeInteger(value.byteLength) || !HASH.test(String(value.sha256))) {
59
78
  deny('yolo-spec-envelope-unsafe');
60
79
  }
61
- const content = normalizeContent(value.content);
80
+ const content = normalizeContent(value.content, value.path);
62
81
  const bytes = Buffer.byteLength(content, 'utf8');
63
82
  if (content !== value.content || bytes !== value.byteLength || sha256(content) !== value.sha256) {
64
83
  deny('yolo-spec-envelope-digest-mismatch');
@@ -71,7 +90,7 @@ export function createYoloSpecEnvelopeV1(input) {
71
90
  if (!isRecord(artifact) || !KINDS.includes(String(artifact.kind)) || !validPath(artifact.path)
72
91
  || typeof artifact.content !== 'string')
73
92
  deny('yolo-spec-envelope-path-out-of-scope');
74
- const content = normalizeContent(artifact.content);
93
+ const content = normalizeContent(artifact.content, artifact.path);
75
94
  return {
76
95
  kind: artifact.kind,
77
96
  path: artifact.path,
@@ -89,6 +108,9 @@ export function createYoloSpecEnvelopeV1(input) {
89
108
  sourceRevision: { headSha: input.headSha, manifestSha256: artifactManifestSha256(artifacts) },
90
109
  collectedAt: input.collectedAt,
91
110
  artifacts,
111
+ ...(input.referencedStories && input.referencedStories.length > 0
112
+ ? { referencedStories: [...new Set(input.referencedStories)].sort() }
113
+ : {}),
92
114
  };
93
115
  const envelope = { ...unsigned, envelopeSha256: unsignedEnvelopeSha256(unsigned) };
94
116
  assertYoloSpecEnvelopeV1(envelope, {
@@ -98,7 +120,8 @@ export function createYoloSpecEnvelopeV1(input) {
98
120
  return envelope;
99
121
  }
100
122
  export function assertYoloSpecEnvelopeV1(value, context) {
101
- if (!isRecord(value) || !hasExactKeys(value, ['schemaVersion', 'storyId', 'epicId', 'targetPath', 'inputSha256', 'sourceRevision', 'collectedAt', 'artifacts', 'envelopeSha256'])
123
+ const hasReferences = isRecord(value) && Object.prototype.hasOwnProperty.call(value, 'referencedStories');
124
+ if (!isRecord(value) || !hasExactKeys(value, hasReferences ? [...ENVELOPE_KEYS, 'referencedStories'] : ENVELOPE_KEYS)
102
125
  || value.schemaVersion !== 1 || typeof value.storyId !== 'string' || !STORY_ID.test(value.storyId)
103
126
  || typeof value.epicId !== 'string' || !EPIC_ID.test(value.epicId)
104
127
  || !validPath(value.targetPath) || !HASH.test(String(value.inputSha256))
@@ -108,6 +131,8 @@ export function assertYoloSpecEnvelopeV1(value, context) {
108
131
  || value.targetPath !== context.targetPath || value.inputSha256 !== context.inputSha256
109
132
  || value.targetPath !== `docs/stories/${value.storyId}.story.md`)
110
133
  deny('yolo-spec-envelope-target-mismatch');
134
+ if (hasReferences)
135
+ checkReferencedStories(value.referencedStories, value.storyId, value.epicId);
111
136
  const source = value.sourceRevision;
112
137
  if (!isRecord(source) || !hasExactKeys(source, ['headSha', 'manifestSha256'])
113
138
  || !HEAD.test(String(source.headSha)) || !HASH.test(String(source.manifestSha256)))
@@ -154,6 +179,7 @@ export function assertYoloSpecEnvelopeV1(value, context) {
154
179
  sourceRevision: value.sourceRevision,
155
180
  collectedAt: value.collectedAt,
156
181
  artifacts: value.artifacts,
182
+ ...(hasReferences ? { referencedStories: value.referencedStories } : {}),
157
183
  };
158
184
  if (unsignedEnvelopeSha256(unsigned) !== value.envelopeSha256)
159
185
  deny('yolo-spec-envelope-digest-mismatch');
@@ -1,9 +1,93 @@
1
+ import { yoloopDomainHash } from './canonical.js';
1
2
  import { canonicalRootMemoryEffectJson, isRootProjectMemoryEffect } from './root-memory-effect.js';
2
3
  /**
3
4
  * Public, deterministic branch-unit contract for epic-owned YOLO/YOLOOP runs.
4
5
  * Pure data/functions only: callers own Git and filesystem effects.
5
6
  */
6
7
  export const BRANCH_UNIT_MODES = Object.freeze(['epic', 'story']);
8
+ export const BRANCH_MODE_CONVERSION_STORY_LIMIT = 256;
9
+ const BRANCH_MODE_CONVERSION_DOMAIN = 'neocortex/branch-mode-conversion/v1';
10
+ const CONVERSION_RECEIPT_KEYS = [
11
+ 'schemaVersion', 'kind', 'epicId', 'previousBranchMode', 'executionBranch', 'originBranch',
12
+ 'originHeadSha', 'stories', 'convertedAt', 'publicSafe', 'receiptDigest',
13
+ ];
14
+ const CONVERSION_STORY_KEYS = ['storyId', 'branch', 'branchSha', 'proof', 'prState', 'prNumber'];
15
+ /** Domain digest over the receipt body; `receiptDigest` never hashes itself. */
16
+ export function computeBranchModeConversionReceiptDigest(body) {
17
+ const { receiptDigest: _ignored, ...rest } = body;
18
+ return yoloopDomainHash(BRANCH_MODE_CONVERSION_DOMAIN, rest);
19
+ }
20
+ /** Pure structural, digest and binding check. Physical proof is client-owned. */
21
+ export function isBranchModeConversionReceipt(value, epic) {
22
+ if (!isPlainRecord(value) || !hasExactKeys(value, CONVERSION_RECEIPT_KEYS))
23
+ return false;
24
+ const receipt = value;
25
+ if (receipt.schemaVersion !== 1 || receipt.kind !== 'branch-mode-conversion' || receipt.publicSafe !== true)
26
+ return false;
27
+ if (!['story', 'unset', 'epic'].includes(String(receipt.previousBranchMode)))
28
+ return false;
29
+ if (!isSafeConversionToken(receipt.epicId) || receipt.epicId !== epic.id)
30
+ return false;
31
+ if (!isSafeConversionRef(receipt.executionBranch) || receipt.executionBranch !== epic.execution_branch)
32
+ return false;
33
+ if (!isSafeConversionRef(receipt.originBranch) || receipt.originBranch === receipt.executionBranch)
34
+ return false;
35
+ if (!isFullSha(receipt.originHeadSha))
36
+ return false;
37
+ if (typeof receipt.convertedAt !== 'string' || !Number.isFinite(Date.parse(receipt.convertedAt)))
38
+ return false;
39
+ if (typeof receipt.receiptDigest !== 'string' || !/^[0-9a-f]{64}$/.test(receipt.receiptDigest))
40
+ return false;
41
+ const stories = receipt.stories;
42
+ if (!Array.isArray(stories) || stories.length > BRANCH_MODE_CONVERSION_STORY_LIMIT)
43
+ return false;
44
+ let previous = null;
45
+ for (const entry of stories) {
46
+ if (!isPlainRecord(entry) || !hasExactKeys(entry, CONVERSION_STORY_KEYS))
47
+ return false;
48
+ const story = entry;
49
+ if (!isSafeConversionToken(story.storyId) || (previous !== null && !(previous < story.storyId)))
50
+ return false;
51
+ previous = story.storyId;
52
+ if (!isSafeConversionRef(story.branch) || story.branch === receipt.executionBranch)
53
+ return false;
54
+ if (!isFullSha(story.branchSha))
55
+ return false;
56
+ if (story.proof !== 'ancestor-of-origin' && story.proof !== 'patch-equivalent')
57
+ return false;
58
+ if (story.prState !== 'none' && story.prState !== 'merged' && story.prState !== 'closed')
59
+ return false;
60
+ if (!(story.prNumber === null || (Number.isSafeInteger(story.prNumber) && Number(story.prNumber) > 0)))
61
+ return false;
62
+ if (story.prState === 'none' && story.prNumber !== null)
63
+ return false;
64
+ }
65
+ return computeBranchModeConversionReceiptDigest(receipt)
66
+ === receipt.receiptDigest;
67
+ }
68
+ /** Branch refs a receipt can carry; Git may accept names this contract does not (P227.20 F8). */
69
+ export function isBranchModeConversionRef(value) {
70
+ return isSafeConversionRef(value);
71
+ }
72
+ function isPlainRecord(value) {
73
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
74
+ }
75
+ function hasExactKeys(value, keys) {
76
+ const actual = Object.keys(value);
77
+ return actual.length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
78
+ }
79
+ function isSafeConversionToken(value) {
80
+ return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
81
+ }
82
+ function isSafeConversionRef(value) {
83
+ return typeof value === 'string' && value.length <= 200
84
+ && /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)
85
+ && !value.includes('..') && !value.includes('//') && !value.endsWith('/')
86
+ && !value.endsWith('.lock') && !value.endsWith('.');
87
+ }
88
+ function isFullSha(value) {
89
+ return typeof value === 'string' && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(value);
90
+ }
7
91
  const LEGACY_INTEGRATION_STEPS = new Set([
8
92
  'step-c-09-sync-main',
9
93
  'step-c-10-create-pr',
@@ -24,11 +108,27 @@ export function resolveBranchUnit(epic, stories) {
24
108
  return resolution('story', 'recorded', true, epic, ['branch-mode-recorded-story']);
25
109
  }
26
110
  if (epic.branch_mode === 'epic') {
27
- const conflictingEvidence = classifyRecordedEpicStoryGitEvidence(epic, stories);
111
+ // P227.20: a valid conversion receipt neutralizes only the evidence it proved.
112
+ const receiptPresent = epic.branch_mode_conversion_receipt !== undefined && epic.branch_mode_conversion_receipt !== null;
113
+ const receipt = receiptPresent && isBranchModeConversionReceipt(epic.branch_mode_conversion_receipt, epic)
114
+ ? epic.branch_mode_conversion_receipt
115
+ : undefined;
116
+ const receiptCodes = !receiptPresent ? []
117
+ : receipt ? ['branch-mode-conversion-receipt-recognized'] : ['branch-mode-conversion-receipt-invalid'];
118
+ // P227.25 DEC (LF-1): a recorded epic mode without `execution_branch` (the
119
+ // create-epic shape P227.22 repairs) derives `epic/<ID>`, the branch the
120
+ // P227.21 start binding captures. Evidence is judged against the derived
121
+ // branch, so any story branch, checkpoint branch or PR that differs still
122
+ // fails closed below. The receipt above was validated against the recorded
123
+ // field only: a derived branch never validates a conversion receipt.
124
+ const derivedExecutionBranch = !nonEmpty(epic.execution_branch) ? `epic/${epic.id}` : undefined;
125
+ const effectiveEpic = derivedExecutionBranch ? { ...epic, execution_branch: derivedExecutionBranch } : epic;
126
+ const conflictingEvidence = classifyRecordedEpicStoryGitEvidence(effectiveEpic, stories, receipt);
28
127
  if (conflictingEvidence === 'strong') {
29
128
  return resolution('story', 'legacy-progress', true, epic, [
30
129
  'branch-mode-conflict-legacy-progress-preserved',
31
130
  'branch-mode-recorded-epic-not-applied',
131
+ ...receiptCodes,
32
132
  ]);
33
133
  }
34
134
  if (conflictingEvidence === 'ambiguous') {
@@ -36,9 +136,14 @@ export function resolveBranchUnit(epic, stories) {
36
136
  'branch-mode-conflict-legacy-progress-preserved',
37
137
  'branch-mode-conflict-ambiguous-story-git-evidence',
38
138
  'branch-mode-recorded-epic-not-applied',
139
+ ...receiptCodes,
39
140
  ]);
40
141
  }
41
- return resolution('epic', 'recorded', hasEpicGitProgress(epic, stories), epic, ['branch-mode-recorded-epic']);
142
+ return resolution('epic', 'recorded', hasEpicGitProgress(epic, stories), effectiveEpic, [
143
+ 'branch-mode-recorded-epic',
144
+ ...(derivedExecutionBranch ? ['branch-mode-recorded-epic-derived-execution-branch'] : []),
145
+ ...receiptCodes,
146
+ ]);
42
147
  }
43
148
  if (legacyProgress || stories.some(hasAnyStoryProgress)) {
44
149
  return resolution('story', 'legacy-progress', true, epic, ['legacy-story-git-progress-detected']);
@@ -315,13 +420,24 @@ function hasLegacyStoryGitProgress(story) {
315
420
  * different branch can override the immutable epic boundary. Malformed PR
316
421
  * metadata at a PR-producing step remains fail-closed and publicly diagnosable.
317
422
  */
318
- function classifyRecordedEpicStoryGitEvidence(epic, stories) {
423
+ function classifyRecordedEpicStoryGitEvidence(epic, stories, conversionReceipt) {
319
424
  let result = 'none';
320
425
  const executionBranch = nonEmpty(epic.execution_branch) ? epic.execution_branch.trim() : null;
426
+ const proven = new Map((conversionReceipt?.stories ?? []).map((entry) => [entry.storyId, entry]));
321
427
  for (const story of stories) {
322
428
  const storyBranch = nonEmpty(story.branch_name) ? story.branch_name.trim() : null;
323
429
  const checkpointBranch = nonEmpty(story.checkpoint?.branch) ? story.checkpoint.branch.trim() : null;
324
430
  const steps = new Set(story.steps_completed ?? []);
431
+ const hasMalformedMarker = story.pr_number !== null && story.pr_number !== undefined &&
432
+ !(typeof story.pr_number === 'number' && story.pr_number > 0);
433
+ // P227.20 R3: proven legacy evidence is not a conflict while it still matches the receipt.
434
+ const entry = proven.get(story.id);
435
+ if (entry && !hasMalformedMarker &&
436
+ (storyBranch === null || storyBranch === executionBranch || storyBranch === entry.branch) &&
437
+ (checkpointBranch === null || checkpointBranch === executionBranch || checkpointBranch === entry.branch) &&
438
+ (!(typeof story.pr_number === 'number' && story.pr_number > 0) || story.pr_number === entry.prNumber)) {
439
+ continue;
440
+ }
325
441
  if ((storyBranch && storyBranch !== executionBranch) ||
326
442
  (checkpointBranch && checkpointBranch !== executionBranch) ||
327
443
  (typeof story.pr_number === 'number' && story.pr_number > 0) ||
@@ -1,5 +1,7 @@
1
1
  /** Public contracts and pure safety decisions for epic-owned terminal Git. */
2
2
  import { createHash } from 'node:crypto';
3
+ // P226.05 (AC4/F2): reconciliation coverage delegates to the shared matcher.
4
+ import { storyWriteSetCoversWithControlFiles } from './story-write-scope.js';
3
5
  /**
4
6
  * P205 complete-gate budgets are declared in config/release-gates.v2.json and
5
7
  * mirrored here so installed clients keep the same closed runtime bounds.
@@ -55,6 +57,10 @@ export const EPIC_TERMINAL_GIT_REASON_CODES = Object.freeze({
55
57
  REMOTE_DELETE_CAS_UNAVAILABLE: 'git-resource-remote-delete-cas-unavailable',
56
58
  ORIGIN_CAPTURE_WINDOW_MISSED: 'epic-origin-binding-capture-window-missed',
57
59
  ORIGIN_PHYSICAL_DRIFT: 'epic-origin-binding-physical-drift',
60
+ /** P227.12: the remote-tracking ref diverged from (or raced) the freshly fetched origin head. */
61
+ ORIGIN_REF_STALE: 'epic-head-reconciliation-origin-ref-stale',
62
+ /** P227.12: a configured `origin` remote could not be queried or fetched; never falls back to local refs. */
63
+ ORIGIN_FETCH_UNAVAILABLE: 'epic-head-reconciliation-origin-fetch-unavailable',
58
64
  PHYSICAL_REVALIDATION_REQUIRED: 'epic-terminal-physical-revalidation-required',
59
65
  PHYSICAL_ANCESTRY_UNPROVEN: 'epic-terminal-physical-ancestry-unproven',
60
66
  PR_STRICT_BASE_GUARD_REQUIRED: 'epic-terminal-pr-strict-base-guard-required',
@@ -98,6 +104,14 @@ export function epicHeadReconciliationInputDigest(value) {
98
104
  changedPathsDigest: value.changedPathsDigest,
99
105
  allowedWriteSet: value.allowedWriteSet,
100
106
  allowedWriteSetDigest: value.allowedWriteSetDigest,
107
+ // Absent optional fields are omitted by JSON.stringify, so legacy receipts
108
+ // keep a byte-identical digest (P226.15 NFR-COMPAT).
109
+ originSyncHeadSha: value.originSyncHeadSha,
110
+ originSyncCommitShas: value.originSyncCommitShas,
111
+ originSyncPaths: value.originSyncPaths,
112
+ originSyncPathsDigest: value.originSyncPathsDigest,
113
+ originSyncResolvedPaths: value.originSyncResolvedPaths,
114
+ originSyncResolvedPathsDigest: value.originSyncResolvedPathsDigest,
101
115
  aggregateReceiptRef: value.aggregateReceiptRef,
102
116
  aggregateManifestDigest: value.aggregateManifestDigest,
103
117
  aggregateResultDigest: value.aggregateResultDigest,
@@ -141,7 +155,9 @@ export function validateEpicHeadReconciliationReceipt(value, expected) {
141
155
  || !sameOrdered(value.allowedWriteSet, [...new Set(value.allowedWriteSet)].sort())
142
156
  || value.changedPaths.some((path) => !safeRepositoryPath(path))
143
157
  || value.allowedWriteSet.some((path) => !safeWriteScope(path))
144
- || value.changedPaths.some((path) => !value.allowedWriteSet.some((scope) => writeScopeCovers(scope, path)))
158
+ || !validOriginSyncEvidence(value)
159
+ || value.changedPaths.some((path) => !storyWriteSetCoversWithControlFiles(value.allowedWriteSet, value.acceptedCheckpointIds, path) && !(value.originSyncPaths ?? []).includes(path)
160
+ && !(value.originSyncResolvedPaths ?? []).includes(path))
145
161
  || value.commitRangeDigest !== epicHeadReconciliationRangeDigest(value.lastAcceptedCheckpointHeadSha, value.executionHeadSha, value.reconciliationCommitShas)
146
162
  || value.changedPathsDigest !== epicHeadReconciliationPathsDigest(value.changedPaths)
147
163
  || value.allowedWriteSetDigest !== epicHeadReconciliationPathsDigest(value.allowedWriteSet)
@@ -157,6 +173,86 @@ export function validateEpicHeadReconciliationReceipt(value, expected) {
157
173
  && now - revalidatedAt <= P205_RELEASE_GATE_BUDGETS.aggregateValidityMs
158
174
  && revalidatedAt - now <= P205_RELEASE_GATE_BUDGETS.cancellationGraceMs;
159
175
  }
176
+ /** P226.15 bounds for origin-sync evidence in the reconciliation receipt. */
177
+ export const EPIC_HEAD_RECONCILIATION_ORIGIN_SYNC_LIMITS = Object.freeze({
178
+ maxCommits: 256,
179
+ maxResolvedPaths: 64,
180
+ });
181
+ const ORIGIN_SYNC_FIELDS = [
182
+ 'originSyncHeadSha', 'originSyncCommitShas', 'originSyncPaths',
183
+ 'originSyncPathsDigest', 'originSyncResolvedPaths', 'originSyncResolvedPathsDigest',
184
+ ];
185
+ function validOriginSyncEvidence(value) {
186
+ const present = ORIGIN_SYNC_FIELDS.filter((field) => value[field] !== undefined);
187
+ if (present.length === 0)
188
+ return true;
189
+ if (present.length !== ORIGIN_SYNC_FIELDS.length)
190
+ return false;
191
+ const commits = value.originSyncCommitShas;
192
+ const paths = value.originSyncPaths;
193
+ const resolved = value.originSyncResolvedPaths;
194
+ if (typeof value.originSyncHeadSha !== 'string' || !isFullSha(value.originSyncHeadSha)
195
+ || !Array.isArray(commits) || !Array.isArray(paths) || !Array.isArray(resolved)
196
+ || commits.length === 0 || commits.length > EPIC_HEAD_RECONCILIATION_ORIGIN_SYNC_LIMITS.maxCommits
197
+ || resolved.length > EPIC_HEAD_RECONCILIATION_ORIGIN_SYNC_LIMITS.maxResolvedPaths
198
+ || paths.length > 2_048
199
+ || commits.some((sha) => typeof sha !== 'string' || !isFullSha(sha))
200
+ || unique(commits).length !== commits.length)
201
+ return false;
202
+ // Sync merges are first-parent commits of the reconciled range, in order.
203
+ let cursor = 0;
204
+ for (const sha of commits) {
205
+ while (cursor < value.reconciliationCommitShas.length && value.reconciliationCommitShas[cursor] !== sha)
206
+ cursor += 1;
207
+ if (cursor >= value.reconciliationCommitShas.length)
208
+ return false;
209
+ cursor += 1;
210
+ }
211
+ const changed = new Set(value.changedPaths);
212
+ const covered = (path) => storyWriteSetCoversWithControlFiles(value.allowedWriteSet, value.acceptedCheckpointIds, path);
213
+ for (const list of [paths, resolved]) {
214
+ if (list.some((path) => typeof path !== 'string' || !safeRepositoryPath(path) || !changed.has(path) || covered(path))
215
+ || !sameOrdered(list, [...new Set(list)].sort()))
216
+ return false;
217
+ }
218
+ const pathSet = new Set(paths);
219
+ return !resolved.some((path) => pathSet.has(path))
220
+ && value.originSyncPathsDigest === epicHeadReconciliationPathsDigest(paths)
221
+ && value.originSyncResolvedPathsDigest === epicHeadReconciliationPathsDigest(resolved);
222
+ }
223
+ const ORIGIN_BINDING_V1_KEYS = ['schemaVersion', 'originBranch', 'originHeadSha', 'executionBranch', 'capturedFromCurrentCheckout', 'capturedAt'];
224
+ const ORIGIN_BINDING_V2_KEYS = ['schemaVersion', 'originBranch', 'originHeadSha', 'executionBranch', 'capturedFrom', 'capturedAt'];
225
+ /**
226
+ * P226.15 (D-01 from P226.08): accept exactly the v1 or the v2 origin binding.
227
+ * Mixed shapes, extra keys, unknown sources, equal branches or malformed SHAs
228
+ * fail closed. Consumers still prove ancestry physically where they have Git.
229
+ */
230
+ export function isEpicOriginBindingEvidence(value) {
231
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
232
+ return false;
233
+ const item = value;
234
+ const keys = Object.keys(item).sort();
235
+ const common = typeof item.originBranch === 'string' && typeof item.executionBranch === 'string'
236
+ && safeBindingBranch(item.originBranch) && safeBindingBranch(item.executionBranch)
237
+ && item.originBranch !== item.executionBranch
238
+ && typeof item.originHeadSha === 'string' && isFullSha(item.originHeadSha)
239
+ && typeof item.capturedAt === 'string' && Number.isFinite(Date.parse(item.capturedAt));
240
+ if (!common)
241
+ return false;
242
+ if (item.schemaVersion === 1) {
243
+ return sameOrdered(keys, [...ORIGIN_BINDING_V1_KEYS].sort()) && item.capturedFromCurrentCheckout === true;
244
+ }
245
+ if (item.schemaVersion === 2) {
246
+ return sameOrdered(keys, [...ORIGIN_BINDING_V2_KEYS].sort())
247
+ && (item.capturedFrom === 'current-checkout' || item.capturedFrom === 'branch-ref');
248
+ }
249
+ return false;
250
+ }
251
+ function safeBindingBranch(value) {
252
+ return value.length > 0 && value.length <= 240 && !value.startsWith('-') && !value.startsWith('/')
253
+ && !value.endsWith('/') && !value.endsWith('.lock') && !value.includes('..') && !value.includes('\\')
254
+ && !value.includes('@{') && !value.includes('//') && /^[A-Za-z0-9._/-]+$/.test(value);
255
+ }
160
256
  /**
161
257
  * P225.06 ownership of a registered worktree: managed only with both the
162
258
  * journal entry and the nonce marker; anything else is manual and preserved.
@@ -210,8 +306,7 @@ export function validateEpicTerminalGitDirective(directive, actual) {
210
306
  }
211
307
  const originBinding = actual.originBinding;
212
308
  if (!originBinding
213
- || originBinding.schemaVersion !== 1
214
- || originBinding.capturedFromCurrentCheckout !== true
309
+ || !isEpicOriginBindingEvidence(originBinding)
215
310
  || originBinding.originBranch !== directive.originBranch
216
311
  || originBinding.executionBranch !== directive.executionBranch
217
312
  || !isSha(originBinding.originHeadSha)
@@ -404,6 +499,3 @@ function safeWriteScope(value) {
404
499
  return parts.length > 0 && parts.every((part) => part.length > 0 && part !== '.' && part !== '..')
405
500
  && parts[0] !== '.git';
406
501
  }
407
- function writeScopeCovers(scope, path) {
408
- return scope === path || scope.endsWith('/') && path.startsWith(scope);
409
- }