@ornexus/neocortex 4.60.79 → 4.60.81

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 (28) 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/commands/refresh-memory.d.ts +3 -1
  7. package/packages/client/dist/commands/refresh-memory.js +17 -2
  8. package/packages/client/dist/git/direct-yolo-checkpoint.js +144 -29
  9. package/packages/client/dist/git/git-lifecycle-store.js +22 -17
  10. package/packages/client/dist/git/neocortex-trailers.d.ts +26 -0
  11. package/packages/client/dist/git/neocortex-trailers.js +53 -0
  12. package/packages/client/dist/memory/project-memory-writer.d.ts +16 -1
  13. package/packages/client/dist/memory/project-memory-writer.js +55 -5
  14. package/packages/client/dist/runner/headless/run-yoloop.js +5 -1
  15. package/packages/client/dist/yolo/change-evidence-collector.d.ts +1 -1
  16. package/packages/client/dist/yolo/change-evidence-collector.js +26 -3
  17. package/packages/shared/dist/yoloop/epic-terminal-git.js +12 -0
  18. package/targets-stubs/antigravity/gemini.md +1 -1
  19. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  20. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  21. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  22. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  23. package/targets-stubs/claude-code/neocortex.md +2 -2
  24. package/targets-stubs/codex/AGENTS.md +1 -1
  25. package/targets-stubs/cursor/agent.md +2 -2
  26. package/targets-stubs/gemini-cli/agent.md +2 -2
  27. package/targets-stubs/opencode/neocortex-root.md +1 -1
  28. package/targets-stubs/vscode/neocortex.agent.md +2 -2
package/install.ps1 CHANGED
@@ -17,7 +17,7 @@ param(
17
17
  [string]$ServerUrl = ('https://{0}.{1}.{2}' -f 'api','neocortex','sh')
18
18
  )
19
19
 
20
- $VERSION = "4.60.79"
20
+ $VERSION = "4.60.81"
21
21
 
22
22
  # =============================================================================
23
23
  # CONFIGURACOES
package/install.sh CHANGED
@@ -4,7 +4,7 @@
4
4
  # Development Orchestrator
5
5
 
6
6
  # Versao do instalador
7
- VERSION="4.60.79"
7
+ VERSION="4.60.81"
8
8
 
9
9
  # Flags
10
10
  MIGRATION_DETECTED=false
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ornexus/neocortex",
3
- "version": "4.60.79",
4
- "description": "Neocortex v4.60.79",
3
+ "version": "4.60.81",
4
+ "description": "Neocortex v4.60.81",
5
5
  "keywords": [
6
6
  "claude",
7
7
  "claude-code",
@@ -1,5 +1,5 @@
1
1
  import { type ProjectMemoryTargetId } from '../memory/shared-project-memory-types.js';
2
- import { type WriteProjectMemoryTargetFilesResult } from '../memory/project-memory-writer.js';
2
+ import { type LegacyAgentPathWrapperResult, type WriteProjectMemoryTargetFilesResult } from '../memory/project-memory-writer.js';
3
3
  export interface RefreshMemoryCliOptions {
4
4
  readonly projectRoot: string;
5
5
  readonly targetIds: readonly ProjectMemoryTargetId[];
@@ -17,6 +17,8 @@ export interface ProjectMemoryVerification {
17
17
  }
18
18
  export declare function parseRefreshMemoryArgs(args: readonly string[]): RefreshMemoryCliOptions;
19
19
  export declare function refreshProjectMemoryTargets(options: RefreshMemoryCliOptions): readonly WriteProjectMemoryTargetFilesResult[];
20
+ /** Deduplicated (by path) tracked legacy wrappers that refresh refused to delete. */
21
+ export declare function trackedLegacyAgentPathWrappers(results: readonly WriteProjectMemoryTargetFilesResult[]): readonly LegacyAgentPathWrapperResult[];
20
22
  /** Root-only, read-only physical check; this is not independent stage QA or server authority. */
21
23
  export declare function verifyProjectMemoryTargets(options: RefreshMemoryCliOptions): ProjectMemoryVerification;
22
24
  export declare function refreshMemoryCliHandler(args: readonly string[]): Promise<number>;
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { lstatSync, readFileSync } from 'node:fs';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { getProjectMemoryTarget, isProjectMemoryTargetId, listProjectMemoryTargets } from '../memory/shared-project-memory-types.js';
5
- import { writeProjectMemoryTargetFiles } from '../memory/project-memory-writer.js';
5
+ import { LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON, writeProjectMemoryTargetFiles, } from '../memory/project-memory-writer.js';
6
6
  function parseCsv(value) {
7
7
  return (value ?? '').split(',').map((entry) => entry.trim()).filter(Boolean);
8
8
  }
@@ -72,6 +72,15 @@ export function refreshProjectMemoryTargets(options) {
72
72
  backupDirectory: options.backupDirectory,
73
73
  }));
74
74
  }
