@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
@@ -173,6 +173,347 @@ function isKnownLegacyProfile(bytes) {
173
173
  (/architecture:\s*['"]?thin-client/i.test(content) && /id:\s*agents\/neocortex/i.test(content));
174
174
  }
175
175
 
176
+ // P226.12: the managed `description:` line written by the description patch
177
+ // (`🧠 Neocortex v<ver> (<Tier>) | OrNexus Team`, tier optional).
178
+ const DESCRIPTION_LINE_PATTERN = /^description:[ \t]*"(.*)"[ \t]*$/gm;
179
+ const MANAGED_DESCRIPTION_VALUE = /^\u{1F9E0} Neocortex v(\d+(?:\.\d+)*)(?: \((?:Free|Pro|Enterprise)\))? \| OrNexus Team$/u;
180
+ const BANNER_VERSION_LINE = /^│ ### ######## v(\d+(?:\.\d+)*)\s*│$/m;
181
+ const MAX_DESCRIPTION_CANDIDATES = 13;
182
+
183
+ function descriptionLines(text) {
184
+ return [...text.matchAll(DESCRIPTION_LINE_PATTERN)];
185
+ }
186
+
187
+ /**
188
+ * True when the only delta between the current bytes and the installed bytes
189
+ * (known by hash only) is the managed `description:` line. The installed line
190
+ * is reconstructed from a closed, deterministic candidate set; anything else
191
+ * stays user drift (fail closed).
192
+ */
193
+ function isManagedDescriptionOnlyDelta(currentBytes, desiredBytes, installedHash) {
194
+ if (!currentBytes || typeof installedHash !== 'string' || !installedHash) return false;
195
+ const current = currentBytes.toString('utf8');
196
+ const lines = descriptionLines(current);
197
+ if (lines.length !== 1) return false;
198
+ const currentValue = lines[0][1];
199
+ const currentMatch = MANAGED_DESCRIPTION_VALUE.exec(currentValue);
200
+ if (!currentMatch) return false;
201
+
202
+ const desired = desiredBytes ? Buffer.from(desiredBytes).toString('utf8') : '';
203
+ const desiredLines = descriptionLines(desired);
204
+ const desiredValue = desiredLines.length === 1 ? desiredLines[0][1] : null;
205
+
206
+ const versions = [];
207
+ const addVersion = (value) => { if (value && !versions.includes(value)) versions.push(value); };
208
+ addVersion(currentMatch[1]);
209
+ addVersion(BANNER_VERSION_LINE.exec(current)?.[1]);
210
+ addVersion(desiredValue ? MANAGED_DESCRIPTION_VALUE.exec(desiredValue)?.[1] : null);
211
+
212
+ const candidates = [];
213
+ const addCandidate = (value) => {
214
+ if (value !== null && value !== currentValue && !candidates.includes(value)) candidates.push(value);
215
+ };
216
+ addCandidate(desiredValue);
217
+ for (const version of versions) {
218
+ addCandidate(`\u{1F9E0} Neocortex v${version} | OrNexus Team`);
219
+ for (const tier of ['Free', 'Pro', 'Enterprise']) {
220
+ addCandidate(`\u{1F9E0} Neocortex v${version} (${tier}) | OrNexus Team`);
221
+ }
222
+ }
223
+
224
+ const start = lines[0].index;
225
+ const end = start + lines[0][0].length;
226
+ for (const candidate of candidates.slice(0, MAX_DESCRIPTION_CANDIDATES)) {
227
+ const rebuilt = `${current.slice(0, start)}description: "${candidate}"${current.slice(end)}`;
228
+ if (sha256(Buffer.from(rebuilt, 'utf8')) === installedHash) return true;
229
+ }
230
+ return false;
231
+ }
232
+
233
+ // P227-CON-MANAGED-PROFILE: closed set of managed lines. A line is managed
234
+ // only when the whole line (without a trailing CR) matches one of these kinds.
235
+ const MANAGED_VER = '\\d+(?:\\.\\d+){0,3}';
236
+ const MANAGED_TIER = '(?:Free|Pro|Enterprise)';
237
+ const MANAGED_TIERS = ['Free', 'Pro', 'Enterprise'];
238
+ const BANNER_INNER_WIDTH = 60;
239
+ const BANNER_VERSION_PREFIX = ' ### ######## ';
240
+ const BANNER_TIER_PREFIX = ' ## ### ###### ## ';
241
+ const MANAGED_LINE_MATCHERS = [
242
+ {
243
+ kind: 'description',
244
+ re: new RegExp(`^description:[ \\t]*"\\u{1F9E0} Neocortex v(${MANAGED_VER})(?: \\((${MANAGED_TIER})\\))? \\| OrNexus Team"[ \\t]*$`, 'u'),
245
+ read: (m) => ({ indent: '', version: m[1], tier: m[2] || null }),
246
+ },
247
+ {
248
+ kind: 'h1',
249
+ re: new RegExp(`^# (\\u{1F9E0} )?Neocortex v(${MANAGED_VER})(?: \\((${MANAGED_TIER})\\))? \\| OrNexus Team$`, 'u'),
250
+ read: (m) => ({ indent: '', version: m[2], tier: m[3] || null, variant: m[1] ? 'emoji' : 'plain' }),
251
+ },
252
+ {
253
+ kind: 'h1',
254
+ re: new RegExp(`^# \\u{1F9E0} Neocortex v(${MANAGED_VER}) - Development Orchestrator \\| OrNexus Team \\((${MANAGED_TIER})\\)$`, 'u'),
255
+ read: (m) => ({ indent: '', version: m[1], tier: m[2], variant: 'orchestrator' }),
256
+ },
257
+ {
258
+ kind: 'banner-version',
259
+ re: new RegExp(`^\\u2502${BANNER_VERSION_PREFIX}v(${MANAGED_VER})\\s*\\u2502$`, 'u'),
260
+ read: (m) => ({ indent: '', version: m[1], tier: null }),
261
+ },
262
+ {
263
+ kind: 'banner-tier',
264
+ re: new RegExp(`^\\u2502${BANNER_TIER_PREFIX}OrNexus Team(?: \\((${MANAGED_TIER})\\))?\\s*\\u2502$`, 'u'),
265
+ read: (m) => ({ indent: '', version: null, tier: m[1] || null }),
266
+ },
267
+ {
268
+ kind: 'yaml-version',
269
+ re: new RegExp(`^([ \\t]*)version:[ \\t]*'(${MANAGED_VER})'[ \\t]*$`),
270
+ read: (m) => ({ indent: m[1], version: m[2], tier: null }),
271
+ },
272
+ {
273
+ kind: 'yaml-title',
274
+ re: new RegExp(`^([ \\t]*)title:[ \\t]*'Development Orchestrator(?: \\((${MANAGED_TIER})\\))?'[ \\t]*$`),
275
+ read: (m) => ({ indent: m[1], version: null, tier: m[2] || null }),
276
+ },
277
+ ];
278
+ const TIER_BEARING_KINDS = new Set(['description', 'h1', 'banner-tier', 'yaml-title']);
279
+ const MAX_LEGACY_VERSIONS = 96;
280
+ const MAX_LEGACY_HASHES = 4096;
281
+ const LEGACY_MINOR_WINDOW = 7;
282
+ const LEGACY_PATCH_MAX = 9;
283
+
284
+ function splitManagedLines(text) {
285
+ return text.split('\n').map((raw) => {
286
+ const cr = raw.endsWith('\r') ? '\r' : '';
287
+ const line = cr ? raw.slice(0, -1) : raw;
288
+ for (const matcher of MANAGED_LINE_MATCHERS) {
289
+ const m = matcher.re.exec(line);
290
+ if (m) return { raw, cr, managed: { kind: matcher.kind, ...matcher.read(m) } };
291
+ }
292
+ return { raw, cr, managed: null };
293
+ });
294
+ }
295
+
296
+ function managedLinesCanonical(bytes) {
297
+ const text = Buffer.isBuffer(bytes) ? bytes.toString('utf8') : String(bytes ?? '');
298
+ return splitManagedLines(text)
299
+ .map((line) => (line.managed
300
+ ? `${line.managed.indent}\u0000NEOCORTEX-MANAGED:${line.managed.kind}\u0000${line.cr}`
301
+ : line.raw))
302
+ .join('\n');
303
+ }
304
+
305
+ function managedLinesDigest(bytes) {
306
+ return sha256(Buffer.from(managedLinesCanonical(bytes), 'utf8'));
307
+ }
308
+
309
+ function padBanner(inner) {
310
+ return `│${inner}${' '.repeat(Math.max(0, BANNER_INNER_WIDTH - inner.length))}│`;
311
+ }
312
+
313
+ function renderManagedLine(managed, version, tier) {
314
+ const tierPart = tier ? ` (${tier})` : '';
315
+ switch (managed.kind) {
316
+ case 'description':
317
+ return `description: "\u{1F9E0} Neocortex v${version}${tierPart} | OrNexus Team"`;
318
+ case 'h1':
319
+ if (managed.variant === 'orchestrator') {
320
+ return tier ? `# \u{1F9E0} Neocortex v${version} - Development Orchestrator | OrNexus Team (${tier})` : null;
321
+ }
322
+ return `# ${managed.variant === 'emoji' ? '\u{1F9E0} ' : ''}Neocortex v${version}${tierPart} | OrNexus Team`;
323
+ case 'banner-version':
324
+ return padBanner(`${BANNER_VERSION_PREFIX}v${version}`);
325
+ case 'banner-tier':
326
+ return padBanner(`${BANNER_TIER_PREFIX}OrNexus Team${tierPart}`);
327
+ case 'yaml-version':
328
+ return `${managed.indent}version: '${version}'`;
329
+ case 'yaml-title':
330
+ return `${managed.indent}title: 'Development Orchestrator${tierPart}'`;
331
+ default:
332
+ return null;
333
+ }
334
+ }
335
+
336
+ function legacyVersionCandidates(currentLines, desiredLines) {
337
+ const versions = [];
338
+ const add = (value) => {
339
+ if (value && !versions.includes(value) && versions.length < MAX_LEGACY_VERSIONS) versions.push(value);
340
+ };
341
+ for (const line of currentLines) add(line.managed?.version);
342
+ for (const line of desiredLines) add(line.managed?.version);
343
+ const anchor = desiredLines.find((line) => line.managed?.version)?.managed.version;
344
+ const parts = anchor ? anchor.split('.').map((part) => Number(part)) : [];
345
+ if (parts.length >= 2 && parts.every(Number.isInteger)) {
346
+ const [major, minor] = parts;
347
+ for (let m = minor; m >= Math.max(0, minor - LEGACY_MINOR_WINDOW); m -= 1) {
348
+ for (let p = 0; p <= LEGACY_PATCH_MAX; p += 1) add(`${major}.${m}.${p}`);
349
+ }
350
+ }
351
+ return versions;
352
+ }
353
+
354
+ function legacyTierVariants(currentLines) {
355
+ const kinds = [...new Set(currentLines
356
+ .filter((line) => line.managed && TIER_BEARING_KINDS.has(line.managed.kind))
357
+ .map((line) => line.managed.kind))];
358
+ const variants = [{ tier: null, kinds: new Set() }];
359
+ const subsets = [];
360
+ for (let mask = 1; mask < (1 << kinds.length); mask += 1) {
361
+ subsets.push(new Set(kinds.filter((_, index) => mask & (1 << index))));
362
+ }
363
+ for (const tier of MANAGED_TIERS) {
364
+ for (const subset of subsets) variants.push({ tier, kinds: subset });
365
+ }
366
+ return variants;
367
+ }
368
+
369
+ /** Bounded reconstruction of the installed bytes for legacy entries. */
370
+ function isLegacyManagedLinesDelta(currentBytes, desiredBytes, installedHash) {
371
+ const currentLines = splitManagedLines(currentBytes.toString('utf8'));
372
+ if (!currentLines.some((line) => line.managed)) return false;
373
+ const desiredLines = desiredBytes ? splitManagedLines(Buffer.from(desiredBytes).toString('utf8')) : [];
374
+ const versions = legacyVersionCandidates(currentLines, desiredLines);
375
+ const variants = legacyTierVariants(currentLines);
376
+ let hashes = 0;
377
+ for (const version of versions) {
378
+ for (const variant of variants) {
379
+ let valid = true;
380
+ const rebuilt = currentLines.map((line) => {
381
+ if (!line.managed) return line.raw;
382
+ const tier = variant.kinds.has(line.managed.kind) ? variant.tier : null;
383
+ const rendered = renderManagedLine(line.managed, version, tier);
384
+ if (rendered === null) { valid = false; return line.raw; }
385
+ return `${rendered}${line.cr}`;
386
+ }).join('\n');
387
+ if (!valid) continue;
388
+ hashes += 1;
389
+ if (hashes > MAX_LEGACY_HASHES) return false;
390
+ if (sha256(Buffer.from(rebuilt, 'utf8')) === installedHash) return true;
391
+ }
392
+ }
393
+ return false;
394
+ }
395
+
396
+ /**
397
+ * Ownership evidence for a delta restricted to managed lines, or null.
398
+ * Entries with `managedLinesDigest` use the digest only; legacy entries use
399
+ * the P226.12 description check and then a bounded reconstruction.
400
+ */
401
+ function managedDeltaEvidence(currentBytes, desiredBytes, entry) {
402
+ if (!currentBytes || !entry || typeof entry.installedHash !== 'string' || !entry.installedHash) return null;
403
+ const descriptionOnly = () => isManagedDescriptionOnlyDelta(currentBytes, desiredBytes, entry.installedHash);
404
+ if (typeof entry.managedLinesDigest === 'string' && entry.managedLinesDigest) {
405
+ if (managedLinesDigest(currentBytes) !== entry.managedLinesDigest) return null;
406
+ return descriptionOnly() ? 'managed-description-delta' : 'managed-lines-delta';
407
+ }
408
+ if (descriptionOnly()) return 'managed-description-delta';
409
+ return isLegacyManagedLinesDelta(currentBytes, desiredBytes, entry.installedHash) ? 'managed-lines-delta' : null;
410
+ }
411
+
412
+ function isManagedLinesOnlyDelta(currentBytes, desiredBytes, entry) {
413
+ return managedDeltaEvidence(currentBytes, desiredBytes, entry) !== null;
414
+ }
415
+
416
+ // P227.14 T3: physical path of a (possibly missing) file, following symlinked
417
+ // ancestors, so entries from two bases can be compared by the file they own.
418
+ function physicalPath(candidate) {
419
+ let existing = path.resolve(candidate);
420
+ const rest = [];
421
+ while (!fs.existsSync(existing) && existing !== path.dirname(existing)) {
422
+ rest.unshift(path.basename(existing));
423
+ existing = path.dirname(existing);
424
+ }
425
+ try {
426
+ return path.join(fs.realpathSync.native(existing), ...rest);
427
+ } catch {
428
+ return null;
429
+ }
430
+ }
431
+
432
+ function readLegacyDuplicates(legacyBaseDir, baseDir, destination) {
433
+ if (!legacyBaseDir) return null;
434
+ const legacyBase = path.resolve(legacyBaseDir);
435
+ if (legacyBase === path.resolve(baseDir) || !fs.existsSync(legacyBase)) return null;
436
+ const manifestFile = path.join(legacyBase, '.neocortex', 'managed-config-manifest.json');
437
+ if (!fs.existsSync(manifestFile)) return { manifestFile, legacyBase, manifest: null, duplicates: [] };
438
+ const manifest = loadManifest(manifestFile, legacyBase);
439
+ const target = physicalPath(destination);
440
+ const duplicates = Object.entries(manifest.entries)
441
+ .filter(([, candidate]) => candidate && typeof candidate.relativePath === 'string' &&
442
+ target !== null && physicalPath(path.join(legacyBase, candidate.relativePath)) === target)
443
+ .map(([id, candidate]) => ({ id, entry: candidate }));
444
+ return { manifestFile, legacyBase, manifest, duplicates };
445
+ }
446
+
447
+ function settleLegacyDuplicates(legacy, matchingHashes, options) {
448
+ if (!legacy || !legacy.manifest || legacy.duplicates.length === 0) return { action: 'none' };
449
+ const adopted = options.adoptedIds || new Set();
450
+ const blocked = options.blockedIds || new Set();
451
+ const retire = legacy.duplicates.filter(({ id, entry }) => !blocked.has(id) &&
452
+ (adopted.has(id) || matchingHashes.has(entry.installedHash)));
453
+ const keep = legacy.duplicates.length - retire.length;
454
+ if (retire.length === 0) {
455
+ const reasonCode = blocked.size > 0 ? 'managed-duplicate-base-backup-preserved' : 'managed-duplicate-base-drift-preserved';
456
+ return { action: 'preserved', reasonCode, count: keep };
457
+ }
458
+ const preserved = keep ? { preservedCount: keep } : {};
459
+ if (options.dryRun) {
460
+ return { action: 'planned-retire', reasonCode: 'managed-duplicate-base-retired', count: retire.length, ...preserved };
461
+ }
462
+ // C11: re-read the legacy manifest right before the write and delete only
463
+ // the retired ids from that fresh copy, never from the earlier snapshot.
464
+ const latestBytes = fs.readFileSync(legacy.manifestFile);
465
+ const latest = loadManifest(legacy.manifestFile, legacy.legacyBase);
466
+ const stamp = nowIso(options).replace(/[:.]/g, '-');
467
+ const backupFile = path.join(legacy.legacyBase, '.neocortex', 'backups', 'managed-config',
468
+ `managed-config-manifest-${stamp}-${sha256(latestBytes).slice(0, 12)}.bak`);
469
+ resolveWithinBase(legacy.legacyBase, backupFile, 'backup');
470
+ atomicWrite(backupFile, latestBytes, 0o600);
471
+ let removed = 0;
472
+ for (const { id, entry } of retire) {
473
+ const fresh = latest.entries[id];
474
+ if (fresh && fresh.relativePath === entry.relativePath && fresh.installedHash === entry.installedHash) {
475
+ delete latest.entries[id];
476
+ removed += 1;
477
+ }
478
+ }
479
+ saveManifest(legacy.manifestFile, legacy.legacyBase, latest, false);
480
+ return { action: 'retired', reasonCode: 'managed-duplicate-base-retired', count: removed, ...preserved };
481
+ }
482
+
483
+ /**
484
+ * C11: adopt a duplicate entry from the legacy base into the resolved base.
485
+ * Backup fields are relative to the legacy base, so a verified backup is
486
+ * copied into `<base>/.neocortex/backups/managed-config/` and the path is
487
+ * rewritten. A backup that cannot be verified or copied is dropped from the
488
+ * adopted entry and the duplicate is kept (it still carries the only rollback
489
+ * record).
490
+ */
491
+ function adoptDuplicateEntry(duplicate, legacyBase, baseDir, safeId, targetRelative, options) {
492
+ const adopted = {
493
+ ...duplicate.entry,
494
+ relativePath: targetRelative,
495
+ action: 'adopted-identical',
496
+ updatedAt: nowIso(options),
497
+ };
498
+ const { backupRelativePath, backupHash } = duplicate.entry;
499
+ if (!backupRelativePath) return { entry: { ...adopted, backupRelativePath: null, backupHash: null }, retireBlocked: false };
500
+ let bytes = null;
501
+ try {
502
+ const source = resolveWithinBase(legacyBase, path.join(legacyBase, backupRelativePath), 'backup');
503
+ bytes = fs.existsSync(source.resolved) ? fs.readFileSync(source.resolved) : null;
504
+ } catch {
505
+ bytes = null;
506
+ }
507
+ if (!bytes || typeof backupHash !== 'string' || sha256(bytes) !== backupHash) {
508
+ return { entry: { ...adopted, backupRelativePath: null, backupHash: null }, retireBlocked: true };
509
+ }
510
+ const backupFile = path.join(path.resolve(baseDir), '.neocortex', 'backups', 'managed-config',
511
+ `${sanitizeId(safeId)}-adopted-${backupHash.slice(0, 12)}.bak`);
512
+ const location = resolveWithinBase(baseDir, backupFile, 'backup');
513
+ if (!options.dryRun) atomicWrite(location.resolved, bytes, 0o600);
514
+ return { entry: { ...adopted, backupRelativePath: location.relative, backupHash }, retireBlocked: false };
515
+ }
516
+
176
517
  function writeManagedBytes(input) {
177
518
  const {
178
519
  id,
@@ -184,12 +525,23 @@ function writeManagedBytes(input) {
184
525
  dryRun = false,
185
526
  allowLegacyAdoption = false,
186
527
  allowOwnedDriftMerge = false,
528
+ adoptExistingOwner = false,
529
+ legacyBaseDir = null,
187
530
  now,
188
531
  } = input;
189
- const safeId = sanitizeId(id);
532
+ let safeId = sanitizeId(id);
190
533
  const target = resolveWithinBase(baseDir, destination, 'destination');
191
534
  const manifest = loadManifest(manifestFile, baseDir);
192
- const entry = manifest.entries[safeId];
535
+ let ownerAdopted = false;
536
+ if (adoptExistingOwner && !manifest.entries[safeId]) {
537
+ const owners = Object.entries(manifest.entries)
538
+ .filter(([, candidate]) => candidate && candidate.relativePath === target.relative);
539
+ if (owners.length === 1) {
540
+ safeId = owners[0][0];
541
+ ownerAdopted = true;
542
+ }
543
+ }
544
+ let entry = manifest.entries[safeId];
193
545
  if (entry && entry.relativePath !== target.relative) {
194
546
  throw new ManagedConfigError('managed-ownership-conflict', 'Managed id already owns a different destination.', 2);
195
547
  }
@@ -199,16 +551,88 @@ function writeManagedBytes(input) {
199
551
  throw new ManagedConfigError('managed-ownership-conflict', 'Managed destination already has a different owner.', 2);
200
552
  }
201
553
 
554
+ const isProfile = kind === 'profile';
555
+ const extra = ownerAdopted ? { ownerAdopted: true } : {};
556
+ if (isProfile) {
557
+ let stat = null;
558
+ try { stat = fs.lstatSync(target.resolved); } catch { stat = null; }
559
+ if (stat && stat.isSymbolicLink()) {
560
+ return resultFor(safeId, target.relative, 'skipped', 'managed-destination-symlink-preserved', { ...extra, dryRun });
561
+ }
562
+ }
563
+
202
564
  const desiredHash = sha256(desiredBytes);
565
+ const desiredDigest = isProfile ? managedLinesDigest(desiredBytes) : null;
566
+ const digestField = isProfile ? { managedLinesDigest: desiredDigest } : {};
203
567
  const exists = fs.existsSync(target.resolved);
204
568
  const currentBytes = exists ? fs.readFileSync(target.resolved) : null;
205
569
  const currentHash = currentBytes ? sha256(currentBytes) : null;
570
+ const legacy = isProfile ? readLegacyDuplicates(legacyBaseDir, baseDir, target.resolved) : null;
571
+ const priorInstalledHash = entry?.installedHash || null;
572
+
573
+ let ownershipEvidence = null;
574
+ const adoptedIds = new Set();
575
+ const blockedIds = new Set();
576
+ // Adoption from the single duplicate in the legacy base: by identical hash
577
+ // when the file exists, or by ownership when it is missing (C11, so the
578
+ // T1 restore path owns it and the duplicate does not stay forever).
579
+ if (!entry && legacy && legacy.duplicates.length === 1 && kind === 'profile' &&
580
+ (!exists || legacy.duplicates[0].entry.installedHash === currentHash)) {
581
+ const duplicate = legacy.duplicates[0];
582
+ const adoption = adoptDuplicateEntry(duplicate, legacy.legacyBase, baseDir, safeId, target.relative, { dryRun, now });
583
+ entry = adoption.entry;
584
+ manifest.entries[safeId] = entry;
585
+ ownershipEvidence = 'managed-duplicate-base-adopted';
586
+ if (adoption.retireBlocked) blockedIds.add(duplicate.id);
587
+ else adoptedIds.add(duplicate.id);
588
+ }
589
+
590
+ const settle = (finalHash) => {
591
+ if (!legacy) return {};
592
+ const hashes = new Set([finalHash, currentHash, priorInstalledHash].filter(Boolean));
593
+ return { duplicateBase: settleLegacyDuplicates(legacy, hashes, { dryRun, now, adoptedIds, blockedIds }) };
594
+ };
595
+
596
+ // P227.14 T1: an owned destination that disappeared is restored.
597
+ if (isProfile && entry && !exists) {
598
+ if (!dryRun) atomicWrite(target.resolved, desiredBytes, 0o600);
599
+ manifest.entries[safeId] = {
600
+ ...entry,
601
+ kind,
602
+ relativePath: target.relative,
603
+ installedHash: desiredHash,
604
+ previousHash: null,
605
+ backupRelativePath: null,
606
+ backupHash: null,
607
+ createdByApply: true,
608
+ action: 'restored',
609
+ ...digestField,
610
+ updatedAt: nowIso({ now }),
611
+ };
612
+ saveManifest(manifestFile, baseDir, manifest, dryRun);
613
+ return resultFor(safeId, target.relative, dryRun ? 'planned-restored' : 'restored', 'managed-content-applied', {
614
+ beforeHash: null,
615
+ installedHash: desiredHash,
616
+ ownershipEvidence: 'managed-destination-missing',
617
+ ...extra,
618
+ ...settle(desiredHash),
619
+ dryRun,
620
+ });
621
+ }
622
+
623
+ if (
624
+ entry && currentHash !== entry.installedHash && !allowOwnedDriftMerge &&
625
+ isProfile && !ownershipEvidence
626
+ ) {
627
+ ownershipEvidence = managedDeltaEvidence(currentBytes, desiredBytes, entry);
628
+ }
206
629
 
207
- if (entry && currentHash !== entry.installedHash && !allowOwnedDriftMerge) {
630
+ if (entry && currentHash !== entry.installedHash && !allowOwnedDriftMerge && !ownershipEvidence) {
208
631
  return resultFor(safeId, target.relative, 'skipped', 'user-drift-preserved', {
209
632
  beforeHash: currentHash,
210
633
  installedHash: entry.installedHash,
211
634
  desiredHash,
635
+ ...extra,
212
636
  dryRun,
213
637
  });
214
638
  }
@@ -224,13 +648,30 @@ function writeManagedBytes(input) {
224
648
  backupHash: null,
225
649
  createdByApply: false,
226
650
  action: 'adopted-identical',
651
+ ...digestField,
227
652
  updatedAt: nowIso({ now }),
228
653
  };
229
654
  saveManifest(manifestFile, baseDir, manifest, dryRun);
655
+ } else if (ownershipEvidence) {
656
+ manifest.entries[safeId] = {
657
+ ...entry,
658
+ installedHash: desiredHash,
659
+ action: ownershipEvidence === 'managed-duplicate-base-adopted' ? entry.action : 'post-process-reconciled',
660
+ ...digestField,
661
+ updatedAt: nowIso({ now }),
662
+ };
663
+ saveManifest(manifestFile, baseDir, manifest, dryRun);
664
+ } else if (isProfile && entry.managedLinesDigest !== desiredDigest) {
665
+ // Backfill: the hash is exact, only the digest is recorded.
666
+ manifest.entries[safeId] = { ...entry, ...digestField };
667
+ saveManifest(manifestFile, baseDir, manifest, dryRun);
230
668
  }
231
669
  return resultFor(safeId, target.relative, dryRun ? 'planned-noop' : 'noop', 'managed-content-current', {
232
670
  beforeHash: currentHash,
233
671
  installedHash: desiredHash,
672
+ ...(ownershipEvidence ? { ownershipEvidence } : {}),
673
+ ...extra,
674
+ ...settle(desiredHash),
234
675
  dryRun,
235
676
  });
236
677
  }
@@ -242,6 +683,7 @@ function writeManagedBytes(input) {
242
683
  return resultFor(safeId, target.relative, 'skipped', 'unmanaged-content-preserved', {
243
684
  beforeHash: currentHash,
244
685
  desiredHash,
686
+ ...extra,
245
687
  dryRun,
246
688
  });
247
689
  }
@@ -252,6 +694,7 @@ function writeManagedBytes(input) {
252
694
  if (!dryRun) atomicWrite(target.resolved, desiredBytes, 0o600);
253
695
 
254
696
  manifest.entries[safeId] = {
697
+ ...(entry || {}),
255
698
  kind,
256
699
  relativePath: target.relative,
257
700
  installedHash: desiredHash,
@@ -260,6 +703,7 @@ function writeManagedBytes(input) {
260
703
  backupHash: backup?.backupHash || null,
261
704
  createdByApply: !exists,
262
705
  action,
706
+ ...digestField,
263
707
  updatedAt: nowIso({ now }),
264
708
  };
265
709
  saveManifest(manifestFile, baseDir, manifest, dryRun);
@@ -267,6 +711,9 @@ function writeManagedBytes(input) {
267
711
  beforeHash: currentHash,
268
712
  installedHash: desiredHash,
269
713
  backupRelativePath: backup?.backupRelativePath || null,
714
+ ...(ownershipEvidence ? { ownershipEvidence } : {}),
715
+ ...extra,
716
+ ...settle(desiredHash),
270
717
  dryRun,
271
718
  });
272
719
  }
@@ -456,9 +903,11 @@ function reconcile(options) {
456
903
  throw new ManagedConfigError('managed-reconcile-destination-missing', 'Managed destination is missing.', 2);
457
904
  }
458
905
  const [id, entry] = matches[0];
459
- const installedHash = sha256(fs.readFileSync(target.resolved));
906
+ const installedBytes = fs.readFileSync(target.resolved);
907
+ const installedHash = sha256(installedBytes);
460
908
  if (!options.dryRun) {
461
909
  entry.installedHash = installedHash;
910
+ if (entry.kind === 'profile') entry.managedLinesDigest = managedLinesDigest(installedBytes);
462
911
  entry.action = 'post-process-reconciled';
463
912
  entry.updatedAt = nowIso(options);
464
913
  saveManifest(options.manifestFile, options.baseDir, manifest, false);
@@ -470,7 +919,7 @@ function reconcile(options) {
470
919
  }
471
920
 
472
921
  function usage() {
473
- console.error('Usage: managed-config-merge.js profile <source> <dest> <manifest> <base> <id> [--dry-run] [--adopt-legacy] | resolve-base <platform-home> <default-base> | policy <config> <manifest> <base> [--dry-run] | rollback <manifest> <base> <id> [--dry-run] | reconcile <dest> <manifest> <base> [--dry-run]');
922
+ console.error('Usage: managed-config-merge.js profile <source> <dest> <manifest> <base> <id> [--dry-run] [--adopt-legacy] [--tier=<Free|Pro|Enterprise>] [--legacy-base=<dir>] | resolve-base <platform-home> <default-base> | policy <config> <manifest> <base> [--dry-run] | rollback <manifest> <base> <id> [--dry-run] | reconcile <dest> <manifest> <base> [--dry-run]');
474
923
  process.exitCode = 64;
475
924
  }
476
925
 
@@ -491,6 +940,7 @@ function runCli(argv = process.argv.slice(2)) {
491
940
  dryRun,
492
941
  allowLegacyAdoption: args.includes('--adopt-legacy'),
493
942
  tierLabel: args.find((arg) => arg.startsWith('--tier='))?.slice('--tier='.length),
943
+ legacyBaseDir: args.find((arg) => arg.startsWith('--legacy-base='))?.slice('--legacy-base='.length) || null,
494
944
  });
495
945
  } else if (command === 'policy') {
496
946
  const [configFile, manifestFile, baseDir] = args;
@@ -545,4 +995,8 @@ module.exports = {
545
995
  runCli,
546
996
  sha256,
547
997
  isKnownLegacyProfile,
998
+ isManagedDescriptionOnlyDelta,
999
+ isManagedLinesOnlyDelta,
1000
+ managedLinesCanonical,
1001
+ managedLinesDigest,
548
1002
  };
@@ -36,33 +36,80 @@ neocortex_is_user_home() {
36
36
  [ "$real_candidate" = "$real_home" ]
37
37
  }
38
38
 
39
- # Extract action/reasonCode from one helper JSON result line.
39
+ # P226.13: true when the adapter destination is a global install target (the
40
+ # user home). Adapters use it to skip project folders such as .github/agents
41
+ # or .agent/skills; it only guards creation and never removes anything.
42
+ neocortex_is_global_destination() {
43
+ neocortex_is_user_home "$1"
44
+ }
45
+
46
+ # Extract the top-level action/reasonCode from the helper JSON result line.
47
+ # C11: parsed as JSON by node (the helper already requires node), so nested
48
+ # objects or values with braces never turn a success into "failed".
49
+ NEOCORTEX_MANAGED_PARSE_JS='let s="";process.stdin.on("data",(d)=>{s+=d;}).on("end",()=>{const lines=s.split(/\r?\n/).filter((l)=>l.trim().startsWith("{")).reverse();let out="";for(const line of lines){try{const j=JSON.parse(line);if(j&&typeof j.action==="string"){out=j.action+" "+(typeof j.reasonCode==="string"?j.reasonCode:"");break;}}catch(e){}}process.stdout.write(out.replace(/[^A-Za-z0-9 _.-]/g,""));});'
40
50
  neocortex_managed_parse() {
41
- NEOCORTEX_MANAGED_ACTION="$(printf '%s' "$1" | sed -n 's/.*"action":"\([^"]*\)".*/\1/p' | head -n 1)"
42
- NEOCORTEX_MANAGED_REASON="$(printf '%s' "$1" | sed -n 's/.*"reasonCode":"\([^"]*\)".*/\1/p' | head -n 1)"
51
+ local parsed=""
52
+ if command -v node >/dev/null 2>&1; then
53
+ parsed="$(printf '%s' "$1" | node -e "$NEOCORTEX_MANAGED_PARSE_JS" 2>/dev/null)" || parsed=""
54
+ fi
55
+ NEOCORTEX_MANAGED_ACTION="${parsed%% *}"
56
+ NEOCORTEX_MANAGED_REASON=""
57
+ case "$parsed" in
58
+ *" "*) NEOCORTEX_MANAGED_REASON="${parsed#* }" ;;
59
+ esac
43
60
  [ -n "$NEOCORTEX_MANAGED_ACTION" ] || NEOCORTEX_MANAGED_ACTION="failed"
44
61
  [ -n "$NEOCORTEX_MANAGED_REASON" ] || NEOCORTEX_MANAGED_REASON="managed-operation-failed"
45
62
  }
46
63
 
64
+ # P227.14: tier label for managed profile writes, same rule as install.sh.
65
+ neocortex_managed_tier_label() {
66
+ local tier_value
67
+ tier_value="$(grep '"tier"' "$HOME/.neocortex/config.json" 2>/dev/null | head -n 1 | sed 's/.*"tier"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')"
68
+ case "$tier_value" in
69
+ free) printf '%s\n' "Free" ;;
70
+ pro) printf '%s\n' "Pro" ;;
71
+ enterprise) printf '%s\n' "Enterprise" ;;
72
+ *) printf '%s\n' "" ;;
73
+ esac
74
+ }
75
+
76
+ # P227.14: print HOME when the managed base is a platform base outside it, so
77
+ # a duplicate HOME manifest entry for the same file can be adopted or retired.
78
+ neocortex_managed_legacy_base() {
79
+ local base_dir="$1"
80
+ local real_base real_home
81
+ real_base="$(cd "$base_dir" 2>/dev/null && pwd -P)" || return 0
82
+ real_home="$(cd "$HOME" 2>/dev/null && pwd -P)" || return 0
83
+ [ "$real_base" = "$real_home" ] || printf '%s\n' "$HOME"
84
+ }
85
+
47
86
  neocortex_managed_profile() {
48
87
  local source_root="$1"
49
88
  local source_file="$2"
50
89
  local destination="$3"
51
90
  local base_dir="$4"
52
91
  local managed_id="$5"
92
+ # C11: "platform" marks a platform-home base (for example the resolved
93
+ # CODEX_HOME). Only then is HOME passed as the legacy duplicate base;
94
+ # project-scoped installs never consult the HOME manifest.
95
+ local base_scope="${6:-project}"
53
96
  NEOCORTEX_MANAGED_ACTION=""
54
97
  NEOCORTEX_MANAGED_REASON=""
55
98
  # The top-level Bash installer supplies tier-aware managed_copy_file, which
56
99
  # sets the same NEOCORTEX_MANAGED_* variables.
57
100
  if command -v managed_copy_file >/dev/null 2>&1; then
58
- managed_copy_file "$source_file" "$destination" "$managed_id" "$base_dir"
101
+ managed_copy_file "$source_file" "$destination" "$managed_id" "$base_dir" "$base_scope"
59
102
  return $?
60
103
  fi
61
104
  local helper="$source_root/targets-stubs/lib/managed-config-merge.js"
62
105
  local manifest="$base_dir/.neocortex/managed-config-manifest.json"
63
106
  if [ -f "$helper" ] && command -v node >/dev/null 2>&1; then
64
- local output status
65
- output="$(node "$helper" profile "$source_file" "$destination" "$manifest" "$base_dir" "$managed_id" --adopt-legacy 2>&1)"
107
+ local output status tier_label legacy_base
108
+ tier_label="$(neocortex_managed_tier_label)"
109
+ legacy_base=""
110
+ [ "$base_scope" = "platform" ] && legacy_base="$(neocortex_managed_legacy_base "$base_dir")"
111
+ output="$(node "$helper" profile "$source_file" "$destination" "$manifest" "$base_dir" "$managed_id" --adopt-legacy \
112
+ ${tier_label:+"--tier=$tier_label"} ${legacy_base:+"--legacy-base=$legacy_base"} 2>&1)"
66
113
  status=$?
67
114
  neocortex_managed_parse "$output"
68
115
  [ "$status" -eq 0 ] || NEOCORTEX_MANAGED_ACTION="failed"
@@ -95,7 +142,7 @@ neocortex_managed_report() {
95
142
  case "$NEOCORTEX_MANAGED_ACTION" in
96
143
  noop|planned-noop)
97
144
  echo "$prefix Up to date: $label" ;;
98
- created|updated|legacy-migrated|planned-*)
145
+ created|updated|legacy-migrated|restored|planned-*)
99
146
  echo "$prefix Installed: $label" ;;
100
147
  skipped)
101
148
  echo "$prefix Preserved local changes: $label ($NEOCORTEX_MANAGED_REASON)" >&2
@@ -64,7 +64,7 @@ task directive, I keep root-owned inline/shell-loop execution.
64
64
  ┌────────────────────────────────────────────────────────────┐
65
65
  │ │
66
66
  │ ####### N E O C O R T E X │
67
- │ ### ######## v4.61.6 │
67
+ │ ### ######## v4.64.0 │
68
68
  │ ######### ##### │
69
69
  │ ## ############## Development Orchestrator │
70
70
  │ ## ### ###### ## OrNexus Team │