@cleocode/core 2026.11.17 → 2026.11.18-rc.ci.735

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 (56) hide show
  1. package/dist/.source-stamp.json +1 -1
  2. package/dist/agents/scaffold.js +32 -30
  3. package/dist/agents/scaffold.js.map +1 -1
  4. package/dist/build-provenance.json +2 -2
  5. package/dist/docs/doctor.d.ts +103 -0
  6. package/dist/docs/doctor.js +228 -68
  7. package/dist/docs/doctor.js.map +1 -1
  8. package/dist/docs/modernize/apply.d.ts +2 -1
  9. package/dist/docs/modernize/apply.js +133 -39
  10. package/dist/docs/modernize/apply.js.map +1 -1
  11. package/dist/docs/publications-store.d.ts +16 -3
  12. package/dist/docs/publications-store.js +13 -8
  13. package/dist/docs/publications-store.js.map +1 -1
  14. package/dist/doctor/gate-text.d.ts +70 -0
  15. package/dist/doctor/gate-text.js +93 -0
  16. package/dist/doctor/gate-text.js.map +1 -0
  17. package/dist/gateway-client/generated/types.gen.d.ts +16 -0
  18. package/dist/init.js +1 -0
  19. package/dist/init.js.map +1 -1
  20. package/dist/logger.d.ts +14 -10
  21. package/dist/logger.js +29 -57
  22. package/dist/logger.js.map +1 -1
  23. package/dist/memory/brain-lifecycle.d.ts +7 -0
  24. package/dist/memory/brain-lifecycle.js +9 -1
  25. package/dist/memory/brain-lifecycle.js.map +1 -1
  26. package/dist/memory/sleep-consolidation.d.ts +26 -2
  27. package/dist/memory/sleep-consolidation.js +58 -5
  28. package/dist/memory/sleep-consolidation.js.map +1 -1
  29. package/dist/store/agent-doctor.d.ts +36 -1
  30. package/dist/store/agent-doctor.js +158 -5
  31. package/dist/store/agent-doctor.js.map +1 -1
  32. package/dist/store/agent-install.d.ts +12 -0
  33. package/dist/store/agent-install.js +97 -17
  34. package/dist/store/agent-install.js.map +1 -1
  35. package/dist/store/agent-seed-digests.d.ts +26 -0
  36. package/dist/store/agent-seed-digests.js +52 -0
  37. package/dist/store/agent-seed-digests.js.map +1 -0
  38. package/dist/store/schema/cleo-global/agent-registry.d.ts +16 -0
  39. package/dist/store/schema/cleo-global/agent-registry.js +6 -0
  40. package/dist/store/schema/cleo-global/agent-registry.js.map +1 -1
  41. package/dist/store/table-classification.js +5 -0
  42. package/dist/store/table-classification.js.map +1 -1
  43. package/dist/tasks/ac-table.d.ts +18 -0
  44. package/dist/tasks/ac-table.js +57 -0
  45. package/dist/tasks/ac-table.js.map +1 -1
  46. package/dist/tasks/acceptance-input.d.ts +16 -0
  47. package/dist/tasks/acceptance-input.js +10 -3
  48. package/dist/tasks/acceptance-input.js.map +1 -1
  49. package/dist/tasks/req.d.ts +59 -0
  50. package/dist/tasks/req.js +114 -1
  51. package/dist/tasks/req.js.map +1 -1
  52. package/dist/upgrade.d.ts +4 -0
  53. package/dist/upgrade.js +28 -2
  54. package/dist/upgrade.js.map +1 -1
  55. package/migrations/drizzle-cleo-global/20261126090000_t14654-agent-seed-sha256/migration.sql +14 -0
  56. package/package.json +13 -13
