@kaddo/cli 3.121.0 → 3.121.2

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 (35) hide show
  1. package/dist/admin-dist/assets/{architectureDiagram-3BPJPVTR-DIMrrmB9.js → architectureDiagram-3BPJPVTR-Dbr18Web.js} +1 -1
  2. package/dist/admin-dist/assets/{chunk-727SXJPM-Dqr01pM2.js → chunk-727SXJPM-BWbB1dny.js} +1 -1
  3. package/dist/admin-dist/assets/{chunk-AQP2D5EJ-Cq-Ux2er.js → chunk-AQP2D5EJ-CkKNMCVl.js} +1 -1
  4. package/dist/admin-dist/assets/{classDiagram-v2-Q7XG4LA2-ggXfKatP.js → classDiagram-4FO5ZUOK-9HavAioX.js} +1 -1
  5. package/dist/admin-dist/assets/{classDiagram-4FO5ZUOK-ggXfKatP.js → classDiagram-v2-Q7XG4LA2-9HavAioX.js} +1 -1
  6. package/dist/admin-dist/assets/{dagre-BM42HDAG-C6oD5ML4.js → dagre-BM42HDAG-CSnvJYn0.js} +1 -1
  7. package/dist/admin-dist/assets/{diagram-2AECGRRQ-hUz_WSJC.js → diagram-2AECGRRQ-D5mzkmrf.js} +1 -1
  8. package/dist/admin-dist/assets/{diagram-5GNKFQAL-ChltTKxS.js → diagram-5GNKFQAL-EOymLNQi.js} +1 -1
  9. package/dist/admin-dist/assets/{diagram-LMA3HP47-DD3kd-Zq.js → diagram-LMA3HP47-CFppr3p_.js} +1 -1
  10. package/dist/admin-dist/assets/{diagram-OG6HWLK6-BKHyHHw0.js → diagram-OG6HWLK6-IpTbPSwx.js} +1 -1
  11. package/dist/admin-dist/assets/{erDiagram-TEJ5UH35-BE5PDGjy.js → erDiagram-TEJ5UH35-Dsw1KXtJ.js} +1 -1
  12. package/dist/admin-dist/assets/{flowDiagram-I6XJVG4X-lxFDGYVc.js → flowDiagram-I6XJVG4X-CqPlWF-A.js} +1 -1
  13. package/dist/admin-dist/assets/{ganttDiagram-6RSMTGT7-BPeceg0v.js → ganttDiagram-6RSMTGT7-jQtBO2ri.js} +1 -1
  14. package/dist/admin-dist/assets/index-Mg4i_77z.js +92 -0
  15. package/dist/admin-dist/assets/{infoDiagram-5YYISTIA-Boe5ho81.js → infoDiagram-5YYISTIA-D5pnfo1x.js} +1 -1
  16. package/dist/admin-dist/assets/{ishikawaDiagram-YF4QCWOH-3T8K6hMf.js → ishikawaDiagram-YF4QCWOH-WxGtRgZ5.js} +1 -1
  17. package/dist/admin-dist/assets/{kanban-definition-UN3LZRKU-BW97uUmp.js → kanban-definition-UN3LZRKU-Buxhd6Vb.js} +1 -1
  18. package/dist/admin-dist/assets/{linear-BGHTsNfG.js → linear-CB4OadYd.js} +1 -1
  19. package/dist/admin-dist/assets/{mindmap-definition-RKZ34NQL-B-LmLGip.js → mindmap-definition-RKZ34NQL-EjTeYtkU.js} +1 -1
  20. package/dist/admin-dist/assets/{pieDiagram-4H26LBE5-BS0ysj7T.js → pieDiagram-4H26LBE5-DNg0vyEp.js} +1 -1
  21. package/dist/admin-dist/assets/{quadrantDiagram-W4KKPZXB-CJbpr-VT.js → quadrantDiagram-W4KKPZXB-Cw1i1NWC.js} +1 -1
  22. package/dist/admin-dist/assets/{requirementDiagram-4Y6WPE33-CTEMRVel.js → requirementDiagram-4Y6WPE33-B08Cqp6h.js} +1 -1
  23. package/dist/admin-dist/assets/{sequenceDiagram-3UESZ5HK-ff_IANYV.js → sequenceDiagram-3UESZ5HK-D5mOyhQb.js} +1 -1
  24. package/dist/admin-dist/assets/{stateDiagram-AJRCARHV-DCJ7-my6.js → stateDiagram-AJRCARHV-DKkcxwEg.js} +1 -1
  25. package/dist/admin-dist/assets/{stateDiagram-v2-BHNVJYJU-tCHje_1l.js → stateDiagram-v2-BHNVJYJU-BM6DzHMK.js} +1 -1
  26. package/dist/admin-dist/assets/{timeline-definition-PNZ67QCA-DMT8_Cuq.js → timeline-definition-PNZ67QCA-BKThSvYE.js} +1 -1
  27. package/dist/admin-dist/assets/{vennDiagram-CIIHVFJN-DRtPPFKO.js → vennDiagram-CIIHVFJN-C0IC5TPV.js} +1 -1
  28. package/dist/admin-dist/assets/{wardleyDiagram-YWT4CUSO-CDN0fFvU.js → wardleyDiagram-YWT4CUSO-dxdvDU4B.js} +1 -1
  29. package/dist/admin-dist/assets/{xychartDiagram-2RQKCTM6-e4oyuMDO.js → xychartDiagram-2RQKCTM6-_OD2E5cs.js} +1 -1
  30. package/dist/admin-dist/index.html +1 -1
  31. package/dist/admin-server/index.js +118 -0
  32. package/dist/core.js +1149 -78
  33. package/dist/index.js +1382 -137
  34. package/package.json +1 -1
  35. package/dist/admin-dist/assets/index-B7GhDkjv.js +0 -92
package/dist/index.js CHANGED
@@ -144,10 +144,10 @@ Status: pending
144
144
  `;
145
145
  }
146
146
  function ensurePocArtifact(dir, projectName) {
147
- const path13 = join(dir, POC_ARTIFACT_PATH);
148
- if (exists(path13)) return false;
147
+ const path14 = join(dir, POC_ARTIFACT_PATH);
148
+ if (exists(path14)) return false;
149
149
  ensureDir(join(dir, "knowledge", "delivery"));
150
- writeFile(path13, pocTemplate(projectName));
150
+ writeFile(path14, pocTemplate(projectName));
151
151
  return true;
152
152
  }
153
153
  var PLACEHOLDER = /^[_<].*[_>]$|^(describe|list|document|what|how)\b/i;
@@ -162,13 +162,13 @@ function meaningful(text2) {
162
162
  });
163
163
  }
164
164
  function readPocSummary(dir) {
165
- const path13 = join(dir, POC_ARTIFACT_PATH);
166
- if (!exists(path13)) {
165
+ const path14 = join(dir, POC_ARTIFACT_PATH);
166
+ if (!exists(path14)) {
167
167
  return { exists: false, hypothesisDefined: false, successCriteriaCount: 0, constraintsDefined: false, nonGoalsDefined: false, conclusion: "pending" };
168
168
  }
169
169
  let markdown = "";
170
170
  try {
171
- markdown = readFile(path13);
171
+ markdown = readFile(path14);
172
172
  } catch {
173
173
  return { exists: false, hypothesisDefined: false, successCriteriaCount: 0, constraintsDefined: false, nonGoalsDefined: false, conclusion: "pending" };
174
174
  }
@@ -688,8 +688,8 @@ function loadConfig(dir) {
688
688
  const parsed = configSchema.safeParse(raw ?? {});
689
689
  if (!parsed.success) {
690
690
  const issues = parsed.error.issues.map((i) => {
691
- const path13 = i.path.join(".");
692
- return path13 ? ` - ${path13}: ${i.message}` : ` - ${i.message}`;
691
+ const path14 = i.path.join(".");
692
+ return path14 ? ` - ${path14}: ${i.message}` : ` - ${i.message}`;
693
693
  }).join("\n");
694
694
  throw new ConfigError(`Invalid .kaddo/config.yml:
695
695
  ${issues}`);
@@ -6716,8 +6716,8 @@ async function runCreate(type, opts = {}) {
6716
6716
  answers[question.frontMatterField] = answer.trim();
6717
6717
  }
6718
6718
  const id = nextWorkItemId(dir);
6719
- const slug5 = slugify(title);
6720
- const fileName = `${id}-${slug5}.md`;
6719
+ const slug7 = slugify(title);
6720
+ const fileName = `${id}-${slug7}.md`;
6721
6721
  const filePath = join(dir, DRAFT_DIR, fileName);
6722
6722
  const frontMatter2 = buildFrontMatter(id, workItemType, level, title.trim(), answers);
6723
6723
  const body = buildBody(workItemType, level, title.trim(), answers, levelDef.qualityGate);
@@ -6750,8 +6750,8 @@ async function runCreateModule(dir, modType) {
6750
6750
  answers[q.frontMatterField] = answer.trim();
6751
6751
  }
6752
6752
  const id = nextWorkItemId(dir);
6753
- const slug5 = slugify(title);
6754
- const fileName = `${id}-${slug5}.md`;
6753
+ const slug7 = slugify(title);
6754
+ const fileName = `${id}-${slug7}.md`;
6755
6755
  const filePath = join(dir, DRAFT_DIR, fileName);
6756
6756
  const frontMatter2 = buildModuleFrontMatter(id, modType, title.trim(), answers);
6757
6757
  const body = buildModuleBody(modType, title.trim(), answers);
@@ -6916,8 +6916,8 @@ function buildRoadmapWorkItem(opts) {
6916
6916
  const { id, type, level, candidate } = opts;
6917
6917
  const answers = opts.answers ?? {};
6918
6918
  const title = candidate.title.trim();
6919
- const slug5 = slugify(title);
6920
- const fileName = `${id}-${slug5}.md`;
6919
+ const slug7 = slugify(title);
6920
+ const fileName = `${id}-${slug7}.md`;
6921
6921
  const qualityGate = getLevel(level).qualityGate;
6922
6922
  const frontMatter2 = buildRoadmapFrontMatter(id, type, level, title, candidate, answers);
6923
6923
  const body = buildRoadmapBody(type, level, title, candidate, answers, qualityGate);
@@ -7318,10 +7318,10 @@ function analyzeGuard(touchedFiles, artifacts, silentWithoutOwnership) {
7318
7318
  import { parse as parseYaml5, stringify as stringifyYaml4 } from "yaml";
7319
7319
  var IGNORE_FILE = ".kaddo/ignores.yml";
7320
7320
  function loadIgnores(dir) {
7321
- const path13 = join(dir, IGNORE_FILE);
7322
- if (!exists(path13)) return [];
7321
+ const path14 = join(dir, IGNORE_FILE);
7322
+ if (!exists(path14)) return [];
7323
7323
  try {
7324
- const raw = readFile(path13);
7324
+ const raw = readFile(path14);
7325
7325
  const parsed = parseYaml5(raw);
7326
7326
  return Array.isArray(parsed) ? parsed : [];
7327
7327
  } catch {
@@ -7329,7 +7329,7 @@ function loadIgnores(dir) {
7329
7329
  }
7330
7330
  }
7331
7331
  function saveIgnore(dir, entry) {
7332
- const path13 = join(dir, IGNORE_FILE);
7332
+ const path14 = join(dir, IGNORE_FILE);
7333
7333
  const existing = loadIgnores(dir);
7334
7334
  const idx = existing.findIndex((e) => e.artifact_id === entry.artifact_id);
7335
7335
  if (idx >= 0) {
@@ -7337,17 +7337,17 @@ function saveIgnore(dir, entry) {
7337
7337
  } else {
7338
7338
  existing.push(entry);
7339
7339
  }
7340
- writeFile(path13, stringifyYaml4(existing));
7340
+ writeFile(path14, stringifyYaml4(existing));
7341
7341
  }
7342
7342
  function isIgnored(ignores, artifactId) {
7343
7343
  return ignores.find((e) => e.artifact_id === artifactId);
7344
7344
  }
7345
7345
  function removeIgnore(dir, artifactId) {
7346
- const path13 = join(dir, IGNORE_FILE);
7346
+ const path14 = join(dir, IGNORE_FILE);
7347
7347
  const existing = loadIgnores(dir);
7348
7348
  const filtered = existing.filter((e) => e.artifact_id !== artifactId);
7349
7349
  if (filtered.length === existing.length) return false;
7350
- writeFile(path13, stringifyYaml4(filtered));
7350
+ writeFile(path14, stringifyYaml4(filtered));
7351
7351
  return true;
7352
7352
  }
7353
7353
 
@@ -7369,11 +7369,11 @@ function moduleArtifactCoverage(dir, id) {
7369
7369
  };
7370
7370
  }
7371
7371
  function loadMappedModules(dir) {
7372
- const path13 = join(dir, DESCRIPTOR_PATH);
7373
- if (!exists(path13)) return [];
7372
+ const path14 = join(dir, DESCRIPTOR_PATH);
7373
+ if (!exists(path14)) return [];
7374
7374
  let parsed;
7375
7375
  try {
7376
- parsed = parseYaml6(readFile(path13));
7376
+ parsed = parseYaml6(readFile(path14));
7377
7377
  } catch {
7378
7378
  return [];
7379
7379
  }
@@ -8117,7 +8117,7 @@ function buildGuardHistory(dir) {
8117
8117
  const d = hotspotDir(t.code_path);
8118
8118
  hotspotMap.set(d, (hotspotMap.get(d) ?? 0) + 1);
8119
8119
  }
8120
- const hotspots = [...hotspotMap.entries()].map(([path13, warnings]) => ({ path: path13, warnings })).sort((a, b) => b.warnings - a.warnings);
8120
+ const hotspots = [...hotspotMap.entries()].map(([path14, warnings]) => ({ path: path14, warnings })).sort((a, b) => b.warnings - a.warnings);
8121
8121
  return {
8122
8122
  available: true,
8123
8123
  total_runs: sorted.length,
@@ -8637,7 +8637,7 @@ function runIgnoreRemove(artifactId) {
8637
8637
  }
8638
8638
 
8639
8639
  // src/commands/explain.ts
8640
- import matter9 from "gray-matter";
8640
+ import matter10 from "gray-matter";
8641
8641
  import { parse as parseYaml13 } from "yaml";
8642
8642
 
8643
8643
  // src/core/delivery-phase.ts
@@ -10755,10 +10755,10 @@ function slugify2(name) {
10755
10755
  return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
10756
10756
  }
10757
10757
  function readModulesDescriptor(dir) {
10758
- const path13 = join(dir, DESCRIPTOR_PATH2);
10759
- if (!exists(path13)) return { version: 1, modules: [] };
10758
+ const path14 = join(dir, DESCRIPTOR_PATH2);
10759
+ if (!exists(path14)) return { version: 1, modules: [] };
10760
10760
  try {
10761
- const parsed = parseYaml10(readFile(path13));
10761
+ const parsed = parseYaml10(readFile(path14));
10762
10762
  return { version: parsed.version ?? 1, modules: parsed.modules ?? [] };
10763
10763
  } catch {
10764
10764
  return { version: 1, modules: [] };
@@ -11138,7 +11138,7 @@ function sectionParagraph(md, title) {
11138
11138
  }
11139
11139
  return "";
11140
11140
  }
11141
- function parseCapsule(id, path13, md) {
11141
+ function parseCapsule(id, path14, md) {
11142
11142
  const { data } = matter3(md);
11143
11143
  const updatedAt = data.updated_at ? String(data.updated_at) : void 0;
11144
11144
  let ageDays = null;
@@ -11148,7 +11148,7 @@ function parseCapsule(id, path13, md) {
11148
11148
  }
11149
11149
  return {
11150
11150
  id,
11151
- path: path13,
11151
+ path: path14,
11152
11152
  system: data.system ? String(data.system) : id,
11153
11153
  owner: data.owner ? String(data.owner) : void 0,
11154
11154
  updatedAt,
@@ -11502,6 +11502,252 @@ function parseWorkItemResources(fm2) {
11502
11502
  return out;
11503
11503
  }
11504
11504
 
11505
+ // src/core/deprecation.ts
11506
+ import matter6 from "gray-matter";
11507
+ var DEPRECATION_ARTIFACT_TYPE = "deprecation-plan";
11508
+ var DEPRECATION_PLANS_DIR = "knowledge/legacy/deprecations";
11509
+ var TARGET_TYPES = [
11510
+ "module",
11511
+ "route",
11512
+ "function",
11513
+ "ui",
11514
+ "job",
11515
+ "database-object",
11516
+ "integration",
11517
+ "config",
11518
+ "other"
11519
+ ];
11520
+ var LIFECYCLE_STATES2 = [
11521
+ "candidate",
11522
+ "usage-validated",
11523
+ "soft-deprecated",
11524
+ "disabled",
11525
+ "removed-devtest",
11526
+ "production-ready",
11527
+ "production-changed",
11528
+ "observing",
11529
+ "completed",
11530
+ "deprecated-retained"
11531
+ ];
11532
+ var ENVIRONMENTS = ["development", "test", "production"];
11533
+ var ENVIRONMENT_STATES = ["active", "soft-deprecated", "disabled", "removed"];
11534
+ var EVIDENCE_SIGNALS = [
11535
+ "static",
11536
+ "runtime",
11537
+ "database",
11538
+ "external_consumers",
11539
+ "human_review"
11540
+ ];
11541
+ function str2(v) {
11542
+ return typeof v === "string" && v.trim() ? v.trim() : null;
11543
+ }
11544
+ function parseWorkItemDeprecationTargets(fm2) {
11545
+ const v = fm2.deprecation_targets;
11546
+ if (!Array.isArray(v)) return [];
11547
+ const out = [];
11548
+ for (const raw of v) {
11549
+ if (typeof raw === "string") {
11550
+ const s = raw.trim();
11551
+ if (!s) continue;
11552
+ const slash = s.indexOf("/");
11553
+ if (slash > 0) out.push({ plan: s.slice(0, slash).trim(), target: s.slice(slash + 1).trim() });
11554
+ else out.push({ plan: null, target: s });
11555
+ continue;
11556
+ }
11557
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
11558
+ const o = raw;
11559
+ const target = str2(o.target) ?? str2(o.id);
11560
+ if (!target) continue;
11561
+ out.push({ plan: str2(o.plan), target });
11562
+ }
11563
+ }
11564
+ return out;
11565
+ }
11566
+ function strArray2(v) {
11567
+ if (Array.isArray(v)) return v.map((x) => String(x).trim()).filter(Boolean);
11568
+ if (typeof v === "string" && v.trim()) return [v.trim()];
11569
+ return [];
11570
+ }
11571
+ function isValidTargetType(t) {
11572
+ return TARGET_TYPES.includes(t);
11573
+ }
11574
+ function isValidLifecycleState(s) {
11575
+ return LIFECYCLE_STATES2.includes(s);
11576
+ }
11577
+ function isValidEnvironmentState(s) {
11578
+ return ENVIRONMENT_STATES.includes(s);
11579
+ }
11580
+ function parseAssessment(v) {
11581
+ if (!v || typeof v !== "object" || Array.isArray(v)) {
11582
+ return { unusedConfidence: null, blastRadius: null, reversibility: null };
11583
+ }
11584
+ const o = v;
11585
+ return {
11586
+ unusedConfidence: str2(o.unused_confidence),
11587
+ blastRadius: str2(o.blast_radius),
11588
+ reversibility: str2(o.reversibility)
11589
+ };
11590
+ }
11591
+ function parseUsageEvidence(v) {
11592
+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};
11593
+ const out = {};
11594
+ for (const signal of EVIDENCE_SIGNALS) {
11595
+ const raw = v[signal];
11596
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
11597
+ const o = raw;
11598
+ out[signal] = {
11599
+ status: str2(o.status) ?? "unknown",
11600
+ quality: str2(o.quality) ?? "unknown",
11601
+ detail: str2(o.detail)
11602
+ };
11603
+ }
11604
+ return out;
11605
+ }
11606
+ function parseSoftDeprecation(v) {
11607
+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;
11608
+ const o = v;
11609
+ const windowRaw = o.observation_window_days;
11610
+ const window = typeof windowRaw === "number" && Number.isFinite(windowRaw) && windowRaw >= 0 ? Math.floor(windowRaw) : null;
11611
+ const exitCriteria = Array.isArray(o.exit_criteria) ? o.exit_criteria.map((c) => {
11612
+ if (typeof c === "string") return c.trim() ? { description: c.trim(), met: false } : null;
11613
+ if (c && typeof c === "object" && !Array.isArray(c)) {
11614
+ const co = c;
11615
+ const description = str2(co.description) ?? str2(co.criterion);
11616
+ if (!description) return null;
11617
+ return { description, met: co.met === true };
11618
+ }
11619
+ return null;
11620
+ }).filter((c) => Boolean(c)) : [];
11621
+ return {
11622
+ strategy: str2(o.strategy),
11623
+ mechanism: str2(o.mechanism),
11624
+ startedAt: str2(o.started_at),
11625
+ observationWindowDays: window,
11626
+ exitCriteria
11627
+ };
11628
+ }
11629
+ function parseEnvironments(v) {
11630
+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};
11631
+ const out = {};
11632
+ for (const env of ENVIRONMENTS) {
11633
+ const s = str2(v[env]);
11634
+ if (s) out[env] = s;
11635
+ }
11636
+ return out;
11637
+ }
11638
+ function parseTarget(raw) {
11639
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
11640
+ const o = raw;
11641
+ const id = str2(o.id);
11642
+ if (!id) return null;
11643
+ return {
11644
+ id,
11645
+ type: str2(o.type) ?? "other",
11646
+ locator: str2(o.locator),
11647
+ title: str2(o.title),
11648
+ lifecycle: str2(o.lifecycle) ?? "candidate",
11649
+ environments: parseEnvironments(o.environments),
11650
+ assessment: parseAssessment(o.assessment),
11651
+ usageEvidence: parseUsageEvidence(o.usage_evidence),
11652
+ dependsOnRemoval: strArray2(o.depends_on_removal),
11653
+ resource: str2(o.resource),
11654
+ module: str2(o.module),
11655
+ softDeprecation: parseSoftDeprecation(o.soft_deprecation)
11656
+ };
11657
+ }
11658
+ function parseTargets(v) {
11659
+ if (!Array.isArray(v)) return [];
11660
+ const out = [];
11661
+ for (const raw of v) {
11662
+ const t = parseTarget(raw);
11663
+ if (t) out.push(t);
11664
+ }
11665
+ return out;
11666
+ }
11667
+ function lifecycleCountsOf(targets) {
11668
+ const counts = {};
11669
+ for (const t of targets) counts[t.lifecycle] = (counts[t.lifecycle] ?? 0) + 1;
11670
+ return counts;
11671
+ }
11672
+ function purposeFromBody2(body) {
11673
+ const m = body.match(/^#{1,2}\s+Purpose\s*\n+([\s\S]*?)(?=\n#{1,2}\s|\s*$)/m);
11674
+ const text2 = m ? m[1].trim() : "";
11675
+ return text2 || null;
11676
+ }
11677
+ function getDeprecationPlans(dir) {
11678
+ return discoverKnowledge(dir).filter((a) => a.type === DEPRECATION_ARTIFACT_TYPE).map((a) => {
11679
+ const fm2 = a.rawFrontmatter;
11680
+ const targets = parseTargets(fm2.targets);
11681
+ return {
11682
+ id: a.id || str2(fm2.id) || a.title,
11683
+ title: a.title || str2(fm2.title) || a.id,
11684
+ path: a.relPath,
11685
+ status: str2(fm2.status),
11686
+ targetCount: targets.length,
11687
+ lifecycleCounts: lifecycleCountsOf(targets)
11688
+ };
11689
+ }).sort((x, y) => x.id.localeCompare(y.id));
11690
+ }
11691
+ function getDeprecationPlan(dir, id) {
11692
+ const match = discoverKnowledge(dir).find(
11693
+ (a) => a.type === DEPRECATION_ARTIFACT_TYPE && (a.id === id || a.title === id)
11694
+ );
11695
+ if (!match) return null;
11696
+ const raw = readFile(match.filePath);
11697
+ const parsed = matter6(raw);
11698
+ const fm2 = parsed.data ?? {};
11699
+ const body = parsed.content.trim();
11700
+ const targets = parseTargets(fm2.targets);
11701
+ return {
11702
+ id: str2(fm2.id) ?? match.id,
11703
+ title: str2(fm2.title) ?? match.title,
11704
+ path: match.relPath,
11705
+ status: str2(fm2.status),
11706
+ targetCount: targets.length,
11707
+ lifecycleCounts: lifecycleCountsOf(targets),
11708
+ purpose: str2(fm2.purpose) ?? purposeFromBody2(body),
11709
+ targets,
11710
+ markdownBody: body
11711
+ };
11712
+ }
11713
+ function validateTarget(target) {
11714
+ const findings = [];
11715
+ const at = target.id;
11716
+ if (!isValidTargetType(String(target.type))) {
11717
+ findings.push({ severity: "error", target: at, message: `Unknown target type: ${target.type}` });
11718
+ }
11719
+ if (!isValidLifecycleState(String(target.lifecycle))) {
11720
+ findings.push({ severity: "error", target: at, message: `Unknown lifecycle state: ${target.lifecycle}` });
11721
+ }
11722
+ if (!target.locator) {
11723
+ findings.push({ severity: "warning", target: at, message: "Target has no locator \u2014 it may be ambiguous." });
11724
+ }
11725
+ for (const [env, state] of Object.entries(target.environments)) {
11726
+ if (!isValidEnvironmentState(String(state))) {
11727
+ findings.push({ severity: "error", target: at, message: `Unknown environment state for ${env}: ${state}` });
11728
+ }
11729
+ }
11730
+ const prodActive = target.environments.production === "active";
11731
+ if (target.lifecycle === "completed") {
11732
+ const stillActive = ENVIRONMENTS.filter((e) => target.environments[e] === "active");
11733
+ if (stillActive.length > 0) {
11734
+ findings.push({
11735
+ severity: "error",
11736
+ target: at,
11737
+ message: `Target is 'completed' but still active in: ${stillActive.join(", ")}.`
11738
+ });
11739
+ }
11740
+ }
11741
+ if ((target.lifecycle === "production-changed" || target.lifecycle === "observing") && prodActive) {
11742
+ findings.push({
11743
+ severity: "error",
11744
+ target: at,
11745
+ message: `Target is '${target.lifecycle}' but production is still 'active'.`
11746
+ });
11747
+ }
11748
+ return findings;
11749
+ }
11750
+
11505
11751
  // src/core/graph.ts
11506
11752
  var KNOWLEDGE3 = "knowledge";
11507
11753
  var RESOURCE_ROLE_EDGE = {
@@ -11546,9 +11792,9 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
11546
11792
  ];
11547
11793
  const presentLayers = [];
11548
11794
  for (const layer2 of layerDocs) {
11549
- const path13 = layer2.files.map((f) => `${KNOWLEDGE3}/${f}`).find((rel) => exists(join(dir, rel)));
11550
- if (path13) {
11551
- addNode({ id: layer2.id, type: layer2.type, label: layer2.label, path: path13 });
11795
+ const path14 = layer2.files.map((f) => `${KNOWLEDGE3}/${f}`).find((rel) => exists(join(dir, rel)));
11796
+ if (path14) {
11797
+ addNode({ id: layer2.id, type: layer2.type, label: layer2.label, path: path14 });
11552
11798
  presentLayers.push(layer2.id);
11553
11799
  }
11554
11800
  }
@@ -11606,6 +11852,33 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
11606
11852
  addEdge(modId, resId, "depends_on");
11607
11853
  }
11608
11854
  }
11855
+ for (const summary of getDeprecationPlans(dir)) {
11856
+ const plan = getDeprecationPlan(dir, summary.id);
11857
+ if (!plan) continue;
11858
+ const planId = `deprecation-plan:${plan.id}`;
11859
+ addNode({ id: planId, type: "deprecation-plan", label: `${plan.id} ${plan.title}`.trim(), path: plan.path, status: plan.status ?? void 0 });
11860
+ for (const target of plan.targets) {
11861
+ const targetId = `deprecation-target:${target.id}`;
11862
+ addNode({ id: targetId, type: "deprecation-target", label: target.title ? `${target.id} ${target.title}` : target.id, path: plan.path, status: target.lifecycle });
11863
+ addEdge(planId, targetId, "targets");
11864
+ if (target.module) {
11865
+ const moduleId = `module:${target.module}`;
11866
+ addNode({ id: moduleId, type: "module", label: target.module });
11867
+ addEdge(targetId, moduleId, "targets");
11868
+ }
11869
+ if (target.resource) {
11870
+ const resourceId = `resource:${target.resource}`;
11871
+ const title = resourceTitleById.get(target.resource);
11872
+ addNode({ id: resourceId, type: "project-resource", label: title ? `${target.resource} ${title}` : target.resource });
11873
+ addEdge(targetId, resourceId, "targets");
11874
+ }
11875
+ for (const dependency of target.dependsOnRemoval) {
11876
+ const dependencyId = `deprecation-target:${dependency}`;
11877
+ addNode({ id: dependencyId, type: "deprecation-target", label: dependency });
11878
+ addEdge(targetId, dependencyId, "depends_on_removal");
11879
+ }
11880
+ }
11881
+ }
11609
11882
  for (const wi of selectedWIs) {
11610
11883
  const id = wi.id || wi.title;
11611
11884
  if (!id || !id.trim()) continue;
@@ -11636,6 +11909,11 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
11636
11909
  addNode({ id: resId, type: "project-resource", label: title ? `${rel.id} ${title}`.trim() : rel.id });
11637
11910
  addEdge(wiNodeId, resId, RESOURCE_ROLE_EDGE[rel.role] ?? "uses");
11638
11911
  }
11912
+ for (const ref of parseWorkItemDeprecationTargets(wi.rawFrontmatter)) {
11913
+ const targetId = `deprecation-target:${ref.target}`;
11914
+ addNode({ id: targetId, type: "deprecation-target", label: ref.target });
11915
+ addEdge(wiNodeId, targetId, "targets");
11916
+ }
11639
11917
  for (const dec of wi.decisions) {
11640
11918
  if (!dec || !dec.trim()) continue;
11641
11919
  const adrId = `adr:${dec}`;
@@ -12014,7 +12292,7 @@ function loadGraphHints(dir) {
12014
12292
  }
12015
12293
 
12016
12294
  // src/services/installed-skills.ts
12017
- import matter6 from "gray-matter";
12295
+ import matter7 from "gray-matter";
12018
12296
  var SKILLS_DIR = join("knowledge", "skills");
12019
12297
  function discoverInstalledSkills(dir) {
12020
12298
  const base = join(dir, SKILLS_DIR);
@@ -12024,7 +12302,7 @@ function discoverInstalledSkills(dir) {
12024
12302
  const skillFile = join(base, entry, "skill.md");
12025
12303
  if (!isFile(skillFile)) continue;
12026
12304
  try {
12027
- const { data } = matter6(readFile(skillFile));
12305
+ const { data } = matter7(readFile(skillFile));
12028
12306
  if (data.type && String(data.type) !== "skill") continue;
12029
12307
  const id = String(data.id ?? entry);
12030
12308
  out.push({
@@ -13047,7 +13325,7 @@ function buildTechDecisions(dir) {
13047
13325
 
13048
13326
  // src/core/poc-report.ts
13049
13327
  import { createHash } from "crypto";
13050
- import matter7 from "gray-matter";
13328
+ import matter8 from "gray-matter";
13051
13329
  var POC_REPORT_PREFIX = "poc-report-v";
13052
13330
  var SECRET_LINE = /(^|\s)(?:[A-Z][A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY|PRIVATE_KEY)|(?:token|secret|password|api[_-]?key))\s*[:=]\s*\S+/i;
13053
13331
  var reportName = /^poc-report-v(\d{3,})\.md$/;
@@ -13063,11 +13341,11 @@ function redactSecrets(value) {
13063
13341
  return line.replace(/([:=]\s*)\S+.*/, "$1[redacted]");
13064
13342
  }).join("\n");
13065
13343
  }
13066
- function source(dir, path13, kind) {
13067
- const absolute = join(dir, path13);
13344
+ function source(dir, path14, kind) {
13345
+ const absolute = join(dir, path14);
13068
13346
  if (!exists(absolute)) return null;
13069
13347
  const raw = readFile(absolute);
13070
- return { path: posix(path13), kind, digest: sha(raw), content: redactSecrets(raw) };
13348
+ return { path: posix(path14), kind, digest: sha(raw), content: redactSecrets(raw) };
13071
13349
  }
13072
13350
  function reportFiles(dir) {
13073
13351
  const delivery = join(dir, "knowledge", "delivery");
@@ -13075,7 +13353,7 @@ function reportFiles(dir) {
13075
13353
  const match = name.match(reportName);
13076
13354
  if (!match) return [];
13077
13355
  try {
13078
- const parsed = matter7(readFile(join(delivery, name)));
13356
+ const parsed = matter8(readFile(join(delivery, name)));
13079
13357
  const fingerprint = typeof parsed.data.source_fingerprint === "string" ? parsed.data.source_fingerprint : "";
13080
13358
  const manifest = parsed.data.source_manifest;
13081
13359
  const sourceManifest = manifest && typeof manifest === "object" && !Array.isArray(manifest) ? Object.fromEntries(Object.entries(manifest).filter(([, digest]) => typeof digest === "string")) : {};
@@ -13107,9 +13385,9 @@ function buildPocReportContext(dir) {
13107
13385
  };
13108
13386
  }
13109
13387
  const sources = [];
13110
- const add = (path13, kind) => {
13111
- if (sources.some((item2) => item2.path === posix(path13))) return;
13112
- const item = source(dir, path13, kind);
13388
+ const add = (path14, kind) => {
13389
+ if (sources.some((item2) => item2.path === posix(path14))) return;
13390
+ const item = source(dir, path14, kind);
13113
13391
  if (item) sources.push(item);
13114
13392
  };
13115
13393
  add(POC_ARTIFACT_PATH, "poc");
@@ -13137,7 +13415,7 @@ function buildPocReportContext(dir) {
13137
13415
  const sourceFingerprint = sha(sources.map((item) => `${item.path}\0${item.digest}`).join("\n"));
13138
13416
  const status = !latestReport ? "missing" : latestReport.sourceFingerprint === sourceFingerprint ? "current" : "stale";
13139
13417
  const currentManifest = Object.fromEntries(sources.map((item) => [item.path, item.digest]));
13140
- const changesSinceLatest = status === "stale" ? [.../* @__PURE__ */ new Set([...Object.keys(currentManifest), ...Object.keys(latestReport?.sourceManifest ?? {})])].filter((path13) => currentManifest[path13] !== latestReport?.sourceManifest[path13]).sort() : [];
13418
+ const changesSinceLatest = status === "stale" ? [.../* @__PURE__ */ new Set([...Object.keys(currentManifest), ...Object.keys(latestReport?.sourceManifest ?? {})])].filter((path14) => currentManifest[path14] !== latestReport?.sourceManifest[path14]).sort() : [];
13141
13419
  const sourceList = sources.map((item) => `- ${item.path} (${item.kind})`).join("\n") || "- No sources selected.";
13142
13420
  return {
13143
13421
  eligible: true,
@@ -13288,10 +13566,10 @@ function resolveNextStep(dir, now = /* @__PURE__ */ new Date()) {
13288
13566
  const q = (rel) => analyzeKnowledgeArtifact(dir, rel);
13289
13567
  const resolveAgent = (agent) => {
13290
13568
  const file = agent.endsWith(".md") ? agent : `${agent}.md`;
13291
- const path13 = agentInstallPath(file);
13292
- const installed = isFile(join(dir, path13));
13569
+ const path14 = agentInstallPath(file);
13570
+ const installed = isFile(join(dir, path14));
13293
13571
  const group = agentGroupOf(file);
13294
- return { agentPath: path13, agentInstalled: installed, installCommand: installed ? void 0 : `kaddo add agents --group ${group}` };
13572
+ return { agentPath: path14, agentInstalled: installed, installCommand: installed ? void 0 : `kaddo add agents --group ${group}` };
13295
13573
  };
13296
13574
  const moduleRepo = isModule(config);
13297
13575
  const coreRepo = isCore(config);
@@ -13721,7 +13999,7 @@ function deriveDeliveryCompletedStatus(dir) {
13721
13999
  }
13722
14000
 
13723
14001
  // src/core/assets.ts
13724
- import matter8 from "gray-matter";
14002
+ import matter9 from "gray-matter";
13725
14003
  function canonicalAgents() {
13726
14004
  return AGENT_PROMPTS.map((a) => ({
13727
14005
  name: a.fileName.replace(/\.md$/, ""),
@@ -13734,7 +14012,7 @@ function canonicalSkills() {
13734
14012
  }
13735
14013
  function versionOf(content) {
13736
14014
  try {
13737
- const v = matter8(content).data.version;
14015
+ const v = matter9(content).data.version;
13738
14016
  return v === void 0 || v === null ? null : String(v);
13739
14017
  } catch {
13740
14018
  return null;
@@ -15285,7 +15563,7 @@ function readKnowledge(dir) {
15285
15563
  if (!exists(knowledgePath)) return null;
15286
15564
  try {
15287
15565
  const raw = readFile(knowledgePath);
15288
- const { data, content } = matter9(raw);
15566
+ const { data, content } = matter10(raw);
15289
15567
  return { content, data };
15290
15568
  } catch {
15291
15569
  return null;
@@ -15296,7 +15574,7 @@ function readRoadmap(dir) {
15296
15574
  if (!exists(roadmapPath)) return null;
15297
15575
  try {
15298
15576
  const raw = readFile(roadmapPath);
15299
- const { content } = matter9(raw);
15577
+ const { content } = matter10(raw);
15300
15578
  return content.trim();
15301
15579
  } catch {
15302
15580
  return null;
@@ -15465,7 +15743,7 @@ function runExplain(opts) {
15465
15743
  }
15466
15744
 
15467
15745
  // src/core/context-pack.ts
15468
- import matter10 from "gray-matter";
15746
+ import matter11 from "gray-matter";
15469
15747
  var CONTEXT_PACK_VERSION = "1";
15470
15748
  var ARCH_DIR6 = "knowledge";
15471
15749
  function readScanJson(dir) {
@@ -15478,7 +15756,7 @@ function readScanJson(dir) {
15478
15756
  }
15479
15757
  }
15480
15758
  function firstParagraph2(markdown) {
15481
- const body = matter10(markdown).content.trim();
15759
+ const body = matter11(markdown).content.trim();
15482
15760
  const para = body.split("\n\n").map((p) => p.trim()).find((p) => p && !p.startsWith("#"));
15483
15761
  return para ?? "";
15484
15762
  }
@@ -17127,7 +17405,7 @@ function runStatus() {
17127
17405
  // src/commands/learn.ts
17128
17406
  import fs3 from "fs";
17129
17407
  import path7 from "path";
17130
- import matter11 from "gray-matter";
17408
+ import matter12 from "gray-matter";
17131
17409
  var ARCH_DIR9 = "knowledge";
17132
17410
  var WORK_ITEMS_DIR2 = "knowledge/delivery/work-items";
17133
17411
  function completedPathFor(filePath) {
@@ -17142,7 +17420,7 @@ function completedPathFor(filePath) {
17142
17420
  }
17143
17421
  function updateWorkItemFile(filePath, learning) {
17144
17422
  const raw = readFile(filePath);
17145
- const { data, content } = matter11(raw);
17423
+ const { data, content } = matter12(raw);
17146
17424
  data.status = "completed";
17147
17425
  data.completed_at = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
17148
17426
  let updatedContent = content;
@@ -17167,7 +17445,7 @@ ${learning.trim()}
17167
17445
  ${learning.trim()}
17168
17446
  `;
