@kaddo/cli 3.120.0 → 3.121.1

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 (34) hide show
  1. package/dist/admin-dist/assets/{architectureDiagram-3BPJPVTR-DIMrrmB9.js → architectureDiagram-3BPJPVTR-WuDnj7bc.js} +1 -1
  2. package/dist/admin-dist/assets/{chunk-727SXJPM-Dqr01pM2.js → chunk-727SXJPM-B8UhtmH8.js} +1 -1
  3. package/dist/admin-dist/assets/{chunk-AQP2D5EJ-Cq-Ux2er.js → chunk-AQP2D5EJ-BuqHM9y3.js} +1 -1
  4. package/dist/admin-dist/assets/{classDiagram-v2-Q7XG4LA2-ggXfKatP.js → classDiagram-4FO5ZUOK-DvqpwQA7.js} +1 -1
  5. package/dist/admin-dist/assets/{classDiagram-4FO5ZUOK-ggXfKatP.js → classDiagram-v2-Q7XG4LA2-DvqpwQA7.js} +1 -1
  6. package/dist/admin-dist/assets/{dagre-BM42HDAG-C6oD5ML4.js → dagre-BM42HDAG-CD1hlJek.js} +1 -1
  7. package/dist/admin-dist/assets/{diagram-2AECGRRQ-hUz_WSJC.js → diagram-2AECGRRQ-B2ra-Q26.js} +1 -1
  8. package/dist/admin-dist/assets/{diagram-5GNKFQAL-ChltTKxS.js → diagram-5GNKFQAL-B8WZcc5Q.js} +1 -1
  9. package/dist/admin-dist/assets/{diagram-LMA3HP47-DD3kd-Zq.js → diagram-LMA3HP47-CGpykWzf.js} +1 -1
  10. package/dist/admin-dist/assets/{diagram-OG6HWLK6-BKHyHHw0.js → diagram-OG6HWLK6-D7tczyDO.js} +1 -1
  11. package/dist/admin-dist/assets/{erDiagram-TEJ5UH35-BE5PDGjy.js → erDiagram-TEJ5UH35-Ct9avLGD.js} +1 -1
  12. package/dist/admin-dist/assets/{flowDiagram-I6XJVG4X-lxFDGYVc.js → flowDiagram-I6XJVG4X-Cn5dqLqh.js} +1 -1
  13. package/dist/admin-dist/assets/{ganttDiagram-6RSMTGT7-BPeceg0v.js → ganttDiagram-6RSMTGT7-BlsvjpEy.js} +1 -1
  14. package/dist/admin-dist/assets/{index-B7GhDkjv.js → index-DJE6AHaV.js} +16 -16
  15. package/dist/admin-dist/assets/{infoDiagram-5YYISTIA-Boe5ho81.js → infoDiagram-5YYISTIA-DDTHhWtj.js} +1 -1
  16. package/dist/admin-dist/assets/{ishikawaDiagram-YF4QCWOH-3T8K6hMf.js → ishikawaDiagram-YF4QCWOH-CbsDq0PN.js} +1 -1
  17. package/dist/admin-dist/assets/{kanban-definition-UN3LZRKU-BW97uUmp.js → kanban-definition-UN3LZRKU-Dq6HDONo.js} +1 -1
  18. package/dist/admin-dist/assets/{linear-BGHTsNfG.js → linear-B9Zy1Kbd.js} +1 -1
  19. package/dist/admin-dist/assets/{mindmap-definition-RKZ34NQL-B-LmLGip.js → mindmap-definition-RKZ34NQL-BPf0N0zN.js} +1 -1
  20. package/dist/admin-dist/assets/{pieDiagram-4H26LBE5-BS0ysj7T.js → pieDiagram-4H26LBE5-cOJXnH1H.js} +1 -1
  21. package/dist/admin-dist/assets/{quadrantDiagram-W4KKPZXB-CJbpr-VT.js → quadrantDiagram-W4KKPZXB-C9hMSXam.js} +1 -1
  22. package/dist/admin-dist/assets/{requirementDiagram-4Y6WPE33-CTEMRVel.js → requirementDiagram-4Y6WPE33-t5ukcmLR.js} +1 -1
  23. package/dist/admin-dist/assets/{sequenceDiagram-3UESZ5HK-ff_IANYV.js → sequenceDiagram-3UESZ5HK-JhX5oE-v.js} +1 -1
  24. package/dist/admin-dist/assets/{stateDiagram-AJRCARHV-DCJ7-my6.js → stateDiagram-AJRCARHV-CEwpPgs0.js} +1 -1
  25. package/dist/admin-dist/assets/{stateDiagram-v2-BHNVJYJU-tCHje_1l.js → stateDiagram-v2-BHNVJYJU-DPM6NEYS.js} +1 -1
  26. package/dist/admin-dist/assets/{timeline-definition-PNZ67QCA-DMT8_Cuq.js → timeline-definition-PNZ67QCA-DvkxsvVe.js} +1 -1
  27. package/dist/admin-dist/assets/{vennDiagram-CIIHVFJN-DRtPPFKO.js → vennDiagram-CIIHVFJN-reuc9IpD.js} +1 -1
  28. package/dist/admin-dist/assets/{wardleyDiagram-YWT4CUSO-CDN0fFvU.js → wardleyDiagram-YWT4CUSO-D_kUvJVN.js} +1 -1
  29. package/dist/admin-dist/assets/{xychartDiagram-2RQKCTM6-e4oyuMDO.js → xychartDiagram-2RQKCTM6-B2C-FMLW.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 +1195 -78
  33. package/dist/index.js +1428 -137
  34. package/package.json +1 -1
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}`);
@@ -3214,6 +3214,49 @@ After a POC has a canonical conclusion and Core has prepared its deterministic r
3214
3214
  - Use \`Not evaluated in this POC.\`, \`Not applicable.\`, or \`No evidence available.\` when sources do not support a section.
3215
3215
  - Return a proposal for human review; Core persists it only after confirmation.
3216
3216
 
3217
+ ## Representation selection
3218
+
3219
+ - Use prose for context, interpretation, rationale, findings, and conclusions.
3220
+ - Use a Markdown table when supplied evidence has comparable rows, such as success criteria and
3221
+ outcomes, resources, experiments, measurements, costs, risks, recommendations, or traceability.
3222
+ - Use Mermaid only for architecture, topology, or flow relationships explicitly supported by the
3223
+ supplied sources. Prefer it to an ASCII diagram when both can represent the same grounded flow.
3224
+ - Tables and diagrams are communication tools, not completeness requirements. Do not produce one
3225
+ when the context does not support a useful representation.
3226
+ - Never invent table rows, diagram nodes or edges, statuses, priorities, metrics, or relationships
3227
+ to make a report look more complete.
3228
+ - Preserve measured, calculated, estimated, and projected semantics in every representation.
3229
+ - In Traceability, use repository-relative Markdown links or paths; never emit \`file:///\` URLs or
3230
+ local absolute filesystem paths.
3231
+
3232
+ ## Section representation guide
3233
+
3234
+ | Section | Preferred representation when supported by evidence |
3235
+ |---|---|
3236
+ | Executive Summary | Snapshot table and short prose |
3237
+ | Problem and Objective | Prose |
3238
+ | Hypothesis and Success Criteria | Evaluation matrix |
3239
+ | Scope, Constraints and Non-goals | Compact bullets or table |
3240
+ | Technical Approach and Architecture | Mermaid and prose |
3241
+ | Infrastructure and Project Resources | Table, with optional Mermaid |
3242
+ | Implementation and Relevant Technical Decisions | Table or concise prose |
3243
+ | Experiments and Validation | Validation matrix |
3244
+ | Results and Measurements | Measurement tables |
3245
+ | Cost and Efficiency Analysis | Comparison table |
3246
+ | Observability and Operational Findings | Table or prose |
3247
+ | Findings, Learnings, Limitations and Risks | Structured matrix |
3248
+ | Conclusion | Status and concise prose |
3249
+ | Recommendation and Next Steps | Recommendation matrix only when priority is evidenced |
3250
+ | Traceability and Sources | Relative-link table or list |
3251
+
3252
+ ## Quality checklist
3253
+
3254
+ - Structured evidence uses tables when clearer than prose.
3255
+ - Grounded architecture or flows use Mermaid when useful; no decorative or unsupported diagrams exist.
3256
+ - Tables and Mermaid preserve source grounding and measurement semantics.
3257
+ - Traceability contains repository-portable paths.
3258
+ - The report is scannable before reading the full narrative.
3259
+
3217
3260
  ## Required structure
3218
3261
 
3219
3262
  1. Executive Summary
@@ -6673,8 +6716,8 @@ async function runCreate(type, opts = {}) {
6673
6716
  answers[question.frontMatterField] = answer.trim();
6674
6717
  }
6675
6718
  const id = nextWorkItemId(dir);
6676
- const slug5 = slugify(title);
6677
- const fileName = `${id}-${slug5}.md`;
6719
+ const slug7 = slugify(title);
6720
+ const fileName = `${id}-${slug7}.md`;
6678
6721
  const filePath = join(dir, DRAFT_DIR, fileName);
6679
6722
  const frontMatter2 = buildFrontMatter(id, workItemType, level, title.trim(), answers);
6680
6723
  const body = buildBody(workItemType, level, title.trim(), answers, levelDef.qualityGate);
@@ -6707,8 +6750,8 @@ async function runCreateModule(dir, modType) {
6707
6750
  answers[q.frontMatterField] = answer.trim();
6708
6751
  }
6709
6752
  const id = nextWorkItemId(dir);
6710
- const slug5 = slugify(title);
6711
- const fileName = `${id}-${slug5}.md`;
6753
+ const slug7 = slugify(title);
6754
+ const fileName = `${id}-${slug7}.md`;
6712
6755
  const filePath = join(dir, DRAFT_DIR, fileName);
6713
6756
  const frontMatter2 = buildModuleFrontMatter(id, modType, title.trim(), answers);
6714
6757
  const body = buildModuleBody(modType, title.trim(), answers);
@@ -6873,8 +6916,8 @@ function buildRoadmapWorkItem(opts) {
6873
6916
  const { id, type, level, candidate } = opts;
6874
6917
  const answers = opts.answers ?? {};
6875
6918
  const title = candidate.title.trim();
6876
- const slug5 = slugify(title);
6877
- const fileName = `${id}-${slug5}.md`;
6919
+ const slug7 = slugify(title);
6920
+ const fileName = `${id}-${slug7}.md`;
6878
6921
  const qualityGate = getLevel(level).qualityGate;
6879
6922
  const frontMatter2 = buildRoadmapFrontMatter(id, type, level, title, candidate, answers);
6880
6923
  const body = buildRoadmapBody(type, level, title, candidate, answers, qualityGate);
@@ -7275,10 +7318,10 @@ function analyzeGuard(touchedFiles, artifacts, silentWithoutOwnership) {
7275
7318
  import { parse as parseYaml5, stringify as stringifyYaml4 } from "yaml";
7276
7319
  var IGNORE_FILE = ".kaddo/ignores.yml";
7277
7320
  function loadIgnores(dir) {
7278
- const path13 = join(dir, IGNORE_FILE);
7279
- if (!exists(path13)) return [];
7321
+ const path14 = join(dir, IGNORE_FILE);
7322
+ if (!exists(path14)) return [];
7280
7323
  try {
7281
- const raw = readFile(path13);
7324
+ const raw = readFile(path14);
7282
7325
  const parsed = parseYaml5(raw);
7283
7326
  return Array.isArray(parsed) ? parsed : [];
7284
7327
  } catch {
@@ -7286,7 +7329,7 @@ function loadIgnores(dir) {
7286
7329
  }
7287
7330
  }
7288
7331
  function saveIgnore(dir, entry) {
7289
- const path13 = join(dir, IGNORE_FILE);
7332
+ const path14 = join(dir, IGNORE_FILE);
7290
7333
  const existing = loadIgnores(dir);
7291
7334
  const idx = existing.findIndex((e) => e.artifact_id === entry.artifact_id);
7292
7335
  if (idx >= 0) {
@@ -7294,17 +7337,17 @@ function saveIgnore(dir, entry) {
7294
7337
  } else {
7295
7338
  existing.push(entry);
7296
7339
  }
7297
- writeFile(path13, stringifyYaml4(existing));
7340
+ writeFile(path14, stringifyYaml4(existing));
7298
7341
  }
7299
7342
  function isIgnored(ignores, artifactId) {
7300
7343
  return ignores.find((e) => e.artifact_id === artifactId);
7301
7344
  }
7302
7345
  function removeIgnore(dir, artifactId) {
7303
- const path13 = join(dir, IGNORE_FILE);
7346
+ const path14 = join(dir, IGNORE_FILE);
7304
7347
  const existing = loadIgnores(dir);
7305
7348
  const filtered = existing.filter((e) => e.artifact_id !== artifactId);
7306
7349
  if (filtered.length === existing.length) return false;
7307
- writeFile(path13, stringifyYaml4(filtered));
7350
+ writeFile(path14, stringifyYaml4(filtered));
7308
7351
  return true;
7309
7352
  }
7310
7353
 
@@ -7326,11 +7369,11 @@ function moduleArtifactCoverage(dir, id) {
7326
7369
  };
7327
7370
  }
7328
7371
  function loadMappedModules(dir) {
7329
- const path13 = join(dir, DESCRIPTOR_PATH);
7330
- if (!exists(path13)) return [];
7372
+ const path14 = join(dir, DESCRIPTOR_PATH);
7373
+ if (!exists(path14)) return [];
7331
7374
  let parsed;
7332
7375
  try {
7333
- parsed = parseYaml6(readFile(path13));
7376
+ parsed = parseYaml6(readFile(path14));
7334
7377
  } catch {
7335
7378
  return [];
7336
7379
  }
@@ -8074,7 +8117,7 @@ function buildGuardHistory(dir) {
8074
8117
  const d = hotspotDir(t.code_path);
8075
8118
  hotspotMap.set(d, (hotspotMap.get(d) ?? 0) + 1);
8076
8119
  }
8077
- 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);
8078
8121
  return {
8079
8122
  available: true,
8080
8123
  total_runs: sorted.length,
@@ -8594,7 +8637,7 @@ function runIgnoreRemove(artifactId) {
8594
8637
  }
8595
8638
 
8596
8639
  // src/commands/explain.ts
8597
- import matter9 from "gray-matter";
8640
+ import matter10 from "gray-matter";
8598
8641
  import { parse as parseYaml13 } from "yaml";
8599
8642
 
8600
8643
  // src/core/delivery-phase.ts
@@ -10712,10 +10755,10 @@ function slugify2(name) {
10712
10755
  return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
10713
10756
  }
10714
10757
  function readModulesDescriptor(dir) {
10715
- const path13 = join(dir, DESCRIPTOR_PATH2);
10716
- if (!exists(path13)) return { version: 1, modules: [] };
10758
+ const path14 = join(dir, DESCRIPTOR_PATH2);
10759
+ if (!exists(path14)) return { version: 1, modules: [] };
10717
10760
  try {
10718
- const parsed = parseYaml10(readFile(path13));
10761
+ const parsed = parseYaml10(readFile(path14));
10719
10762
  return { version: parsed.version ?? 1, modules: parsed.modules ?? [] };
10720
10763
  } catch {
10721
10764
  return { version: 1, modules: [] };
@@ -11095,7 +11138,7 @@ function sectionParagraph(md, title) {
11095
11138
  }
11096
11139
  return "";
11097
11140
  }
11098
- function parseCapsule(id, path13, md) {
11141
+ function parseCapsule(id, path14, md) {
11099
11142
  const { data } = matter3(md);
11100
11143
  const updatedAt = data.updated_at ? String(data.updated_at) : void 0;
11101
11144
  let ageDays = null;
@@ -11105,7 +11148,7 @@ function parseCapsule(id, path13, md) {
11105
11148
  }
11106
11149
  return {
11107
11150
  id,
11108
- path: path13,
11151
+ path: path14,
11109
11152
  system: data.system ? String(data.system) : id,
11110
11153
  owner: data.owner ? String(data.owner) : void 0,
11111
11154
  updatedAt,
@@ -11459,6 +11502,252 @@ function parseWorkItemResources(fm2) {
11459
11502
  return out;
11460
11503
  }
11461
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
+
11462
11751
  // src/core/graph.ts
11463
11752
  var KNOWLEDGE3 = "knowledge";
11464
11753
  var RESOURCE_ROLE_EDGE = {
@@ -11503,9 +11792,9 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
11503
11792
  ];
11504
11793
  const presentLayers = [];
11505
11794
  for (const layer2 of layerDocs) {
11506
- const path13 = layer2.files.map((f) => `${KNOWLEDGE3}/${f}`).find((rel) => exists(join(dir, rel)));
11507
- if (path13) {
11508
- 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 });
11509
11798
  presentLayers.push(layer2.id);
11510
11799
  }
11511
11800
  }
@@ -11563,6 +11852,33 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
11563
11852
  addEdge(modId, resId, "depends_on");
11564
11853
  }
11565
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
+ }
11566
11882
  for (const wi of selectedWIs) {
11567
11883
  const id = wi.id || wi.title;
11568
11884
  if (!id || !id.trim()) continue;
@@ -11593,6 +11909,11 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
11593
11909
  addNode({ id: resId, type: "project-resource", label: title ? `${rel.id} ${title}`.trim() : rel.id });
11594
11910
  addEdge(wiNodeId, resId, RESOURCE_ROLE_EDGE[rel.role] ?? "uses");
11595
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
+ }
11596
11917
  for (const dec of wi.decisions) {
11597
11918
  if (!dec || !dec.trim()) continue;
11598
11919
  const adrId = `adr:${dec}`;
@@ -11971,7 +12292,7 @@ function loadGraphHints(dir) {
11971
12292
  }
11972
12293
 
11973
12294
  // src/services/installed-skills.ts
11974
- import matter6 from "gray-matter";
12295
+ import matter7 from "gray-matter";
11975
12296
  var SKILLS_DIR = join("knowledge", "skills");
11976
12297
  function discoverInstalledSkills(dir) {
11977
12298
  const base = join(dir, SKILLS_DIR);
@@ -11981,7 +12302,7 @@ function discoverInstalledSkills(dir) {
11981
12302
  const skillFile = join(base, entry, "skill.md");
11982
12303
  if (!isFile(skillFile)) continue;
11983
12304
  try {
11984
- const { data } = matter6(readFile(skillFile));
12305
+ const { data } = matter7(readFile(skillFile));
11985
12306
  if (data.type && String(data.type) !== "skill") continue;
11986
12307
  const id = String(data.id ?? entry);
11987
12308
  out.push({
@@ -13004,7 +13325,7 @@ function buildTechDecisions(dir) {
13004
13325
 
13005
13326
  // src/core/poc-report.ts
13006
13327
  import { createHash } from "crypto";
13007
- import matter7 from "gray-matter";
13328
+ import matter8 from "gray-matter";
13008
13329
  var POC_REPORT_PREFIX = "poc-report-v";
13009
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;
13010
13331
  var reportName = /^poc-report-v(\d{3,})\.md$/;
@@ -13020,11 +13341,11 @@ function redactSecrets(value) {
13020
13341
  return line.replace(/([:=]\s*)\S+.*/, "$1[redacted]");
13021
13342
  }).join("\n");
13022
13343
  }
13023
- function source(dir, path13, kind) {
13024
- const absolute = join(dir, path13);
13344
+ function source(dir, path14, kind) {
13345
+ const absolute = join(dir, path14);
13025
13346
  if (!exists(absolute)) return null;
13026
13347
  const raw = readFile(absolute);
13027
- return { path: posix(path13), kind, digest: sha(raw), content: redactSecrets(raw) };
13348
+ return { path: posix(path14), kind, digest: sha(raw), content: redactSecrets(raw) };
13028
13349
  }
13029
13350
  function reportFiles(dir) {
13030
13351
  const delivery = join(dir, "knowledge", "delivery");
@@ -13032,7 +13353,7 @@ function reportFiles(dir) {
13032
13353
  const match = name.match(reportName);
13033
13354
  if (!match) return [];
13034
13355
  try {
13035
- const parsed = matter7(readFile(join(delivery, name)));
13356
+ const parsed = matter8(readFile(join(delivery, name)));
13036
13357
  const fingerprint = typeof parsed.data.source_fingerprint === "string" ? parsed.data.source_fingerprint : "";
13037
13358
  const manifest = parsed.data.source_manifest;
13038
13359
  const sourceManifest = manifest && typeof manifest === "object" && !Array.isArray(manifest) ? Object.fromEntries(Object.entries(manifest).filter(([, digest]) => typeof digest === "string")) : {};
@@ -13064,9 +13385,9 @@ function buildPocReportContext(dir) {
13064
13385
  };
13065
13386
  }
13066
13387
  const sources = [];
13067
- const add = (path13, kind) => {
13068
- if (sources.some((item2) => item2.path === posix(path13))) return;
13069
- 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);
13070
13391
  if (item) sources.push(item);
13071
13392
  };
13072
13393
  add(POC_ARTIFACT_PATH, "poc");
@@ -13094,7 +13415,7 @@ function buildPocReportContext(dir) {
13094
13415
  const sourceFingerprint = sha(sources.map((item) => `${item.path}\0${item.digest}`).join("\n"));
13095
13416
  const status = !latestReport ? "missing" : latestReport.sourceFingerprint === sourceFingerprint ? "current" : "stale";
13096
13417
  const currentManifest = Object.fromEntries(sources.map((item) => [item.path, item.digest]));
13097
- 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() : [];
13098
13419
  const sourceList = sources.map((item) => `- ${item.path} (${item.kind})`).join("\n") || "- No sources selected.";
13099
13420
  return {
13100
13421
  eligible: true,
@@ -13110,6 +13431,9 @@ function buildPocReportContext(dir) {
13110
13431
  `Canonical conclusion: ${poc.conclusion}. Do not contradict it.`,
13111
13432
  "Use the 15 canonical sections. Mark missing evidence as Not evaluated, Not applicable, or No evidence available.",
13112
13433
  "Distinguish measured, calculated, estimated, and projected values. Never include secret values.",
13434
+ "Choose the representation that best communicates each grounded fact: Markdown tables for structured comparisons, Mermaid for grounded architecture, flows, or relationships, and prose for explanation and interpretation.",
13435
+ "Do not invent data, entities, relationships, priorities, or metrics to create a table or diagram. Do not use ASCII diagrams when Mermaid can represent the same grounded flow.",
13436
+ "In Traceability, use repository-relative Markdown links or paths. Never use file:/// URLs or local absolute filesystem paths.",
13113
13437
  "",
13114
13438
  "Selected sources:",
13115
13439
  sourceList
@@ -13242,10 +13566,10 @@ function resolveNextStep(dir, now = /* @__PURE__ */ new Date()) {
13242
13566
  const q = (rel) => analyzeKnowledgeArtifact(dir, rel);
13243
13567
  const resolveAgent = (agent) => {
13244
13568
  const file = agent.endsWith(".md") ? agent : `${agent}.md`;
13245
- const path13 = agentInstallPath(file);
13246
- const installed = isFile(join(dir, path13));
13569
+ const path14 = agentInstallPath(file);
13570
+ const installed = isFile(join(dir, path14));
13247
13571
  const group = agentGroupOf(file);
13248
- 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}` };
13249
13573
  };