@@ -198,6 +198,35 @@ export const DOCS_DOCTOR_REPAIR_CLASSES = [
198
198
  function isRepairClass(kind) {
199
199
  return DOCS_DOCTOR_REPAIR_CLASSES.includes(kind);
200
200
  }
201
+ /**
202
+ * The `cleo docs doctor` invocation that archives the only-held blob of the
203
+ * ledger row at `publishedPath` into `slug` (T14651). A placeholder `slug`
204
+ * (such as `SLUG`, never one in angle brackets, which a shell reads as a
205
+ * redirect) is printed as given.
206
+ *
207
+ * @param publishedPath - The row's published path, as stored.
208
+ * @param slug - The archive target doc.
209
+ * @returns The command, with the path shell-quoted when it needs it.
210
+ */
211
+ export function docsDoctorArchiveCommand(publishedPath, slug) {
212
+ const quoted = /^[\w./-]+$/.test(publishedPath)
213
+ ? publishedPath
214
+ : `'${publishedPath.replace(/'/g, "'\\''")}'`;
215
+ return `cleo docs doctor --only publication-ledger-drift --apply --publication ${quoted} --archive-into ${slug}`;
216
+ }
217
+ /**
218
+ * The `cleo docs update` invocation that marks `slug` superseded (T14650):
219
+ * the non-deprecated route (`cleo docs supersede` warns W_DEPRECATED_COMMAND,
220
+ * T11179) that takes a duplicate doc out of the archive-target tie. A
221
+ * placeholder `slug` (such as `DUPLICATE`, never one in angle brackets) is
222
+ * printed as given.
223
+ *
224
+ * @param slug - The doc to mark superseded.
225
+ * @returns The command.
226
+ */
227
+ export function docsSupersedeCommand(slug) {
228
+ return `cleo docs update ${slug} --status superseded`;
229
+ }
201
230
  /**
202
231
  * Parse a row's `attachment_json` defensively. Malformed JSON yields null —
203
232
  * such rows are skipped by kind-scoped checks rather than failing the run.
@@ -408,6 +437,84 @@ async function fetchRowContent(row, payload, projectRoot) {
408
437
  return null;
409
438
  }
410
439
  }
440
+ /**
441
+ * Every blob sha a ledger row's blob may rely on besides the ledger: the
442
+ * `docs_attachments` rows and the conduit doc history (blob GC keeps what it
443
+ * names, T14632). A ledger row whose blob is in neither set, and named by no
444
+ * other surviving ledger row, is the blob's last reference.
445
+ *
446
+ * @param projectRoot - Absolute path to the CLEO project root.
447
+ * @param attachmentShas - The `docs_attachments` shas when already loaded.
448
+ * @returns The protecting shas. An unreadable conduit history protects
449
+ * nothing more (fewer removals, never more).
450
+ */
451
+ export async function readBlobHolderShas(projectRoot, attachmentShas) {
452
+ let held = attachmentShas;
453
+ if (held === undefined) {
454
+ const db = await getDb(projectRoot);
455
+ const rows = await db.select({ sha256: docsAttachments.sha256 }).from(docsAttachments).all();
456
+ held = new Set(rows.map((r) => r.sha256));
457
+ }
458
+ const conduitShas = await listConduitHistorySha256Set(projectRoot).catch(() => new Set());
459
+ return new Set([...held, ...conduitShas]);
460
+ }
461
+ /**
462
+ * Build the archive of a blob into the doc `slug` (T14632): `'unadopted'`
463
+ * when the doc has no conduit history yet, `null` when its bytes do not
464
+ * re-hash to `sha256` from any local source.
465
+ *
466
+ * @param projectRoot - Absolute path to the CLEO project root.
467
+ * @param slug - The doc the blob becomes a prior version of.
468
+ * @param sha256 - The blob.
469
+ * @returns The archive, or why there is none.
470
+ */
471
+ export async function buildLedgerArchive(projectRoot, slug, sha256) {
472
+ const docUid = await resolveConduitDocUid(projectRoot, slug).catch(() => null);
473
+ if (docUid === null)
474
+ return 'unadopted';
475
+ const bytes = readVerifiedBlobBytes(resolveCleoDir(projectRoot), sha256);
476
+ if (bytes === null)
477
+ return null;
478
+ return {
479
+ docUid,
480
+ slug,
481
+ sha256,
482
+ sizeBytes: bytes.length,
483
+ tokens: bytes
484
+ .toString('utf-8')
485
+ .split(/\s+/)
486
+ .filter((w) => w.length > 0).length,
487
+ };
488
+ }
489
+ /**
490
+ * Import a ledger row's blob as a prior conduit version of its archive doc
491
+ * (origin {@link DOCS_DOCTOR_ARCHIVE_ORIGIN}, created at the row's
492
+ * `publishedAt`, head untouched), so the blob stays reachable once the row
493
+ * goes (T14632). Additive: no row is lost.
494
+ *
495
+ * @param projectRoot - Absolute path to the CLEO project root.
496
+ * @param record - The ledger row whose blob is archived.
497
+ * @param archive - From {@link buildLedgerArchive}.
498
+ * @param author - The writer's agent id and the version's change summary.
499
+ */
500
+ export async function importLedgerArchive(projectRoot, record, archive, author) {
501
+ await withConduitDocWriteTransaction(projectRoot, async () => {
502
+ await importMigratedConduitVersion(projectRoot, {
503
+ attachmentUid: archive.docUid,
504
+ parentVersionUid: null,
505
+ authorAgentId: author.agentId,
506
+ storageKey: `sha256:${archive.sha256}`,
507
+ contentHash: archive.sha256,
508
+ sizeBytes: archive.sizeBytes,
509
+ tokens: archive.tokens,
510
+ versionNumber: 0,
511
+ createdAt: record.publishedAt,
512
+ changeSummary: author.changeSummary,
513
+ slug: archive.slug,
514
+ origin: DOCS_DOCTOR_ARCHIVE_ORIGIN,
515
+ });
516
+ });
517
+ }
411
518
  /**
412
519
  * Decide whether a missing mirror is provably gone, not merely absent from
413
520
  * this device or this checkout (T14117 review). `docs_publications` syncs
@@ -490,7 +597,7 @@ function provePublicationGone(projectRoot, publishedPath, absPath) {
490
597
  *
491
598
  * @internal
492
599
  */
493
- async function scanPublicationLedger(projectRoot, rows, checkoutRoot) {
600
+ async function scanPublicationLedger(projectRoot, rows, checkoutRoot, named) {
494
601
  const ledger = await readDocsPublications(projectRoot);
495
602
  if (ledger.length === 0)
496
603
  return [];
@@ -500,9 +607,8 @@ async function scanPublicationLedger(projectRoot, rows, checkoutRoot) {
500
607
  const recordByKey = new Map(ledger.map((r) => [key(r), r]));
501
608
  const attachmentShas = new Set(rows.map((r) => r.sha256));
502
609
  // T14632: blob GC keeps what the conduit doc history names, so the doctor
503
- // counts it as protection too. An unreadable history protects nothing more
504
- // (fewer prunes, never more).
505
- const conduitShas = await listConduitHistorySha256Set(projectRoot).catch(() => new Set());
610
+ // counts it as protection too.
611
+ const holderShas = await readBlobHolderShas(projectRoot, attachmentShas);
506
612
  const recordFor = (item) => recordByKey.get(key(item));
507
613
  // T14504: a drifted row is superseded only when its doc's CANONICAL head
508
614
  // (resolved the way slug-rename resolves it: conduit head, else the registry
@@ -511,7 +617,7 @@ async function scanPublicationLedger(projectRoot, rows, checkoutRoot) {
511
617
  // sha `status` reports is best-effort (sync and SDK updates move the head
512
618
  // without it), so it is never trusted here; a head that does not resolve
513
619
  // keeps the row (fail closed).
514
- const { resolveDocRef } = await import('./slug-rename.js');
620
+ const { resolveDocRef, supersessionSlugs } = await import('./slug-rename.js');
515
621
  const headByName = async (blobName) => {
516
622
  for (const name of new Set([blobName, blobName.replace(/\.md$/, '')])) {
517
623
  const ref = await resolveDocRef(projectRoot, name, { quiet: true }).catch(() => null);
@@ -567,35 +673,29 @@ async function scanPublicationLedger(projectRoot, rows, checkoutRoot) {
567
673
  }
568
674
  return false;
569
675
  };
570
- // T14632: a gone row's blob is archived into the doc whose stream it
571
- // published: another row of the SAME (ownerId, blobName) — one blob-manifest
572
- // stream — publishes in sync the exact head of exactly one slugged doc. The
573
- // doc must already be adopted into conduit history; the bytes must re-hash
574
- // to the row's blob. Anything less is no target (the row keeps its refusal).
575
- // T14634: every slugged doc's head is resolved, so two docs with
576
- // byte-identical heads both match and the target is refused as ambiguous
577
- // (one attachments row per sha could only ever name one of them). A
578
- // superseded doc is no target, so `cleo docs supersede` resolves the tie.
579
676
  let slugsByHead;
580
677
  const docsByHead = () => {
581
678
  slugsByHead ??= (async () => {
582
679
  const bySha = new Map();
583
- const live = rows.filter((r) => r.lifecycleStatus !== 'superseded');
584
- for (const slug of new Set(live.flatMap((r) => (r.slug ? [r.slug] : [])))) {
680
+ const live = new Set(rows.flatMap((r) => (r.slug && r.lifecycleStatus !== 'superseded' ? [r.slug] : [])));
681
+ for (const slug of new Set(rows.flatMap((r) => (r.slug ? [r.slug] : [])))) {
585
682
  const ref = await resolveDocRef(projectRoot, slug, { quiet: true }).catch(() => null);
586
683
  if (!ref)
587
684
  continue;
588
- const slugs = bySha.get(ref.sha256) ?? new Set();
589
- slugs.add(slug);
590
- bySha.set(ref.sha256, slugs);
685
+ const docs = bySha.get(ref.sha256) ?? {
686
+ live: new Set(),
687
+ superseded: new Set(),
688
+ };
689
+ (live.has(slug) ? docs.live : docs.superseded).add(slug);
690
+ bySha.set(ref.sha256, docs);
591
691
  }
592
692
  return bySha;
593
693
  })();
594
694
  return slugsByHead;
595
695
  };
596
- const cleoDir = resolveCleoDir(projectRoot);
597
696
  const archiveTarget = async (record) => {
598
697
  const slugs = new Set();
698
+ const supersededSlugs = new Set();
599
699
  for (const item of status.items) {
600
700
  if (item.drift !== 'in-sync')
601
701
  continue;
@@ -604,33 +704,43 @@ async function scanPublicationLedger(projectRoot, rows, checkoutRoot) {
604
704
  continue;
605
705
  if (live.ownerId !== record.ownerId || live.blobName !== record.blobName)
606
706
  continue;
607
- for (const slug of (await docsByHead()).get(live.lastBlobSha) ?? [])
707
+ const docs = (await docsByHead()).get(live.lastBlobSha);
708
+ for (const slug of docs?.live ?? [])
608
709
  slugs.add(slug);
710
+ for (const slug of docs?.superseded ?? [])
711
+ supersededSlugs.add(slug);
609
712
  }
610
713
  const [slug, ...others] = [...slugs].sort();
611
- if (slug === undefined)
612
- return null;
714
+ if (slug === undefined) {
715
+ const [gone] = [...supersededSlugs].sort();
716
+ if (gone === undefined)
717
+ return null;
718
+ const ref = await resolveDocRef(projectRoot, gone, { quiet: true }).catch(() => null);
719
+ const successor = ref ? (await supersessionSlugs(projectRoot, ref)).supersededBy : null;
720
+ return { kind: 'superseded', slug: gone, successor };
721
+ }
613
722
  if (others.length > 0)
614
723
  return { kind: 'ambiguous', slugs: [slug, ...others] };
615
- const docUid = await resolveConduitDocUid(projectRoot, slug).catch(() => null);
616
- if (docUid === null)
724
+ return namedTarget(slug, record);
725
+ };
726
+ // T14651: a caller-named doc (a merged or deleted mirror has no sibling
727
+ // row). It gets the automatic path's lifecycle rules: an alias resolves to
728
+ // the doc's live slug, a superseded doc is no target (T14634), and a slug
729
+ // that names no doc is refused as such.
730
+ const namedTarget = async (named, record) => {
731
+ const ref = await resolveDocRef(projectRoot, named, { quiet: true }).catch(() => null);
732
+ if (ref === null)
733
+ return { kind: 'unknown', slug: named };
734
+ const slug = ref.slug;
735
+ const { supersededBy } = await supersessionSlugs(projectRoot, ref);
736
+ const lifecycle = ref.meta.lifecycleStatus ?? ref.ownRow.lifecycleStatus;
737
+ if (lifecycle === 'superseded' || supersededBy !== null) {
738
+ return { kind: 'superseded', slug, successor: supersededBy };
739
+ }
740
+ const archive = await buildLedgerArchive(projectRoot, slug, record.lastBlobSha);
741
+ if (archive === 'unadopted')
617
742
  return { kind: 'unadopted', slug };
618
- const bytes = readVerifiedBlobBytes(cleoDir, record.lastBlobSha);
619
- if (bytes === null)
620
- return null;
621
- return {
622
- kind: 'adopted',
623
- archive: {
624
- docUid,
625
- slug,
626
- sha256: record.lastBlobSha,
627
- sizeBytes: bytes.length,
628
- tokens: bytes
629
- .toString('utf-8')
630
- .split(/\s+/)
631
- .filter((w) => w.length > 0).length,
632
- },
633
- };
743
+ return archive === null ? { kind: 'no-bytes', slug } : { kind: 'adopted', archive };
634
744
  };
635
745
  const drafts = [];
636
746
  for (const item of status.items) {
@@ -686,7 +796,15 @@ async function scanPublicationLedger(projectRoot, rows, checkoutRoot) {
686
796
  continue;
687
797
  }
688
798
  const proof = provePublicationGone(checkoutRoot, record.publishedPath, absPath);
689
- const target = proof.gone ? await archiveTarget(record) : null;
799
+ const mine = named?.publishedPath === record.publishedPath ? named : undefined;
800
+ const target = !proof.gone
801
+ ? null
802
+ : mine
803
+ ? await namedTarget(mine.slug, record)
804
+ : await archiveTarget(record);
805
+ const rerun = mine
806
+ ? `\`${docsDoctorArchiveCommand(record.publishedPath, mine.slug)}\``
807
+ : '`cleo docs doctor --only publication-ledger-drift --apply`';
690
808
  drafts.push({
691
809
  record,
692
810
  drift: 'deleted',
@@ -712,24 +830,39 @@ async function scanPublicationLedger(projectRoot, rows, checkoutRoot) {
712
830
  : target?.kind === 'unadopted'
713
831
  ? {
714
832
  action: 'republish-or-prune',
715
- detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}…; doc '${target.slug}' has no conduit history yet — adopt it with \`cleo docs migrate\`, then \`cleo docs doctor --only publication-ledger-drift --apply\` archives the blob into it`,
833
+ detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}…; doc '${target.slug}' has no conduit history yet — adopt it with \`cleo docs migrate\`, then ${rerun} archives the blob into it`,
716
834
  }
717
835
  : target?.kind === 'ambiguous'
718
836
  ? {
719
837
  action: 'republish-or-prune',
720
- detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}…; the archive target is ambiguous: docs ${target.slugs.map((s) => `'${s}'`).join(', ')} share the head its stream publishes — keep the doc the stream belongs to and supersede each other one with \`cleo docs supersede <duplicate> <kept>\`, then \`cleo docs doctor --only publication-ledger-drift --apply\` archives the blob into it`,
838
+ detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}…; the archive target is ambiguous: docs ${target.slugs.map((s) => `'${s}'`).join(', ')} share the head its stream publishes — keep the doc the stream belongs to and mark each other one superseded with \`${docsSupersedeCommand('DUPLICATE')}\`, then \`cleo docs doctor --only publication-ledger-drift --apply\` archives the blob into it`,
721
839
  }
722
- : {
723
- action: 'republish-or-prune',
724
- detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}… — republish it, or archive the doc before pruning`,
725
- },
840
+ : target?.kind === 'unknown'
841
+ ? {
842
+ action: 'republish-or-prune',
843
+ detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}…; no doc named '${target.slug}' — name an existing doc with --archive-into (\`cleo docs list\` lists them)`,
844
+ }
845
+ : target?.kind === 'superseded'
846
+ ? {
847
+ action: 'republish-or-prune',
848
+ detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}…; doc '${target.slug}' is superseded, so it takes no archive${target.successor ? ` — archive into its successor: \`${docsDoctorArchiveCommand(record.publishedPath, target.successor)}\`` : ` — name the doc that replaced it: \`${docsDoctorArchiveCommand(record.publishedPath, 'SLUG')}\``}`,
849
+ }
850
+ : target?.kind === 'no-bytes'
851
+ ? {
852
+ action: 'republish-or-prune',
853
+ detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}…, whose bytes are not in this device's blob store — run ${rerun} on a device that holds them`,
854
+ }
855
+ : {
856
+ action: 'republish-or-prune',
857
+ detail: `mirror ${record.publishedPath} is gone (${proof.reason}) and this row is the only reference to blob ${blob}… — republish it, or archive the doc before pruning`,
858
+ },
726
859
  });
727
860
  }
728
861
  // A blob is protected only by an attachments row or by a ledger row that
729
862
  // survives this run: two prune candidates never protect each other (T14504),
730
863
  // so the last row naming a blob is never deleted and the blob never exposed to GC.
731
864
  const candidateRecords = new Set(drafts.filter((d) => d.candidate).map((d) => d.record));
732
- const survivorShas = new Set([...attachmentShas, ...conduitShas]);
865
+ const survivorShas = new Set(holderShas);
733
866
  for (const item of status.items) {
734
867
  if (item.drift === 'deleted')
735
868
  continue;
@@ -761,7 +894,7 @@ async function scanPublicationLedger(projectRoot, rows, checkoutRoot) {
761
894
  *
762
895
  * @internal
763
896
  */
764
- async function scanStore(projectRoot, db, olderThanDays, checkoutRoot) {
897
+ async function scanStore(projectRoot, db, olderThanDays, checkoutRoot, archiveInto) {
765
898
  const rows = await db.select().from(docsAttachments).all();
766
899
  const payloadById = new Map();
767
900
  for (const row of rows)
@@ -953,7 +1086,7 @@ async function scanStore(projectRoot, db, olderThanDays, checkoutRoot) {
953
1086
  // planner reads the audit file, the registry and (hash-verified) bytes,
954
1087
  // and writes nothing.
955
1088
  const conduitBackfill = await planConduitHistoryBackfill(projectRoot);
956
- const ledger = await scanPublicationLedger(projectRoot, rows, checkoutRoot);
1089
+ const ledger = await scanPublicationLedger(projectRoot, rows, checkoutRoot, archiveInto);
957
1090
  // T14336: docs left on the pre-T14332 identity because the shared uid is held.
958
1091
  const { planOldMigrateRekeys } = await import('../store/conduit-doc-history.js');
959
1092
  const { skipped: stuck } = await planOldMigrateRekeys(projectRoot);
@@ -1138,6 +1271,31 @@ export async function runDocsDoctor(projectRoot, opts = {}) {
1138
1271
  only = [...new Set(opts.only)].filter((c) => valid.has(c));
1139
1272
  }
1140
1273
  const inScope = (kind) => only === null || only.includes(kind);
1274
+ // T14651 — a named archive target is a publication-ledger repair.
1275
+ const archiveInto = opts.archiveInto;
1276
+ if (archiveInto !== undefined) {
1277
+ if (archiveInto.publishedPath.trim() === '' || archiveInto.slug.trim() === '') {
1278
+ return {
1279
+ ok: false,
1280
+ error: {
1281
+ // @sync-invariant none:input-shape an argument refusal before any repair write; nothing was written
1282
+ code: 'E_DOCS_DOCTOR_ARCHIVE_INTO_INVALID',
1283
+ message: 'docs doctor: --archive-into needs both a ledger path (--publication <path>) and a doc slug',
1284
+ },
1285
+ };
1286
+ }
1287
+ if (repair || !inScope('publication-ledger-drift')) {
1288
+ return {
1289
+ ok: false,
1290
+ error: {
1291
+ // @sync-invariant none:input-shape a flag-combination refusal before any repair write; nothing was written
1292
+ code: 'E_DOCS_DOCTOR_FLAG_CONFLICT',
1293
+ message: 'docs doctor: --archive-into is a publication-ledger-drift repair — it cannot run with ' +
1294
+ '--repair or an --only that leaves that class out.',
1295
+ },
1296
+ };
1297
+ }
1298
+ }
1141
1299
  const rebuildWikilinks = inScope('wikilinks-drift') || inScope('empty-provenance');
1142
1300
  if (mutate) {
1143
1301
  const refusal = checkBackupReceipt(opts.backupReceiptPath);
@@ -1159,7 +1317,19 @@ export async function runDocsDoctor(projectRoot, opts = {}) {
1159
1317
  },
1160
1318
  };
1161
1319
  }
1162
- const pre = await scanStore(projectRoot, db, olderThanDays, checkoutRoot);
1320
+ const pre = await scanStore(projectRoot, db, olderThanDays, checkoutRoot, opts.archiveInto);
1321
+ if (archiveInto !== undefined &&
1322
+ !pre.ledger.some((f) => f.drift === 'deleted' && f.record.publishedPath === archiveInto.publishedPath)) {
1323
+ return {
1324
+ ok: false,
1325
+ error: {
1326
+ // @sync-invariant none:input-shape an argument refusal before any repair write; nothing was written
1327
+ code: 'E_DOCS_DOCTOR_ARCHIVE_ROW_NOT_FOUND',
1328
+ message: `docs doctor: no docs_publications row at ${archiveInto.publishedPath} has a missing mirror; ` +
1329
+ 'name the path exactly as `cleo docs status` lists it',
1330
+ },
1331
+ };
1332
+ }
1163
1333
  const repairs = [];
1164
1334
  // T13653: in repair mode ONLY the blob backfill runs — apply mode plans it
1165
1335
  // alongside the other repairs.
@@ -1385,21 +1555,9 @@ export async function runDocsDoctor(projectRoot, opts = {}) {
1385
1555
  for (const { record, archive } of archivable) {
1386
1556
  if (archive === undefined)
1387
1557
  continue;
1388
- await withConduitDocWriteTransaction(projectRoot, async () => {
1389
- await importMigratedConduitVersion(projectRoot, {
1390
- attachmentUid: archive.docUid,
1391
- parentVersionUid: null,
1392
- authorAgentId: 'cleo:docs-doctor',
1393
- storageKey: `sha256:${archive.sha256}`,
1394
- contentHash: archive.sha256,
1395
- sizeBytes: archive.sizeBytes,
1396
- tokens: archive.tokens,
1397
- versionNumber: 0,
1398
- createdAt: record.publishedAt,
1399
- changeSummary: `archived by docs doctor from ledger row ${record.publishedPath} (owner ${record.ownerId}, blob ${record.blobName})`,
1400
- slug: archive.slug,
1401
- origin: DOCS_DOCTOR_ARCHIVE_ORIGIN,
1402
- });
1558
+ await importLedgerArchive(projectRoot, record, archive, {
1559
+ agentId: 'cleo:docs-doctor',
1560
+ changeSummary: `archived by docs doctor from ledger row ${record.publishedPath} (owner ${record.ownerId}, blob ${record.blobName})`,
1403
1561
  });
1404
1562
  // The import has committed: a failed audit append must not hide it
1405
1563
  // from the report or stop the remaining archives and prunes (T14634).
@@ -1434,7 +1592,9 @@ export async function runDocsDoctor(projectRoot, opts = {}) {
1434
1592
  // T13560: on a mutating run, re-scan so the envelope's diagnostics (and the
1435
1593
  // summary computed from them) describe POST-repair state, consistent with
1436
1594
  // a follow-up dry run. Dry runs keep the pre-repair scan.
1437
- const post = mutate ? await scanStore(projectRoot, db, olderThanDays, checkoutRoot) : pre;
1595
+ const post = mutate
1596
+ ? await scanStore(projectRoot, db, olderThanDays, checkoutRoot, opts.archiveInto)
1597
+ : pre;
1438
1598
  const findings = post.diagnostics.reduce((sum, d) => sum + d.count, 0);
1439
1599
  // T13727 — surface the conduit backfill counts in the one-line summary so
1440
1600
  // operators see backfilled/skipped/gap per run without reading the report.