17169
17447
  }
17170
- const newRaw = matter11.stringify(updatedContent, data);
17448
+ const newRaw = matter12.stringify(updatedContent, data);
17171
17449
  const newPath = completedPathFor(filePath);
17172
17450
  if (newPath !== filePath) {
17173
17451
  ensureDir(path7.dirname(newPath));
@@ -17219,7 +17497,7 @@ async function runLearn(artifactId, opts = {}) {
17219
17497
  process.exit(1);
17220
17498
  }
17221
17499
  const wiRaw = readFile(filePath);
17222
- const wiData = matter11(wiRaw).data;
17500
+ const wiData = matter12(wiRaw).data;
17223
17501
  if (!opts.force) {
17224
17502
  const completionBlockers = [];
17225
17503
  const releaseGates = Array.isArray(wiData.release_gates) ? wiData.release_gates : [];
@@ -17475,7 +17753,7 @@ function runAdd(moduleName, opts = {}, dir = cwd()) {
17475
17753
  }
17476
17754
 
17477
17755
  // src/core/ownership-suggest.ts
17478
- import matter12 from "gray-matter";
17756
+ import matter13 from "gray-matter";
17479
17757
  var SCAN_PATH = ".kaddo/scan.json";
17480
17758
  function normalizeGlob(input) {
17481
17759
  let g = input.trim().replace(/\\/g, "/");
@@ -17597,11 +17875,11 @@ function suggestGlobs(artifact, signals) {
17597
17875
  return [...new Set(out)];
17598
17876
  }
17599
17877
  function applyOwnership(raw, globs, mode = "replace") {
17600
- const parsed = matter12(raw);
17878
+ const parsed = matter13(raw);
17601
17879
  const existing = toStringArray3(parsed.data.code);
17602
17880
  const next = mode === "append" ? [.../* @__PURE__ */ new Set([...existing, ...globs])] : [...new Set(globs)];
17603
17881
  const data = { ...parsed.data, code: next };
17604
- return matter12.stringify(parsed.content, data);
17882
+ return matter13.stringify(parsed.content, data);
17605
17883
  }
17606
17884
 
17607
17885
  // src/commands/owners.ts
@@ -18851,7 +19129,7 @@ async function runTopologyApply(file, opts = {}) {
18851
19129
  // src/core/resource-write.ts
18852
19130
  import fs5 from "fs";
18853
19131
  import path9 from "path";
18854
- import matter13 from "gray-matter";
19132
+ import matter14 from "gray-matter";
18855
19133
  var RESOURCES_DIR = "knowledge/tech/resources";
18856
19134
  var ResourceWriteError = class extends Error {
18857
19135
  constructor(code, message) {
@@ -18931,7 +19209,7 @@ function buildFrontmatter(id, input, base = {}) {
18931
19209
  return data;
18932
19210
  }
18933
19211
  function serialize(data, body) {
18934
- return matter13.stringify(`
19212
+ return matter14.stringify(`
18935
19213
  ${body.trim()}
18936
19214
  `, data);
18937
19215
  }
@@ -18971,7 +19249,7 @@ function updateResource(dir, id, input) {
18971
19249
  throw new ResourceWriteError("VALIDATION_FAILED", findings.filter((f) => f.level === "error").map((f) => f.message).join("; "));
18972
19250
  }
18973
19251
  const raw = readFile(match.filePath);
18974
- const parsed = matter13(raw);
19252
+ const parsed = matter14(raw);
18975
19253
  const base = parsed.data ?? {};
18976
19254
  const data = buildFrontmatter(match.id || id, input, base);
18977
19255
  let body = parsed.content.trim();
@@ -19205,15 +19483,960 @@ async function runResourcesDelete(id, opts = {}, dir = cwd()) {
19205
19483
  }
19206
19484
  }
19207
19485
 
19208
- // src/services/integrations.ts
19486
+ // src/core/deprecation-observation.ts
19487
+ var DAY_MS = 24 * 60 * 60 * 1e3;
19488
+ function addDaysIso(startIso, days) {
19489
+ const start = Date.parse(startIso);
19490
+ if (Number.isNaN(start)) return null;
19491
+ return new Date(start + days * DAY_MS).toISOString().slice(0, 10);
19492
+ }
19493
+ function observationStatus(target, now = /* @__PURE__ */ new Date()) {
19494
+ const sd = target.softDeprecation;
19495
+ const reasons = [];
19496
+ if (!sd) {
19497
+ return {
19498
+ declared: false,
19499
+ windowElapsed: false,
19500
+ windowEndsAt: null,
19501
+ criteriaTotal: 0,
19502
+ criteriaMet: 0,
19503
+ allCriteriaMet: false,
19504
+ eligibleForRemovalReview: false,
19505
+ reasons: ["No soft-deprecation/observation window declared \u2014 not eligible for removal review."]
19506
+ };
19507
+ }
19508
+ const criteriaTotal = sd.exitCriteria.length;
19509
+ const criteriaMet = sd.exitCriteria.filter((c) => c.met).length;
19510
+ const allCriteriaMet = criteriaTotal > 0 && criteriaMet === criteriaTotal;
19511
+ let windowElapsed = false;
19512
+ let windowEndsAt = null;
19513
+ if (sd.startedAt && sd.observationWindowDays != null) {
19514
+ windowEndsAt = addDaysIso(sd.startedAt, sd.observationWindowDays);
19515
+ if (windowEndsAt) {
19516
+ windowElapsed = now.getTime() >= Date.parse(windowEndsAt);
19517
+ }
19518
+ }
19519
+ if (!sd.startedAt) reasons.push("Observation has not started (no started_at).");
19520
+ else if (sd.observationWindowDays == null) reasons.push("No observation_window_days declared.");
19521
+ else if (!windowElapsed) reasons.push(`Observation window not elapsed (ends ${windowEndsAt ?? "unknown"}).`);
19522
+ if (criteriaTotal === 0) reasons.push("No exit criteria declared.");
19523
+ else if (!allCriteriaMet) reasons.push(`Exit criteria not all met (${criteriaMet}/${criteriaTotal}).`);
19524
+ const eligibleForRemovalReview = windowElapsed && allCriteriaMet;
19525
+ if (eligibleForRemovalReview) {
19526
+ reasons.length = 0;
19527
+ reasons.push("Observation window elapsed and all exit criteria met \u2014 eligible for removal REVIEW (human decision).");
19528
+ }
19529
+ return {
19530
+ declared: true,
19531
+ windowElapsed,
19532
+ windowEndsAt,
19533
+ criteriaTotal,
19534
+ criteriaMet,
19535
+ allCriteriaMet,
19536
+ eligibleForRemovalReview,
19537
+ reasons
19538
+ };
19539
+ }
19540
+ function environmentSummary(target) {
19541
+ const perEnvironment = {};
19542
+ for (const env of ENVIRONMENTS) perEnvironment[env] = String(target.environments[env] ?? "active");
19543
+ return {
19544
+ perEnvironment,
19545
+ removedInDevTest: perEnvironment.development === "removed" && perEnvironment.test === "removed",
19546
+ productionActive: perEnvironment.production === "active"
19547
+ };
19548
+ }
19549
+
19550
+ // src/core/deprecation-intelligence.ts
19551
+ function isStrongNoUsage(sig2) {
19552
+ return sig2.status === "no-usage" && (sig2.quality === "observed-fact" || sig2.quality === "human-confirmed");
19553
+ }
19554
+ function deriveUnusedConfidence(evidence) {
19555
+ const present = EVIDENCE_SIGNALS.map((name) => ({ name, sig: evidence[name] })).filter(
19556
+ (e) => Boolean(e.sig)
19557
+ );
19558
+ const usageFound = present.filter((e) => e.sig.status === "usage-found");
19559
+ if (usageFound.length > 0) {
19560
+ return {
19561
+ confidence: "in-use",
19562
+ requiresHumanConfirmation: false,
19563
+ rationale: [`Usage found via: ${usageFound.map((e) => e.name).join(", ")}.`]
19564
+ };
19565
+ }
19566
+ const strong = present.filter((e) => isStrongNoUsage(e.sig));
19567
+ const unknown = present.filter((e) => e.sig.status === "unknown");
19568
+ const notEvaluated = EVIDENCE_SIGNALS.filter(
19569
+ (name) => !evidence[name] || evidence[name]?.status === "not-evaluated"
19570
+ );
19571
+ const rationale = [];
19572
+ if (strong.length > 0) rationale.push(`No usage observed via: ${strong.map((e) => e.name).join(", ")}.`);
19573
+ if (unknown.length > 0) {
19574
+ rationale.push(`Unknown (looked but could not determine): ${unknown.map((e) => e.name).join(", ")} \u2014 NOT treated as no-usage.`);
19575
+ }
19576
+ if (notEvaluated.length > 0) {
19577
+ rationale.push(`Not evaluated: ${notEvaluated.join(", ")} \u2014 absence of a reference is not evidence of no usage.`);
19578
+ }
19579
+ let confidence;
19580
+ if (strong.length === 0) {
19581
+ confidence = "insufficient-evidence";
19582
+ } else if (unknown.length > 0) {
19583
+ confidence = "medium";
19584
+ } else if (strong.length >= 2) {
19585
+ confidence = "high";
19586
+ } else {
19587
+ confidence = "medium";
19588
+ }
19589
+ return { confidence, requiresHumanConfirmation: true, rationale };
19590
+ }
19591
+ function deriveRemovalWaves(plan) {
19592
+ const ids = new Set(plan.targets.map((t) => t.id));
19593
+ const deps = /* @__PURE__ */ new Map();
19594
+ const blocked = [];
19595
+ for (const t of plan.targets) {
19596
+ const resolved = [];
19597
+ for (const d of t.dependsOnRemoval) {
19598
+ if (d === t.id) {
19599
+ blocked.push({ target: t.id, reason: "Target depends on its own removal." });
19600
+ continue;
19601
+ }
19602
+ if (!ids.has(d)) {
19603
+ blocked.push({ target: t.id, reason: `depends_on_removal references unknown target: ${d}.` });
19604
+ continue;
19605
+ }
19606
+ resolved.push(d);
19607
+ }
19608
+ deps.set(t.id, resolved);
19609
+ }
19610
+ const placed = /* @__PURE__ */ new Set();
19611
+ const waves = [];
19612
+ let remaining = plan.targets.map((t) => t.id);
19613
+ while (remaining.length > 0) {
19614
+ const wave = remaining.filter((id) => (deps.get(id) ?? []).every((d) => placed.has(d)));
19615
+ if (wave.length === 0) break;
19616
+ for (const id of wave) placed.add(id);
19617
+ waves.push(wave);
19618
+ remaining = remaining.filter((id) => !placed.has(id));
19619
+ }
19620
+ for (const id of remaining) {
19621
+ blocked.push({ target: id, reason: "Involved in a removal dependency cycle \u2014 cannot be ordered." });
19622
+ }
19623
+ return { waves, blocked };
19624
+ }
19625
+ var RETIRED_STATES = /* @__PURE__ */ new Set([
19626
+ "removed-devtest",
19627
+ "production-changed",
19628
+ "observing",
19629
+ "completed",
19630
+ "deprecated-retained"
19631
+ ]);
19632
+ function isRetiredLifecycle(state) {
19633
+ return RETIRED_STATES.has(state);
19634
+ }
19635
+ function targetsEligibleForRemoval(plan) {
19636
+ const byId = new Map(plan.targets.map((t) => [t.id, t]));
19637
+ return plan.targets.filter((t) => !isRetiredLifecycle(String(t.lifecycle))).filter(
19638
+ (t) => t.dependsOnRemoval.every((d) => {
19639
+ const dep = byId.get(d);
19640
+ return dep ? isRetiredLifecycle(String(dep.lifecycle)) : false;
19641
+ })
19642
+ ).map((t) => t.id);
19643
+ }
19644
+ function planIntelligence(plan) {
19645
+ const waves = deriveRemovalWaves(plan);
19646
+ const eligible = new Set(targetsEligibleForRemoval(plan));
19647
+ const byId = new Map(plan.targets.map((t) => [t.id, t]));
19648
+ const targets = plan.targets.map((t) => ({
19649
+ id: t.id,
19650
+ unused: deriveUnusedConfidence(t.usageEvidence),
19651
+ eligibleForRemovalReview: eligible.has(t.id),
19652
+ blockedBy: t.dependsOnRemoval.filter((d) => {
19653
+ const dep = byId.get(d);
19654
+ return !dep || !isRetiredLifecycle(String(dep.lifecycle));
19655
+ }),
19656
+ observation: observationStatus(t)
19657
+ }));
19658
+ return { waves, eligible: [...eligible], targets };
19659
+ }
19660
+ function proposeWorkItemCandidates(plan) {
19661
+ const { waves } = deriveRemovalWaves(plan);
19662
+ const byId = new Map(plan.targets.map((t) => [t.id, t]));
19663
+ const candidates = [];
19664
+ waves.forEach((waveIds, waveIndex) => {
19665
+ const wave = waveIndex + 1;
19666
+ const groups = /* @__PURE__ */ new Map();
19667
+ for (const id of waveIds) {
19668
+ const t = byId.get(id);
19669
+ if (!t) continue;
19670
+ const key = t.module;
19671
+ const list2 = groups.get(key) ?? [];
19672
+ list2.push(t);
19673
+ groups.set(key, list2);
19674
+ }
19675
+ const keys = [...groups.keys()].sort((a, b) => {
19676
+ if (a === null) return 1;
19677
+ if (b === null) return -1;
19678
+ return a.localeCompare(b);
19679
+ });
19680
+ for (const key of keys) {
19681
+ const targets = groups.get(key);
19682
+ const resources = [...new Set(targets.map((t) => t.resource).filter((r) => Boolean(r)))];
19683
+ candidates.push({
19684
+ wave,
19685
+ module: key,
19686
+ title: `${plan.id} wave ${wave}${key ? ` (${key})` : ""}: retire ${targets.map((t) => t.id).join(", ")}`,
19687
+ deprecationTargets: targets.map((t) => t.id),
19688
+ resources
19689
+ });
19690
+ }
19691
+ });
19692
+ return candidates;
19693
+ }
19694
+ var CANDIDATE_DISCOVERY_GUIDANCE = [
19695
+ "Propose deprecation candidates from multiple sources: static references (code/routes/UI/jobs),",
19696
+ "the System Graph (dependencies and blast radius), Legacy Knowledge (risks/unknowns/modernization",
19697
+ "candidates), Project Resources (databases/external systems and their boundaries), runtime evidence",
19698
+ "when telemetry exists, and database metadata when reachable.",
19699
+ "",
19700
+ "Rules:",
19701
+ "- Discovery is a PROPOSAL, not a materialization: never create or retire anything automatically.",
19702
+ "- Always explain WHY something is a candidate, citing the signal(s) observed.",
19703
+ "- Absence of a reference is NOT evidence of no usage. If a source cannot be evaluated, record it",
19704
+ " as not-evaluated/unknown and require human investigation \u2014 never collapse it to no-usage.",
19705
+ "- A modernization candidate is not automatically a deprecation target.",
19706
+ "- Soft deprecation precedes physical removal; order retirements by dependency, dependents first."
19707
+ ].join("\n");
19708
+
19709
+ // src/core/deprecation-write.ts
19710
+ import fs6 from "fs";
19711
+ import path10 from "path";
19209
19712
  import matter15 from "gray-matter";
19713
+ var DeprecationWriteError = class extends Error {
19714
+ constructor(code, message) {
19715
+ super(message);
19716
+ this.code = code;
19717
+ this.name = "DeprecationWriteError";
19718
+ }
19719
+ code;
19720
+ };
19721
+ function slug5(s) {
19722
+ return s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
19723
+ }
19724
+ function atomicWrite3(filePath, content) {
19725
+ const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
19726
+ fs6.writeFileSync(tmp, content, "utf-8");
19727
+ fs6.renameSync(tmp, filePath);
19728
+ }
19729
+ function serialize2(data, body) {
19730
+ return matter15.stringify(`
19731
+ ${body.trim()}
19732
+ `, data);
19733
+ }
19734
+ function allPlanArtifacts(dir) {
19735
+ return discoverKnowledge(dir).filter((a) => a.type === DEPRECATION_ARTIFACT_TYPE);
19736
+ }
19737
+ function nextPlanId(dir, explicit) {
19738
+ if (explicit && explicit.trim()) return explicit.trim();
19739
+ let max = 0;
19740
+ for (const a of allPlanArtifacts(dir)) {
19741
+ const m = (a.id || "").match(/^DEP-(\d+)$/i);
19742
+ if (m) max = Math.max(max, parseInt(m[1], 10));
19743
+ }
19744
+ return `DEP-${String(max + 1).padStart(3, "0")}`;
19745
+ }
19746
+ function nextTargetId(targetIds) {
19747
+ let max = 0;
19748
+ for (const id of targetIds) {
19749
+ const m = id.match(/^DEP-TGT-(\d+)$/i);
19750
+ if (m) max = Math.max(max, parseInt(m[1], 10));
19751
+ }
19752
+ return `DEP-TGT-${String(max + 1).padStart(3, "0")}`;
19753
+ }
19754
+ function buildTargetRaw(input, base = {}) {
19755
+ const out = { ...base };
19756
+ if (input.id != null) out.id = input.id;
19757
+ if (input.type != null) out.type = input.type;
19758
+ if (input.locator != null) out.locator = input.locator;
19759
+ if (input.title != null) out.title = input.title;
19760
+ if (input.lifecycle != null) out.lifecycle = input.lifecycle;
19761
+ if (input.environments != null) out.environments = input.environments;
19762
+ if (input.assessment != null) {
19763
+ const a = { ...typeof base.assessment === "object" && base.assessment ? base.assessment : {} };
19764
+ if (input.assessment.unusedConfidence != null) a.unused_confidence = input.assessment.unusedConfidence;
19765
+ if (input.assessment.blastRadius != null) a.blast_radius = input.assessment.blastRadius;
19766
+ if (input.assessment.reversibility != null) a.reversibility = input.assessment.reversibility;
19767
+ out.assessment = a;
19768
+ }
19769
+ if (input.dependsOnRemoval != null) out.depends_on_removal = input.dependsOnRemoval;
19770
+ if (input.resource != null) out.resource = input.resource;
19771
+ if (input.module != null) out.module = input.module;
19772
+ return out;
19773
+ }
19774
+ function validateTargetInput(dir, raw) {
19775
+ const findings = [];
19776
+ const parsed = parseTarget(raw);
19777
+ if (!parsed) {
19778
+ findings.push({ level: "error", message: "A target id is required." });
19779
+ return findings;
19780
+ }
19781
+ for (const f of validateTarget(parsed)) {
19782
+ findings.push({ level: f.severity === "error" ? "error" : "warning", message: f.message });
19783
+ }
19784
+ const mapped = loadMappedModules(dir).map((m) => m.id);
19785
+ if (parsed.module && mapped.length > 0 && !mapped.includes(parsed.module)) {
19786
+ findings.push({ level: "warning", message: `Module "${parsed.module}" is not in .kaddo/modules.yml.` });
19787
+ }
19788
+ if (parsed.resource && !getResource(dir, parsed.resource)) {
19789
+ findings.push({ level: "warning", message: `Project Resource "${parsed.resource}" not found.` });
19790
+ }
19791
+ return findings;
19792
+ }
19793
+ function loadPlanRaw(dir, planId) {
19794
+ const match = allPlanArtifacts(dir).find((a) => a.id === planId || a.title === planId);
19795
+ if (!match) throw new DeprecationWriteError("NOT_FOUND", `Deprecation Plan "${planId}" not found.`);
19796
+ const parsed = matter15(readFile(match.filePath));
19797
+ const data = { ...parsed.data ?? {} };
19798
+ return { filePath: match.filePath, data, body: parsed.content.trim() };
19799
+ }
19800
+ function rawTargets(data) {
19801
+ return Array.isArray(data.targets) ? data.targets : [];
19802
+ }
19803
+ function createPlan(dir, input) {
19804
+ const title = (input.title ?? "").trim();
19805
+ if (!title) throw new DeprecationWriteError("INVALID_INPUT", "A plan title is required.");
19806
+ const existing = allPlanArtifacts(dir);
19807
+ if (input.id && existing.some((a) => (a.id || "").toUpperCase() === input.id.toUpperCase())) {
19808
+ throw new DeprecationWriteError("DUPLICATE", `A plan with id "${input.id}" already exists.`);
19809
+ }
19810
+ if (existing.some((a) => (a.title || "").toLowerCase() === title.toLowerCase())) {
19811
+ throw new DeprecationWriteError("DUPLICATE", `A plan titled "${title}" already exists.`);
19812
+ }
19813
+ const id = nextPlanId(dir, input.id);
19814
+ const data = {
19815
+ type: DEPRECATION_ARTIFACT_TYPE,
19816
+ id,
19817
+ title,
19818
+ status: (input.status ?? "draft").trim() || "draft",
19819
+ targets: []
19820
+ };
19821
+ const body = `# Purpose
19822
+
19823
+ ${(input.purpose ?? "").trim() || "TODO: describe what this plan retires and why."}`;
19824
+ const relPath = `${DEPRECATION_PLANS_DIR}/${id}-${slug5(title) || "plan"}.md`;
19825
+ const filePath = join(dir, relPath);
19826
+ if (exists(filePath)) throw new DeprecationWriteError("DUPLICATE", `Plan file already exists: ${relPath}`);
19827
+ ensureDir(path10.dirname(filePath));
19828
+ atomicWrite3(filePath, serialize2(data, body));
19829
+ return { id, path: relPath, findings: [] };
19830
+ }
19831
+ function addTarget(dir, planId, input) {
19832
+ const { filePath, data, body } = loadPlanRaw(dir, planId);
19833
+ const targets = rawTargets(data);
19834
+ const existingIds = targets.map((t) => String(t.id ?? ""));
19835
+ const targetId = (input.id ?? "").trim() || nextTargetId(existingIds);
19836
+ if (existingIds.some((id) => id.toUpperCase() === targetId.toUpperCase())) {
19837
+ throw new DeprecationWriteError("DUPLICATE", `Target "${targetId}" already exists in ${planId}.`);
19838
+ }
19839
+ const raw = buildTargetRaw({ ...input, id: targetId, lifecycle: input.lifecycle ?? "candidate" });
19840
+ const findings = validateTargetInput(dir, raw);
19841
+ if (findings.some((f) => f.level === "error")) {
19842
+ throw new DeprecationWriteError("VALIDATION_FAILED", findings.filter((f) => f.level === "error").map((f) => f.message).join("; "));
19843
+ }
19844
+ data.targets = [...targets, raw];
19845
+ atomicWrite3(filePath, serialize2(data, body));
19846
+ return { planId, targetId, path: `${DEPRECATION_PLANS_DIR}/${path10.basename(filePath)}`, findings };
19847
+ }
19848
+ function updateTarget(dir, planId, targetId, patch) {
19849
+ const { filePath, data, body } = loadPlanRaw(dir, planId);
19850
+ const targets = rawTargets(data);
19851
+ const idx = targets.findIndex((t) => String(t.id ?? "").toUpperCase() === targetId.toUpperCase());
19852
+ if (idx === -1) throw new DeprecationWriteError("NOT_FOUND", `Target "${targetId}" not found in ${planId}.`);
19853
+ const merged = buildTargetRaw({ ...patch, id: String(targets[idx].id) }, targets[idx]);
19854
+ const findings = validateTargetInput(dir, merged);
19855
+ if (findings.some((f) => f.level === "error")) {
19856
+ throw new DeprecationWriteError("VALIDATION_FAILED", findings.filter((f) => f.level === "error").map((f) => f.message).join("; "));
19857
+ }
19858
+ const next = [...targets];
19859
+ next[idx] = merged;
19860
+ data.targets = next;
19861
+ atomicWrite3(filePath, serialize2(data, body));
19862
+ return { planId, targetId: String(targets[idx].id), path: `${DEPRECATION_PLANS_DIR}/${path10.basename(filePath)}`, findings };
19863
+ }
19864
+ function removeTarget(dir, planId, targetId, opts = {}) {
19865
+ const { filePath, data, body } = loadPlanRaw(dir, planId);
19866
+ const targets = rawTargets(data);
19867
+ const exists3 = targets.some((t) => String(t.id ?? "").toUpperCase() === targetId.toUpperCase());
19868
+ if (!exists3) throw new DeprecationWriteError("NOT_FOUND", `Target "${targetId}" not found in ${planId}.`);
19869
+ const dependents = targets.filter((t) => (Array.isArray(t.depends_on_removal) ? t.depends_on_removal.map(String) : []).some((d) => d.toUpperCase() === targetId.toUpperCase())).map((t) => String(t.id));
19870
+ if (!opts.confirm) {
19871
+ return { removed: false, preview: { planId, targetId, dependents } };
19872
+ }
19873
+ data.targets = targets.filter((t) => String(t.id ?? "").toUpperCase() !== targetId.toUpperCase());
19874
+ atomicWrite3(filePath, serialize2(data, body));
19875
+ return { removed: true, path: `${DEPRECATION_PLANS_DIR}/${path10.basename(filePath)}` };
19876
+ }
19877
+
19878
+ // src/core/deprecation-runbook.ts
19879
+ import matter16 from "gray-matter";
19880
+ var PRODUCTION_RUNBOOK_ARTIFACT_TYPE = "production-runbook";
19881
+ var PRODUCTION_RUNBOOKS_DIR = "knowledge/delivery/runbooks";
19882
+ var RUNBOOK_SECTIONS = [
19883
+ "Purpose",
19884
+ "Preconditions",
19885
+ "Dependencies",
19886
+ "Backup/Recovery",
19887
+ "Impact",
19888
+ "Execution Order",
19889
+ "Commands",
19890
+ "Expected Results",
19891
+ "Validation",
19892
+ "Rollback",
19893
+ "Abort Conditions",
19894
+ "Observation Window",
19895
+ "Evidence",
19896
+ "Approval"
19897
+ ];
19898
+ var ProductionRunbookError = class extends Error {
19899
+ constructor(message) {
19900
+ super(message);
19901
+ this.name = "ProductionRunbookError";
19902
+ }
19903
+ };
19904
+ function stringValue(value) {
19905
+ return typeof value === "string" && value.trim() ? value.trim() : null;
19906
+ }
19907
+ function slug6(value) {
19908
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "production-change";
19909
+ }
19910
+ function nextRunbookNumber(dir) {
19911
+ const root = join(dir, PRODUCTION_RUNBOOKS_DIR);
19912
+ return readDir(root).reduce((highest, name) => {
19913
+ const match = name.match(/^RB-(\d+)-.+\.md$/i);
19914
+ return match ? Math.max(highest, Number(match[1])) : highest;
19915
+ }, 0) + 1;
19916
+ }
19917
+ function runbookPath(dir, target) {
19918
+ const id = `RB-${String(nextRunbookNumber(dir)).padStart(3, "0")}`;
19919
+ return `${PRODUCTION_RUNBOOKS_DIR}/${id}-${slug6(target.title ?? target.id)}.md`;
19920
+ }
19921
+ function parseApproval(value) {
19922
+ const data = value && typeof value === "object" && !Array.isArray(value) ? value : {};
19923
+ const status = data.status === "approved" ? "approved" : "pending";
19924
+ return {
19925
+ required: data.required === true,
19926
+ status,
19927
+ approvedBy: stringValue(data.approved_by),
19928
+ approvedAt: stringValue(data.approved_at)
19929
+ };
19930
+ }
19931
+ function sectionPresent(body, section4) {
19932
+ const escaped = section4.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace("/", "\\/");
19933
+ return new RegExp(`^##\\s+${escaped}\\s*$`, "mi").test(body);
19934
+ }
19935
+ function destructiveCommands(body) {
19936
+ const lines = body.split(/\r?\n/);
19937
+ return lines.filter((line) => /\b(drop|truncate|delete\s+from|alter\s+(table|database|schema)|create\s+or\s+replace)\b/i.test(line));
19938
+ }
19939
+ function relatedTargets(plan, target) {
19940
+ const ids = new Set(target.dependsOnRemoval);
19941
+ return plan.targets.filter((candidate) => ids.has(candidate.id));
19942
+ }
19943
+ function buildProductionRunbookContext(dir, planId, targetId) {
19944
+ const plan = getDeprecationPlan(dir, planId);
19945
+ if (!plan) throw new ProductionRunbookError(`Deprecation Plan "${planId}" not found.`);
19946
+ const target = plan.targets.find((candidate) => candidate.id === targetId);
19947
+ if (!target) throw new ProductionRunbookError(`Target "${targetId}" not found in ${plan.id}.`);
19948
+ const environment = environmentSummary(target);
19949
+ const dependencies = relatedTargets(plan, target);
19950
+ const blockers = [];
19951
+ if (!environment.removedInDevTest) blockers.push("Development and test must both be removed before preparing a production runbook.");
19952
+ if (target.lifecycle !== "production-ready") blockers.push(`Target lifecycle must be production-ready (current: ${target.lifecycle}).`);
19953
+ for (const dependency of dependencies) {
19954
+ if (!["completed", "deprecated-retained"].includes(String(dependency.lifecycle))) {
19955
+ blockers.push(`Dependency ${dependency.id} is not retired (current: ${dependency.lifecycle}).`);
19956
+ }
19957
+ }
19958
+ const path14 = runbookPath(dir, target);
19959
+ return {
19960
+ eligible: blockers.length === 0,
19961
+ plan: { id: plan.id, title: plan.title, purpose: plan.purpose },
19962
+ target,
19963
+ resource: target.resource ? getResource(dir, target.resource) : null,
19964
+ dependencies,
19965
+ blockers,
19966
+ nextPath: path14,
19967
+ nextStep: blockers.length > 0 ? "Resolve the listed safeguards; no production proposal can be persisted yet." : "Review the generated proposal, obtain human approval, execute manually, then record evidence and validate the observation window."
19968
+ };
19969
+ }
19970
+ function renderRunbook(context) {
19971
+ const target = context.target;
19972
+ const resource = context.resource;
19973
+ const dependencies = context.dependencies.length > 0 ? context.dependencies.map((item) => `- ${item.id}: ${item.title ?? item.locator ?? item.id}`).join("\n") : "- None declared.";
19974
+ const evidence = Object.entries(target.usageEvidence).map(([signal, value]) => `- ${signal}: ${value.status} (${value.quality})${value.detail ? ` \u2014 ${value.detail}` : ""}`).join("\n") || "- No usage evidence declared. Do not infer no usage.";
19975
+ const observation = observationStatus(target);
19976
+ const resourceBoundary = resource ? `- Resource: ${resource.id} (${resource.title})
19977
+ - Production boundary: ${(resource.boundaries.production ?? []).join(", ") || "not declared"}
19978
+ - Interfaces: ${resource.interfaces.map((item) => item.type).join(", ") || "not declared"}` : "- No Project Resource is linked to this target.";
19979
+ return [
19980
+ "# Production Runbook",
19981
+ "",
19982
+ "## Purpose",
19983
+ "",
19984
+ `Safely apply the approved production change for ${target.id} (${target.title ?? target.locator ?? target.id}) in ${context.plan.id}.`,
19985
+ "",
19986
+ "## Preconditions",
19987
+ "",
19988
+ "- [ ] Development and test are removed and verified.",
19989
+ "- [ ] A human has reviewed this proposal and explicitly approved the production window.",
19990
+ "- [ ] Required backups/recovery points are verified before any change.",
19991
+ "",
19992
+ "## Dependencies",
19993
+ "",
19994
+ dependencies,
19995
+ "",
19996
+ "## Backup/Recovery",
19997
+ "",
19998
+ "- [ ] Record the backup, snapshot, export, or recovery point identifier before execution.",
19999
+ "- [ ] Confirm the restoration owner and recovery procedure.",
20000
+ "",
20001
+ "## Impact",
20002
+ "",
20003
+ `- Target: ${target.type} at ${target.locator ?? "not declared"}.`,
20004
+ `- Assessment: blast radius=${target.assessment.blastRadius ?? "not evaluated"}; reversibility=${target.assessment.reversibility ?? "not evaluated"}.`,
20005
+ resourceBoundary,
20006
+ "",
20007
+ "## Execution Order",
20008
+ "",
20009
+ "1. Confirm approval and the production change window.",
20010
+ "2. Verify the backup/recovery point.",
20011
+ "3. Execute the reviewed command manually.",
20012
+ "4. Capture actual results and validate before continuing.",
20013
+ "",
20014
+ "## Commands",
20015
+ "",
20016
+ "> Kaddo never executes production commands. Add only human-reviewed commands here after approval; do not place unattended automation in this runbook.",
20017
+ "",
20018
+ "## Expected Results",
20019
+ "",
20020
+ "- The approved target changes only in production.",
20021
+ "- No unrelated dependency or resource boundary is changed.",
20022
+ "",
20023
+ "## Validation",
20024
+ "",
20025
+ "- [ ] Validate the expected result using the linked resource/interface.",
20026
+ "- [ ] Confirm no unexpected errors or consumer regressions.",
20027
+ "",
20028
+ "## Rollback",
20029
+ "",
20030
+ "- [ ] Stop the change and apply the documented recovery procedure if validation fails.",
20031
+ "- [ ] Record the rollback result in Evidence.",
20032
+ "",
20033
+ "## Abort Conditions",
20034
+ "",
20035
+ "- Abort if the backup/recovery point is missing or cannot be restored.",
20036
+ "- Abort if approval is absent, the production window changes, or validation reveals unexpected impact.",
20037
+ "",
20038
+ "## Observation Window",
20039
+ "",
20040
+ `- ${observation.declared ? `Existing observation: ${observation.reasons.join(" ")}` : "After the production change, declare the observation window and exit criteria."}`,
20041
+ "- After manual validation, progress the target through production-changed \u2192 observing \u2192 completed only when the declared criteria are met. Kaddo never advances this lifecycle automatically.",
20042
+ "",
20043
+ "## Evidence",
20044
+ "",
20045
+ evidence,
20046
+ "",
20047
+ "## Approval",
20048
+ "",
20049
+ "- Required: human approval before manual execution.",
20050
+ "- Status: pending.",
20051
+ "- Approved by: not recorded.",
20052
+ "- Approved at: not recorded.",
20053
+ ""
20054
+ ].join("\n");
20055
+ }
20056
+ function createProductionRunbook(dir, planId, targetId) {
20057
+ const context = buildProductionRunbookContext(dir, planId, targetId);
20058
+ if (!context.eligible) throw new ProductionRunbookError(context.blockers.join(" "));
20059
+ const path14 = context.nextPath;
20060
+ const id = path14.split("/").pop()?.match(/^(RB-\d+)-/)?.[1] ?? "";
20061
+ const content = matter16.stringify(renderRunbook(context), {
20062
+ id,
20063
+ type: PRODUCTION_RUNBOOK_ARTIFACT_TYPE,
20064
+ title: `Production runbook \u2014 ${context.target.title ?? context.target.id}`,
20065
+ deprecation_plan: context.plan.id,
20066
+ deprecation_target: context.target.id,
20067
+ resource: context.target.resource,
20068
+ approval: { required: true, status: "pending", approved_by: null, approved_at: null }
20069
+ });
20070
+ const absolute = join(dir, path14);
20071
+ if (exists(absolute)) throw new ProductionRunbookError(`Runbook already exists: ${path14}`);
20072
+ writeFile(absolute, content);
20073
+ return {
20074
+ id,
20075
+ title: `Production runbook \u2014 ${context.target.title ?? context.target.id}`,
20076
+ path: path14,
20077
+ planId: context.plan.id,
20078
+ targetId: context.target.id,
20079
+ approval: { required: true, status: "pending", approvedBy: null, approvedAt: null },
20080
+ markdownBody: renderRunbook(context)
20081
+ };
20082
+ }
20083
+ function getProductionRunbook(dir, id) {
20084
+ const root = join(dir, PRODUCTION_RUNBOOKS_DIR);
20085
+ for (const name of readDir(root)) {
20086
+ if (!name.toLowerCase().startsWith(`${id.toLowerCase()}-`) || !name.endsWith(".md")) continue;
20087
+ const path14 = `${PRODUCTION_RUNBOOKS_DIR}/${name}`;
20088
+ const parsed = matter16(readFile(join(dir, path14)));
20089
+ const data = parsed.data;
20090
+ if (data.type !== PRODUCTION_RUNBOOK_ARTIFACT_TYPE) continue;
20091
+ return {
20092
+ id: stringValue(data.id) ?? id,
20093
+ title: stringValue(data.title) ?? id,
20094
+ path: path14,
20095
+ planId: stringValue(data.deprecation_plan) ?? "",
20096
+ targetId: stringValue(data.deprecation_target) ?? "",
20097
+ approval: parseApproval(data.approval),
20098
+ markdownBody: parsed.content.trim()
20099
+ };
20100
+ }
20101
+ return null;
20102
+ }
20103
+ function validateProductionRunbook(runbook) {
20104
+ const findings = [];
20105
+ for (const section4 of RUNBOOK_SECTIONS) {
20106
+ if (!sectionPresent(runbook.markdownBody, section4)) findings.push({ level: "error", message: `Missing required section: ${section4}.` });
20107
+ }
20108
+ if (!runbook.approval.required) findings.push({ level: "error", message: "Human approval must be required for a production runbook." });
20109
+ const destructive = destructiveCommands(runbook.markdownBody);
20110
+ if (destructive.length > 0 && (runbook.approval.status !== "approved" || !runbook.approval.approvedBy || !runbook.approval.approvedAt)) {
20111
+ findings.push({ level: "error", message: "Destructive production commands require explicit human approval with approver and timestamp." });
20112
+ }
20113
+ if (destructive.length > 0) findings.push({ level: "warning", message: "Destructive commands are documentation only; Kaddo will never execute them." });
20114
+ return findings;
20115
+ }
20116
+
20117
+ // src/commands/deprecation.ts
20118
+ function printFindings3(findings) {
20119
+ for (const f of findings) (f.level === "error" ? log.error : log.warn)(f.message);
20120
+ }
20121
+ function runDeprecationList(dir = cwd(), opts = {}) {
20122
+ const plans = getDeprecationPlans(dir);
20123
+ if (opts.json) {
20124
+ console.log(JSON.stringify(plans, null, 2));
20125
+ return;
20126
+ }
20127
+ if (plans.length === 0) {
20128
+ console.log("\nNo Deprecation Plans are defined for this project.\n");
20129
+ console.log('Add one with: kaddo deprecation create --title "<name>"\n');
20130
+ return;
20131
+ }
20132
+ console.log("\nDeprecation Plans:");
20133
+ for (const p of plans) {
20134
+ console.log(` ${p.id.padEnd(10)} ${String(p.status ?? "\u2014").padEnd(10)} ${p.targetCount} target(s) ${p.title}`);
20135
+ }
20136
+ console.log("");
20137
+ }
20138
+ function runDeprecationShow(id, dir = cwd(), opts = {}) {
20139
+ const plan = getDeprecationPlan(dir, id);
20140
+ if (!plan) {
20141
+ if (opts.json) console.log(JSON.stringify({ error: `Deprecation Plan "${id}" not found.` }, null, 2));
20142
+ else console.error(`Deprecation Plan "${id}" not found under knowledge/legacy/deprecations/.`);
20143
+ process.exit(1);
20144
+ }
20145
+ if (opts.json) {
20146
+ console.log(JSON.stringify(plan, null, 2));
20147
+ return;
20148
+ }
20149
+ const p = plan;
20150
+ console.log(`
20151
+ ${p.id} \u2014 ${p.title}`);
20152
+ console.log(` Status: ${p.status ?? "\u2014"} Targets: ${p.targetCount}`);
20153
+ if (p.purpose) console.log(` Purpose: ${p.purpose}`);
20154
+ if (p.targets.length > 0) {
20155
+ console.log("\n Targets:");
20156
+ for (const t of p.targets) {
20157
+ const envs = Object.entries(t.environments).map(([e, s]) => `${e}=${s}`).join(" ");
20158
+ console.log(` - ${t.id} [${t.type}] ${t.lifecycle}${envs ? " (" + envs + ")" : ""}`);
20159
+ if (t.locator) console.log(` locator: ${t.locator}`);
20160
+ if (t.dependsOnRemoval.length > 0) console.log(` depends_on_removal: ${t.dependsOnRemoval.join(", ")}`);
20161
+ if (t.resource) console.log(` resource: ${t.resource}`);
20162
+ }
20163
+ }
20164
+ console.log("");
20165
+ }
20166
+ function runDeprecationStatus(id, dir = cwd(), opts = {}) {
20167
+ const plan = getDeprecationPlan(dir, id);
20168
+ if (!plan) {
20169
+ console.error(`Deprecation Plan "${id}" not found.`);
20170
+ process.exit(1);
20171
+ }
20172
+ const p = plan;
20173
+ const intel = planIntelligence(p);
20174
+ const payload = {
20175
+ id: p.id,
20176
+ status: p.status,
20177
+ targetCount: p.targetCount,
20178
+ lifecycleCounts: p.lifecycleCounts,
20179
+ eligibleForRemovalReview: intel.eligible
20180
+ };
20181
+ if (opts.json) {
20182
+ console.log(JSON.stringify(payload, null, 2));
20183
+ return;
20184
+ }
20185
+ console.log(`
20186
+ ${p.id} \u2014 pipeline`);
20187
+ for (const [state, n] of Object.entries(p.lifecycleCounts)) console.log(` ${String(state).padEnd(20)} ${n}`);
20188
+ console.log(`
20189
+ Eligible for removal review: ${intel.eligible.length > 0 ? intel.eligible.join(", ") : "\u2014"}
20190
+ `);
20191
+ }
20192
+ function runDeprecationPlan(id, dir = cwd(), opts = {}) {
20193
+ const plan = getDeprecationPlan(dir, id);
20194
+ if (!plan) {
20195
+ console.error(`Deprecation Plan "${id}" not found.`);
20196
+ process.exit(1);
20197
+ }
20198
+ const { waves, blocked } = deriveRemovalWaves(plan);
20199
+ if (opts.json) {
20200
+ console.log(JSON.stringify({ waves, blocked }, null, 2));
20201
+ return;
20202
+ }
20203
+ console.log(`
20204
+ ${plan.id} \u2014 removal waves (dependents first)`);
20205
+ waves.forEach((wave, i) => console.log(` Wave ${i + 1}: ${wave.join(", ")}`));
20206
+ if (blocked.length > 0) {
20207
+ console.log("\n Blocked:");
20208
+ for (const b of blocked) console.log(` - ${b.target}: ${b.reason}`);
20209
+ }
20210
+ console.log("");
20211
+ }
20212
+ function runDeprecationAnalyze(id, dir = cwd(), opts = {}) {
20213
+ const plan = getDeprecationPlan(dir, id);
20214
+ if (!plan) {
20215
+ console.error(`Deprecation Plan "${id}" not found.`);
20216
+ process.exit(1);
20217
+ }
20218
+ const intel = planIntelligence(plan);
20219
+ if (opts.json) {
20220
+ console.log(JSON.stringify(intel, null, 2));
20221
+ return;
20222
+ }
20223
+ console.log(`
20224
+ ${plan.id} \u2014 analysis`);
20225
+ for (const t of intel.targets) {
20226
+ console.log(` ${t.id}: unused=${t.unused.confidence}${t.unused.requiresHumanConfirmation ? " (human confirmation required)" : ""}`);
20227
+ for (const r of t.unused.rationale) console.log(` \xB7 ${r}`);
20228
+ if (t.blockedBy.length > 0) console.log(` blocked by: ${t.blockedBy.join(", ")}`);
20229
+ if (t.observation.declared) {
20230
+ const o = t.observation;
20231
+ console.log(` observation: ${o.eligibleForRemovalReview ? "eligible for removal REVIEW" : "pending"} \u2014 criteria ${o.criteriaMet}/${o.criteriaTotal}${o.windowEndsAt ? `, window ends ${o.windowEndsAt}` : ""}`);
20232
+ }
20233
+ }
20234
+ console.log("");
20235
+ }
20236
+ function runDeprecationCandidates(id, dir = cwd(), opts = {}) {
20237
+ const plan = getDeprecationPlan(dir, id);
20238
+ if (!plan) {
20239
+ console.error(`Deprecation Plan "${id}" not found.`);
20240
+ process.exit(1);
20241
+ }
20242
+ const candidates = proposeWorkItemCandidates(plan);
20243
+ if (opts.json) {
20244
+ console.log(JSON.stringify(candidates, null, 2));
20245
+ return;
20246
+ }
20247
+ console.log(`
20248
+ ${plan.id} \u2014 proposed Work Item candidates (one WI per wave/module; references targets, not copies)`);
20249
+ if (candidates.length === 0) {
20250
+ console.log(" (no targets yet)\n");
20251
+ return;
20252
+ }
20253
+ for (const c of candidates) {
20254
+ console.log(` Wave ${c.wave}${c.module ? ` \xB7 ${c.module}` : ""}: ${c.deprecationTargets.join(", ")}`);
20255
+ if (c.resources.length > 0) console.log(` resources: ${c.resources.join(", ")}`);
20256
+ }
20257
+ console.log("\n Materialize each as a Work Item with deprecation_targets referencing these ids.\n");
20258
+ }
20259
+ async function runDeprecationCreate(opts = {}, dir = cwd()) {
20260
+ let title = opts.title?.trim();
20261
+ const interactive = !opts.json && process.stdin.isTTY && !title;
20262
+ if (interactive) {
20263
+ intro("kaddo deprecation create");
20264
+ if (!title) title = (await text({ message: "Plan title", placeholder: "Retire legacy credit scoring" })).trim();
20265
+ }
20266
+ if (!title) {
20267
+ console.error("A plan title is required. Use --title (or run interactively).");
20268
+ process.exit(1);
20269
+ }
20270
+ const input = { title };
20271
+ if (opts.purpose != null) input.purpose = opts.purpose;
20272
+ if (opts.status != null) input.status = opts.status;
20273
+ try {
20274
+ const res = createPlan(dir, input);
20275
+ if (opts.json) {
20276
+ console.log(JSON.stringify(res, null, 2));
20277
+ return;
20278
+ }
20279
+ log.success(`Created ${res.id}`);
20280
+ console.log(` ${res.path}`);
20281
+ console.log(` Add targets with: kaddo deprecation add-target ${res.id} --type <type> --locator <locator>`);
20282
+ if (interactive) outro("Plan created.");
20283
+ } catch (err) {
20284
+ console.error(err instanceof DeprecationWriteError ? err.message : String(err));
20285
+ process.exit(1);
20286
+ }
20287
+ }
20288
+ function toTargetInput(opts) {
20289
+ const input = {};
20290
+ if (opts.id != null) input.id = opts.id;
20291
+ if (opts.type != null) input.type = opts.type;
20292
+ if (opts.locator != null) input.locator = opts.locator;
20293
+ if (opts.title != null) input.title = opts.title;
20294
+ if (opts.lifecycle != null) input.lifecycle = opts.lifecycle;
20295
+ if (opts.resource != null) input.resource = opts.resource;
20296
+ if (opts.module != null) input.module = opts.module;
20297
+ if (opts.dependsOn != null) input.dependsOnRemoval = opts.dependsOn.split(",").map((s) => s.trim()).filter(Boolean);
20298
+ return input;
20299
+ }
20300
+ function runDeprecationAddTarget(planId, opts = {}, dir = cwd()) {
20301
+ try {
20302
+ const res = addTarget(dir, planId, toTargetInput(opts));
20303
+ if (opts.json) {
20304
+ console.log(JSON.stringify(res, null, 2));
20305
+ return;
20306
+ }
20307
+ printFindings3(res.findings);
20308
+ log.success(`Added ${res.targetId} to ${res.planId} (${res.path}).`);
20309
+ } catch (err) {
20310
+ console.error(err instanceof DeprecationWriteError ? err.message : String(err));
20311
+ process.exit(1);
20312
+ }
20313
+ }
20314
+ function runDeprecationUpdateTarget(planId, targetId, opts = {}, dir = cwd()) {
20315
+ const input = toTargetInput(opts);
20316
+ delete input.id;
20317
+ if (Object.keys(input).length === 0) {
20318
+ console.error("Nothing to update. Pass at least one field (e.g. --lifecycle, --locator, --resource).");
20319
+ process.exit(1);
20320
+ }
20321
+ try {
20322
+ const res = updateTarget(dir, planId, targetId, input);
20323
+ if (opts.json) {
20324
+ console.log(JSON.stringify(res, null, 2));
20325
+ return;
20326
+ }
20327
+ printFindings3(res.findings);
20328
+ log.success(`Updated ${res.targetId} in ${res.planId} (${res.path}).`);
20329
+ } catch (err) {
20330
+ console.error(err instanceof DeprecationWriteError ? err.message : String(err));
20331
+ process.exit(1);
20332
+ }
20333
+ }
20334
+ async function runDeprecationRemoveTarget(planId, targetId, opts = {}, dir = cwd()) {
20335
+ let preview;
20336
+ try {
20337
+ preview = removeTarget(dir, planId, targetId);
20338
+ } catch (err) {
20339
+ console.error(err instanceof DeprecationWriteError ? err.message : String(err));
20340
+ process.exit(1);
20341
+ }
20342
+ const dependents = preview.preview?.dependents ?? [];
20343
+ if (opts.json && !opts.yes) {
20344
+ console.log(JSON.stringify(preview.preview, null, 2));
20345
+ return;
20346
+ }
20347
+ if (dependents.length > 0) {
20348
+ console.log(`
20349
+ Target "${targetId}" is depended on by: ${dependents.join(", ")}`);
20350
+ console.log("Removing it will NOT rewrite their depends_on_removal.\n");
20351
+ }
20352
+ let proceed = opts.yes === true;
20353
+ if (!proceed) {
20354
+ if (process.stdin.isTTY) proceed = await confirm({ message: `Remove target "${targetId}" from ${planId}?`, initialValue: false });
20355
+ else {
20356
+ console.error(`Refusing to remove without confirmation. Re-run with --yes.`);
20357
+ process.exit(1);
20358
+ }
20359
+ }
20360
+ if (!proceed) {
20361
+ console.log("Aborted.");
20362
+ return;
20363
+ }
20364
+ try {
20365
+ const done = removeTarget(dir, planId, targetId, { confirm: true });
20366
+ if (opts.json) {
20367
+ console.log(JSON.stringify(done, null, 2));
20368
+ return;
20369
+ }
20370
+ log.success(`Removed ${targetId} from ${planId} (${done.path}).`);
20371
+ } catch (err) {
20372
+ console.error(err instanceof DeprecationWriteError ? err.message : String(err));
20373
+ process.exit(1);
20374
+ }
20375
+ }
20376
+ function runDeprecationRunbookContext(planId, targetId, dir = cwd(), opts = {}) {
20377
+ try {
20378
+ const context = buildProductionRunbookContext(dir, planId, targetId);
20379
+ if (opts.json) {
20380
+ console.log(JSON.stringify(context, null, 2));
20381
+ return;
20382
+ }
20383
+ console.log(`
20384
+ ${context.plan.id}/${context.target.id} \u2014 production runbook context`);
20385
+ console.log(` Eligible: ${context.eligible ? "yes" : "no"}`);
20386
+ console.log(` Next path: ${context.nextPath}`);
20387
+ if (context.blockers.length > 0) for (const blocker of context.blockers) console.log(` Blocked: ${blocker}`);
20388
+ console.log(`
20389
+ ${context.nextStep}
20390
+ `);
20391
+ } catch (err) {
20392
+ console.error(err instanceof ProductionRunbookError ? err.message : String(err));
20393
+ process.exitCode = 1;
20394
+ }
20395
+ }
20396
+ function runDeprecationRunbookCreate(planId, targetId, dir = cwd(), opts = {}) {
20397
+ try {
20398
+ const runbook = createProductionRunbook(dir, planId, targetId);
20399
+ if (opts.json) {
20400
+ console.log(JSON.stringify(runbook, null, 2));
20401
+ return;
20402
+ }
20403
+ console.log(`
20404
+ Created ${runbook.id}: ${runbook.path}`);
20405
+ console.log("This is a proposal only. Obtain human approval, execute manually, record evidence, then validate it.\n");
20406
+ } catch (err) {
20407
+ console.error(err instanceof ProductionRunbookError ? err.message : String(err));
20408
+ process.exitCode = 1;
20409
+ }
20410
+ }
20411
+ function runDeprecationRunbookValidate(id, dir = cwd(), opts = {}) {
20412
+ const runbook = getProductionRunbook(dir, id);
20413
+ if (!runbook) {
20414
+ console.error(`Production Runbook "${id}" not found.`);
20415
+ process.exitCode = 1;
20416
+ return;
20417
+ }
20418
+ const findings = validateProductionRunbook(runbook);
20419
+ const payload = { runbook: { id: runbook.id, path: runbook.path }, valid: !findings.some((item) => item.level === "error"), findings };
20420
+ if (opts.json) {
20421
+ console.log(JSON.stringify(payload, null, 2));
20422
+ return;
20423
+ }
20424
+ console.log(`
20425
+ ${runbook.id} \u2014 ${payload.valid ? "valid" : "invalid"}`);
20426
+ for (const finding of findings) console.log(` ${finding.level}: ${finding.message}`);
20427
+ console.log("");
20428
+ if (!payload.valid) process.exitCode = 1;
20429
+ }
20430
+
20431
+ // src/services/integrations.ts
20432
+ import matter18 from "gray-matter";
19210
20433
  import { parse as parseYaml18, stringify as stringifyYaml10 } from "yaml";
19211
20434
 
19212
20435
  // src/core/work-item-write.ts
19213
- import fs6 from "fs";
19214
- import path10 from "path";
20436
+ import fs7 from "fs";
20437
+ import path11 from "path";
19215
20438
  import crypto2 from "crypto";
19216
- import matter14 from "gray-matter";
20439
+ import matter17 from "gray-matter";
19217
20440
  var WORK_ITEMS_DIR3 = "knowledge/delivery/work-items";
19218
20441
  var WorkItemWriteError = class extends Error {
19219
20442
  constructor(code, message) {
@@ -19234,7 +20457,7 @@ function nextWorkItemId2(dir) {
19234
20457
  let max = 0;
19235
20458
  const walk = (d) => {
19236
20459
  if (!exists(d)) return;
19237
- for (const entry of fs6.readdirSync(d)) {
20460
+ for (const entry of fs7.readdirSync(d)) {
19238
20461
  const full = join(d, entry);
19239
20462
  if (isFile(full)) {
19240
20463
  const m = entry.match(/WI-(\d+)/);
@@ -19247,15 +20470,15 @@ function nextWorkItemId2(dir) {
19247
20470
  walk(wiDir);
19248
20471
  return `WI-${String(max + 1).padStart(3, "0")}`;
19249
20472
  }
19250
- function atomicWrite3(filePath, content) {
19251
- fs6.mkdirSync(path10.dirname(filePath), { recursive: true });
20473
+ function atomicWrite4(filePath, content) {
20474
+ fs7.mkdirSync(path11.dirname(filePath), { recursive: true });
19252
20475
  const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
19253
- fs6.writeFileSync(tmp, content, "utf-8");
20476
+ fs7.writeFileSync(tmp, content, "utf-8");
19254
20477
  try {
19255
- fs6.renameSync(tmp, filePath);
20478
+ fs7.renameSync(tmp, filePath);
19256
20479
  } catch (err) {
19257
20480
  try {
19258
- fs6.rmSync(tmp, { force: true });
20481
+ fs7.rmSync(tmp, { force: true });
19259
20482
  } catch {
19260
20483
  }
19261
20484
  throw err;
@@ -19316,8 +20539,8 @@ function ensureH1(body, title) {
19316
20539
 
19317
20540
  ${trimmed}`;
19318
20541
  }
19319
- function serialize2(data, body) {
19320
- return matter14.stringify(`
20542
+ function serialize3(data, body) {
20543
+ return matter17.stringify(`
19321
20544
  ${body.trim()}
19322
20545
  `, data);
19323
20546
  }
@@ -19385,8 +20608,8 @@ function createWorkItem(dir, opts) {
19385
20608
  const relPath = `${WORK_ITEMS_DIR3}/draft/${id}-${slugify5(title)}.md`;
19386
20609
  const filePath = join(dir, relPath);
19387
20610
  if (exists(filePath)) throw new WorkItemWriteError("INVALID_INPUT", `Work Item file already exists: ${relPath}`);
19388
- const raw = serialize2(data, body);
19389
- atomicWrite3(filePath, raw);
20611
+ const raw = serialize3(data, body);
20612
+ atomicWrite4(filePath, raw);
19390
20613
  return { id, path: relPath, revision: revisionOf(raw) };
19391
20614
  }
19392
20615
 
@@ -20074,8 +21297,8 @@ async function handleJiraResponse(res) {
20074
21297
  }
20075
21298
  return await res.json();
20076
21299
  }
20077
- async function jiraFetch(baseUrl, path13, auth, timeoutMs, params) {
20078
- const url = new URL(path13, baseUrl + "/");
21300
+ async function jiraFetch(baseUrl, path14, auth, timeoutMs, params) {
21301
+ const url = new URL(path14, baseUrl + "/");
20079
21302
  if (params) for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
20080
21303
  const controller = new AbortController();
20081
21304
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -20093,8 +21316,8 @@ async function jiraFetch(baseUrl, path13, auth, timeoutMs, params) {
20093
21316
  clearTimeout(timer);
20094
21317
  }
20095
21318
  }
20096
- async function jiraPost(baseUrl, path13, auth, timeoutMs, body) {
20097
- const url = new URL(path13, baseUrl + "/");
21319
+ async function jiraPost(baseUrl, path14, auth, timeoutMs, body) {
21320
+ const url = new URL(path14, baseUrl + "/");
20098
21321
  const controller = new AbortController();
20099
21322
  const timer = setTimeout(() => controller.abort(), timeoutMs);
20100
21323
  try {
@@ -20394,7 +21617,7 @@ function findLinkedWorkItem(dir, integrationId, externalId) {
20394
21617
  for (const art of discoverWorkItems(dir)) {
20395
21618
  let data;
20396
21619
  try {
20397
- data = matter15(readFile(art.filePath)).data;
21620
+ data = matter18(readFile(art.filePath)).data;
20398
21621
  } catch {
20399
21622
  continue;
20400
21623
  }
@@ -20607,7 +21830,7 @@ async function runIntegrationsImport(dir, id, externalId, opts) {
20607
21830
  }
20608
21831
 
20609
21832
  // src/core/impact-report.ts
20610
- import matter16 from "gray-matter";
21833
+ import matter19 from "gray-matter";
20611
21834
  function isBroadGlob(glob) {
20612
21835
  if (!glob.endsWith("/**")) return false;
20613
21836
  const prefix = glob.slice(0, -3);
@@ -20676,7 +21899,7 @@ function buildImpactReport(dir, opts = {}, now = /* @__PURE__ */ new Date()) {
20676
21899
  }
20677
21900
  }
20678
21901
  try {
20679
- const body = matter16(readFile(wi.filePath)).content;
21902
+ const body = matter19(readFile(wi.filePath)).content;
20680
21903
  if (hasSection(body, /acceptance|criterios de aceptaci/i)) withAcceptance++;
20681
21904
  else gaps.missing_acceptance_criteria.push(gapItem(wi, "Add an `## Acceptance Criteria` section."));
20682
21905
  if (hasSection(body, /definition of done|^#{1,6}\s*dod\b|definici[oó]n de (terminado|hecho)/i)) withDoD++;
@@ -21753,7 +22976,7 @@ function runAdr(opts = {}) {
21753
22976
  }
21754
22977
 
21755
22978
  // src/commands/tech.ts
21756
- import fs7 from "fs";
22979
+ import fs8 from "fs";
21757
22980
  var DISCOVERY_FILES = ["architecture-notes.md", "decision-candidates.md"];
21758
22981
  var DISCOVERY_DIR = "knowledge/tech/discovery";
21759
22982
  function runTechOrganize(dir = cwd()) {
@@ -21770,7 +22993,7 @@ function runTechOrganize(dir = cwd()) {
21770
22993
  continue;
21771
22994
  }
21772
22995
  ensureDir(join(dir, DISCOVERY_DIR));
21773
- fs7.renameSync(from, to);
22996
+ fs8.renameSync(from, to);
21774
22997
  moved.push(`knowledge/tech/${file} \u2192 ${DISCOVERY_DIR}/${file}`);
21775
22998
  }
21776
22999
  if (moved.length > 0) {
@@ -21852,9 +23075,9 @@ function runAssetsUpdate(kind, opts = {}) {
21852
23075
  }
21853
23076
 
21854
23077
  // src/commands/ready.ts
21855
- import fs8 from "fs";
21856
- import path11 from "path";
21857
- import matter17 from "gray-matter";
23078
+ import fs9 from "fs";
23079
+ import path12 from "path";
23080
+ import matter20 from "gray-matter";
21858
23081
  function validateReadiness(content, frontmatter) {
21859
23082
  const warnings = [];
21860
23083
  const body = content.replace(/^---[\s\S]*?---/, "").trim();
@@ -21908,18 +23131,18 @@ function isResolvedSection(text2) {
21908
23131
  }
21909
23132
  function transitionToReady(filePath) {
21910
23133
  const raw = readFile(filePath);
21911
- const { data, content } = matter17(raw);
23134
+ const { data, content } = matter20(raw);
21912
23135
  const today3 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
21913
23136
  data.status = "ready";
21914
23137
  data.ready_at = today3;
21915
- const newContent = matter17.stringify(content, data);
23138
+ const newContent = matter20.stringify(content, data);
21916
23139
  const posix2 = filePath.replace(/\\/g, "/");
21917
23140
  let newPath = filePath;
21918
23141
  if (posix2.includes("/work-items/draft/")) {
21919
- const readyDir = path11.dirname(filePath).replace(/[/\\]draft$/, path11.sep + "ready");
23142
+ const readyDir = path12.dirname(filePath).replace(/[/\\]draft$/, path12.sep + "ready");
21920
23143
  ensureDir(readyDir);
21921
- const fileName = path11.basename(filePath);
21922
- newPath = path11.join(readyDir, fileName);
23144
+ const fileName = path12.basename(filePath);
23145
+ newPath = path12.join(readyDir, fileName);
21923
23146
  }
21924
23147
  return { newPath, newContent };
21925
23148
  }
@@ -21952,7 +23175,7 @@ async function runReady(id, opts = {}) {
21952
23175
  process.exit(1);
21953
23176
  }
21954
23177
  const raw = readFile(wi.filePath);
21955
- const { data } = matter17(raw);
23178
+ const { data } = matter20(raw);
21956
23179
  const source2 = parseWorkItemSource(data);
21957
23180
  const warnings = validateReadiness(raw, data);
21958
23181
  log.info(`Work Item found:`);
@@ -21987,11 +23210,11 @@ async function runReady(id, opts = {}) {
21987
23210
  const { newPath, newContent } = transitionToReady(wi.filePath);
21988
23211
  if (newPath !== wi.filePath) {
21989
23212
  writeFile(newPath, newContent);
21990
- fs8.unlinkSync(wi.filePath);
23213
+ fs9.unlinkSync(wi.filePath);
21991
23214
  log.success(`Updated status: ready`);
21992
23215
  log.success(`Moved file:`);
21993
- log.info(` ${path11.relative(dir, wi.filePath)}`);
21994
- log.info(` \u2192 ${path11.relative(dir, newPath)}`);
23216
+ log.info(` ${path12.relative(dir, wi.filePath)}`);
23217
+ log.info(` \u2192 ${path12.relative(dir, newPath)}`);
21995
23218
  } else {
21996
23219
  writeFile(wi.filePath, newContent);
21997
23220
  log.success(`Updated status: ready`);
@@ -22002,7 +23225,7 @@ async function runReady(id, opts = {}) {
22002
23225
  }
22003
23226
 
22004
23227
  // src/commands/admin.ts
22005
- import path12 from "path";
23228
+ import path13 from "path";
22006
23229
  import { fileURLToPath as fileURLToPath2 } from "url";
22007
23230
  import net from "net";
22008
23231
  function isPortAvailable(port, host) {
@@ -22017,17 +23240,17 @@ function isPortAvailable(port, host) {
22017
23240
  });
22018
23241
  }
22019
23242
  function resolveStaticDir() {
22020
- const __dirname = path12.dirname(fileURLToPath2(import.meta.url));
23243
+ const __dirname = path13.dirname(fileURLToPath2(import.meta.url));
22021
23244
  const candidates = [
22022
23245
  // Monorepo development: prefer the freshly built admin over the copy bundled into the CLI dist.
22023
23246
  // The CLI build copies admin/dist into dist/admin-dist, but that copy can be stale when the admin
22024
23247
  // was rebuilt after the CLI (build order is not guaranteed in `pnpm -r build`). Serving the admin
22025
23248
  // package's own dist first ensures `kaddo admin` always shows the current frontend in dev. This
22026
23249
  // path does not exist in a published npm install (admin is private), so it falls back below.
22027
- path12.resolve(__dirname, "..", "..", "admin", "dist"),
22028
- path12.resolve(__dirname, "..", "node_modules", "@kaddo", "admin", "dist"),
23250
+ path13.resolve(__dirname, "..", "..", "admin", "dist"),
23251
+ path13.resolve(__dirname, "..", "node_modules", "@kaddo", "admin", "dist"),
22029
23252
  // Bundled inside CLI dist (npm install)
22030
- path12.resolve(__dirname, "admin-dist")
23253
+ path13.resolve(__dirname, "admin-dist")
22031
23254
  ];
22032
23255
  for (const c of candidates) {
22033
23256
  if (exists(join(c, "index.html"))) return c;
@@ -22069,8 +23292,8 @@ async function runAdmin(opts = {}) {
22069
23292
  }
22070
23293
  let adminServer;
22071
23294
  try {
22072
- const __dirname = path12.dirname(fileURLToPath2(import.meta.url));
22073
- const bundled = path12.resolve(__dirname, "admin-server", "index.js");
23295
+ const __dirname = path13.dirname(fileURLToPath2(import.meta.url));
23296
+ const bundled = path13.resolve(__dirname, "admin-server", "index.js");
22074
23297
  if (exists(bundled)) {
22075
23298
  const { pathToFileURL } = await import("url");
22076
23299
  adminServer = await import(pathToFileURL(bundled).href);
@@ -22127,11 +23350,11 @@ async function runAdmin(opts = {}) {
22127
23350
 
22128
23351
  // src/core/work-item-import.ts
22129
23352
  import crypto3 from "crypto";
22130
- import fs9 from "fs";
22131
- import matter19 from "gray-matter";
23353
+ import fs10 from "fs";
23354
+ import matter22 from "gray-matter";
22132
23355
 
22133
23356
  // src/core/work-items.ts
22134
- import matter18 from "gray-matter";
23357
+ import matter21 from "gray-matter";
22135
23358
  function computeRefinementStatus(wi) {
22136
23359
  const aspects = {
22137
23360
  outcome: Boolean(wi.currentBehavior?.trim() || wi.targetBehavior?.trim()),
@@ -22201,6 +23424,8 @@ function getWorkItem(dir, workItemId) {
22201
23424
  markdownBody: body.trim(),
22202
23425
  // External systems this WI relates to (WI-030), separate from affectedModules (code).
22203
23426
  resources: parseWorkItemResources(fm2),
23427
+ // Deprecation Targets this WI retires (WI-050), referenced not copied.
23428
+ deprecationTargets: parseWorkItemDeprecationTargets(fm2),
22204
23429
  ...parseSystemImpact(dir, fm2)
22205
23430
  };
22206
23431
  return { ...detail, refinement: computeRefinementStatus(detail) };
@@ -22209,8 +23434,8 @@ function parseGraphReason(v) {
22209
23434
  if (!v || typeof v !== "object") return null;
22210
23435
  const o = v;
22211
23436
  const relationship = typeof o.relationship === "string" && o.relationship.trim() ? o.relationship.trim() : null;
22212
- const path13 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
22213
- return relationship || path13.length ? { relationship, path: path13 } : null;
23437
+ const path14 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
23438
+ return relationship || path14.length ? { relationship, path: path14 } : null;
22214
23439
  }
22215
23440
  function parseExplain(o) {
22216
23441
  const refs = Array.isArray(o.evidence) ? o.evidence : Array.isArray(o.evidence_refs) ? o.evidence_refs : [];
@@ -22265,7 +23490,7 @@ function parseOriginalSnapshot(fm2) {
22265
23490
  function readBody(filePath) {
22266
23491
  try {
22267
23492
  const raw = readFile(filePath);
22268
- return matter18(raw).content;
23493
+ return matter21(raw).content;
22269
23494
  } catch {
22270
23495
  return "";
22271
23496
  }
@@ -22724,7 +23949,7 @@ function detectFormat(raw) {
22724
23949
  if (!trimmed) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
22725
23950
  if (trimmed.startsWith("---")) {
22726
23951
  try {
22727
- const { data } = matter19(trimmed);
23952
+ const { data } = matter22(trimmed);
22728
23953
  if (data && typeof data === "object" && Object.keys(data).length > 0) {
22729
23954
  const d = data;
22730
23955
  if (d.type === "work-item" || d.id && typeof d.id === "string" && /^WI-\d+/.test(d.id)) {
@@ -22746,7 +23971,7 @@ function parseContent(raw) {
22746
23971
  let bodyText = trimmed;
22747
23972
  if (format === "kaddo-frontmatter" || format === "markdown-frontmatter") {
22748
23973
  try {
22749
- const parsed = matter19(trimmed);
23974
+ const parsed = matter22(trimmed);
22750
23975
  frontmatterFields = parsed.data ?? {};
22751
23976
  bodyText = parsed.content.trim();
22752
23977
  } catch {
@@ -22843,7 +24068,7 @@ function findDuplicateByHash(dir, hash) {
22843
24068
  const raw = readFile(item.filePath);
22844
24069
  if (!raw) continue;
22845
24070
  try {
22846
- const { data } = matter19(raw);
24071
+ const { data } = matter22(raw);
22847
24072
  const source2 = data?.source;
22848
24073
  if (source2 && typeof source2 === "object" && !Array.isArray(source2)) {
22849
24074
  const s = source2;
@@ -22910,7 +24135,7 @@ function importWorkItem(dir, opts) {
22910
24135
  };
22911
24136
  }
22912
24137
  if (opts.onConflict === "replace") {
22913
- fs9.rmSync(existing.filePath, { force: true });
24138
+ fs10.rmSync(existing.filePath, { force: true });
22914
24139
  replacedWorkItem = existing.workItemId;
22915
24140
  }
22916
24141
  }
@@ -23084,7 +24309,7 @@ ${report.handoff}
23084
24309
  }
23085
24310
 
23086
24311
  // src/commands/verify.ts
23087
- import matter20 from "gray-matter";
24312
+ import matter23 from "gray-matter";
23088
24313
 
23089
24314
  // src/core/implementation-evidence.ts
23090
24315
  var WorkItemNotInProgressError = class extends Error {
@@ -23316,17 +24541,17 @@ function extractACsFromBody(body) {
23316
24541
  let inAC = false;
23317
24542
  const acs = [];
23318
24543
  for (const line of lines) {
23319
- if (/^#{1,6}\s+acceptance\s+criteria/i.test(line)) {
24544
+ if (/^#{1,6}\s+(acceptance\s+criteria|criterios\s+de\s+aceptaci[oó]n)/i.test(line)) {
23320
24545
  inAC = true;
23321
24546
  continue;
23322
24547
  }
23323
24548
  if (inAC && /^#{1,6}\s+/.test(line)) break;
23324
24549
  if (inAC) {
23325
- const m = line.match(/^\s*[-*+]\s+(?:\[[ xX]\]\s*)?(.+)$/);
24550
+ const m = line.match(/^\s*[-*+]\s+(?:\[([ xX])\]\s*)?(.+)$/);
23326
24551
  if (m) {
23327
- const text2 = m[1].trim();
24552
+ const text2 = m[2].trim();
23328
24553
  if (text2 && !/^_.*_$/.test(text2) && !/^tbd$/i.test(text2)) {
23329
- acs.push(text2);
24554
+ acs.push({ criterion: text2, checked: m[1]?.toLowerCase() === "x" });
23330
24555
  }
23331
24556
  }
23332
24557
  }
@@ -23361,7 +24586,7 @@ async function runVerify(workItemId, opts = {}) {
23361
24586
  }
23362
24587
  const changedPaths = await getModifiedFiles("head");
23363
24588
  const raw = readFile(match.filePath);
23364
- const parsed = matter20(raw);
24589
+ const parsed = matter23(raw);
23365
24590
  const fm2 = parsed.data;
23366
24591
  const acs = extractACsFromBody(parsed.content);
23367
24592
  const existingEvidence = fm2.implementation_evidence;
@@ -23386,8 +24611,9 @@ async function runVerify(workItemId, opts = {}) {
23386
24611
  };
23387
24612
  }) : [{ repoId: "core", changedPaths, validations: [] }];
23388
24613
  const acVerifications = acs.map((ac) => ({
23389
- criterion: ac,
23390
- status: "not-verified"
24614
+ criterion: ac.criterion,
24615
+ status: ac.checked ? "passed" : "not-verified",
24616
+ ...ac.checked ? { evidence: "Explicitly checked in the Work Item acceptance criteria." } : {}
23391
24617
  }));
23392
24618
  const input = {
23393
24619
  repos,
@@ -23478,13 +24704,13 @@ async function runVerify(workItemId, opts = {}) {
23478
24704
  if (shouldPersist) {
23479
24705
  const filePath = match.filePath;
23480
24706
  const wiRaw = readFile(filePath);
23481
- const wiParsed = matter20(wiRaw);
24707
+ const wiParsed = matter23(wiRaw);
23482
24708
  const data = wiParsed.data;
23483
24709
  data.implementation_evidence = verification.implementationEvidence;
23484
24710
  data.implementation_status = verification.implementationStatus;
23485
24711
  data.validation_status = verification.validationStatus;
23486
24712
  data.verified_at = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
23487
- const newRaw = matter20.stringify(wiParsed.content, data);
24713
+ const newRaw = matter23.stringify(wiParsed.content, data);
23488
24714
  writeFile(filePath, newRaw);
23489
24715
  log.success("Work Item frontmatter updated with verification evidence.");
23490
24716
  }
@@ -23534,9 +24760,9 @@ function markRegistered(dir, identity) {
23534
24760
  ensureDir(join(dir, TELEMETRY_DIR));
23535
24761
  writeFile(identityPath(dir), JSON.stringify(identity, null, 2));
23536
24762
  }
23537
- function signPayload(identity, method, path13, timestamp, nonce, bodySha256) {
24763
+ function signPayload(identity, method, path14, timestamp, nonce, bodySha256) {
23538
24764
  const canonical = `${method}
23539
- ${path13}
24765
+ ${path14}
23540
24766
  ${identity.installationId}
23541
24767
  ${timestamp}
23542
24768
  ${nonce}
@@ -23762,7 +24988,7 @@ function runTelemetryDisable() {
23762
24988
  }
23763
24989
 
23764
24990
  // src/core/initiative-write.ts
23765
- import matter21 from "gray-matter";
24991
+ import matter24 from "gray-matter";
23766
24992
  var WORK_ITEMS_DIR4 = "knowledge/delivery/work-items";
23767
24993
  var DRAFT_DIR2 = `${WORK_ITEMS_DIR4}/draft`;
23768
24994
  var InitiativeWriteError = class extends Error {
@@ -23874,7 +25100,7 @@ function buildInitiativeContent(id, input) {
23874
25100
  if (input.priority) data.priority = input.priority;
23875
25101
  if (input.source) data.source = input.source;
23876
25102
  if (input.sourceId) data.source_id = input.sourceId;
23877
- return matter21.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
25103
+ return matter24.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
23878
25104
  }
23879
25105
  function createInitiative(dir, input) {
23880
25106
  if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
@@ -23898,10 +25124,10 @@ function transitionInitiative(dir, id, to) {
23898
25124
  throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
23899
25125
  }
23900
25126
  const raw = readFile(ini.filePath);
23901
- const { data, content } = matter21(raw, {});
25127
+ const { data, content } = matter24(raw, {});
23902
25128
  data.status = to;
23903
25129
  if (to === "completed") data.completed_at = today2();
23904
- const newContent = matter21.stringify(content, data);
25130
+ const newContent = matter24.stringify(content, data);
23905
25131
  writeFile(ini.filePath, newContent);
23906
25132
  const updated = parseInitiative(dir, ini.filePath, newContent);
23907
25133
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
@@ -23970,7 +25196,7 @@ function buildWorkItemContent(wiId, iniId, candidate) {
23970
25196
  "_What did we learn? Update after completion._",
23971
25197
  ""
23972
25198
  ].join("\n");
23973
- return matter21.stringify("\n" + body, data);
25199
+ return matter24.stringify("\n" + body, data);
23974
25200
  }
23975
25201
  function materializeCandidate(dir, id, candidateId) {
23976
25202
  const ini = getInitiative(dir, id);
@@ -23987,13 +25213,13 @@ function materializeCandidate(dir, id, candidateId) {
23987
25213
  ensureDir(join(dir, DRAFT_DIR2));
23988
25214
  writeFile(join(dir, DRAFT_DIR2, fileName), buildWorkItemContent(wiId, ini.id, candidate));
23989
25215
  const raw = readFile(ini.filePath);
23990
- const { data, content } = matter21(raw, {});
25216
+ const { data, content } = matter24(raw, {});
23991
25217
  const cands = Array.isArray(data.candidates) ? data.candidates : [];
23992
25218
  for (const c of cands) {
23993
25219
  if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
23994
25220
  }
23995
25221
  data.candidates = cands;
23996
- const newContent = matter21.stringify(content, data);
25222
+ const newContent = matter24.stringify(content, data);
23997
25223
  writeFile(ini.filePath, newContent);
23998
25224
  const updated = parseInitiative(dir, ini.filePath, newContent);
23999
25225
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
@@ -24355,8 +25581,8 @@ var capsuleCmd = program.command("capsule").description("Export this project as
24355
25581
  capsuleCmd.command("export").description("Write a Knowledge Capsule about this project to .kaddo/exports/").option("--scope <scope>", 'Export scope: "system" includes all mapped modules').option("--module <id>", "Export a capsule for a specific mapped module").action((opts) => {
24356
25582
  runCapsuleExport(opts);
24357
25583
  });
24358
- capsuleCmd.command("add <path>").description("Register an external Knowledge Capsule as project context (.kaddo/external.yml)").action((path13) => {
24359
- runCapsuleAdd(path13);
25584
+ capsuleCmd.command("add <path>").description("Register an external Knowledge Capsule as project context (.kaddo/external.yml)").action((path14) => {
25585
+ runCapsuleAdd(path14);
24360
25586
  });
24361
25587
  var graphCmd = program.command("graph").description("Export the lightweight, file-based knowledge graph of the project");
24362
25588
  graphCmd.command("export").description("Write the knowledge graph to .kaddo/graph.json and .kaddo/graph.mmd").option("--scope <scope>", "Graph scope: active (default) or all").option("--format <format>", "Output format: json, mermaid (default: both)").action((opts) => {
@@ -24379,6 +25605,25 @@ resourcesCmd.command("update <id>").description("Update a Project Resource (no-l
24379
25605
  resourcesCmd.command("delete <id>").description("Delete a Project Resource after showing what references it (requires confirmation)").option("-y, --yes", "Skip the confirmation prompt").option("--json", "Output JSON").action(async (id, opts) => {
24380
25606
  await runResourcesDelete(id, opts, cwd());
24381
25607
  });
25608
+ var deprecationCmd = program.command("deprecation").description("Controlled Deprecation \u2014 plan the safe, traceable retirement of legacy functionality");
25609
+ deprecationCmd.command("list").description("List Deprecation Plans under knowledge/legacy/deprecations/").option("--json", "Output JSON").action((opts) => runDeprecationList(cwd(), opts));
25610
+ deprecationCmd.command("show <id>").description("Show one Deprecation Plan: purpose, targets, lifecycle and environments").option("--json", "Output JSON").action((id, opts) => runDeprecationShow(id, cwd(), opts));
25611
+ deprecationCmd.command("status <id>").description("Pipeline view: target counts by lifecycle state + targets eligible for removal review").option("--json", "Output JSON").action((id, opts) => runDeprecationStatus(id, cwd(), opts));
25612
+ deprecationCmd.command("plan <id>").description("Derive the removal waves (dependents first) from depends_on_removal").option("--json", "Output JSON").action((id, opts) => runDeprecationPlan(id, cwd(), opts));
25613
+ deprecationCmd.command("analyze <id>").description("Per-target unused-confidence from usage evidence (never auto-removes)").option("--json", "Output JSON").action((id, opts) => runDeprecationAnalyze(id, cwd(), opts));
25614
+ deprecationCmd.command("candidates <id>").description("Propose Work Item candidates from the plan (one WI per wave/module). Does not create WIs.").option("--json", "Output JSON").action((id, opts) => runDeprecationCandidates(id, cwd(), opts));
25615
+ deprecationCmd.command("create").description("Create a Deprecation Plan (interactive, or with --title). Writes via Core.").option("--title <title>", "Plan title").option("--purpose <purpose>", "What this plan retires and why").option("--status <status>", "Plan status (default: draft)").option("--json", "Output JSON").action(async (opts) => {
25616
+ await runDeprecationCreate(opts, cwd());
25617
+ });
25618
+ deprecationCmd.command("add-target <planId>").description("Add a typed Deprecation Target to a plan (no-lossy). Writes via Core.").option("--id <id>", "Explicit target id (otherwise derived)").option("--type <type>", "Target type: module|route|function|ui|job|database-object|integration|config|other").option("--locator <locator>", "Type-appropriate locator (path#symbol, route, DB object\u2026)").option("--title <title>", "Human title").option("--lifecycle <state>", "Lifecycle state (default: candidate)").option("--resource <id>", "Project Resource id (RES-\u2026) for database/external targets").option("--module <id>", "Module id (validated against .kaddo/modules.yml)").option("--depends-on <ids>", "Comma-separated target ids that must retire before this one").option("--json", "Output JSON").action((planId, opts) => runDeprecationAddTarget(planId, opts, cwd()));
25619
+ deprecationCmd.command("update-target <planId> <targetId>").description("Update a target in place (no-lossy). Pass the fields to change.").option("--type <type>", "New target type").option("--locator <locator>", "New locator").option("--title <title>", "New title").option("--lifecycle <state>", "New lifecycle state").option("--resource <id>", "Project Resource id").option("--module <id>", "Module id").option("--depends-on <ids>", "Comma-separated target ids that must retire before this one").option("--json", "Output JSON").action((planId, targetId, opts) => runDeprecationUpdateTarget(planId, targetId, opts, cwd()));
25620
+ deprecationCmd.command("remove-target <planId> <targetId>").description("Remove a target after showing what depends on it (requires confirmation)").option("-y, --yes", "Skip the confirmation prompt").option("--json", "Output JSON").action(async (planId, targetId, opts) => {
25621
+ await runDeprecationRemoveTarget(planId, targetId, opts, cwd());
25622
+ });
25623
+ var deprecationRunbookCmd = deprecationCmd.command("runbook").description("Prepare and validate versioned production runbooks (never executes production commands)");
25624
+ deprecationRunbookCmd.command("context <planId> <targetId>").description("Show bounded target/resource/evidence context and safeguards (read-only)").option("--json", "Output JSON").action((planId, targetId, opts) => runDeprecationRunbookContext(planId, targetId, cwd(), opts));
25625
+ deprecationRunbookCmd.command("create <planId> <targetId>").description("Create a production runbook proposal; execution always remains manual").option("--json", "Output JSON").action((planId, targetId, opts) => runDeprecationRunbookCreate(planId, targetId, cwd(), opts));
25626
+ deprecationRunbookCmd.command("validate <id>").description("Validate required sections and the human approval boundary").option("--json", "Output JSON").action((id, opts) => runDeprecationRunbookValidate(id, cwd(), opts));
24382
25627
  var integrationsCmd = program.command("integrations").description("Connect Kaddo to external work systems (read-first; import requires human confirmation)");
24383
25628
  integrationsCmd.command("list").description("List configured integrations and their capabilities").option("--json", "Output JSON").action((opts) => runIntegrationsList(cwd(), opts));
24384
25629
  integrationsCmd.command("status").description("Verify each enabled integration and report its connection status").option("--json", "Output JSON").action(async (opts) => {