@ornexus/neocortex 4.62.0 → 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 (77) 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 +28 -5
  5. package/package.json +3 -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/commands/invoke.d.ts +7 -0
  9. package/packages/client/dist/commands/invoke.js +50 -50
  10. package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
  11. package/packages/client/dist/commands/refresh-memory.js +5 -3
  12. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +86 -1
  13. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -3
  14. package/packages/client/dist/git/git-lifecycle-store.d.ts +30 -2
  15. package/packages/client/dist/git/git-lifecycle-store.js +7 -7
  16. package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
  17. package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
  18. package/packages/client/dist/git/release-gate-env.d.ts +2 -41
  19. package/packages/client/dist/git/release-gate-env.js +1 -1
  20. package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
  21. package/packages/client/dist/git/state-json-field-merge.js +2 -0
  22. package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
  23. package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
  24. package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
  25. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  26. package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
  27. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  28. package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
  29. package/packages/client/dist/git/story-worktree-paths.js +1 -1
  30. package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
  31. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  32. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  33. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +30 -0
  34. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +8 -8
  35. package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
  36. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  37. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  38. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  39. package/packages/client/dist/runner/headless/types.d.ts +9 -1
  40. package/packages/client/dist/runner/headless/types.js +2 -2
  41. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  42. package/packages/client/dist/state/state-json-repair.d.ts +23 -0
  43. package/packages/client/dist/state/state-json-repair.js +4 -3
  44. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  45. package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
  46. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  47. package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
  48. package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
  49. package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
  50. package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
  51. package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
  52. package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
  53. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +46 -1
  54. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  55. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
  56. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  57. package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +92 -0
  58. package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
  59. package/packages/shared/dist/compatibility/index.js +6 -0
  60. package/packages/shared/dist/project-manifest-projection.js +6 -3
  61. package/packages/shared/dist/release-gate-env-contract.js +129 -0
  62. package/packages/shared/dist/yoloop/branch-unit.js +119 -3
  63. package/packages/shared/dist/yoloop/epic-terminal-git.js +4 -0
  64. package/targets-stubs/antigravity/gemini.md +1 -1
  65. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  66. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  67. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  68. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  69. package/targets-stubs/claude-code/neocortex.md +2 -2
  70. package/targets-stubs/codex/AGENTS.md +1 -1
  71. package/targets-stubs/codex/install-codex.sh +12 -4
  72. package/targets-stubs/cursor/agent.md +2 -2
  73. package/targets-stubs/gemini-cli/agent.md +2 -2
  74. package/targets-stubs/lib/managed-config-merge.js +385 -7
  75. package/targets-stubs/lib/managed-profile.sh +47 -7
  76. package/targets-stubs/opencode/neocortex-root.md +1 -1
  77. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -230,6 +230,290 @@ function isManagedDescriptionOnlyDelta(currentBytes, desiredBytes, installedHash
230
230
  return false;
231
231
  }
232
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
+
233
517
  function writeManagedBytes(input) {
234
518
  const {
235
519
  id,
@@ -241,12 +525,23 @@ function writeManagedBytes(input) {
241
525
  dryRun = false,
242
526
  allowLegacyAdoption = false,
243
527
  allowOwnedDriftMerge = false,
528
+ adoptExistingOwner = false,
529
+ legacyBaseDir = null,
244
530
  now,
245
531
  } = input;
246
- const safeId = sanitizeId(id);
532
+ let safeId = sanitizeId(id);
247
533
  const target = resolveWithinBase(baseDir, destination, 'destination');
248
534
  const manifest = loadManifest(manifestFile, baseDir);
249
- 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];
250
545
  if (entry && entry.relativePath !== target.relative) {
251
546
  throw new ManagedConfigError('managed-ownership-conflict', 'Managed id already owns a different destination.', 2);
252
547
  }
@@ -256,17 +551,80 @@ function writeManagedBytes(input) {
256
551
  throw new ManagedConfigError('managed-ownership-conflict', 'Managed destination already has a different owner.', 2);
257
552
  }
258
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
+
259
564
  const desiredHash = sha256(desiredBytes);
565
+ const desiredDigest = isProfile ? managedLinesDigest(desiredBytes) : null;
566
+ const digestField = isProfile ? { managedLinesDigest: desiredDigest } : {};
260
567
  const exists = fs.existsSync(target.resolved);
261
568
  const currentBytes = exists ? fs.readFileSync(target.resolved) : null;
262
569
  const currentHash = currentBytes ? sha256(currentBytes) : null;
570
+ const legacy = isProfile ? readLegacyDuplicates(legacyBaseDir, baseDir, target.resolved) : null;
571
+ const priorInstalledHash = entry?.installedHash || null;
263
572
 
264
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
+
265
623
  if (
266
624
  entry && currentHash !== entry.installedHash && !allowOwnedDriftMerge &&
267
- kind === 'profile' && isManagedDescriptionOnlyDelta(currentBytes, desiredBytes, entry.installedHash)
625
+ isProfile && !ownershipEvidence
268
626
  ) {
269
- ownershipEvidence = 'managed-description-delta';
627
+ ownershipEvidence = managedDeltaEvidence(currentBytes, desiredBytes, entry);
270
628
  }
271
629
 
272
630
  if (entry && currentHash !== entry.installedHash && !allowOwnedDriftMerge && !ownershipEvidence) {
@@ -274,6 +632,7 @@ function writeManagedBytes(input) {
274
632
  beforeHash: currentHash,
275
633
  installedHash: entry.installedHash,
276
634
  desiredHash,
635
+ ...extra,
277
636
  dryRun,
278
637
  });
279
638
  }