75
+ /** Deduplicated (by path) tracked legacy wrappers that refresh refused to delete. */
76
+ export function trackedLegacyAgentPathWrappers(results) {
77
+ const byPath = new Map();
78
+ for (const entry of results.flatMap((result) => result.legacyAgentPathWrappers ?? [])) {
79
+ if (entry.status === 'tracked-blocked' && !byPath.has(entry.relativeFile))
80
+ byPath.set(entry.relativeFile, entry);
81
+ }
82
+ return [...byPath.values()].sort((a, b) => a.relativeFile.localeCompare(b.relativeFile));
83
+ }
75
84
  /** Root-only, read-only physical check; this is not independent stage QA or server authority. */
76
85
  export function verifyProjectMemoryTargets(options) {
77
86
  if (!options.verify || !options.dryRun || options.memoryNotes?.length
@@ -100,6 +109,10 @@ export function verifyProjectMemoryTargets(options) {
100
109
  }
101
110
  const refreshed = refreshProjectMemoryTargets(options);
102
111
  const files = refreshed.flatMap((result) => result.files);
112
+ const trackedBlocked = trackedLegacyAgentPathWrappers(refreshed);
113
+ if (trackedBlocked.length > 0) {
114
+ throw new Error(`Project memory verification blocked: ${LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON} ${trackedBlocked.map((entry) => `${entry.relativeFile} hint=${entry.remediation ?? `git rm ${entry.relativeFile}`}`).join('; ')}`);
115
+ }
103
116
  if (refreshed.some((result) => (result.retiredFiles?.length ?? 0) > 0) || files.some((file) => file.changed || file.mode === 'compatibility-materialized-fallback'
104
117
  || file.fallbackReason || file.remediationDebt)) {
105
118
  throw new Error('Project memory verification found stale or fallback targets.');
@@ -147,8 +160,10 @@ export async function refreshMemoryCliHandler(args) {
147
160
  ].filter(Boolean).join(' ')));
148
161
  const retiredRows = [...new Set(results.flatMap((result) => result.retiredFiles ?? []))]
149
162
  .map((relativeFile) => `${options.dryRun ? 'would-retire' : 'retired'} legacy-agent-path-wrapper ${relativeFile}`);
163
+ const blockedRows = trackedLegacyAgentPathWrappers(results)
164
+ .map((entry) => `blocked ${LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON} ${entry.relativeFile} hint=${entry.remediation ?? `git rm ${entry.relativeFile}`}`);
150
165
  console.log(`${options.dryRun ? 'Project memory preview' : 'Project memory refreshed'}: ${options.projectRoot}`);
151
- for (const row of [...rows, ...retiredRows])
166
+ for (const row of [...rows, ...retiredRows, ...blockedRows])
152
167
  console.log(row);
153
168
  return 0;
154
169
  }
@@ -1,13 +1,15 @@
1
1
  /** Root-owned two-phase commit/checkpoint boundary for direct `*yolo` runs. */
2
2
  import { execFile } from 'node:child_process';
3
3
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
4
+ import { existsSync } from 'node:fs';
4
5
  import { readFile } from 'node:fs/promises';
5
6
  import { join, resolve } from 'node:path';
6
7
  import { promisify } from 'node:util';
7
8
  import { readRootMemoryEffectForCheckpoint } from '../private-execution/root-memory-scope.js';
8
9
  import { rootMemoryEffectDigest, verifyRootMemoryPhysicalWriteSet } from '../private-execution/root-memory-git-evidence.js';
9
10
  import { acquireGitLifecyclePhysicalIntegrationLock, applyGitLifecycleRuntimeOverlay, computeImmutableStoryQaEvidenceDigest, computeGitLifecyclePhysicalIntegrationLockOwnerDigest, computeP205StoryQaEvidenceDigest, computeLegacyDirectYoloRecoveryReceiptRef, ensureRuntimeEpic, ensureRuntimeStory, ensureGitLifecyclePrivateChildDirectory, executeP205TransientAuthority, projectP205TransientExecutionEvidence, publicStoryReviewArtifactFromGit, LEGACY_DIRECT_YOLO_RECOVERY_COMMITS, mutateGitLifecycleRuntime, P205_COMPLETE_COMMAND, readGitLifecycleRuntime, gitLifecycleRuntimeDirectory, assertGitLifecyclePrivateFile, releaseGitLifecyclePhysicalIntegrationLock, releaseGitLifecyclePhysicalIntegrationLockForCheckpoint, verifyGitLifecyclePhysicalIntegrationLock, verifyAcceptedGitLifecycleStoryCheckpoint, } from './git-lifecycle-store.js';
10
- import { anchoredAtomicWriteFile } from './secure-filesystem-boundary.js';
11
+ import { anchoredAtomicWriteFile, anchoredRemoveFile } from './secure-filesystem-boundary.js';
12
+ import { parseNeocortexTrailers, trailerReasonKey, trailerValue } from './neocortex-trailers.js';
11
13
  import { GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID, GIT_LIFECYCLE_REVIEW_PR_STEP_ID, GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID, } from './git-lifecycle-step-ids.js';
12
14
  const execFileAsync = promisify(execFile);
13
15
  // The canonical complete P205 gate can legitimately exceed the former