13250
13574
  const moduleRepo = isModule(config);
13251
13575
  const coreRepo = isCore(config);
@@ -13675,7 +13999,7 @@ function deriveDeliveryCompletedStatus(dir) {
13675
13999
  }
13676
14000
 
13677
14001
  // src/core/assets.ts
13678
- import matter8 from "gray-matter";
14002
+ import matter9 from "gray-matter";
13679
14003
  function canonicalAgents() {
13680
14004
  return AGENT_PROMPTS.map((a) => ({
13681
14005
  name: a.fileName.replace(/\.md$/, ""),
@@ -13688,7 +14012,7 @@ function canonicalSkills() {
13688
14012
  }
13689
14013
  function versionOf(content) {
13690
14014
  try {
13691
- const v = matter8(content).data.version;
14015
+ const v = matter9(content).data.version;
13692
14016
  return v === void 0 || v === null ? null : String(v);
13693
14017
  } catch {
13694
14018
  return null;
@@ -15239,7 +15563,7 @@ function readKnowledge(dir) {
15239
15563
  if (!exists(knowledgePath)) return null;
15240
15564
  try {
15241
15565
  const raw = readFile(knowledgePath);
15242
- const { data, content } = matter9(raw);
15566
+ const { data, content } = matter10(raw);
15243
15567
  return { content, data };
15244
15568
  } catch {
15245
15569
  return null;
@@ -15250,7 +15574,7 @@ function readRoadmap(dir) {
15250
15574
  if (!exists(roadmapPath)) return null;
15251
15575
  try {
15252
15576
  const raw = readFile(roadmapPath);
15253
- const { content } = matter9(raw);
15577
+ const { content } = matter10(raw);
15254
15578
  return content.trim();
15255
15579
  } catch {
15256
15580
  return null;
@@ -15419,7 +15743,7 @@ function runExplain(opts) {
15419
15743
  }
15420
15744
 
15421
15745
  // src/core/context-pack.ts
15422
- import matter10 from "gray-matter";
15746
+ import matter11 from "gray-matter";
15423
15747
  var CONTEXT_PACK_VERSION = "1";
15424
15748
  var ARCH_DIR6 = "knowledge";
15425
15749
  function readScanJson(dir) {
@@ -15432,7 +15756,7 @@ function readScanJson(dir) {
15432
15756
  }
15433
15757
  }
15434
15758
  function firstParagraph2(markdown) {
15435
- const body = matter10(markdown).content.trim();
15759
+ const body = matter11(markdown).content.trim();
15436
15760
  const para = body.split("\n\n").map((p) => p.trim()).find((p) => p && !p.startsWith("#"));
15437
15761
  return para ?? "";
15438
15762
  }
@@ -17081,7 +17405,7 @@ function runStatus() {
17081
17405
  // src/commands/learn.ts
17082
17406
  import fs3 from "fs";
17083
17407
  import path7 from "path";
17084
- import matter11 from "gray-matter";
17408
+ import matter12 from "gray-matter";
17085
17409
  var ARCH_DIR9 = "knowledge";
17086
17410
  var WORK_ITEMS_DIR2 = "knowledge/delivery/work-items";
17087
17411
  function completedPathFor(filePath) {
@@ -17096,7 +17420,7 @@ function completedPathFor(filePath) {
17096
17420
  }
17097
17421
  function updateWorkItemFile(filePath, learning) {
17098
17422
  const raw = readFile(filePath);
17099
- const { data, content } = matter11(raw);
17423
+ const { data, content } = matter12(raw);
17100
17424
  data.status = "completed";
17101
17425
  data.completed_at = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
17102
17426
  let updatedContent = content;
@@ -17121,7 +17445,7 @@ ${learning.trim()}
17121
17445
  ${learning.trim()}
17122
17446
  `;
17123
17447
  }
17124
- const newRaw = matter11.stringify(updatedContent, data);
17448
+ const newRaw = matter12.stringify(updatedContent, data);
17125
17449
  const newPath = completedPathFor(filePath);
17126
17450
  if (newPath !== filePath) {
17127
17451
  ensureDir(path7.dirname(newPath));
@@ -17173,7 +17497,7 @@ async function runLearn(artifactId, opts = {}) {
17173
17497
  process.exit(1);
17174
17498
  }
17175
17499
  const wiRaw = readFile(filePath);
17176
- const wiData = matter11(wiRaw).data;
17500
+ const wiData = matter12(wiRaw).data;
17177
17501
  if (!opts.force) {
17178
17502
  const completionBlockers = [];
17179
17503
  const releaseGates = Array.isArray(wiData.release_gates) ? wiData.release_gates : [];
@@ -17429,7 +17753,7 @@ function runAdd(moduleName, opts = {}, dir = cwd()) {
17429
17753
  }
17430
17754
 
17431
17755
  // src/core/ownership-suggest.ts
17432
- import matter12 from "gray-matter";
17756
+ import matter13 from "gray-matter";
17433
17757
  var SCAN_PATH = ".kaddo/scan.json";
17434
17758
  function normalizeGlob(input) {
17435
17759
  let g = input.trim().replace(/\\/g, "/");
@@ -17551,11 +17875,11 @@ function suggestGlobs(artifact, signals) {
17551
17875
  return [...new Set(out)];
17552
17876
  }
17553
17877
  function applyOwnership(raw, globs, mode = "replace") {
17554
- const parsed = matter12(raw);
17878
+ const parsed = matter13(raw);
17555
17879
  const existing = toStringArray3(parsed.data.code);
17556
17880
  const next = mode === "append" ? [.../* @__PURE__ */ new Set([...existing, ...globs])] : [...new Set(globs)];
17557
17881
  const data = { ...parsed.data, code: next };
17558
- return matter12.stringify(parsed.content, data);
17882
+ return matter13.stringify(parsed.content, data);
17559
17883
  }
17560
17884
 
17561
17885
  // src/commands/owners.ts
@@ -18805,7 +19129,7 @@ async function runTopologyApply(file, opts = {}) {
18805
19129
  // src/core/resource-write.ts
18806
19130
  import fs5 from "fs";
18807
19131
  import path9 from "path";
18808
- import matter13 from "gray-matter";
19132
+ import matter14 from "gray-matter";
18809
19133
  var RESOURCES_DIR = "knowledge/tech/resources";
18810
19134
  var ResourceWriteError = class extends Error {
18811
19135
  constructor(code, message) {
@@ -18885,7 +19209,7 @@ function buildFrontmatter(id, input, base = {}) {
18885
19209
  return data;
18886
19210
  }
18887
19211
  function serialize(data, body) {
18888
- return matter13.stringify(`
19212
+ return matter14.stringify(`
18889
19213
  ${body.trim()}
18890
19214
  `, data);
18891
19215
  }
@@ -18925,7 +19249,7 @@ function updateResource(dir, id, input) {
18925
19249
  throw new ResourceWriteError("VALIDATION_FAILED", findings.filter((f) => f.level === "error").map((f) => f.message).join("; "));
18926
19250
  }
18927
19251
  const raw = readFile(match.filePath);
18928
- const parsed = matter13(raw);
19252
+ const parsed = matter14(raw);
18929
19253
  const base = parsed.data ?? {};
18930
19254
  const data = buildFrontmatter(match.id || id, input, base);
18931
19255
  let body = parsed.content.trim();
@@ -19159,15 +19483,960 @@ async function runResourcesDelete(id, opts = {}, dir = cwd()) {
19159
19483
  }
19160
19484
  }
19161
19485
 
19162
- // 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";
19163
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";
19164
20433
  import { parse as parseYaml18, stringify as stringifyYaml10 } from "yaml";
19165
20434
 
19166
20435
  // src/core/work-item-write.ts
19167
- import fs6 from "fs";
19168
- import path10 from "path";
20436
+ import fs7 from "fs";
20437
+ import path11 from "path";
19169
20438
  import crypto2 from "crypto";
19170
- import matter14 from "gray-matter";
20439
+ import matter17 from "gray-matter";
19171
20440
  var WORK_ITEMS_DIR3 = "knowledge/delivery/work-items";
19172
20441
  var WorkItemWriteError = class extends Error {
19173
20442
  constructor(code, message) {
@@ -19188,7 +20457,7 @@ function nextWorkItemId2(dir) {
19188
20457
  let max = 0;
19189
20458
  const walk = (d) => {
19190
20459
  if (!exists(d)) return;
19191
- for (const entry of fs6.readdirSync(d)) {
20460
+ for (const entry of fs7.readdirSync(d)) {
19192
20461
  const full = join(d, entry);
19193
20462
  if (isFile(full)) {
19194
20463
  const m = entry.match(/WI-(\d+)/);
@@ -19201,15 +20470,15 @@ function nextWorkItemId2(dir) {
19201
20470
  walk(wiDir);
19202
20471
  return `WI-${String(max + 1).padStart(3, "0")}`;
19203
20472
  }
19204
- function atomicWrite3(filePath, content) {
19205
- fs6.mkdirSync(path10.dirname(filePath), { recursive: true });
20473
+ function atomicWrite4(filePath, content) {
20474
+ fs7.mkdirSync(path11.dirname(filePath), { recursive: true });
19206
20475
  const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
19207
- fs6.writeFileSync(tmp, content, "utf-8");
20476
+ fs7.writeFileSync(tmp, content, "utf-8");
19208
20477
  try {
19209
- fs6.renameSync(tmp, filePath);
20478
+ fs7.renameSync(tmp, filePath);
19210
20479
  } catch (err) {
19211
20480
  try {
19212
- fs6.rmSync(tmp, { force: true });
20481
+ fs7.rmSync(tmp, { force: true });
19213
20482
  } catch {
19214
20483
  }
19215
20484
  throw err;
@@ -19270,8 +20539,8 @@ function ensureH1(body, title) {
19270
20539
 
19271
20540
  ${trimmed}`;
19272
20541
  }
19273
- function serialize2(data, body) {
19274
- return matter14.stringify(`
20542
+ function serialize3(data, body) {
20543
+ return matter17.stringify(`
19275
20544
  ${body.trim()}
19276
20545
  `, data);
19277
20546
  }
@@ -19339,8 +20608,8 @@ function createWorkItem(dir, opts) {
19339
20608
  const relPath = `${WORK_ITEMS_DIR3}/draft/${id}-${slugify5(title)}.md`;
19340
20609
  const filePath = join(dir, relPath);
19341
20610
  if (exists(filePath)) throw new WorkItemWriteError("INVALID_INPUT", `Work Item file already exists: ${relPath}`);
19342
- const raw = serialize2(data, body);
19343
- atomicWrite3(filePath, raw);
20611
+ const raw = serialize3(data, body);
20612
+ atomicWrite4(filePath, raw);
19344
20613
  return { id, path: relPath, revision: revisionOf(raw) };
19345
20614
  }
19346
20615
 
@@ -20028,8 +21297,8 @@ async function handleJiraResponse(res) {
20028
21297
  }
20029
21298
  return await res.json();
20030
21299
  }
20031
- async function jiraFetch(baseUrl, path13, auth, timeoutMs, params) {
20032
- const url = new URL(path13, baseUrl + "/");
21300
+ async function jiraFetch(baseUrl, path14, auth, timeoutMs, params) {
21301
+ const url = new URL(path14, baseUrl + "/");
20033
21302
  if (params) for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
20034
21303
  const controller = new AbortController();
20035
21304
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -20047,8 +21316,8 @@ async function jiraFetch(baseUrl, path13, auth, timeoutMs, params) {
20047
21316
  clearTimeout(timer);
20048
21317
  }
20049
21318
  }
20050
- async function jiraPost(baseUrl, path13, auth, timeoutMs, body) {
20051
- const url = new URL(path13, baseUrl + "/");
21319
+ async function jiraPost(baseUrl, path14, auth, timeoutMs, body) {
21320
+ const url = new URL(path14, baseUrl + "/");
20052
21321
  const controller = new AbortController();
20053
21322
  const timer = setTimeout(() => controller.abort(), timeoutMs);
20054
21323
  try {
@@ -20348,7 +21617,7 @@ function findLinkedWorkItem(dir, integrationId, externalId) {
20348
21617
  for (const art of discoverWorkItems(dir)) {
20349
21618
  let data;
20350
21619
  try {
20351
- data = matter15(readFile(art.filePath)).data;
21620
+ data = matter18(readFile(art.filePath)).data;
20352
21621
  } catch {
20353
21622
  continue;
20354
21623
  }
@@ -20561,7 +21830,7 @@ async function runIntegrationsImport(dir, id, externalId, opts) {
20561
21830
  }
20562
21831
 
20563
21832
  // src/core/impact-report.ts
20564
- import matter16 from "gray-matter";
21833
+ import matter19 from "gray-matter";
20565
21834
  function isBroadGlob(glob) {
20566
21835
  if (!glob.endsWith("/**")) return false;
20567
21836
  const prefix = glob.slice(0, -3);
@@ -20630,7 +21899,7 @@ function buildImpactReport(dir, opts = {}, now = /* @__PURE__ */ new Date()) {
20630
21899
  }
20631
21900
  }
20632
21901
  try {
20633
- const body = matter16(readFile(wi.filePath)).content;
21902
+ const body = matter19(readFile(wi.filePath)).content;
20634
21903
  if (hasSection(body, /acceptance|criterios de aceptaci/i)) withAcceptance++;
20635
21904
  else gaps.missing_acceptance_criteria.push(gapItem(wi, "Add an `## Acceptance Criteria` section."));
20636
21905
  if (hasSection(body, /definition of done|^#{1,6}\s*dod\b|definici[oó]n de (terminado|hecho)/i)) withDoD++;
@@ -21707,7 +22976,7 @@ function runAdr(opts = {}) {
21707
22976
  }
21708
22977
 
21709
22978
  // src/commands/tech.ts
21710
- import fs7 from "fs";
22979
+ import fs8 from "fs";
21711
22980
  var DISCOVERY_FILES = ["architecture-notes.md", "decision-candidates.md"];
21712
22981
  var DISCOVERY_DIR = "knowledge/tech/discovery";
21713
22982
  function runTechOrganize(dir = cwd()) {
@@ -21724,7 +22993,7 @@ function runTechOrganize(dir = cwd()) {
21724
22993
  continue;
21725
22994
  }
21726
22995
  ensureDir(join(dir, DISCOVERY_DIR));
21727
- fs7.renameSync(from, to);
22996
+ fs8.renameSync(from, to);
21728
22997
  moved.push(`knowledge/tech/${file} \u2192 ${DISCOVERY_DIR}/${file}`);
21729
22998
  }
21730
22999
  if (moved.length > 0) {
@@ -21806,9 +23075,9 @@ function runAssetsUpdate(kind, opts = {}) {
21806
23075
  }
21807
23076
 
21808
23077
  // src/commands/ready.ts
21809
- import fs8 from "fs";
21810
- import path11 from "path";
21811
- import matter17 from "gray-matter";
23078
+ import fs9 from "fs";
23079
+ import path12 from "path";
23080
+ import matter20 from "gray-matter";
21812
23081
  function validateReadiness(content, frontmatter) {
21813
23082
  const warnings = [];
21814
23083
  const body = content.replace(/^---[\s\S]*?---/, "").trim();
@@ -21862,18 +23131,18 @@ function isResolvedSection(text2) {
21862
23131
  }
21863
23132
  function transitionToReady(filePath) {
21864
23133
  const raw = readFile(filePath);
21865
- const { data, content } = matter17(raw);
23134
+ const { data, content } = matter20(raw);
21866
23135
  const today3 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
21867
23136
  data.status = "ready";
21868
23137
  data.ready_at = today3;
21869
- const newContent = matter17.stringify(content, data);
23138
+ const newContent = matter20.stringify(content, data);
21870
23139
  const posix2 = filePath.replace(/\\/g, "/");
21871
23140
  let newPath = filePath;
21872
23141
  if (posix2.includes("/work-items/draft/")) {
21873
- const readyDir = path11.dirname(filePath).replace(/[/\\]draft$/, path11.sep + "ready");
23142
+ const readyDir = path12.dirname(filePath).replace(/[/\\]draft$/, path12.sep + "ready");
21874
23143
  ensureDir(readyDir);
21875
- const fileName = path11.basename(filePath);
21876
- newPath = path11.join(readyDir, fileName);
23144
+ const fileName = path12.basename(filePath);
23145
+ newPath = path12.join(readyDir, fileName);
21877
23146
  }
21878
23147
  return { newPath, newContent };
21879
23148
  }
@@ -21906,7 +23175,7 @@ async function runReady(id, opts = {}) {
21906
23175
  process.exit(1);
21907
23176
  }
21908
23177
  const raw = readFile(wi.filePath);
21909
- const { data } = matter17(raw);
23178
+ const { data } = matter20(raw);
21910
23179
  const source2 = parseWorkItemSource(data);
21911
23180
  const warnings = validateReadiness(raw, data);
21912
23181
  log.info(`Work Item found:`);
@@ -21941,11 +23210,11 @@ async function runReady(id, opts = {}) {
21941
23210
  const { newPath, newContent } = transitionToReady(wi.filePath);
21942
23211
  if (newPath !== wi.filePath) {
21943
23212
  writeFile(newPath, newContent);
21944
- fs8.unlinkSync(wi.filePath);
23213
+ fs9.unlinkSync(wi.filePath);
21945
23214
  log.success(`Updated status: ready`);
21946
23215
  log.success(`Moved file:`);
21947
- log.info(` ${path11.relative(dir, wi.filePath)}`);
21948
- log.info(` \u2192 ${path11.relative(dir, newPath)}`);
23216
+ log.info(` ${path12.relative(dir, wi.filePath)}`);
23217
+ log.info(` \u2192 ${path12.relative(dir, newPath)}`);
21949
23218
  } else {
21950
23219
  writeFile(wi.filePath, newContent);
21951
23220
  log.success(`Updated status: ready`);
@@ -21956,7 +23225,7 @@ async function runReady(id, opts = {}) {
21956
23225
  }
21957
23226
 
21958
23227
  // src/commands/admin.ts
21959
- import path12 from "path";
23228
+ import path13 from "path";
21960
23229
  import { fileURLToPath as fileURLToPath2 } from "url";
21961
23230
  import net from "net";
21962
23231
  function isPortAvailable(port, host) {
@@ -21971,17 +23240,17 @@ function isPortAvailable(port, host) {
21971
23240
  });
21972
23241
  }
21973
23242
  function resolveStaticDir() {
21974
- const __dirname = path12.dirname(fileURLToPath2(import.meta.url));
23243
+ const __dirname = path13.dirname(fileURLToPath2(import.meta.url));
21975
23244
  const candidates = [
21976
23245
  // Monorepo development: prefer the freshly built admin over the copy bundled into the CLI dist.
21977
23246
  // The CLI build copies admin/dist into dist/admin-dist, but that copy can be stale when the admin
21978
23247
  // was rebuilt after the CLI (build order is not guaranteed in `pnpm -r build`). Serving the admin
21979
23248
  // package's own dist first ensures `kaddo admin` always shows the current frontend in dev. This
21980
23249
  // path does not exist in a published npm install (admin is private), so it falls back below.
21981
- path12.resolve(__dirname, "..", "..", "admin", "dist"),
21982
- path12.resolve(__dirname, "..", "node_modules", "@kaddo", "admin", "dist"),
23250
+ path13.resolve(__dirname, "..", "..", "admin", "dist"),
23251
+ path13.resolve(__dirname, "..", "node_modules", "@kaddo", "admin", "dist"),
21983
23252
  // Bundled inside CLI dist (npm install)
21984
- path12.resolve(__dirname, "admin-dist")
23253
+ path13.resolve(__dirname, "admin-dist")
21985
23254
  ];
21986
23255
  for (const c of candidates) {
21987
23256
  if (exists(join(c, "index.html"))) return c;
@@ -22023,8 +23292,8 @@ async function runAdmin(opts = {}) {
22023
23292
  }
22024
23293
  let adminServer;
22025
23294
  try {
22026
- const __dirname = path12.dirname(fileURLToPath2(import.meta.url));
22027
- 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");
22028
23297
  if (exists(bundled)) {
22029
23298
  const { pathToFileURL } = await import("url");
22030
23299
  adminServer = await import(pathToFileURL(bundled).href);
@@ -22081,11 +23350,11 @@ async function runAdmin(opts = {}) {
22081
23350
 
22082
23351
  // src/core/work-item-import.ts
22083
23352
  import crypto3 from "crypto";
22084
- import fs9 from "fs";
22085
- import matter19 from "gray-matter";
23353
+ import fs10 from "fs";
23354
+ import matter22 from "gray-matter";
22086
23355
 
22087
23356
  // src/core/work-items.ts
22088
- import matter18 from "gray-matter";
23357
+ import matter21 from "gray-matter";
22089
23358
  function computeRefinementStatus(wi) {
22090
23359
  const aspects = {
22091
23360
  outcome: Boolean(wi.currentBehavior?.trim() || wi.targetBehavior?.trim()),
@@ -22155,6 +23424,8 @@ function getWorkItem(dir, workItemId) {
22155
23424
  markdownBody: body.trim(),
22156
23425
  // External systems this WI relates to (WI-030), separate from affectedModules (code).
22157
23426
  resources: parseWorkItemResources(fm2),
23427
+ // Deprecation Targets this WI retires (WI-050), referenced not copied.
23428
+ deprecationTargets: parseWorkItemDeprecationTargets(fm2),
22158
23429
  ...parseSystemImpact(dir, fm2)
22159
23430
  };
22160
23431
  return { ...detail, refinement: computeRefinementStatus(detail) };
@@ -22163,8 +23434,8 @@ function parseGraphReason(v) {
22163
23434
  if (!v || typeof v !== "object") return null;
22164
23435
  const o = v;
22165
23436
  const relationship = typeof o.relationship === "string" && o.relationship.trim() ? o.relationship.trim() : null;
22166
- const path13 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
22167
- 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;
22168
23439
  }
22169
23440
  function parseExplain(o) {
22170
23441
  const refs = Array.isArray(o.evidence) ? o.evidence : Array.isArray(o.evidence_refs) ? o.evidence_refs : [];
@@ -22219,7 +23490,7 @@ function parseOriginalSnapshot(fm2) {
22219
23490
  function readBody(filePath) {
22220
23491
  try {
22221
23492
  const raw = readFile(filePath);
22222
- return matter18(raw).content;
23493
+ return matter21(raw).content;
22223
23494
  } catch {
22224
23495
  return "";
22225
23496
  }
@@ -22678,7 +23949,7 @@ function detectFormat(raw) {
22678
23949
  if (!trimmed) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
22679
23950
  if (trimmed.startsWith("---")) {
22680
23951
  try {
22681
- const { data } = matter19(trimmed);
23952
+ const { data } = matter22(trimmed);
22682
23953
  if (data && typeof data === "object" && Object.keys(data).length > 0) {
22683
23954
  const d = data;
22684
23955
  if (d.type === "work-item" || d.id && typeof d.id === "string" && /^WI-\d+/.test(d.id)) {
@@ -22700,7 +23971,7 @@ function parseContent(raw) {
22700
23971
  let bodyText = trimmed;
22701
23972
  if (format === "kaddo-frontmatter" || format === "markdown-frontmatter") {
22702
23973
  try {
22703
- const parsed = matter19(trimmed);
23974
+ const parsed = matter22(trimmed);
22704
23975
  frontmatterFields = parsed.data ?? {};
22705
23976
  bodyText = parsed.content.trim();
22706
23977
  } catch {
@@ -22797,7 +24068,7 @@ function findDuplicateByHash(dir, hash) {
22797
24068
  const raw = readFile(item.filePath);
22798
24069
  if (!raw) continue;
22799
24070
  try {
22800
- const { data } = matter19(raw);
24071
+ const { data } = matter22(raw);
22801
24072
  const source2 = data?.source;
22802
24073
  if (source2 && typeof source2 === "object" && !Array.isArray(source2)) {
22803
24074
  const s = source2;
@@ -22864,7 +24135,7 @@ function importWorkItem(dir, opts) {
22864
24135
  };
22865
24136
  }
22866
24137
  if (opts.onConflict === "replace") {
22867
- fs9.rmSync(existing.filePath, { force: true });
24138
+ fs10.rmSync(existing.filePath, { force: true });
22868
24139
  replacedWorkItem = existing.workItemId;
22869
24140
  }
22870
24141
  }
@@ -23038,7 +24309,7 @@ ${report.handoff}
23038
24309
  }
23039
24310
 
23040
24311
  // src/commands/verify.ts
23041
- import matter20 from "gray-matter";
24312
+ import matter23 from "gray-matter";
23042
24313
 
23043
24314
  // src/core/implementation-evidence.ts
23044
24315
  var WorkItemNotInProgressError = class extends Error {
@@ -23270,17 +24541,17 @@ function extractACsFromBody(body) {
23270
24541
  let inAC = false;
23271
24542
  const acs = [];
23272
24543
  for (const line of lines) {
23273
- 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)) {
23274
24545
  inAC = true;
23275
24546
  continue;
23276
24547
  }
23277
24548
  if (inAC && /^#{1,6}\s+/.test(line)) break;
23278
24549
  if (inAC) {
23279
- const m = line.match(/^\s*[-*+]\s+(?:\[[ xX]\]\s*)?(.+)$/);
24550
+ const m = line.match(/^\s*[-*+]\s+(?:\[([ xX])\]\s*)?(.+)$/);
23280
24551
  if (m) {
23281
- const text2 = m[1].trim();
24552
+ const text2 = m[2].trim();
23282
24553
  if (text2 && !/^_.*_$/.test(text2) && !/^tbd$/i.test(text2)) {
23283
- acs.push(text2);
24554
+ acs.push({ criterion: text2, checked: m[1]?.toLowerCase() === "x" });
23284
24555
  }
23285
24556
  }
23286
24557
  }
@@ -23315,7 +24586,7 @@ async function runVerify(workItemId, opts = {}) {
23315
24586
  }
23316
24587
  const changedPaths = await getModifiedFiles("head");
23317
24588
  const raw = readFile(match.filePath);
23318
- const parsed = matter20(raw);
24589
+ const parsed = matter23(raw);
23319
24590
  const fm2 = parsed.data;
23320
24591
  const acs = extractACsFromBody(parsed.content);
23321
24592
  const existingEvidence = fm2.implementation_evidence;
@@ -23340,8 +24611,9 @@ async function runVerify(workItemId, opts = {}) {
23340
24611
  };
23341
24612
  }) : [{ repoId: "core", changedPaths, validations: [] }];
23342
24613
  const acVerifications = acs.map((ac) => ({
23343
- criterion: ac,
23344
- 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." } : {}
23345
24617
  }));
23346
24618
  const input = {
23347
24619
  repos,
@@ -23432,13 +24704,13 @@ async function runVerify(workItemId, opts = {}) {
23432
24704
  if (shouldPersist) {
23433
24705
  const filePath = match.filePath;
23434
24706
  const wiRaw = readFile(filePath);
23435
- const wiParsed = matter20(wiRaw);
24707
+ const wiParsed = matter23(wiRaw);
23436
24708
  const data = wiParsed.data;
23437
24709
  data.implementation_evidence = verification.implementationEvidence;
23438
24710
  data.implementation_status = verification.implementationStatus;
23439
24711
  data.validation_status = verification.validationStatus;
23440
24712
  data.verified_at = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
23441
- const newRaw = matter20.stringify(wiParsed.content, data);
24713
+ const newRaw = matter23.stringify(wiParsed.content, data);
23442
24714
  writeFile(filePath, newRaw);
23443
24715
  log.success("Work Item frontmatter updated with verification evidence.");
23444
24716
  }
@@ -23488,9 +24760,9 @@ function markRegistered(dir, identity) {
23488
24760
  ensureDir(join(dir, TELEMETRY_DIR));
23489
24761
  writeFile(identityPath(dir), JSON.stringify(identity, null, 2));
23490
24762
  }
23491
- function signPayload(identity, method, path13, timestamp, nonce, bodySha256) {
24763
+ function signPayload(identity, method, path14, timestamp, nonce, bodySha256) {
23492
24764
  const canonical = `${method}
23493
- ${path13}
24765
+ ${path14}
23494
24766
  ${identity.installationId}
23495
24767
  ${timestamp}
23496
24768
  ${nonce}
@@ -23716,7 +24988,7 @@ function runTelemetryDisable() {
23716
24988
  }
23717
24989
 
23718
24990
  // src/core/initiative-write.ts
23719
- import matter21 from "gray-matter";
24991
+ import matter24 from "gray-matter";
23720
24992
  var WORK_ITEMS_DIR4 = "knowledge/delivery/work-items";
23721
24993
  var DRAFT_DIR2 = `${WORK_ITEMS_DIR4}/draft`;
23722
24994
  var InitiativeWriteError = class extends Error {
@@ -23828,7 +25100,7 @@ function buildInitiativeContent(id, input) {
23828
25100
  if (input.priority) data.priority = input.priority;
23829
25101
  if (input.source) data.source = input.source;
23830
25102
  if (input.sourceId) data.source_id = input.sourceId;
23831
- return matter21.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
25103
+ return matter24.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
23832
25104
  }
23833
25105
  function createInitiative(dir, input) {
23834
25106
  if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
@@ -23852,10 +25124,10 @@ function transitionInitiative(dir, id, to) {
23852
25124
  throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
23853
25125
  }
23854
25126
  const raw = readFile(ini.filePath);
23855
- const { data, content } = matter21(raw, {});
25127
+ const { data, content } = matter24(raw, {});
23856
25128
  data.status = to;
23857
25129
  if (to === "completed") data.completed_at = today2();
23858
- const newContent = matter21.stringify(content, data);
25130
+ const newContent = matter24.stringify(content, data);
23859
25131
  writeFile(ini.filePath, newContent);
23860
25132
  const updated = parseInitiative(dir, ini.filePath, newContent);
23861
25133
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
@@ -23924,7 +25196,7 @@ function buildWorkItemContent(wiId, iniId, candidate) {
23924
25196
  "_What did we learn? Update after completion._",
23925
25197
  ""
23926
25198
  ].join("\n");
23927
- return matter21.stringify("\n" + body, data);
25199
+ return matter24.stringify("\n" + body, data);
23928
25200
  }
23929
25201
  function materializeCandidate(dir, id, candidateId) {
23930
25202
  const ini = getInitiative(dir, id);
@@ -23941,13 +25213,13 @@ function materializeCandidate(dir, id, candidateId) {
23941
25213
  ensureDir(join(dir, DRAFT_DIR2));
23942
25214
  writeFile(join(dir, DRAFT_DIR2, fileName), buildWorkItemContent(wiId, ini.id, candidate));
23943
25215
  const raw = readFile(ini.filePath);
23944
- const { data, content } = matter21(raw, {});
25216
+ const { data, content } = matter24(raw, {});
23945
25217
  const cands = Array.isArray(data.candidates) ? data.candidates : [];
23946
25218
  for (const c of cands) {
23947
25219
  if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
23948
25220
  }
23949
25221
  data.candidates = cands;
23950
- const newContent = matter21.stringify(content, data);
25222
+ const newContent = matter24.stringify(content, data);
23951
25223
  writeFile(ini.filePath, newContent);
23952
25224
  const updated = parseInitiative(dir, ini.filePath, newContent);
23953
25225
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
@@ -24309,8 +25581,8 @@ var capsuleCmd = program.command("capsule").description("Export this project as
24309
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) => {
24310
25582
  runCapsuleExport(opts);
24311
25583
  });
24312
- capsuleCmd.command("add <path>").description("Register an external Knowledge Capsule as project context (.kaddo/external.yml)").action((path13) => {
24313
- runCapsuleAdd(path13);
25584
+ capsuleCmd.command("add <path>").description("Register an external Knowledge Capsule as project context (.kaddo/external.yml)").action((path14) => {
25585
+ runCapsuleAdd(path14);
24314
25586
  });
24315
25587
  var graphCmd = program.command("graph").description("Export the lightweight, file-based knowledge graph of the project");
24316
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) => {
@@ -24333,6 +25605,25 @@ resourcesCmd.command("update <id>").description("Update a Project Resource (no-l
24333
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) => {
24334
25606
  await runResourcesDelete(id, opts, cwd());
24335
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));
24336
25627
  var integrationsCmd = program.command("integrations").description("Connect Kaddo to external work systems (read-first; import requires human confirmation)");
24337
25628
  integrationsCmd.command("list").description("List configured integrations and their capabilities").option("--json", "Output JSON").action((opts) => runIntegrationsList(cwd(), opts));
24338
25629
  integrationsCmd.command("status").description("Verify each enabled integration and report its connection status").option("--json", "Output JSON").action(async (opts) => {