@@ -289,6 +648,7 @@ function writeManagedBytes(input) {
289
648
  backupHash: null,
290
649
  createdByApply: false,
291
650
  action: 'adopted-identical',
651
+ ...digestField,
292
652
  updatedAt: nowIso({ now }),
293
653
  };
294
654
  saveManifest(manifestFile, baseDir, manifest, dryRun);
@@ -296,15 +656,22 @@ function writeManagedBytes(input) {
296
656
  manifest.entries[safeId] = {
297
657
  ...entry,
298
658
  installedHash: desiredHash,
299
- action: 'post-process-reconciled',
659
+ action: ownershipEvidence === 'managed-duplicate-base-adopted' ? entry.action : 'post-process-reconciled',
660
+ ...digestField,
300
661
  updatedAt: nowIso({ now }),
301
662
  };
302
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);
303
668
  }
304
669
  return resultFor(safeId, target.relative, dryRun ? 'planned-noop' : 'noop', 'managed-content-current', {
305
670
  beforeHash: currentHash,
306
671
  installedHash: desiredHash,
307
672
  ...(ownershipEvidence ? { ownershipEvidence } : {}),
673
+ ...extra,
674
+ ...settle(desiredHash),
308
675
  dryRun,
309
676
  });
310
677
  }
@@ -316,6 +683,7 @@ function writeManagedBytes(input) {
316
683
  return resultFor(safeId, target.relative, 'skipped', 'unmanaged-content-preserved', {
317
684
  beforeHash: currentHash,
318
685
  desiredHash,
686
+ ...extra,
319
687
  dryRun,
320
688
  });
321
689
  }
@@ -326,6 +694,7 @@ function writeManagedBytes(input) {
326
694
  if (!dryRun) atomicWrite(target.resolved, desiredBytes, 0o600);
327
695
 
328
696
  manifest.entries[safeId] = {
697
+ ...(entry || {}),
329
698
  kind,
330
699
  relativePath: target.relative,
331
700
  installedHash: desiredHash,
@@ -334,6 +703,7 @@ function writeManagedBytes(input) {
334
703
  backupHash: backup?.backupHash || null,
335
704
  createdByApply: !exists,
336
705
  action,
706
+ ...digestField,
337
707
  updatedAt: nowIso({ now }),
338
708
  };
339
709
  saveManifest(manifestFile, baseDir, manifest, dryRun);
@@ -342,6 +712,8 @@ function writeManagedBytes(input) {
342
712
  installedHash: desiredHash,
343
713
  backupRelativePath: backup?.backupRelativePath || null,
344
714
  ...(ownershipEvidence ? { ownershipEvidence } : {}),
715
+ ...extra,
716
+ ...settle(desiredHash),
345
717
  dryRun,
346
718
  });
347
719
  }
@@ -531,9 +903,11 @@ function reconcile(options) {
531
903
  throw new ManagedConfigError('managed-reconcile-destination-missing', 'Managed destination is missing.', 2);
532
904
  }
533
905
  const [id, entry] = matches[0];