@@ -409,11 +411,28 @@ export async function beginDirectYoloStoryCommit(options) {
409
411
  return failure('direct-yolo-staged-diff-empty');
410
412
  const bundleDigest = digest(payload);
411
413
  const claimRevision = digest([...authority.authorizedWriteSet].sort().join('\0'));
412
- const idempotencyKey = digest([
413
- 'direct-yolo-commit-v1', options.storyId, authority.epicId, authority.executionBranch,
414
- baseSha, bundleDigest, authority.graphRevision, claimRevision,
415
- ].join('\0'));
414
+ // A begin replay for the exact same staged content keeps the graph epoch it
415
+ // was first issued under; the epic epoch may advance while no lease is held.
416
+ const priorPlan = await readDirectCommitPlan(authority.projectRoot, options.storyId);
417
+ const replayedPlan = priorPlan.state === 'valid'
418
+ && priorPlan.plan.epicId === authority.epicId
419
+ && priorPlan.plan.executionBranch === authority.executionBranch
420
+ && priorPlan.plan.preparedBase === baseSha
421
+ && priorPlan.plan.bundleDigest === bundleDigest
422
+ && priorPlan.plan.claimRevision === claimRevision
423
+ ? priorPlan.plan : undefined;
424
+ const boundGraphRevision = replayedPlan?.graphRevision ?? authority.graphRevision;
425
+ const idempotencyKey = directCommitIdempotencyKey({
426
+ storyId: options.storyId, epicId: authority.epicId, executionBranch: authority.executionBranch,
427
+ baseSha, bundleDigest, graphRevision: boundGraphRevision, claimRevision,
428
+ });
416
429
  const nowIso = normalizedTime(options.nowIso);
430
+ const commitPlan = {
431
+ schemaVersion: 1, kind: 'direct-yolo-commit-plan', storyId: options.storyId,
432
+ epicId: authority.epicId, executionBranch: authority.executionBranch,
433
+ graphRevision: boundGraphRevision, preparedBase: baseSha, bundleDigest, claimRevision,
434
+ idempotencyKey, issuedAt: replayedPlan?.issuedAt ?? nowIso,
435
+ };
417
436
  let issuedHandoff = options.setupLeaseHandoff
418
437
  ?? await resolveIssuedSetupLeaseHandoff(authority.projectRoot, options.storyId, bundleDigest, claimRevision, nowIso);
419
438
  const runtimeBeforeLock = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
@@ -516,6 +535,9 @@ export async function beginDirectYoloStoryCommit(options) {
516
535
  if (!(await verifyGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner))) {
517
536
  throw new Error('direct-yolo-integration-lock-raced');
518
537
  }
538
+ // Durable under the runtime lock and independent of the lease: a
539
+ // failed/expired finalize releases the lease, never the plan epoch.
540
+ await writeDirectCommitPlan(authority.projectRoot, commitPlan);
519
541
  },
520
542
  });
521
543
  }
@@ -534,7 +556,7 @@ export async function beginDirectYoloStoryCommit(options) {
534
556
  `Neocortex-Prepared-Base: ${baseSha}`,
535
557
  `Neocortex-Bundle-Digest: ${bundleDigest}`,
536
558
  `Neocortex-Review-Artifact-Digest: ${stagedReview.digest}`,
537
- `Neocortex-Graph-Revision: ${authority.graphRevision}`,
559
+ `Neocortex-Graph-Revision: ${boundGraphRevision}`,
538
560
  `Neocortex-Claim-Revision: ${claimRevision}`,
539
561
  ...(authority.rootMemoryEffect ? [`Neocortex-Root-Memory-Effect: ${rootMemoryEffectDigest(authority.rootMemoryEffect)}`] : []),
540
562
  ]);
@@ -542,7 +564,7 @@ export async function beginDirectYoloStoryCommit(options) {
542
564
  schemaVersion: 1, storyId: options.storyId, epicId: authority.epicId,
543
565
  executionBranch: authority.executionBranch, baseSha, bundleDigest,
544
566
  reviewArtifactDigest: stagedReview.digest,
545
- graphRevision: authority.graphRevision, claimRevision, idempotencyKey,
567
+ graphRevision: boundGraphRevision, claimRevision, idempotencyKey,
546
568
  changedPaths: Object.freeze(changedPaths), trailers,
547
569
  }) };
548
570
  }
@@ -589,6 +611,7 @@ export async function finalizeDirectYoloStoryCheckpoint(options) {
589
611
  ownerDigest: physicalOwnerRef.slice('physical-lock-owner:'.length),
590
612
  });
591
613
  }
614
+ await removeDirectCommitPlan(authority.projectRoot, options.storyId).catch(() => undefined);
592
615
  return { ok: true, value: existing };
593
616
  }
594
617
  const headSha = aggregateHeadSha;
@@ -600,33 +623,64 @@ export async function finalizeDirectYoloStoryCheckpoint(options) {
600
623
  return failure(writeSet.reasonCode);
601
624
  if (authority.rootMemoryEffect)
602
625
  verifyRootMemoryPhysicalWriteSet(authority.projectRoot, authority.rootMemoryEffect, { storyId: options.storyId, executionBranch: authority.executionBranch, baseSha, headRef: headSha, childPaths: authority.authorizedWriteSet });
603
- const bundleDigest = trailer(commitBody, 'Neocortex-Bundle-Digest');
604
- const graphRevision = trailer(commitBody, 'Neocortex-Graph-Revision');
605
- const claimRevision = trailer(commitBody, 'Neocortex-Claim-Revision');
606
- const required = new Map([
626
+ const expectedClaimRevision = digest([...authority.authorizedWriteSet].sort().join('\0'));
627
+ // The begin plan binds the graph epoch the trailers were issued under. The
628
+ // epic epoch may legitimately advance after the lease is released (failed
629
+ // finalize, expiry); the checkpoint keeps its own epoch, as in terminal
630
+ // readiness. Content, claim and base bindings remain exact.
631
+ const storedPlan = await readDirectCommitPlan(authority.projectRoot, options.storyId);
632
+ if (storedPlan.state === 'invalid')
633
+ return failure('direct-yolo-commit-plan-invalid');
634
+ const plan = storedPlan.state === 'valid' ? storedPlan.plan : undefined;
635
+ if (plan && (plan.epicId !== authority.epicId || plan.executionBranch !== authority.executionBranch)) {
636
+ return failure('direct-yolo-commit-plan-invalid');
637
+ }
638
+ if (plan && plan.claimRevision !== expectedClaimRevision)
639
+ return failure('direct-yolo-commit-plan-claim-changed');
640
+ if (plan && plan.preparedBase !== baseSha)
641
+ return failure('direct-yolo-commit-plan-base-mismatch');
642
+ const parsedTrailers = parseNeocortexTrailers(commitBody);
643
+ if (!parsedTrailers.ok)
644
+ return failure(`direct-yolo-trailer-duplicate:${parsedTrailers.key}`);
645
+ const trailers = parsedTrailers.values;
646
+ const graphRevision = plan?.graphRevision ?? authority.graphRevision;
647
+ const claimRevision = expectedClaimRevision;
648
+ const required = [
607
649
  ['Neocortex-Story', options.storyId], ['Neocortex-Epic', authority.epicId],
608
650
  ['Neocortex-Execution-Branch', authority.executionBranch], ['Neocortex-Prepared-Base', baseSha],
609
- ['Neocortex-Graph-Revision', authority.graphRevision],
610
- ['Neocortex-Claim-Revision', digest([...authority.authorizedWriteSet].sort().join('\0'))],
611
- ]);
612
- if (!bundleDigest || !/^[a-f0-9]{64}$/.test(bundleDigest) || !graphRevision || !claimRevision
613
- || [...required].some(([key, value]) => trailer(commitBody, key) !== value)) {
614
- return failure('direct-yolo-trailers-invalid');
651
+ ['Neocortex-Bundle-Digest', plan?.bundleDigest ?? ''],
652
+ ['Neocortex-Graph-Revision', graphRevision],
653
+ ['Neocortex-Claim-Revision', claimRevision],
654
+ ];
655
+ for (const [key, value] of required) {
656
+ const actual = trailerValue(trailers, key);
657
+ if (actual === undefined)
658
+ return failure(`direct-yolo-trailer-missing:${trailerReasonKey(key)}`);
659
+ if (key === 'Neocortex-Bundle-Digest' && !plan) {
660
+ if (!/^[a-f0-9]{64}$/.test(actual))
661
+ return failure(`direct-yolo-trailer-mismatch:${trailerReasonKey(key)}`);
662
+ continue;
663
+ }
664
+ if (actual !== value)
665
+ return failure(`direct-yolo-trailer-mismatch:${trailerReasonKey(key)}`);
615
666
  }
667
+ const bundleDigest = trailerValue(trailers, 'Neocortex-Bundle-Digest');
616
668
  const publicReview = publicStoryReviewArtifactFromGit(authority.projectRoot, options.storyId, headSha);
617
669
  if (publicReview?.verdict !== 'approved')
618
670
  return failure('direct-yolo-review-artifact-not-approved');
619
- const reviewTrailer = trailer(commitBody, 'Neocortex-Review-Artifact-Digest');
671
+ const reviewTrailer = trailerValue(trailers, 'Neocortex-Review-Artifact-Digest');
620
672
  if (reviewTrailer !== undefined && reviewTrailer !== publicReview.digest) {
621
673
  return failure('direct-yolo-review-artifact-digest-mismatch');
622
674
  }
623
675
  const expectedPayloadDigest = digest(await gitRaw(authority.projectRoot, ['diff', '--binary', '--full-index', `${baseSha}..${headSha}`]));
624
676
  if (bundleDigest !== expectedPayloadDigest)
625
677
  return failure('direct-yolo-bundle-digest-mismatch');
626
- const idempotencyKey = digest([
627
- 'direct-yolo-commit-v1', options.storyId, authority.epicId, authority.executionBranch,
678
+ const idempotencyKey = directCommitIdempotencyKey({
679
+ storyId: options.storyId, epicId: authority.epicId, executionBranch: authority.executionBranch,
628
680
  baseSha, bundleDigest, graphRevision, claimRevision,
629
- ].join('\0'));
681
+ });
682
+ if (plan && plan.idempotencyKey !== idempotencyKey)
683
+ return failure('direct-yolo-commit-plan-invalid');
630
684
  const currentLease = asRecord(runtime.epics[authority.epicId]?.branch_lease);
631
685
  const nowIso = normalizedTime(options.nowIso);
632
686
  const matchingLease = currentLease?.ownerStoryId === options.storyId
@@ -658,6 +712,8 @@ export async function finalizeDirectYoloStoryCheckpoint(options) {
658
712
  if (current && Date.parse(String(current.expiresAt)) > Date.parse(nowIso)) {
659
713
  throw new Error('direct-yolo-writer-active');
660
714
  }
715
+ // Race guard only: the epic epoch must not move while this finalize
716
+ // owns the writer; the checkpoint itself stays bound to the plan epoch.
661
717
  if (epic.graph_revision !== authority.graphRevision)
662
718
  throw new Error('direct-yolo-graph-revision-raced');
663
719
  epic.branch_lease = requestedLease;
@@ -666,7 +722,7 @@ export async function finalizeDirectYoloStoryCheckpoint(options) {
666
722
  }
667
723
  cleanupLease = requestedLease;
668
724
  {
669
- const qaExecution = await runQa(options, authority.projectRoot, headSha, authority.graphRevision);
725
+ const qaExecution = await runQa(options, authority.projectRoot, headSha, graphRevision);
670
726
  if (!(await physicalCheckoutUnchanged(authority.projectRoot, authority.executionBranch, headSha, changedPaths))) {
671
727
  return failure('direct-yolo-head-raced');
672
728
  }
@@ -690,12 +746,14 @@ export async function finalizeDirectYoloStoryCheckpoint(options) {
690
746
  remote: options.push ? options.remote ?? 'origin' : undefined,
691
747
  expectedRevision: runtime.revision, expectedLease: requestedLease,
692
748
  expectedGraphRevision: authority.graphRevision,
749
+ expectedCheckpointGraphRevision: graphRevision,
693
750
  physicalLockPath: physicalLock.path, physicalLockOwner: physicalLock.owner,
694
751
  transientAuthority: qaExecution.transientAuthority,
695
752
  authorizedWriteSet: authority.authorizedWriteSet,
696
753
  });
697
754
  if (!persisted)
698
755
  return failure('direct-yolo-checkpoint-persist-failed');
756
+ await removeDirectCommitPlan(authority.projectRoot, options.storyId).catch(() => undefined);
699
757
  await options.afterCheckpointPersist?.();
700
758
  return { ok: true, value: checkpoint };
701
759
  }
@@ -936,7 +994,8 @@ async function persistCheckpoint(input) {
936
994
  throw new Error('direct-yolo-runtime-revision-conflict');
937
995
  if (Date.parse(String(currentLease?.expiresAt)) <= Date.now())
938
996
  throw new Error('direct-yolo-writer-lease-expired');
939
- if (epic.graph_revision !== input.expectedGraphRevision || checkpoint.graphRevision !== input.expectedGraphRevision) {
997
+ if (epic.graph_revision !== input.expectedGraphRevision
998
+ || checkpoint.graphRevision !== (input.expectedCheckpointGraphRevision ?? input.expectedGraphRevision)) {
940
999
  throw new Error('direct-yolo-graph-revision-raced');
941
1000
  }
942
1001
  }
@@ -981,6 +1040,67 @@ async function remoteContainsHead(projectRoot, remoteInput, branch, headSha) {
981
1040
  const remoteHead = (await git(projectRoot, ['ls-remote', '--heads', remote, `refs/heads/${branch}`])).split(/\s+/)[0];
982
1041
  return Boolean(remoteHead && await gitExitOk(projectRoot, ['merge-base', '--is-ancestor', headSha, remoteHead]));
983
1042
  }
1043
+ function directCommitIdempotencyKey(input) {
1044
+ return digest([
1045
+ 'direct-yolo-commit-v1', input.storyId, input.epicId, input.executionBranch,
1046
+ input.baseSha, input.bundleDigest, input.graphRevision, input.claimRevision,
1047
+ ].join('\0'));
1048
+ }
1049
+ const DIRECT_COMMIT_PLAN_KEYS = [
1050
+ 'schemaVersion', 'kind', 'storyId', 'epicId', 'executionBranch', 'graphRevision',
1051
+ 'preparedBase', 'bundleDigest', 'claimRevision', 'idempotencyKey', 'issuedAt',
1052
+ ];
1053
+ async function directCommitPlanLocation(projectRoot, storyId) {
1054
+ const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
1055
+ const parent = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'commit-plans');
1056
+ const name = `direct-${digest(storyId)}.json`;
1057
+ return { parent, name, path: join(parent, name) };
1058
+ }
1059
+ async function writeDirectCommitPlan(projectRoot, plan) {
1060
+ const location = await directCommitPlanLocation(projectRoot, plan.storyId);
1061
+ await anchoredAtomicWriteFile(location.parent, location.name, `${JSON.stringify(plan, null, 2)}\n`);
1062
+ await assertGitLifecyclePrivateFile(location.path, location.parent);
1063
+ }
1064
+ async function readDirectCommitPlan(projectRoot, storyId) {
1065
+ let location;
1066
+ try {
1067
+ location = await directCommitPlanLocation(projectRoot, storyId);
1068
+ }
1069
+ catch {
1070
+ return { state: 'invalid' };
1071
+ }
1072
+ try {
1073
+ if (!existsSync(location.path))
1074
+ return { state: 'absent' };
1075
+ await assertGitLifecyclePrivateFile(location.path, location.parent);
1076
+ const raw = await readFile(location.path, 'utf8');
1077
+ if (raw.length > 16 * 1024)
1078
+ return { state: 'invalid' };
1079
+ const item = asRecord(JSON.parse(raw));
1080
+ if (!item || Object.keys(item).sort().join('\0') !== [...DIRECT_COMMIT_PLAN_KEYS].sort().join('\0')
1081
+ || item.schemaVersion !== 1 || item.kind !== 'direct-yolo-commit-plan' || item.storyId !== storyId
1082
+ || typeof item.epicId !== 'string' || typeof item.executionBranch !== 'string' || !safeRef(item.executionBranch)
1083
+ || typeof item.preparedBase !== 'string' || !/^[a-f0-9]{40,64}$/.test(item.preparedBase)
1084
+ || ![item.graphRevision, item.bundleDigest, item.claimRevision, item.idempotencyKey].every((value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value))
1085
+ || typeof item.issuedAt !== 'string' || !Number.isFinite(Date.parse(item.issuedAt))) {
1086
+ return { state: 'invalid' };
1087
+ }
1088
+ const plan = item;
1089
+ if (plan.idempotencyKey !== directCommitIdempotencyKey({ ...plan, baseSha: plan.preparedBase })) {
1090
+ return { state: 'invalid' };
1091
+ }
1092
+ return { state: 'valid', plan };
1093
+ }
1094
+ catch {
1095
+ return { state: 'invalid' };
1096
+ }
1097
+ }
1098
+ async function removeDirectCommitPlan(projectRoot, storyId) {
1099
+ const location = await directCommitPlanLocation(projectRoot, storyId);
1100
+ if (!existsSync(location.path))
1101
+ return;
1102
+ await anchoredRemoveFile(location.parent, location.name);
1103
+ }
984
1104
  function isLiveSameStorySetupLease(lease, storyId, nowIso) {
985
1105
  return Boolean(lease?.ownerStoryId === storyId
986
1106
  && lease.sessionId === lease.idempotencyKey
@@ -1210,11 +1330,6 @@ function safeRemote(value) {
1210
1330
  throw new Error('direct-yolo-remote-invalid');
1211
1331
  return value;
1212
1332
  }
1213
- function trailer(body, key) {
1214
- const prefix = `${key}: `;
1215
- const values = body.split('\n').map((line) => line.trim()).filter((line) => line.startsWith(prefix)).map((line) => line.slice(prefix.length));
1216
- return values.length === 1 ? values[0] : undefined;
1217
- }
1218
1333
  function digest(value) { return createHash('sha256').update(value).digest('hex'); }
1219
1334
  function splitNull(value) { return value.split('\0').filter(Boolean); }
1220
1335
  function normalizedTime(value) {
@@ -1321,7 +1436,7 @@ function publicReason(error, fallback) {
1321
1436
  if (error instanceof Error && error.message === 'git-lifecycle-runtime-revision-conflict') {
1322
1437
  return 'direct-yolo-runtime-revision-conflict';
1323
1438
  }
1324
- return error instanceof Error && /^direct-yolo-[a-z0-9-]+$/.test(error.message) ? error.message : fallback;
1439
+ return error instanceof Error && /^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(error.message) ? error.message : fallback;
1325
1440
  }
1326
1441
  function failure(reasonCode) { return { ok: false, reasonCode }; }
1327
1442
  async function git(cwd, args) {
@@ -19,6 +19,7 @@ import { resolveBranchUnit, } from '../../../shared/dist/yoloop/branch-unit.js';
19
19
  import { epicHeadReconciliationInputDigest, epicHeadReconciliationPathsDigest, epicHeadReconciliationRangeDigest, validateEpicHeadReconciliationReceipt, } from '../../../shared/dist/yoloop/epic-terminal-git.js';
20
20
  import { anchoredAtomicWriteFile, anchoredCreateOwnedDirectory, anchoredEnsureDirectory, anchoredExecuteGit, anchoredExecuteNode, anchoredRemoveDirectory, anchoredRenameDirectory, } from './secure-filesystem-boundary.js';
21
21
  import { GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID, GIT_LIFECYCLE_REVIEW_PR_STEP_ID, GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID, } from './git-lifecycle-step-ids.js';
22
+ import { parseNeocortexTrailers, trailerValue } from './neocortex-trailers.js';
22
23
  const execFileAsync = promisify(execFile);
23
24
  export const GIT_LIFECYCLE_RUNTIME_DIRECTORY = 'neocortex-yoloop';
24
25
  export const GIT_LIFECYCLE_RUNTIME_FILE = 'runtime.json';
@@ -517,27 +518,29 @@ export function verifyAcceptedGitLifecycleStoryCheckpointSync(projectRoot, value
517
518
  const commitCount = gitSync(projectRoot, ['rev-list', '--count', `${baseSha}..${headSha}`]).trim();
518
519
  if (parentSha !== baseSha || commitCount !== '1')
519
520
  return rejected();
520
- const trailers = new Set(commitBody.split('\n').map((line) => line.trim()));
521
- const reviewTrailers = commitBody.split('\n').map((line) => line.trim())
522
- .filter((line) => line.startsWith('Neocortex-Review-Artifact-Digest: '));
523
- if (reviewTrailers.length > 0 && (reviewTrailers.length !== 1
524
- || reviewTrailers[0] !== `Neocortex-Review-Artifact-Digest: ${publicReview?.digest}`
521
+ // Same single-valued parser as the direct C08 finalizer: identical repeated
522
+ // lines collapse, a checkpoint key with two different values is ambiguous.
523
+ const parsedTrailers = parseNeocortexTrailers(commitBody);
524
+ if (!parsedTrailers.ok)
525
+ return rejected();
526
+ const trailers = parsedTrailers.values;
527
+ const reviewTrailer = trailerValue(trailers, 'Neocortex-Review-Artifact-Digest');
528
+ if (reviewTrailer !== undefined && (reviewTrailer !== publicReview?.digest
525
529
  || review.reviewArtifactDigest !== publicReview?.digest))
526
530
  return rejected();
527
531
  const requiredTrailers = [
528
- `Neocortex-Story: ${storyId}`,
529
- `Neocortex-Epic: ${epicId}`,
530
- `Neocortex-Execution-Branch: ${executionBranch}`,
531
- `Neocortex-Bundle-Digest: ${String(checkpoint.bundleDigest)}`,
532
- `Neocortex-Graph-Revision: ${String(checkpoint.graphRevision)}`,
533
- ...(checkpoint.dispatchId ? [`Neocortex-Dispatch: ${String(checkpoint.dispatchId)}`] : []),
534
- ...(checkpoint.bundleId ? [`Neocortex-Bundle: ${String(checkpoint.bundleId)}`] : []),
535
- ...(checkpoint.claimRevision ? [`Neocortex-Claim-Revision: ${String(checkpoint.claimRevision)}`] : []),
532
+ ['Neocortex-Story', storyId],
533
+ ['Neocortex-Epic', epicId],
534
+ ['Neocortex-Execution-Branch', executionBranch],
535
+ ['Neocortex-Bundle-Digest', String(checkpoint.bundleDigest)],
536
+ ['Neocortex-Graph-Revision', String(checkpoint.graphRevision)],
537
+ ...(checkpoint.dispatchId ? [['Neocortex-Dispatch', String(checkpoint.dispatchId)]] : []),
538
+ ...(checkpoint.bundleId ? [['Neocortex-Bundle', String(checkpoint.bundleId)]] : []),
539
+ ...(checkpoint.claimRevision ? [['Neocortex-Claim-Revision', String(checkpoint.claimRevision)]] : []),
536
540
  ];
537
- const hasCanonicalTrailers = requiredTrailers.every((trailer) => trailers.has(trailer));
541
+ const hasCanonicalTrailers = requiredTrailers.every(([key, value]) => trailerValue(trailers, key) === value);
538
542
  if (hasCanonicalTrailers) {
539
- const preparedBaseLine = [...trailers].find((line) => line.startsWith('Neocortex-Prepared-Base: '));
540
- const preparedBase = preparedBaseLine?.slice('Neocortex-Prepared-Base: '.length) ?? '';
543
+ const preparedBase = trailerValue(trailers, 'Neocortex-Prepared-Base') ?? '';
541
544
  if (!/^[a-f0-9]{40,64}$/i.test(preparedBase))
542
545
  return rejected();
543
546
  execFileSync('git', ['merge-base', '--is-ancestor', preparedBase, headSha], { cwd: projectRoot, stdio: 'ignore' });
@@ -903,7 +906,9 @@ function checkpointClaimProof(input) {
903
906
  }
904
907
  function normalizeAuthorizedWriteSet(values) {
905
908
  const normalized = values.map((value) => value.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/{2,}/g, '/'));
906
- if (normalized.some((value) => !safeRepositoryPath(value)))
909
+ // Directory scopes (`dir/`) are valid write-set entries: writeSetCovers and the
910
+ // direct checkpoint already admit them, so the checkpoint claim proof must too.
911
+ if (normalized.some((value) => !safeWriteScope(value)))
907
912
  return Object.freeze([]);
908
913
  return Object.freeze([...new Set(normalized)].sort());
909
914
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Single-valued `Neocortex-*` story checkpoint trailers.
3
+ *
4
+ * Agents may paste the trailer block and also pass it through `--trailer`, or
5
+ * append a separate `Co-Authored-By` paragraph. Parsing is therefore line
6
+ * based over the whole commit body: identical repeated lines collapse into one
7
+ * value, non-`Neocortex-` lines are ignored, and a key repeated with a
8
+ * different value is ambiguous and fails closed. Keys are reported in
9
+ * lowercase; they are fixed public identifiers, never user content.
10
+ */
11
+ export declare const STORY_CHECKPOINT_TRAILER_KEYS: readonly ["Neocortex-Story", "Neocortex-Epic", "Neocortex-Execution-Branch", "Neocortex-Prepared-Base", "Neocortex-Bundle-Digest", "Neocortex-Review-Artifact-Digest", "Neocortex-Graph-Revision", "Neocortex-Claim-Revision", "Neocortex-Root-Memory-Effect", "Neocortex-Dispatch", "Neocortex-Bundle"];
12
+ export type NeocortexTrailerParse = {
13
+ readonly ok: true;
14
+ readonly values: ReadonlyMap<string, string>;
15
+ } | {
16
+ readonly ok: false;
17
+ readonly key: string;
18
+ };
19
+ /** Lowercase public key used in `direct-yolo-trailer-*:<key>` reason codes. */
20
+ export declare function trailerReasonKey(key: string): string;
21
+ /**
22
+ * Collect the single value of each tracked key. Keys outside `keys` (for
23
+ * example multi-valued review-reconciliation trailers) are ignored.
24
+ */
25
+ export declare function parseNeocortexTrailers(body: string, keys?: readonly string[]): NeocortexTrailerParse;
26
+ export declare function trailerValue(values: ReadonlyMap<string, string>, key: string): string | undefined;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Single-valued `Neocortex-*` story checkpoint trailers.
3
+ *
4
+ * Agents may paste the trailer block and also pass it through `--trailer`, or
5
+ * append a separate `Co-Authored-By` paragraph. Parsing is therefore line
6
+ * based over the whole commit body: identical repeated lines collapse into one
7
+ * value, non-`Neocortex-` lines are ignored, and a key repeated with a
8
+ * different value is ambiguous and fails closed. Keys are reported in
9
+ * lowercase; they are fixed public identifiers, never user content.
10
+ */
11
+ export const STORY_CHECKPOINT_TRAILER_KEYS = Object.freeze([
12
+ 'Neocortex-Story',
13
+ 'Neocortex-Epic',
14
+ 'Neocortex-Execution-Branch',
15
+ 'Neocortex-Prepared-Base',
16
+ 'Neocortex-Bundle-Digest',
17
+ 'Neocortex-Review-Artifact-Digest',
18
+ 'Neocortex-Graph-Revision',
19
+ 'Neocortex-Claim-Revision',
20
+ 'Neocortex-Root-Memory-Effect',
21
+ 'Neocortex-Dispatch',
22
+ 'Neocortex-Bundle',
23
+ ]);
24
+ const TRAILER_LINE = /^(neocortex-[a-z0-9][a-z0-9-]{0,63}):[ \t]*(.*?)[ \t]*$/i;
25
+ /** Lowercase public key used in `direct-yolo-trailer-*:<key>` reason codes. */
26
+ export function trailerReasonKey(key) {
27
+ return key.toLowerCase();
28
+ }
29
+ /**
30
+ * Collect the single value of each tracked key. Keys outside `keys` (for
31
+ * example multi-valued review-reconciliation trailers) are ignored.
32
+ */
33
+ export function parseNeocortexTrailers(body, keys = STORY_CHECKPOINT_TRAILER_KEYS) {
34
+ const tracked = new Set(keys.map(trailerReasonKey));
35
+ const values = new Map();
36
+ for (const raw of body.split('\n')) {
37
+ const match = TRAILER_LINE.exec(raw.trim());
38
+ if (!match)
39
+ continue;
40
+ const key = trailerReasonKey(match[1]);
41
+ if (!tracked.has(key))
42
+ continue;
43
+ const value = match[2];
44
+ const previous = values.get(key);
45
+ if (previous !== undefined && previous !== value)
46
+ return { ok: false, key };
47
+ values.set(key, value);
48
+ }
49
+ return { ok: true, values };
50
+ }
51
+ export function trailerValue(values, key) {
52
+ return values.get(trailerReasonKey(key));
53
+ }
@@ -55,8 +55,23 @@ export interface WriteProjectMemoryTargetFilesResult {
55
55
  readonly canonicalFilePath: string;
56
56
  readonly files: readonly WriteProjectMemoryFileResult[];
57
57
  readonly changed: boolean;
58
- /** Legacy wrappers removed from (or stripped out of) agent discovery paths. */
58
+ /**
59
+ * Legacy wrappers removed from (or stripped out of) agent discovery paths.
60
+ * Backward-compatible projection: only `retired`/`would-retire` entries.
61
+ */
59
62
  readonly retiredFiles?: readonly string[];
63
+ /** Typed outcome for every legacy agent-path wrapper that was found. */
64
+ readonly legacyAgentPathWrappers?: readonly LegacyAgentPathWrapperResult[];
65
+ }
66
+ export type LegacyAgentPathWrapperStatus = 'retired' | 'would-retire' | 'tracked-blocked';
67
+ export declare const LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON = "legacy-agent-path-wrapper-tracked";
68
+ export interface LegacyAgentPathWrapperResult {
69
+ readonly relativeFile: string;
70
+ readonly status: LegacyAgentPathWrapperStatus;
71
+ /** Present only for `tracked-blocked`. */
72
+ readonly reasonCode?: typeof LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON;
73
+ /** Present only for `tracked-blocked`; operator-run remediation. */
74
+ readonly remediation?: string;
60
75
  }
61
76
  export declare function createNodeProjectMemoryFs(backupDirectory?: string): ProjectMemoryWriterFs;
62
77
  export declare const PROJECT_MEMORY_LAYER_CATEGORIES: readonly ["skills-agents", "frontend", "backend", "api", "db", "schemas", "envs", "devops", "cyber-security", "testing-qa", "observability", "product-business", "docs-architecture", "platform-memory", "command-behavior", "generic"];