534
- const installedHash = sha256(fs.readFileSync(target.resolved));
906
+ const installedBytes = fs.readFileSync(target.resolved);
907
+ const installedHash = sha256(installedBytes);
535
908
  if (!options.dryRun) {
536
909
  entry.installedHash = installedHash;
910
+ if (entry.kind === 'profile') entry.managedLinesDigest = managedLinesDigest(installedBytes);
537
911
  entry.action = 'post-process-reconciled';
538
912
  entry.updatedAt = nowIso(options);
539
913
  saveManifest(options.manifestFile, options.baseDir, manifest, false);
@@ -545,7 +919,7 @@ function reconcile(options) {
545
919
  }
546
920
 
547
921
  function usage() {
548
- 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]');
549
923
  process.exitCode = 64;
550
924
  }
551
925
 
@@ -566,6 +940,7 @@ function runCli(argv = process.argv.slice(2)) {
566
940
  dryRun,
567
941
  allowLegacyAdoption: args.includes('--adopt-legacy'),
568
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,
569
944
  });
570
945
  } else if (command === 'policy') {
571
946
  const [configFile, manifestFile, baseDir] = args;
@@ -621,4 +996,7 @@ module.exports = {
621
996
  sha256,
622
997
  isKnownLegacyProfile,
623
998
  isManagedDescriptionOnlyDelta,
999
+ isManagedLinesOnlyDelta,
1000
+ managedLinesCanonical,
1001
+ managedLinesDigest,
624
1002
  };
@@ -43,33 +43,73 @@ neocortex_is_global_destination() {
43
43
  neocortex_is_user_home "$1"
44
44
  }
45
45
 
46
- # Extract action/reasonCode from one helper JSON result line.
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,""));});'
47
50
  neocortex_managed_parse() {
48
- NEOCORTEX_MANAGED_ACTION="$(printf '%s' "$1" | sed -n 's/.*"action":"\([^"]*\)".*/\1/p' | head -n 1)"
49
- 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
50
60
  [ -n "$NEOCORTEX_MANAGED_ACTION" ] || NEOCORTEX_MANAGED_ACTION="failed"
51
61
  [ -n "$NEOCORTEX_MANAGED_REASON" ] || NEOCORTEX_MANAGED_REASON="managed-operation-failed"
52
62
  }
53
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
+
54
86
  neocortex_managed_profile() {
55
87
  local source_root="$1"
56
88
  local source_file="$2"
57
89
  local destination="$3"
58
90
  local base_dir="$4"
59
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}"
60
96
  NEOCORTEX_MANAGED_ACTION=""
61
97
  NEOCORTEX_MANAGED_REASON=""
62
98
  # The top-level Bash installer supplies tier-aware managed_copy_file, which
63
99
  # sets the same NEOCORTEX_MANAGED_* variables.
64
100
  if command -v managed_copy_file >/dev/null 2>&1; then
65
- managed_copy_file "$source_file" "$destination" "$managed_id" "$base_dir"
101
+ managed_copy_file "$source_file" "$destination" "$managed_id" "$base_dir" "$base_scope"
66
102
  return $?
67
103
  fi
68
104
  local helper="$source_root/targets-stubs/lib/managed-config-merge.js"
69
105
  local manifest="$base_dir/.neocortex/managed-config-manifest.json"
70
106
  if [ -f "$helper" ] && command -v node >/dev/null 2>&1; then
71
- local output status
72
- 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)"
73
113
  status=$?
74
114
  neocortex_managed_parse "$output"
75
115
  [ "$status" -eq 0 ] || NEOCORTEX_MANAGED_ACTION="failed"
@@ -102,7 +142,7 @@ neocortex_managed_report() {
102
142
  case "$NEOCORTEX_MANAGED_ACTION" in
103
143
  noop|planned-noop)
104
144
  echo "$prefix Up to date: $label" ;;
105
- created|updated|legacy-migrated|planned-*)
145
+ created|updated|legacy-migrated|restored|planned-*)
106
146
  echo "$prefix Installed: $label" ;;
107
147
  skipped)
108
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.62.0 │
67
+ │ ### ######## v4.64.0 │
68
68
  │ ######### ##### │
69
69
  │ ## ############## Development Orchestrator │
70
70
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: "neocortex"
3
- description: "Neocortex v4.62.0 | OrNexus Team"
3
+ description: "Neocortex v4.64.0 | OrNexus Team"
4
4
  tools:
5
5
  # Read / Edit (built-in tool sets)
6
6
  - read
@@ -72,7 +72,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
72
72
  ┌────────────────────────────────────────────────────────────┐
73
73
  │ │
74
74
  │ ####### N E O C O R T E X │
75
- │ ### ######## v4.62.0 │
75
+ │ ### ######## v4.64.0 │
76
76
  │ ######### ##### │
77
77
  │ ## ############## Development Orchestrator │
78
78
  │ ## ### ###### ## OrNexus Team │