@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/core.js CHANGED
@@ -141,8 +141,8 @@ function loadConfig(dir) {
141
141
  const parsed = configSchema.safeParse(raw ?? {});
142
142
  if (!parsed.success) {
143
143
  const issues = parsed.error.issues.map((i) => {
144
- const path5 = i.path.join(".");
145
- return path5 ? ` - ${path5}: ${i.message}` : ` - ${i.message}`;
144
+ const path6 = i.path.join(".");
145
+ return path6 ? ` - ${path6}: ${i.message}` : ` - ${i.message}`;
146
146
  }).join("\n");
147
147
  throw new ConfigError(`Invalid .kaddo/config.yml:
148
148
  ${issues}`);
@@ -394,11 +394,11 @@ function moduleArtifactCoverage(dir, id) {
394
394
  };
395
395
  }
396
396
  function loadMappedModules(dir) {
397
- const path5 = join(dir, DESCRIPTOR_PATH);
398
- if (!exists(path5)) return [];
397
+ const path6 = join(dir, DESCRIPTOR_PATH);
398
+ if (!exists(path6)) return [];
399
399
  let parsed;
400
400
  try {
401
- parsed = parseYaml3(readFile(path5));
401
+ parsed = parseYaml3(readFile(path6));
402
402
  } catch {
403
403
  return [];
404
404
  }
@@ -1629,7 +1629,7 @@ function sectionParagraph(md, title) {
1629
1629
  }
1630
1630
  return "";
1631
1631
  }
1632
- function parseCapsule(id, path5, md) {
1632
+ function parseCapsule(id, path6, md) {
1633
1633
  const { data } = matter2(md);
1634
1634
  const updatedAt = data.updated_at ? String(data.updated_at) : void 0;
1635
1635
  let ageDays = null;
@@ -1639,7 +1639,7 @@ function parseCapsule(id, path5, md) {
1639
1639
  }
1640
1640
  return {
1641
1641
  id,
1642
- path: path5,
1642
+ path: path6,
1643
1643
  system: data.system ? String(data.system) : id,
1644
1644
  owner: data.owner ? String(data.owner) : void 0,
1645
1645
  updatedAt,
@@ -2004,6 +2004,302 @@ function parseWorkItemResources(fm) {
2004
2004
  return out;
2005
2005
  }
2006
2006
 
2007
+ // src/core/deprecation.ts
2008
+ import matter5 from "gray-matter";
2009
+ var DEPRECATION_ARTIFACT_TYPE = "deprecation-plan";
2010
+ var DEPRECATION_PLANS_DIR = "knowledge/legacy/deprecations";
2011
+ var TARGET_TYPES = [
2012
+ "module",
2013
+ "route",
2014
+ "function",
2015
+ "ui",
2016
+ "job",
2017
+ "database-object",
2018
+ "integration",
2019
+ "config",
2020
+ "other"
2021
+ ];
2022
+ var LIFECYCLE_STATES2 = [
2023
+ "candidate",
2024
+ "usage-validated",
2025
+ "soft-deprecated",
2026
+ "disabled",
2027
+ "removed-devtest",
2028
+ "production-ready",
2029
+ "production-changed",
2030
+ "observing",
2031
+ "completed",
2032
+ "deprecated-retained"
2033
+ ];
2034
+ var LIFECYCLE_TRANSITIONS = {
2035
+ candidate: ["usage-validated", "deprecated-retained"],
2036
+ "usage-validated": ["soft-deprecated", "deprecated-retained"],
2037
+ "soft-deprecated": ["disabled", "deprecated-retained"],
2038
+ disabled: ["removed-devtest", "deprecated-retained"],
2039
+ "removed-devtest": ["production-ready", "deprecated-retained"],
2040
+ "production-ready": ["production-changed"],
2041
+ "production-changed": ["observing"],
2042
+ observing: ["completed", "deprecated-retained"],
2043
+ completed: [],
2044
+ "deprecated-retained": []
2045
+ };
2046
+ var ENVIRONMENTS = ["development", "test", "production"];
2047
+ var ENVIRONMENT_STATES = ["active", "soft-deprecated", "disabled", "removed"];
2048
+ var EVIDENCE_SIGNALS = [
2049
+ "static",
2050
+ "runtime",
2051
+ "database",
2052
+ "external_consumers",
2053
+ "human_review"
2054
+ ];
2055
+ var USAGE_STATUSES = ["no-usage", "usage-found", "unknown", "not-evaluated"];
2056
+ var EVIDENCE_QUALITIES = ["observed-fact", "human-confirmed", "inferred", "unknown"];
2057
+ var SOFT_DEPRECATION_STRATEGIES = [
2058
+ "feature-flag",
2059
+ "hide-ui",
2060
+ "disable-route",
2061
+ "deprecation-warning",
2062
+ "stop-scheduler",
2063
+ "remove-caller",
2064
+ "stop-writes",
2065
+ "read-only",
2066
+ "telemetry",
2067
+ "manual"
2068
+ ];
2069
+ function str2(v) {
2070
+ return typeof v === "string" && v.trim() ? v.trim() : null;
2071
+ }
2072
+ function parseWorkItemDeprecationTargets(fm) {
2073
+ const v = fm.deprecation_targets;
2074
+ if (!Array.isArray(v)) return [];
2075
+ const out = [];
2076
+ for (const raw of v) {
2077
+ if (typeof raw === "string") {
2078
+ const s = raw.trim();
2079
+ if (!s) continue;
2080
+ const slash = s.indexOf("/");
2081
+ if (slash > 0) out.push({ plan: s.slice(0, slash).trim(), target: s.slice(slash + 1).trim() });
2082
+ else out.push({ plan: null, target: s });
2083
+ continue;
2084
+ }
2085
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
2086
+ const o = raw;
2087
+ const target = str2(o.target) ?? str2(o.id);
2088
+ if (!target) continue;
2089
+ out.push({ plan: str2(o.plan), target });
2090
+ }
2091
+ }
2092
+ return out;
2093
+ }
2094
+ function strArray2(v) {
2095
+ if (Array.isArray(v)) return v.map((x) => String(x).trim()).filter(Boolean);
2096
+ if (typeof v === "string" && v.trim()) return [v.trim()];
2097
+ return [];
2098
+ }
2099
+ function isValidTargetType(t) {
2100
+ return TARGET_TYPES.includes(t);
2101
+ }
2102
+ function isValidLifecycleState(s) {
2103
+ return LIFECYCLE_STATES2.includes(s);
2104
+ }
2105
+ function isValidEnvironmentState(s) {
2106
+ return ENVIRONMENT_STATES.includes(s);
2107
+ }
2108
+ function isValidLifecycleTransition(from, to) {
2109
+ if (!isValidLifecycleState(from) || !isValidLifecycleState(to)) return false;
2110
+ return LIFECYCLE_TRANSITIONS[from].includes(to);
2111
+ }
2112
+ function parseAssessment(v) {
2113
+ if (!v || typeof v !== "object" || Array.isArray(v)) {
2114
+ return { unusedConfidence: null, blastRadius: null, reversibility: null };
2115
+ }
2116
+ const o = v;
2117
+ return {
2118
+ unusedConfidence: str2(o.unused_confidence),
2119
+ blastRadius: str2(o.blast_radius),
2120
+ reversibility: str2(o.reversibility)
2121
+ };
2122
+ }
2123
+ function parseUsageEvidence(v) {
2124
+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};
2125
+ const out = {};
2126
+ for (const signal of EVIDENCE_SIGNALS) {
2127
+ const raw = v[signal];
2128
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
2129
+ const o = raw;
2130
+ out[signal] = {
2131
+ status: str2(o.status) ?? "unknown",
2132
+ quality: str2(o.quality) ?? "unknown",
2133
+ detail: str2(o.detail)
2134
+ };
2135
+ }
2136
+ return out;
2137
+ }
2138
+ function parseSoftDeprecation(v) {
2139
+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;
2140
+ const o = v;
2141
+ const windowRaw = o.observation_window_days;
2142
+ const window = typeof windowRaw === "number" && Number.isFinite(windowRaw) && windowRaw >= 0 ? Math.floor(windowRaw) : null;
2143
+ const exitCriteria = Array.isArray(o.exit_criteria) ? o.exit_criteria.map((c) => {
2144
+ if (typeof c === "string") return c.trim() ? { description: c.trim(), met: false } : null;
2145
+ if (c && typeof c === "object" && !Array.isArray(c)) {
2146
+ const co = c;
2147
+ const description = str2(co.description) ?? str2(co.criterion);
2148
+ if (!description) return null;
2149
+ return { description, met: co.met === true };
2150
+ }
2151
+ return null;
2152
+ }).filter((c) => Boolean(c)) : [];
2153
+ return {
2154
+ strategy: str2(o.strategy),
2155
+ mechanism: str2(o.mechanism),
2156
+ startedAt: str2(o.started_at),
2157
+ observationWindowDays: window,
2158
+ exitCriteria
2159
+ };
2160
+ }
2161
+ function parseEnvironments(v) {
2162
+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};
2163
+ const out = {};
2164
+ for (const env of ENVIRONMENTS) {
2165
+ const s = str2(v[env]);
2166
+ if (s) out[env] = s;
2167
+ }
2168
+ return out;
2169
+ }
2170
+ function parseTarget(raw) {
2171
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
2172
+ const o = raw;
2173
+ const id = str2(o.id);
2174
+ if (!id) return null;
2175
+ return {
2176
+ id,
2177
+ type: str2(o.type) ?? "other",
2178
+ locator: str2(o.locator),
2179
+ title: str2(o.title),
2180
+ lifecycle: str2(o.lifecycle) ?? "candidate",
2181
+ environments: parseEnvironments(o.environments),
2182
+ assessment: parseAssessment(o.assessment),
2183
+ usageEvidence: parseUsageEvidence(o.usage_evidence),
2184
+ dependsOnRemoval: strArray2(o.depends_on_removal),
2185
+ resource: str2(o.resource),
2186
+ module: str2(o.module),
2187
+ softDeprecation: parseSoftDeprecation(o.soft_deprecation)
2188
+ };
2189
+ }
2190
+ function parseTargets(v) {
2191
+ if (!Array.isArray(v)) return [];
2192
+ const out = [];
2193
+ for (const raw of v) {
2194
+ const t = parseTarget(raw);
2195
+ if (t) out.push(t);
2196
+ }
2197
+ return out;
2198
+ }
2199
+ function lifecycleCountsOf(targets) {
2200
+ const counts = {};
2201
+ for (const t of targets) counts[t.lifecycle] = (counts[t.lifecycle] ?? 0) + 1;
2202
+ return counts;
2203
+ }
2204
+ function purposeFromBody2(body) {
2205
+ const m = body.match(/^#{1,2}\s+Purpose\s*\n+([\s\S]*?)(?=\n#{1,2}\s|\s*$)/m);
2206
+ const text2 = m ? m[1].trim() : "";
2207
+ return text2 || null;
2208
+ }
2209
+ function getDeprecationPlans(dir) {
2210
+ return discoverKnowledge(dir).filter((a) => a.type === DEPRECATION_ARTIFACT_TYPE).map((a) => {
2211
+ const fm = a.rawFrontmatter;
2212
+ const targets = parseTargets(fm.targets);
2213
+ return {
2214
+ id: a.id || str2(fm.id) || a.title,
2215
+ title: a.title || str2(fm.title) || a.id,
2216
+ path: a.relPath,
2217
+ status: str2(fm.status),
2218
+ targetCount: targets.length,
2219
+ lifecycleCounts: lifecycleCountsOf(targets)
2220
+ };
2221
+ }).sort((x, y) => x.id.localeCompare(y.id));
2222
+ }
2223
+ function getDeprecationPlan(dir, id) {
2224
+ const match = discoverKnowledge(dir).find(
2225
+ (a) => a.type === DEPRECATION_ARTIFACT_TYPE && (a.id === id || a.title === id)
2226
+ );
2227
+ if (!match) return null;
2228
+ const raw = readFile(match.filePath);
2229
+ const parsed = matter5(raw);
2230
+ const fm = parsed.data ?? {};
2231
+ const body = parsed.content.trim();
2232
+ const targets = parseTargets(fm.targets);
2233
+ return {
2234
+ id: str2(fm.id) ?? match.id,
2235
+ title: str2(fm.title) ?? match.title,
2236
+ path: match.relPath,
2237
+ status: str2(fm.status),
2238
+ targetCount: targets.length,
2239
+ lifecycleCounts: lifecycleCountsOf(targets),
2240
+ purpose: str2(fm.purpose) ?? purposeFromBody2(body),
2241
+ targets,
2242
+ markdownBody: body
2243
+ };
2244
+ }
2245
+ function validateTarget(target) {
2246
+ const findings = [];
2247
+ const at = target.id;
2248
+ if (!isValidTargetType(String(target.type))) {
2249
+ findings.push({ severity: "error", target: at, message: `Unknown target type: ${target.type}` });
2250
+ }
2251
+ if (!isValidLifecycleState(String(target.lifecycle))) {
2252
+ findings.push({ severity: "error", target: at, message: `Unknown lifecycle state: ${target.lifecycle}` });
2253
+ }
2254
+ if (!target.locator) {
2255
+ findings.push({ severity: "warning", target: at, message: "Target has no locator \u2014 it may be ambiguous." });
2256
+ }
2257
+ for (const [env, state] of Object.entries(target.environments)) {
2258
+ if (!isValidEnvironmentState(String(state))) {
2259
+ findings.push({ severity: "error", target: at, message: `Unknown environment state for ${env}: ${state}` });
2260
+ }
2261
+ }
2262
+ const prodActive = target.environments.production === "active";
2263
+ if (target.lifecycle === "completed") {
2264
+ const stillActive = ENVIRONMENTS.filter((e) => target.environments[e] === "active");
2265
+ if (stillActive.length > 0) {
2266
+ findings.push({
2267
+ severity: "error",
2268
+ target: at,
2269
+ message: `Target is 'completed' but still active in: ${stillActive.join(", ")}.`
2270
+ });
2271
+ }
2272
+ }
2273
+ if ((target.lifecycle === "production-changed" || target.lifecycle === "observing") && prodActive) {
2274
+ findings.push({
2275
+ severity: "error",
2276
+ target: at,
2277
+ message: `Target is '${target.lifecycle}' but production is still 'active'.`
2278
+ });
2279
+ }
2280
+ return findings;
2281
+ }
2282
+ function validatePlan(plan) {
2283
+ const findings = [];
2284
+ const ids = new Set(plan.targets.map((t) => t.id));
2285
+ for (const t of plan.targets) {
2286
+ findings.push(...validateTarget(t));
2287
+ for (const dep of t.dependsOnRemoval) {
2288
+ if (!ids.has(dep)) {
2289
+ findings.push({
2290
+ severity: "error",
2291
+ target: t.id,
2292
+ message: `depends_on_removal references unknown target: ${dep}`
2293
+ });
2294
+ }
2295
+ if (dep === t.id) {
2296
+ findings.push({ severity: "error", target: t.id, message: "Target depends on its own removal." });
2297
+ }
2298
+ }
2299
+ }
2300
+ return findings;
2301
+ }
2302
+
2007
2303
  // src/core/graph.ts
2008
2304
  var KNOWLEDGE2 = "knowledge";
2009
2305
  var RESOURCE_ROLE_EDGE = {
@@ -2048,9 +2344,9 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
2048
2344
  ];
2049
2345
  const presentLayers = [];
2050
2346
  for (const layer of layerDocs) {
2051
- const path5 = layer.files.map((f) => `${KNOWLEDGE2}/${f}`).find((rel) => exists(join(dir, rel)));
2052
- if (path5) {
2053
- addNode({ id: layer.id, type: layer.type, label: layer.label, path: path5 });
2347
+ const path6 = layer.files.map((f) => `${KNOWLEDGE2}/${f}`).find((rel) => exists(join(dir, rel)));
2348
+ if (path6) {
2349
+ addNode({ id: layer.id, type: layer.type, label: layer.label, path: path6 });
2054
2350
  presentLayers.push(layer.id);
2055
2351
  }
2056
2352
  }
@@ -2108,6 +2404,33 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
2108
2404
  addEdge(modId, resId, "depends_on");
2109
2405
  }
2110
2406
  }
2407
+ for (const summary of getDeprecationPlans(dir)) {
2408
+ const plan = getDeprecationPlan(dir, summary.id);
2409
+ if (!plan) continue;
2410
+ const planId = `deprecation-plan:${plan.id}`;
2411
+ addNode({ id: planId, type: "deprecation-plan", label: `${plan.id} ${plan.title}`.trim(), path: plan.path, status: plan.status ?? void 0 });
2412
+ for (const target of plan.targets) {
2413
+ const targetId = `deprecation-target:${target.id}`;
2414
+ addNode({ id: targetId, type: "deprecation-target", label: target.title ? `${target.id} ${target.title}` : target.id, path: plan.path, status: target.lifecycle });
2415
+ addEdge(planId, targetId, "targets");
2416
+ if (target.module) {
2417
+ const moduleId = `module:${target.module}`;
2418
+ addNode({ id: moduleId, type: "module", label: target.module });
2419
+ addEdge(targetId, moduleId, "targets");
2420
+ }
2421
+ if (target.resource) {
2422
+ const resourceId = `resource:${target.resource}`;
2423
+ const title = resourceTitleById.get(target.resource);
2424
+ addNode({ id: resourceId, type: "project-resource", label: title ? `${target.resource} ${title}` : target.resource });
2425
+ addEdge(targetId, resourceId, "targets");
2426
+ }
2427
+ for (const dependency of target.dependsOnRemoval) {
2428
+ const dependencyId = `deprecation-target:${dependency}`;
2429
+ addNode({ id: dependencyId, type: "deprecation-target", label: dependency });
2430
+ addEdge(targetId, dependencyId, "depends_on_removal");
2431
+ }
2432
+ }
2433
+ }
2111
2434
  for (const wi of selectedWIs) {
2112
2435
  const id = wi.id || wi.title;
2113
2436
  if (!id || !id.trim()) continue;
@@ -2138,6 +2461,11 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
2138
2461
  addNode({ id: resId, type: "project-resource", label: title ? `${rel.id} ${title}`.trim() : rel.id });
2139
2462
  addEdge(wiNodeId, resId, RESOURCE_ROLE_EDGE[rel.role] ?? "uses");
2140
2463
  }
2464
+ for (const ref of parseWorkItemDeprecationTargets(wi.rawFrontmatter)) {
2465
+ const targetId = `deprecation-target:${ref.target}`;
2466
+ addNode({ id: targetId, type: "deprecation-target", label: ref.target });
2467
+ addEdge(wiNodeId, targetId, "targets");
2468
+ }
2141
2469
  for (const dec of wi.decisions) {
2142
2470
  if (!dec || !dec.trim()) continue;
2143
2471
  const adrId = `adr:${dec}`;
@@ -2412,7 +2740,7 @@ function loadGraphHints(dir) {
2412
2740
  }
2413
2741
 
2414
2742
  // src/services/installed-skills.ts
2415
- import matter5 from "gray-matter";
2743
+ import matter6 from "gray-matter";
2416
2744
  var SKILLS_DIR = join("knowledge", "skills");
2417
2745
  function discoverInstalledSkills(dir) {
2418
2746
  const base = join(dir, SKILLS_DIR);
@@ -2422,7 +2750,7 @@ function discoverInstalledSkills(dir) {
2422
2750
  const skillFile = join(base, entry, "skill.md");
2423
2751
  if (!isFile(skillFile)) continue;
2424
2752
  try {
2425
- const { data } = matter5(readFile(skillFile));
2753
+ const { data } = matter6(readFile(skillFile));
2426
2754
  if (data.type && String(data.type) !== "skill") continue;
2427
2755
  const id = String(data.id ?? entry);
2428
2756
  out.push({
@@ -3424,13 +3752,13 @@ function meaningful(text2) {
3424
3752
  });
3425
3753
  }
3426
3754
  function readPocSummary(dir) {
3427
- const path5 = join(dir, POC_ARTIFACT_PATH);
3428
- if (!exists(path5)) {
3755
+ const path6 = join(dir, POC_ARTIFACT_PATH);
3756
+ if (!exists(path6)) {
3429
3757
  return { exists: false, hypothesisDefined: false, successCriteriaCount: 0, constraintsDefined: false, nonGoalsDefined: false, conclusion: "pending" };
3430
3758
  }
3431
3759
  let markdown = "";
3432
3760
  try {
3433
- markdown = readFile(path5);
3761
+ markdown = readFile(path6);
3434
3762
  } catch {
3435
3763
  return { exists: false, hypothesisDefined: false, successCriteriaCount: 0, constraintsDefined: false, nonGoalsDefined: false, conclusion: "pending" };
3436
3764
  }
@@ -3449,7 +3777,7 @@ function readPocSummary(dir) {
3449
3777
 
3450
3778
  // src/core/poc-report.ts
3451
3779
  import { createHash } from "crypto";
3452
- import matter6 from "gray-matter";
3780
+ import matter7 from "gray-matter";
3453
3781
  var POC_REPORT_PREFIX = "poc-report-v";
3454
3782
  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;
3455
3783
  var reportName = /^poc-report-v(\d{3,})\.md$/;
@@ -3465,11 +3793,11 @@ function redactSecrets(value) {
3465
3793
  return line.replace(/([:=]\s*)\S+.*/, "$1[redacted]");
3466
3794
  }).join("\n");
3467
3795
  }
3468
- function source(dir, path5, kind) {
3469
- const absolute = join(dir, path5);
3796
+ function source(dir, path6, kind) {
3797
+ const absolute = join(dir, path6);
3470
3798
  if (!exists(absolute)) return null;
3471
3799
  const raw = readFile(absolute);
3472
- return { path: posix(path5), kind, digest: sha(raw), content: redactSecrets(raw) };
3800
+ return { path: posix(path6), kind, digest: sha(raw), content: redactSecrets(raw) };
3473
3801
  }
3474
3802
  function reportFiles(dir) {
3475
3803
  const delivery = join(dir, "knowledge", "delivery");
@@ -3477,7 +3805,7 @@ function reportFiles(dir) {
3477
3805
  const match = name.match(reportName);
3478
3806
  if (!match) return [];
3479
3807
  try {
3480
- const parsed = matter6(readFile(join(delivery, name)));
3808
+ const parsed = matter7(readFile(join(delivery, name)));
3481
3809
  const fingerprint = typeof parsed.data.source_fingerprint === "string" ? parsed.data.source_fingerprint : "";
3482
3810
  const manifest = parsed.data.source_manifest;
3483
3811
  const sourceManifest = manifest && typeof manifest === "object" && !Array.isArray(manifest) ? Object.fromEntries(Object.entries(manifest).filter(([, digest]) => typeof digest === "string")) : {};
@@ -3509,9 +3837,9 @@ function buildPocReportContext(dir) {
3509
3837
  };
3510
3838
  }
3511
3839
  const sources = [];
3512
- const add = (path5, kind) => {
3513
- if (sources.some((item2) => item2.path === posix(path5))) return;
3514
- const item = source(dir, path5, kind);
3840
+ const add = (path6, kind) => {
3841
+ if (sources.some((item2) => item2.path === posix(path6))) return;
3842
+ const item = source(dir, path6, kind);
3515
3843
  if (item) sources.push(item);
3516
3844
  };
3517
3845
  add(POC_ARTIFACT_PATH, "poc");
@@ -3539,7 +3867,7 @@ function buildPocReportContext(dir) {
3539
3867
  const sourceFingerprint = sha(sources.map((item) => `${item.path}\0${item.digest}`).join("\n"));
3540
3868
  const status = !latestReport ? "missing" : latestReport.sourceFingerprint === sourceFingerprint ? "current" : "stale";
3541
3869
  const currentManifest = Object.fromEntries(sources.map((item) => [item.path, item.digest]));
3542
- const changesSinceLatest = status === "stale" ? [.../* @__PURE__ */ new Set([...Object.keys(currentManifest), ...Object.keys(latestReport?.sourceManifest ?? {})])].filter((path5) => currentManifest[path5] !== latestReport?.sourceManifest[path5]).sort() : [];
3870
+ const changesSinceLatest = status === "stale" ? [.../* @__PURE__ */ new Set([...Object.keys(currentManifest), ...Object.keys(latestReport?.sourceManifest ?? {})])].filter((path6) => currentManifest[path6] !== latestReport?.sourceManifest[path6]).sort() : [];
3543
3871
  const sourceList = sources.map((item) => `- ${item.path} (${item.kind})`).join("\n") || "- No sources selected.";
3544
3872
  return {
3545
3873
  eligible: true,
@@ -3555,6 +3883,9 @@ function buildPocReportContext(dir) {
3555
3883
  `Canonical conclusion: ${poc.conclusion}. Do not contradict it.`,
3556
3884
  "Use the 15 canonical sections. Mark missing evidence as Not evaluated, Not applicable, or No evidence available.",
3557
3885
  "Distinguish measured, calculated, estimated, and projected values. Never include secret values.",
3886
+ "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.",
3887
+ "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.",
3888
+ "In Traceability, use repository-relative Markdown links or paths. Never use file:/// URLs or local absolute filesystem paths.",
3558
3889
  "",
3559
3890
  "Selected sources:",
3560
3891
  sourceList
@@ -3573,7 +3904,7 @@ function canonicalReport(context, proposal) {
3573
3904
  source_manifest: Object.fromEntries(context.sources.map((item) => [item.path, item.digest]))
3574
3905
  };
3575
3906
  if (supersedes) data.supersedes = supersedes;
3576
- return matter6.stringify(redactSecrets(proposal).trimEnd() + "\n", data);
3907
+ return matter7.stringify(redactSecrets(proposal).trimEnd() + "\n", data);
3577
3908
  }
3578
3909
  function persistPocReport(dir, proposal, opts = {}) {
3579
3910
  const context = buildPocReportContext(dir);
@@ -3712,10 +4043,10 @@ function resolveNextStep(dir, now = /* @__PURE__ */ new Date()) {
3712
4043
  const q = (rel) => analyzeKnowledgeArtifact(dir, rel);
3713
4044
  const resolveAgent = (agent) => {
3714
4045
  const file = agent.endsWith(".md") ? agent : `${agent}.md`;
3715
- const path5 = agentInstallPath(file);
3716
- const installed = isFile(join(dir, path5));
4046
+ const path6 = agentInstallPath(file);
4047
+ const installed = isFile(join(dir, path6));
3717
4048
  const group = agentGroupOf(file);
3718
- return { agentPath: path5, agentInstalled: installed, installCommand: installed ? void 0 : `kaddo add agents --group ${group}` };
4049
+ return { agentPath: path6, agentInstalled: installed, installCommand: installed ? void 0 : `kaddo add agents --group ${group}` };
3719
4050
  };
3720
4051
  const moduleRepo = isModule(config);
3721
4052
  const coreRepo = isCore(config);
@@ -4145,7 +4476,7 @@ function deriveDeliveryCompletedStatus(dir) {
4145
4476
  }
4146
4477
 
4147
4478
  // src/core/assets.ts
4148
- import matter7 from "gray-matter";
4479
+ import matter8 from "gray-matter";
4149
4480
 
4150
4481
  // src/core/version.ts
4151
4482
  import { fileURLToPath } from "url";
@@ -4846,6 +5177,49 @@ After a POC has a canonical conclusion and Core has prepared its deterministic r
4846
5177
  - Use \`Not evaluated in this POC.\`, \`Not applicable.\`, or \`No evidence available.\` when sources do not support a section.
4847
5178
  - Return a proposal for human review; Core persists it only after confirmation.
4848
5179
 
5180
+ ## Representation selection
5181
+
5182
+ - Use prose for context, interpretation, rationale, findings, and conclusions.
5183
+ - Use a Markdown table when supplied evidence has comparable rows, such as success criteria and
5184
+ outcomes, resources, experiments, measurements, costs, risks, recommendations, or traceability.
5185
+ - Use Mermaid only for architecture, topology, or flow relationships explicitly supported by the
5186
+ supplied sources. Prefer it to an ASCII diagram when both can represent the same grounded flow.
5187
+ - Tables and diagrams are communication tools, not completeness requirements. Do not produce one
5188
+ when the context does not support a useful representation.
5189
+ - Never invent table rows, diagram nodes or edges, statuses, priorities, metrics, or relationships
5190
+ to make a report look more complete.
5191
+ - Preserve measured, calculated, estimated, and projected semantics in every representation.
5192
+ - In Traceability, use repository-relative Markdown links or paths; never emit \`file:///\` URLs or
5193
+ local absolute filesystem paths.
5194
+
5195
+ ## Section representation guide
5196
+
5197
+ | Section | Preferred representation when supported by evidence |
5198
+ |---|---|
5199
+ | Executive Summary | Snapshot table and short prose |
5200
+ | Problem and Objective | Prose |
5201
+ | Hypothesis and Success Criteria | Evaluation matrix |
5202
+ | Scope, Constraints and Non-goals | Compact bullets or table |
5203
+ | Technical Approach and Architecture | Mermaid and prose |
5204
+ | Infrastructure and Project Resources | Table, with optional Mermaid |
5205
+ | Implementation and Relevant Technical Decisions | Table or concise prose |
5206
+ | Experiments and Validation | Validation matrix |
5207
+ | Results and Measurements | Measurement tables |
5208
+ | Cost and Efficiency Analysis | Comparison table |
5209
+ | Observability and Operational Findings | Table or prose |
5210
+ | Findings, Learnings, Limitations and Risks | Structured matrix |
5211
+ | Conclusion | Status and concise prose |
5212
+ | Recommendation and Next Steps | Recommendation matrix only when priority is evidenced |
5213
+ | Traceability and Sources | Relative-link table or list |
5214
+
5215
+ ## Quality checklist
5216
+
5217
+ - Structured evidence uses tables when clearer than prose.
5218
+ - Grounded architecture or flows use Mermaid when useful; no decorative or unsupported diagrams exist.
5219
+ - Tables and Mermaid preserve source grounding and measurement semantics.
5220
+ - Traceability contains repository-portable paths.
5221
+ - The report is scannable before reading the full narrative.
5222
+
4849
5223
  ## Required structure
4850
5224
 
4851
5225
  1. Executive Summary
@@ -7413,7 +7787,7 @@ function canonicalSkills() {
7413
7787
  }
7414
7788
  function versionOf(content) {
7415
7789
  try {
7416
- const v = matter7(content).data.version;
7790
+ const v = matter8(content).data.version;
7417
7791
  return v === void 0 || v === null ? null : String(v);
7418
7792
  } catch {
7419
7793
  return null;
@@ -8172,7 +8546,7 @@ function buildProjectRoute(dir) {
8172
8546
  }
8173
8547
 
8174
8548
  // src/core/metadata-health.ts
8175
- import matter8 from "gray-matter";
8549
+ import matter9 from "gray-matter";
8176
8550
  var KNOWLEDGE_FILES2 = [
8177
8551
  "knowledge/business/business.md",
8178
8552
  "knowledge/product/product.md",
@@ -8192,7 +8566,7 @@ function analyzeMetadataHealth(dir) {
8192
8566
  let data;
8193
8567
  try {
8194
8568
  const raw = readFile(p);
8195
- data = matter8(raw).data;
8569
+ data = matter9(raw).data;
8196
8570
  } catch {
8197
8571
  continue;
8198
8572
  }
@@ -8224,7 +8598,7 @@ function analyzeMetadataHealth(dir) {
8224
8598
  if (isFile(p) && entry.endsWith(".md")) {
8225
8599
  try {
8226
8600
  const raw = readFile(p);
8227
- const fm = matter8(raw).data;
8601
+ const fm = matter9(raw).data;
8228
8602
  if (fm.status === "done") {
8229
8603
  const rel = p.replace(dir + "/", "").replace(dir + "\\", "").replace(/\\/g, "/");
8230
8604
  findings.push({
@@ -8588,7 +8962,7 @@ function buildProjectExplanation(dir) {
8588
8962
  // src/core/resource-write.ts
8589
8963
  import fs2 from "fs";
8590
8964
  import path2 from "path";
8591
- import matter9 from "gray-matter";
8965
+ import matter10 from "gray-matter";
8592
8966
  var RESOURCES_DIR = "knowledge/tech/resources";
8593
8967
  var ResourceWriteError = class extends Error {
8594
8968
  constructor(code, message) {
@@ -8668,7 +9042,7 @@ function buildFrontmatter(id, input, base = {}) {
8668
9042
  return data;
8669
9043
  }
8670
9044
  function serialize(data, body) {
8671
- return matter9.stringify(`
9045
+ return matter10.stringify(`
8672
9046
  ${body.trim()}
8673
9047
  `, data);
8674
9048
  }
@@ -8708,7 +9082,7 @@ function updateResource(dir, id, input) {
8708
9082
  throw new ResourceWriteError("VALIDATION_FAILED", findings.filter((f) => f.level === "error").map((f) => f.message).join("; "));
8709
9083
  }
8710
9084
  const raw = readFile(match.filePath);
8711
- const parsed = matter9(raw);
9085
+ const parsed = matter10(raw);
8712
9086
  const base = parsed.data ?? {};
8713
9087
  const data = buildFrontmatter(match.id || id, input, base);
8714
9088
  let body = parsed.content.trim();
@@ -8979,7 +9353,7 @@ function analyzeCrossRepoEvidence(input) {
8979
9353
  }
8980
9354
 
8981
9355
  // src/core/work-items.ts
8982
- import matter10 from "gray-matter";
9356
+ import matter11 from "gray-matter";
8983
9357
 
8984
9358
  // src/core/system-topology.ts
8985
9359
  import { parse as parseYaml8, stringify as stringifyYaml5 } from "yaml";
@@ -9351,6 +9725,8 @@ function getWorkItem(dir, workItemId) {
9351
9725
  markdownBody: body.trim(),
9352
9726
  // External systems this WI relates to (WI-030), separate from affectedModules (code).
9353
9727
  resources: parseWorkItemResources(fm),
9728
+ // Deprecation Targets this WI retires (WI-050), referenced not copied.
9729
+ deprecationTargets: parseWorkItemDeprecationTargets(fm),
9354
9730
  ...parseSystemImpact(dir, fm)
9355
9731
  };
9356
9732
  return { ...detail, refinement: computeRefinementStatus(detail) };
@@ -9359,8 +9735,8 @@ function parseGraphReason(v) {
9359
9735
  if (!v || typeof v !== "object") return null;
9360
9736
  const o = v;
9361
9737
  const relationship = typeof o.relationship === "string" && o.relationship.trim() ? o.relationship.trim() : null;
9362
- const path5 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
9363
- return relationship || path5.length ? { relationship, path: path5 } : null;
9738
+ const path6 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
9739
+ return relationship || path6.length ? { relationship, path: path6 } : null;
9364
9740
  }
9365
9741
  function parseExplain(o) {
9366
9742
  const refs = Array.isArray(o.evidence) ? o.evidence : Array.isArray(o.evidence_refs) ? o.evidence_refs : [];
@@ -9415,7 +9791,7 @@ function parseOriginalSnapshot(fm) {
9415
9791
  function readBody(filePath) {
9416
9792
  try {
9417
9793
  const raw = readFile(filePath);
9418
- return matter10(raw).content;
9794
+ return matter11(raw).content;
9419
9795
  } catch {
9420
9796
  return "";
9421
9797
  }
@@ -9582,7 +9958,7 @@ function parseRelatedKnowledge(fm, knowledgeById) {
9582
9958
  import fs4 from "fs";
9583
9959
  import path4 from "path";
9584
9960
  import crypto2 from "crypto";
9585
- import matter11 from "gray-matter";
9961
+ import matter12 from "gray-matter";
9586
9962
 
9587
9963
  // src/core/knowledge-levels.ts
9588
9964
  var WORK_ITEM_TYPES2 = ["feature", "bugfix", "hotfix", "spike", "chore"];
@@ -9989,7 +10365,7 @@ function applyFrontmatter(data, input) {
9989
10365
  return next;
9990
10366
  }
9991
10367
  function serialize2(data, body) {
9992
- return matter11.stringify(`
10368
+ return matter12.stringify(`
9993
10369
  ${body.trim()}
9994
10370
  `, data);
9995
10371
  }
@@ -10048,7 +10424,7 @@ function toInput(data, content) {
10048
10424
  function getWorkItemForEdit(dir, id) {
10049
10425
  const { filePath, relPath } = findArtifact(dir, id);
10050
10426
  const raw = readFile(filePath);
10051
- const { data, content } = matter11(raw);
10427
+ const { data, content } = matter12(raw);
10052
10428
  const status = lifecycleStateOf({ status: String(data.status ?? ""), filePath });
10053
10429
  const input = toInput(data, content);
10054
10430
  const editable = EDITABLE_STATES.includes(status);
@@ -10141,7 +10517,7 @@ function updateWorkItem(dir, id, input, expectedRevision) {
10141
10517
  if (revisionOf(raw) !== expectedRevision) {
10142
10518
  throw new WorkItemWriteError("WORK_ITEM_CONFLICT", "This Work Item changed outside Kaddo Admin. Reload the latest version before saving.");
10143
10519
  }
10144
- const { data, content } = matter11(raw);
10520
+ const { data, content } = matter12(raw);
10145
10521
  const status = lifecycleStateOf({ status: String(data.status ?? ""), filePath });
10146
10522
  if (!EDITABLE_STATES.includes(status)) {
10147
10523
  throw new WorkItemWriteError("WORK_ITEM_NOT_EDITABLE", `A ${status} Work Item cannot be edited. Reopen it as Draft first.`);
@@ -10155,7 +10531,7 @@ function updateWorkItem(dir, id, input, expectedRevision) {
10155
10531
  function validateWorkItem(dir, id) {
10156
10532
  const { filePath } = findArtifact(dir, id);
10157
10533
  const raw = readFile(filePath);
10158
- const { data, content } = matter11(raw);
10534
+ const { data, content } = matter12(raw);
10159
10535
  const input = toInput(data, content);
10160
10536
  const findings = [];
10161
10537
  const modules = validModuleIds(dir);
@@ -10208,7 +10584,7 @@ function transitionWorkItem(dir, id, to, expectedRevision) {
10208
10584
  if (revisionOf(raw) !== expectedRevision) {
10209
10585
  throw new WorkItemWriteError("WORK_ITEM_CONFLICT", "This Work Item changed outside Kaddo Admin. Reload the latest version before continuing.");
10210
10586
  }
10211
- const { data, content } = matter11(raw);
10587
+ const { data, content } = matter12(raw);
10212
10588
  const from = lifecycleStateOf({ status: String(data.status ?? ""), filePath });
10213
10589
  if (!(ALLOWED[from] ?? []).includes(to)) {
10214
10590
  throw new WorkItemWriteError("INVALID_TRANSITION", `Cannot transition a ${from} Work Item to ${to}.`);
@@ -10474,16 +10850,16 @@ function findSystemPaths(dir, source2, target, opts = {}) {
10474
10850
  out.get(r.source).push(r.target);
10475
10851
  }
10476
10852
  const paths = [];
10477
- const walk = (node, path5) => {
10853
+ const walk = (node, path6) => {
10478
10854
  if (paths.length >= 20) return;
10479
- if (node === target && path5.length > 1) {
10480
- paths.push([...path5]);
10855
+ if (node === target && path6.length > 1) {
10856
+ paths.push([...path6]);
10481
10857
  return;
10482
10858
  }
10483
- if (path5.length > maxDepth) return;
10859
+ if (path6.length > maxDepth) return;
10484
10860
  for (const nxt of out.get(node) ?? []) {
10485
- if (path5.includes(nxt)) continue;
10486
- walk(nxt, [...path5, nxt]);
10861
+ if (path6.includes(nxt)) continue;
10862
+ walk(nxt, [...path6, nxt]);
10487
10863
  }
10488
10864
  };
10489
10865
  walk(source2, [source2]);
@@ -10508,14 +10884,14 @@ function getImpactCandidates(dir, seedIds, opts = {}) {
10508
10884
  existing.reason.push(reason);
10509
10885
  continue;
10510
10886
  }
10511
- const path5 = findSystemPaths(dir, seed, n.id, { maxDepth: opts.maxDepth ?? DEFAULT_MAX_DEPTH })[0];
10887
+ const path6 = findSystemPaths(dir, seed, n.id, { maxDepth: opts.maxDepth ?? DEFAULT_MAX_DEPTH })[0];
10512
10888
  candidates.set(n.id, {
10513
10889
  nodeId: n.id,
10514
10890
  label: n.label,
10515
10891
  kind: n.type,
10516
10892
  ...n.moduleId ? { moduleId: n.moduleId } : {},
10517
10893
  reason: [reason],
10518
- ...path5 ? { graphPath: path5.map((id) => byId.get(id)?.label ?? id) } : {},
10894
+ ...path6 ? { graphPath: path6.map((id) => byId.get(id)?.label ?? id) } : {},
10519
10895
  ...n.implementationRefs?.length ? { implementationRefs: n.implementationRefs } : {},
10520
10896
  ...n.knowledgeRefs?.length ? { knowledgeRefs: n.knowledgeRefs } : {},
10521
10897
  status: "candidate",
@@ -10675,6 +11051,235 @@ function buildRefinementHandoff(dir, workItemId) {
10675
11051
  };
10676
11052
  }
10677
11053
 
11054
+ // src/core/deprecation-observation.ts
11055
+ var DAY_MS = 24 * 60 * 60 * 1e3;
11056
+ function addDaysIso(startIso, days) {
11057
+ const start = Date.parse(startIso);
11058
+ if (Number.isNaN(start)) return null;
11059
+ return new Date(start + days * DAY_MS).toISOString().slice(0, 10);
11060
+ }
11061
+ function observationStatus(target, now = /* @__PURE__ */ new Date()) {
11062
+ const sd = target.softDeprecation;
11063
+ const reasons = [];
11064
+ if (!sd) {
11065
+ return {
11066
+ declared: false,
11067
+ windowElapsed: false,
11068
+ windowEndsAt: null,
11069
+ criteriaTotal: 0,
11070
+ criteriaMet: 0,
11071
+ allCriteriaMet: false,
11072
+ eligibleForRemovalReview: false,
11073
+ reasons: ["No soft-deprecation/observation window declared \u2014 not eligible for removal review."]
11074
+ };
11075
+ }
11076
+ const criteriaTotal = sd.exitCriteria.length;
11077
+ const criteriaMet = sd.exitCriteria.filter((c) => c.met).length;
11078
+ const allCriteriaMet = criteriaTotal > 0 && criteriaMet === criteriaTotal;
11079
+ let windowElapsed = false;
11080
+ let windowEndsAt = null;
11081
+ if (sd.startedAt && sd.observationWindowDays != null) {
11082
+ windowEndsAt = addDaysIso(sd.startedAt, sd.observationWindowDays);
11083
+ if (windowEndsAt) {
11084
+ windowElapsed = now.getTime() >= Date.parse(windowEndsAt);
11085
+ }
11086
+ }
11087
+ if (!sd.startedAt) reasons.push("Observation has not started (no started_at).");
11088
+ else if (sd.observationWindowDays == null) reasons.push("No observation_window_days declared.");
11089
+ else if (!windowElapsed) reasons.push(`Observation window not elapsed (ends ${windowEndsAt ?? "unknown"}).`);
11090
+ if (criteriaTotal === 0) reasons.push("No exit criteria declared.");
11091
+ else if (!allCriteriaMet) reasons.push(`Exit criteria not all met (${criteriaMet}/${criteriaTotal}).`);
11092
+ const eligibleForRemovalReview = windowElapsed && allCriteriaMet;
11093
+ if (eligibleForRemovalReview) {
11094
+ reasons.length = 0;
11095
+ reasons.push("Observation window elapsed and all exit criteria met \u2014 eligible for removal REVIEW (human decision).");
11096
+ }
11097
+ return {
11098
+ declared: true,
11099
+ windowElapsed,
11100
+ windowEndsAt,
11101
+ criteriaTotal,
11102
+ criteriaMet,
11103
+ allCriteriaMet,
11104
+ eligibleForRemovalReview,
11105
+ reasons
11106
+ };
11107
+ }
11108
+ function targetsPastObservation(plan, now = /* @__PURE__ */ new Date()) {
11109
+ return plan.targets.filter((t) => observationStatus(t, now).eligibleForRemovalReview).map((t) => t.id);
11110
+ }
11111
+ function isRetainedOutcome(target) {
11112
+ return String(target.lifecycle) === "deprecated-retained";
11113
+ }
11114
+ function environmentSummary(target) {
11115
+ const perEnvironment = {};
11116
+ for (const env of ENVIRONMENTS) perEnvironment[env] = String(target.environments[env] ?? "active");
11117
+ return {
11118
+ perEnvironment,
11119
+ removedInDevTest: perEnvironment.development === "removed" && perEnvironment.test === "removed",
11120
+ productionActive: perEnvironment.production === "active"
11121
+ };
11122
+ }
11123
+
11124
+ // src/core/deprecation-intelligence.ts
11125
+ function isStrongNoUsage(sig) {
11126
+ return sig.status === "no-usage" && (sig.quality === "observed-fact" || sig.quality === "human-confirmed");
11127
+ }
11128
+ function deriveUnusedConfidence(evidence) {
11129
+ const present = EVIDENCE_SIGNALS.map((name) => ({ name, sig: evidence[name] })).filter(
11130
+ (e) => Boolean(e.sig)
11131
+ );
11132
+ const usageFound = present.filter((e) => e.sig.status === "usage-found");
11133
+ if (usageFound.length > 0) {
11134
+ return {
11135
+ confidence: "in-use",
11136
+ requiresHumanConfirmation: false,
11137
+ rationale: [`Usage found via: ${usageFound.map((e) => e.name).join(", ")}.`]
11138
+ };
11139
+ }
11140
+ const strong = present.filter((e) => isStrongNoUsage(e.sig));
11141
+ const unknown = present.filter((e) => e.sig.status === "unknown");
11142
+ const notEvaluated = EVIDENCE_SIGNALS.filter(
11143
+ (name) => !evidence[name] || evidence[name]?.status === "not-evaluated"
11144
+ );
11145
+ const rationale = [];
11146
+ if (strong.length > 0) rationale.push(`No usage observed via: ${strong.map((e) => e.name).join(", ")}.`);
11147
+ if (unknown.length > 0) {
11148
+ rationale.push(`Unknown (looked but could not determine): ${unknown.map((e) => e.name).join(", ")} \u2014 NOT treated as no-usage.`);
11149
+ }
11150
+ if (notEvaluated.length > 0) {
11151
+ rationale.push(`Not evaluated: ${notEvaluated.join(", ")} \u2014 absence of a reference is not evidence of no usage.`);
11152
+ }
11153
+ let confidence;
11154
+ if (strong.length === 0) {
11155
+ confidence = "insufficient-evidence";
11156
+ } else if (unknown.length > 0) {
11157
+ confidence = "medium";
11158
+ } else if (strong.length >= 2) {
11159
+ confidence = "high";
11160
+ } else {
11161
+ confidence = "medium";
11162
+ }
11163
+ return { confidence, requiresHumanConfirmation: true, rationale };
11164
+ }
11165
+ function deriveRemovalWaves(plan) {
11166
+ const ids = new Set(plan.targets.map((t) => t.id));
11167
+ const deps = /* @__PURE__ */ new Map();
11168
+ const blocked = [];
11169
+ for (const t of plan.targets) {
11170
+ const resolved = [];
11171
+ for (const d of t.dependsOnRemoval) {
11172
+ if (d === t.id) {
11173
+ blocked.push({ target: t.id, reason: "Target depends on its own removal." });
11174
+ continue;
11175
+ }
11176
+ if (!ids.has(d)) {
11177
+ blocked.push({ target: t.id, reason: `depends_on_removal references unknown target: ${d}.` });
11178
+ continue;
11179
+ }
11180
+ resolved.push(d);
11181
+ }
11182
+ deps.set(t.id, resolved);
11183
+ }
11184
+ const placed = /* @__PURE__ */ new Set();
11185
+ const waves = [];
11186
+ let remaining = plan.targets.map((t) => t.id);
11187
+ while (remaining.length > 0) {
11188
+ const wave = remaining.filter((id) => (deps.get(id) ?? []).every((d) => placed.has(d)));
11189
+ if (wave.length === 0) break;
11190
+ for (const id of wave) placed.add(id);
11191
+ waves.push(wave);
11192
+ remaining = remaining.filter((id) => !placed.has(id));
11193
+ }
11194
+ for (const id of remaining) {
11195
+ blocked.push({ target: id, reason: "Involved in a removal dependency cycle \u2014 cannot be ordered." });
11196
+ }
11197
+ return { waves, blocked };
11198
+ }
11199
+ var RETIRED_STATES = /* @__PURE__ */ new Set([
11200
+ "removed-devtest",
11201
+ "production-changed",
11202
+ "observing",
11203
+ "completed",
11204
+ "deprecated-retained"
11205
+ ]);
11206
+ function isRetiredLifecycle(state) {
11207
+ return RETIRED_STATES.has(state);
11208
+ }
11209
+ function targetsEligibleForRemoval(plan) {
11210
+ const byId = new Map(plan.targets.map((t) => [t.id, t]));
11211
+ return plan.targets.filter((t) => !isRetiredLifecycle(String(t.lifecycle))).filter(
11212
+ (t) => t.dependsOnRemoval.every((d) => {
11213
+ const dep = byId.get(d);
11214
+ return dep ? isRetiredLifecycle(String(dep.lifecycle)) : false;
11215
+ })
11216
+ ).map((t) => t.id);
11217
+ }
11218
+ function planIntelligence(plan) {
11219
+ const waves = deriveRemovalWaves(plan);
11220
+ const eligible = new Set(targetsEligibleForRemoval(plan));
11221
+ const byId = new Map(plan.targets.map((t) => [t.id, t]));
11222
+ const targets = plan.targets.map((t) => ({
11223
+ id: t.id,
11224
+ unused: deriveUnusedConfidence(t.usageEvidence),
11225
+ eligibleForRemovalReview: eligible.has(t.id),
11226
+ blockedBy: t.dependsOnRemoval.filter((d) => {
11227
+ const dep = byId.get(d);
11228
+ return !dep || !isRetiredLifecycle(String(dep.lifecycle));
11229
+ }),
11230
+ observation: observationStatus(t)
11231
+ }));
11232
+ return { waves, eligible: [...eligible], targets };
11233
+ }
11234
+ function proposeWorkItemCandidates(plan) {
11235
+ const { waves } = deriveRemovalWaves(plan);
11236
+ const byId = new Map(plan.targets.map((t) => [t.id, t]));
11237
+ const candidates = [];
11238
+ waves.forEach((waveIds, waveIndex) => {
11239
+ const wave = waveIndex + 1;
11240
+ const groups = /* @__PURE__ */ new Map();
11241
+ for (const id of waveIds) {
11242
+ const t = byId.get(id);
11243
+ if (!t) continue;
11244
+ const key = t.module;
11245
+ const list2 = groups.get(key) ?? [];
11246
+ list2.push(t);
11247
+ groups.set(key, list2);
11248
+ }
11249
+ const keys = [...groups.keys()].sort((a, b) => {
11250
+ if (a === null) return 1;
11251
+ if (b === null) return -1;
11252
+ return a.localeCompare(b);
11253
+ });
11254
+ for (const key of keys) {
11255
+ const targets = groups.get(key);
11256
+ const resources = [...new Set(targets.map((t) => t.resource).filter((r) => Boolean(r)))];
11257
+ candidates.push({
11258
+ wave,
11259
+ module: key,
11260
+ title: `${plan.id} wave ${wave}${key ? ` (${key})` : ""}: retire ${targets.map((t) => t.id).join(", ")}`,
11261
+ deprecationTargets: targets.map((t) => t.id),
11262
+ resources
11263
+ });
11264
+ }
11265
+ });
11266
+ return candidates;
11267
+ }
11268
+ var CANDIDATE_DISCOVERY_GUIDANCE = [
11269
+ "Propose deprecation candidates from multiple sources: static references (code/routes/UI/jobs),",
11270
+ "the System Graph (dependencies and blast radius), Legacy Knowledge (risks/unknowns/modernization",
11271
+ "candidates), Project Resources (databases/external systems and their boundaries), runtime evidence",
11272
+ "when telemetry exists, and database metadata when reachable.",
11273
+ "",
11274
+ "Rules:",
11275
+ "- Discovery is a PROPOSAL, not a materialization: never create or retire anything automatically.",
11276
+ "- Always explain WHY something is a candidate, citing the signal(s) observed.",
11277
+ "- Absence of a reference is NOT evidence of no usage. If a source cannot be evaluated, record it",
11278
+ " as not-evaluated/unknown and require human investigation \u2014 never collapse it to no-usage.",
11279
+ "- A modernization candidate is not automatically a deprecation target.",
11280
+ "- Soft deprecation precedes physical removal; order retirements by dependency, dependents first."
11281
+ ].join("\n");
11282
+
10678
11283
  // src/core/implementation-handoff.ts
10679
11284
  var WorkItemNotReadyError = class extends Error {
10680
11285
  constructor(workItemId, actualState) {
@@ -10706,6 +11311,16 @@ function buildImplementationHandoff(dir, workItemId) {
10706
11311
  const domains = match.domains;
10707
11312
  const scopeConfidence = match.scopeConfidence;
10708
11313
  const wiResources = parseWorkItemResources(match.rawFrontmatter);
11314
+ const wiDeprecationRefs = parseWorkItemDeprecationTargets(match.rawFrontmatter);
11315
+ const resolveTarget = (ref) => {
11316
+ const plans = ref.plan ? [getDeprecationPlan(dir, ref.plan)].filter(Boolean) : getDeprecationPlans(dir).map((p) => getDeprecationPlan(dir, p.id));
11317
+ for (const p of plans) {
11318
+ if (!p) continue;
11319
+ const t = p.targets.find((x) => x.id.toUpperCase() === ref.target.toUpperCase());
11320
+ if (t) return { planId: p.id, target: t };
11321
+ }
11322
+ return null;
11323
+ };
10709
11324
  const lines = [
10710
11325
  `Implement Work Item ${wiId} \u2014 "${wiTitle}" \u2014 in project "${projectName}" using Kaddo.`,
10711
11326
  "",
@@ -10830,6 +11445,48 @@ function buildImplementationHandoff(dir, workItemId) {
10830
11445
  "installed or connected. Do not execute any interface or migration without explicit human confirmation."
10831
11446
  );
10832
11447
  }
11448
+ if (wiDeprecationRefs.length > 0) {
11449
+ lines.push(
11450
+ "",
11451
+ "--- Relevant Deprecation Targets ---",
11452
+ "",
11453
+ "This Work Item is part of a Controlled Deprecation plan. It RETIRES the targets below. Soft",
11454
+ "deprecation precedes physical removal; in Dev/Test you may remove code/endpoints/dev-test data",
11455
+ "when the resource boundary allows and there is confirmation. A production change needs a Runbook",
11456
+ "and explicit human approval \u2014 never execute a destructive production operation autonomously."
11457
+ );
11458
+ for (const ref of wiDeprecationRefs) {
11459
+ const resolved = resolveTarget(ref);
11460
+ if (!resolved) {
11461
+ lines.push("", `- ${ref.target}${ref.plan ? ` (plan ${ref.plan})` : ""} \u2014 target not found in any Deprecation Plan.`);
11462
+ continue;
11463
+ }
11464
+ const { planId, target: t } = resolved;
11465
+ lines.push("", `- ${t.id} [${t.type}] \u2014 plan ${planId}, lifecycle: ${t.lifecycle}`);
11466
+ if (t.locator) lines.push(` locator: ${t.locator}`);
11467
+ const envs = Object.entries(t.environments).map(([e, s]) => `${e}=${s}`).join(" ");
11468
+ if (envs) lines.push(` environments: ${envs}`);
11469
+ const unused = deriveUnusedConfidence(t.usageEvidence);
11470
+ lines.push(` unused confidence: ${unused.confidence}${unused.requiresHumanConfirmation ? " (human confirmation required)" : ""}`);
11471
+ if (t.assessment.blastRadius) lines.push(` blast radius: ${t.assessment.blastRadius}`);
11472
+ if (t.assessment.reversibility) lines.push(` reversibility: ${t.assessment.reversibility}`);
11473
+ if (t.dependsOnRemoval.length > 0) lines.push(` depends_on_removal: ${t.dependsOnRemoval.join(", ")} (retire these first)`);
11474
+ if (t.resource) {
11475
+ const res = getResource(dir, t.resource);
11476
+ if (res) {
11477
+ const bounds = Object.entries(res.boundaries).map(([env, ops]) => `${env}: ${ops.join("/")}`).join(" \xB7 ");
11478
+ lines.push(` resource: ${res.id} \u2014 ${res.title}${bounds ? ` (boundaries \u2014 ${bounds})` : ""}`);
11479
+ } else {
11480
+ lines.push(` resource: ${t.resource} \u2014 definition not found under knowledge/tech/resources/.`);
11481
+ }
11482
+ }
11483
+ }
11484
+ lines.push(
11485
+ "",
11486
+ "Record what you actually retired as Evidence. Prepare a rollback for every change; for production,",
11487
+ "the rollback/abort path lives in the Runbook, not here."
11488
+ );
11489
+ }
10833
11490
  lines.push(
10834
11491
  "",
10835
11492
  "--- Implementation Plan ---",
@@ -10851,6 +11508,7 @@ function buildImplementationHandoff(dir, workItemId) {
10851
11508
  lifecycle,
10852
11509
  affectedModules,
10853
11510
  resources: wiResources,
11511
+ deprecationTargets: wiDeprecationRefs,
10854
11512
  domains,
10855
11513
  scopeConfidence,
10856
11514
  hasUnmaterializedDecisions: unmaterialized,
@@ -11087,7 +11745,7 @@ function deriveImplementationStatus(repos) {
11087
11745
  // src/core/work-item-import.ts
11088
11746
  import crypto3 from "crypto";
11089
11747
  import fs5 from "fs";
11090
- import matter12 from "gray-matter";
11748
+ import matter13 from "gray-matter";
11091
11749
  var MAX_INPUT_BYTES = 102400;
11092
11750
  var LIFECYCLE_FIELDS = /* @__PURE__ */ new Set([
11093
11751
  "id",
@@ -11109,7 +11767,7 @@ function detectFormat(raw) {
11109
11767
  if (!trimmed) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
11110
11768
  if (trimmed.startsWith("---")) {
11111
11769
  try {
11112
- const { data } = matter12(trimmed);
11770
+ const { data } = matter13(trimmed);
11113
11771
  if (data && typeof data === "object" && Object.keys(data).length > 0) {
11114
11772
  const d = data;
11115
11773
  if (d.type === "work-item" || d.id && typeof d.id === "string" && /^WI-\d+/.test(d.id)) {
@@ -11131,7 +11789,7 @@ function parseContent(raw) {
11131
11789
  let bodyText = trimmed;
11132
11790
  if (format === "kaddo-frontmatter" || format === "markdown-frontmatter") {
11133
11791
  try {
11134
- const parsed = matter12(trimmed);
11792
+ const parsed = matter13(trimmed);
11135
11793
  frontmatterFields = parsed.data ?? {};
11136
11794
  bodyText = parsed.content.trim();
11137
11795
  } catch {
@@ -11228,7 +11886,7 @@ function findDuplicateByHash(dir, hash) {
11228
11886
  const raw = readFile(item.filePath);
11229
11887
  if (!raw) continue;
11230
11888
  try {
11231
- const { data } = matter12(raw);
11889
+ const { data } = matter13(raw);
11232
11890
  const source2 = data?.source;
11233
11891
  if (source2 && typeof source2 === "object" && !Array.isArray(source2)) {
11234
11892
  const s = source2;
@@ -11337,7 +11995,7 @@ var ImportError = class extends Error {
11337
11995
  };
11338
11996
 
11339
11997
  // src/services/integrations.ts
11340
- import matter13 from "gray-matter";
11998
+ import matter14 from "gray-matter";
11341
11999
  import { parse as parseYaml9, stringify as stringifyYaml6 } from "yaml";
11342
12000
 
11343
12001
  // ../integrations/src/errors.ts
@@ -12106,8 +12764,8 @@ async function handleJiraResponse(res) {
12106
12764
  }
12107
12765
  return await res.json();
12108
12766
  }
12109
- async function jiraFetch(baseUrl, path5, auth, timeoutMs, params) {
12110
- const url = new URL(path5, baseUrl + "/");
12767
+ async function jiraFetch(baseUrl, path6, auth, timeoutMs, params) {
12768
+ const url = new URL(path6, baseUrl + "/");
12111
12769
  if (params) for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
12112
12770
  const controller = new AbortController();
12113
12771
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -12125,8 +12783,8 @@ async function jiraFetch(baseUrl, path5, auth, timeoutMs, params) {
12125
12783
  clearTimeout(timer);
12126
12784
  }
12127
12785
  }
12128
- async function jiraPost(baseUrl, path5, auth, timeoutMs, body) {
12129
- const url = new URL(path5, baseUrl + "/");
12786
+ async function jiraPost(baseUrl, path6, auth, timeoutMs, body) {
12787
+ const url = new URL(path6, baseUrl + "/");
12130
12788
  const controller = new AbortController();
12131
12789
  const timer = setTimeout(() => controller.abort(), timeoutMs);
12132
12790
  try {
@@ -12679,7 +13337,7 @@ function findLinkedWorkItem(dir, integrationId, externalId) {
12679
13337
  for (const art of discoverWorkItems(dir)) {
12680
13338
  let data;
12681
13339
  try {
12682
- data = matter13(readFile(art.filePath)).data;
13340
+ data = matter14(readFile(art.filePath)).data;
12683
13341
  } catch {
12684
13342
  continue;
12685
13343
  }
@@ -12695,7 +13353,7 @@ function buildImportIndex(dir) {
12695
13353
  for (const art of discoverWorkItems(dir)) {
12696
13354
  let data;
12697
13355
  try {
12698
- data = matter13(readFile(art.filePath)).data;
13356
+ data = matter14(readFile(art.filePath)).data;
12699
13357
  } catch {
12700
13358
  continue;
12701
13359
  }
@@ -12871,7 +13529,7 @@ function getStatus(dir) {
12871
13529
  }
12872
13530
 
12873
13531
  // src/core/initiative-write.ts
12874
- import matter14 from "gray-matter";
13532
+ import matter15 from "gray-matter";
12875
13533
  var WORK_ITEMS_DIR2 = "knowledge/delivery/work-items";
12876
13534
  var DRAFT_DIR = `${WORK_ITEMS_DIR2}/draft`;
12877
13535
  var ROADMAP_PATH2 = "knowledge/delivery/roadmap.md";
@@ -12984,7 +13642,7 @@ function buildInitiativeContent(id, input) {
12984
13642
  if (input.priority) data.priority = input.priority;
12985
13643
  if (input.source) data.source = input.source;
12986
13644
  if (input.sourceId) data.source_id = input.sourceId;
12987
- return matter14.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
13645
+ return matter15.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
12988
13646
  }
12989
13647
  function createInitiative(dir, input) {
12990
13648
  if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
@@ -13008,10 +13666,10 @@ function transitionInitiative(dir, id, to) {
13008
13666
  throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
13009
13667
  }
13010
13668
  const raw = readFile(ini.filePath);
13011
- const { data, content } = matter14(raw, {});
13669
+ const { data, content } = matter15(raw, {});
13012
13670
  data.status = to;
13013
13671
  if (to === "completed") data.completed_at = today();
13014
- const newContent = matter14.stringify(content, data);
13672
+ const newContent = matter15.stringify(content, data);
13015
13673
  writeFile(ini.filePath, newContent);
13016
13674
  const updated = parseInitiative(dir, ini.filePath, newContent);
13017
13675
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
@@ -13021,7 +13679,7 @@ function addCandidate(dir, id, candidate) {
13021
13679
  const ini = getInitiative(dir, id);
13022
13680
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
13023
13681
  const raw = readFile(ini.filePath);
13024
- const { data, content } = matter14(raw, {});
13682
+ const { data, content } = matter15(raw, {});
13025
13683
  const existing = Array.isArray(data.candidates) ? data.candidates : [];
13026
13684
  const fallbackId = `WI-CANDIDATE-${String(existing.length + 1).padStart(3, "0")}`;
13027
13685
  const normalized = normalizeCandidate(candidate, fallbackId);
@@ -13029,7 +13687,7 @@ function addCandidate(dir, id, candidate) {
13029
13687
  throw new InitiativeWriteError(`Candidate ${normalized.id} already exists in ${id}.`);
13030
13688
  }
13031
13689
  data.candidates = [...existing, candidateToData(normalized)];
13032
- const newContent = matter14.stringify(content, data);
13690
+ const newContent = matter15.stringify(content, data);
13033
13691
  writeFile(ini.filePath, newContent);
13034
13692
  const updated = parseInitiative(dir, ini.filePath, newContent);
13035
13693
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding a candidate.");
@@ -13039,7 +13697,7 @@ function updateInitiative(dir, id, patch) {
13039
13697
  const ini = getInitiative(dir, id);
13040
13698
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
13041
13699
  const raw = readFile(ini.filePath);
13042
- const { data, content } = matter14(raw, {});
13700
+ const { data, content } = matter15(raw, {});
13043
13701
  if (patch.title !== void 0) {
13044
13702
  if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
13045
13703
  data.title = patch.title.trim();
@@ -13049,7 +13707,7 @@ function updateInitiative(dir, id, patch) {
13049
13707
  if (patch.knowledgeLevel !== void 0) data.knowledge_level = patch.knowledgeLevel;
13050
13708
  if (patch.domains !== void 0) data.domains = patch.domains;
13051
13709
  if (patch.relatedCapabilities !== void 0) data.related_capabilities = patch.relatedCapabilities;
13052
- const newContent = matter14.stringify(content, data);
13710
+ const newContent = matter15.stringify(content, data);
13053
13711
  writeFile(ini.filePath, newContent);
13054
13712
  const updated = parseInitiative(dir, ini.filePath, newContent);
13055
13713
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after update.");
@@ -13067,10 +13725,10 @@ function addExternalLink(dir, id, link) {
13067
13725
  throw new InitiativeWriteError(`External link ${link.integration}:${link.externalId} already exists on ${id}.`);
13068
13726
  }
13069
13727
  const raw = readFile(ini.filePath);
13070
- const { data, content } = matter14(raw, {});
13728
+ const { data, content } = matter15(raw, {});
13071
13729
  const existing = Array.isArray(data.external_links) ? data.external_links : [];
13072
13730
  data.external_links = [...existing, externalLinkToData(link)];
13073
- const newContent = matter14.stringify(content, data);
13731
+ const newContent = matter15.stringify(content, data);
13074
13732
  writeFile(ini.filePath, newContent);
13075
13733
  const updated = parseInitiative(dir, ini.filePath, newContent);
13076
13734
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding an external link.");
@@ -13139,7 +13797,7 @@ function buildWorkItemContent(wiId, iniId, candidate) {
13139
13797
  "_What did we learn? Update after completion._",
13140
13798
  ""
13141
13799
  ].join("\n");
13142
- return matter14.stringify("\n" + body, data);
13800
+ return matter15.stringify("\n" + body, data);
13143
13801
  }
13144
13802
  function materializeCandidate(dir, id, candidateId) {
13145
13803
  const ini = getInitiative(dir, id);
@@ -13156,13 +13814,13 @@ function materializeCandidate(dir, id, candidateId) {
13156
13814
  ensureDir(join(dir, DRAFT_DIR));
13157
13815
  writeFile(join(dir, DRAFT_DIR, fileName), buildWorkItemContent(wiId, ini.id, candidate));
13158
13816
  const raw = readFile(ini.filePath);
13159
- const { data, content } = matter14(raw, {});
13817
+ const { data, content } = matter15(raw, {});
13160
13818
  const cands = Array.isArray(data.candidates) ? data.candidates : [];
13161
13819
  for (const c of cands) {
13162
13820
  if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
13163
13821
  }
13164
13822
  data.candidates = cands;
13165
- const newContent = matter14.stringify(content, data);
13823
+ const newContent = matter15.stringify(content, data);
13166
13824
  writeFile(ini.filePath, newContent);
13167
13825
  const updated = parseInitiative(dir, ini.filePath, newContent);
13168
13826
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
@@ -13309,8 +13967,424 @@ function evaluateInitiativeCompletion(dir, ini) {
13309
13967
  reasons
13310
13968
  };
13311
13969
  }
13970
+
13971
+ // src/core/deprecation-write.ts
13972
+ import fs6 from "fs";
13973
+ import path5 from "path";
13974
+ import matter16 from "gray-matter";
13975
+ var DeprecationWriteError = class extends Error {
13976
+ constructor(code, message) {
13977
+ super(message);
13978
+ this.code = code;
13979
+ this.name = "DeprecationWriteError";
13980
+ }
13981
+ code;
13982
+ };
13983
+ function slug4(s) {
13984
+ return s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
13985
+ }
13986
+ function atomicWrite4(filePath, content) {
13987
+ const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
13988
+ fs6.writeFileSync(tmp, content, "utf-8");
13989
+ fs6.renameSync(tmp, filePath);
13990
+ }
13991
+ function serialize3(data, body) {
13992
+ return matter16.stringify(`
13993
+ ${body.trim()}
13994
+ `, data);
13995
+ }
13996
+ function allPlanArtifacts(dir) {
13997
+ return discoverKnowledge(dir).filter((a) => a.type === DEPRECATION_ARTIFACT_TYPE);
13998
+ }
13999
+ function nextPlanId(dir, explicit) {
14000
+ if (explicit && explicit.trim()) return explicit.trim();
14001
+ let max = 0;
14002
+ for (const a of allPlanArtifacts(dir)) {
14003
+ const m = (a.id || "").match(/^DEP-(\d+)$/i);
14004
+ if (m) max = Math.max(max, parseInt(m[1], 10));
14005
+ }
14006
+ return `DEP-${String(max + 1).padStart(3, "0")}`;
14007
+ }
14008
+ function nextTargetId(targetIds) {
14009
+ let max = 0;
14010
+ for (const id of targetIds) {
14011
+ const m = id.match(/^DEP-TGT-(\d+)$/i);
14012
+ if (m) max = Math.max(max, parseInt(m[1], 10));
14013
+ }
14014
+ return `DEP-TGT-${String(max + 1).padStart(3, "0")}`;
14015
+ }
14016
+ function buildTargetRaw(input, base = {}) {
14017
+ const out = { ...base };
14018
+ if (input.id != null) out.id = input.id;
14019
+ if (input.type != null) out.type = input.type;
14020
+ if (input.locator != null) out.locator = input.locator;
14021
+ if (input.title != null) out.title = input.title;
14022
+ if (input.lifecycle != null) out.lifecycle = input.lifecycle;
14023
+ if (input.environments != null) out.environments = input.environments;
14024
+ if (input.assessment != null) {
14025
+ const a = { ...typeof base.assessment === "object" && base.assessment ? base.assessment : {} };
14026
+ if (input.assessment.unusedConfidence != null) a.unused_confidence = input.assessment.unusedConfidence;
14027
+ if (input.assessment.blastRadius != null) a.blast_radius = input.assessment.blastRadius;
14028
+ if (input.assessment.reversibility != null) a.reversibility = input.assessment.reversibility;
14029
+ out.assessment = a;
14030
+ }
14031
+ if (input.dependsOnRemoval != null) out.depends_on_removal = input.dependsOnRemoval;
14032
+ if (input.resource != null) out.resource = input.resource;
14033
+ if (input.module != null) out.module = input.module;
14034
+ return out;
14035
+ }
14036
+ function validateTargetInput(dir, raw) {
14037
+ const findings = [];
14038
+ const parsed = parseTarget(raw);
14039
+ if (!parsed) {
14040
+ findings.push({ level: "error", message: "A target id is required." });
14041
+ return findings;
14042
+ }
14043
+ for (const f of validateTarget(parsed)) {
14044
+ findings.push({ level: f.severity === "error" ? "error" : "warning", message: f.message });
14045
+ }
14046
+ const mapped = loadMappedModules(dir).map((m) => m.id);
14047
+ if (parsed.module && mapped.length > 0 && !mapped.includes(parsed.module)) {
14048
+ findings.push({ level: "warning", message: `Module "${parsed.module}" is not in .kaddo/modules.yml.` });
14049
+ }
14050
+ if (parsed.resource && !getResource(dir, parsed.resource)) {
14051
+ findings.push({ level: "warning", message: `Project Resource "${parsed.resource}" not found.` });
14052
+ }
14053
+ return findings;
14054
+ }
14055
+ function loadPlanRaw(dir, planId) {
14056
+ const match = allPlanArtifacts(dir).find((a) => a.id === planId || a.title === planId);
14057
+ if (!match) throw new DeprecationWriteError("NOT_FOUND", `Deprecation Plan "${planId}" not found.`);
14058
+ const parsed = matter16(readFile(match.filePath));
14059
+ const data = { ...parsed.data ?? {} };
14060
+ return { filePath: match.filePath, data, body: parsed.content.trim() };
14061
+ }
14062
+ function rawTargets(data) {
14063
+ return Array.isArray(data.targets) ? data.targets : [];
14064
+ }
14065
+ function createPlan(dir, input) {
14066
+ const title = (input.title ?? "").trim();
14067
+ if (!title) throw new DeprecationWriteError("INVALID_INPUT", "A plan title is required.");
14068
+ const existing = allPlanArtifacts(dir);
14069
+ if (input.id && existing.some((a) => (a.id || "").toUpperCase() === input.id.toUpperCase())) {
14070
+ throw new DeprecationWriteError("DUPLICATE", `A plan with id "${input.id}" already exists.`);
14071
+ }
14072
+ if (existing.some((a) => (a.title || "").toLowerCase() === title.toLowerCase())) {
14073
+ throw new DeprecationWriteError("DUPLICATE", `A plan titled "${title}" already exists.`);
14074
+ }
14075
+ const id = nextPlanId(dir, input.id);
14076
+ const data = {
14077
+ type: DEPRECATION_ARTIFACT_TYPE,
14078
+ id,
14079
+ title,
14080
+ status: (input.status ?? "draft").trim() || "draft",
14081
+ targets: []
14082
+ };
14083
+ const body = `# Purpose
14084
+
14085
+ ${(input.purpose ?? "").trim() || "TODO: describe what this plan retires and why."}`;
14086
+ const relPath = `${DEPRECATION_PLANS_DIR}/${id}-${slug4(title) || "plan"}.md`;
14087
+ const filePath = join(dir, relPath);
14088
+ if (exists(filePath)) throw new DeprecationWriteError("DUPLICATE", `Plan file already exists: ${relPath}`);
14089
+ ensureDir(path5.dirname(filePath));
14090
+ atomicWrite4(filePath, serialize3(data, body));
14091
+ return { id, path: relPath, findings: [] };
14092
+ }
14093
+ function addTarget(dir, planId, input) {
14094
+ const { filePath, data, body } = loadPlanRaw(dir, planId);
14095
+ const targets = rawTargets(data);
14096
+ const existingIds = targets.map((t) => String(t.id ?? ""));
14097
+ const targetId = (input.id ?? "").trim() || nextTargetId(existingIds);
14098
+ if (existingIds.some((id) => id.toUpperCase() === targetId.toUpperCase())) {
14099
+ throw new DeprecationWriteError("DUPLICATE", `Target "${targetId}" already exists in ${planId}.`);
14100
+ }
14101
+ const raw = buildTargetRaw({ ...input, id: targetId, lifecycle: input.lifecycle ?? "candidate" });
14102
+ const findings = validateTargetInput(dir, raw);
14103
+ if (findings.some((f) => f.level === "error")) {
14104
+ throw new DeprecationWriteError("VALIDATION_FAILED", findings.filter((f) => f.level === "error").map((f) => f.message).join("; "));
14105
+ }
14106
+ data.targets = [...targets, raw];
14107
+ atomicWrite4(filePath, serialize3(data, body));
14108
+ return { planId, targetId, path: `${DEPRECATION_PLANS_DIR}/${path5.basename(filePath)}`, findings };
14109
+ }
14110
+ function updateTarget(dir, planId, targetId, patch) {
14111
+ const { filePath, data, body } = loadPlanRaw(dir, planId);
14112
+ const targets = rawTargets(data);
14113
+ const idx = targets.findIndex((t) => String(t.id ?? "").toUpperCase() === targetId.toUpperCase());
14114
+ if (idx === -1) throw new DeprecationWriteError("NOT_FOUND", `Target "${targetId}" not found in ${planId}.`);
14115
+ const merged = buildTargetRaw({ ...patch, id: String(targets[idx].id) }, targets[idx]);
14116
+ const findings = validateTargetInput(dir, merged);
14117
+ if (findings.some((f) => f.level === "error")) {
14118
+ throw new DeprecationWriteError("VALIDATION_FAILED", findings.filter((f) => f.level === "error").map((f) => f.message).join("; "));
14119
+ }
14120
+ const next = [...targets];
14121
+ next[idx] = merged;
14122
+ data.targets = next;
14123
+ atomicWrite4(filePath, serialize3(data, body));
14124
+ return { planId, targetId: String(targets[idx].id), path: `${DEPRECATION_PLANS_DIR}/${path5.basename(filePath)}`, findings };
14125
+ }
14126
+ function removeTarget(dir, planId, targetId, opts = {}) {
14127
+ const { filePath, data, body } = loadPlanRaw(dir, planId);
14128
+ const targets = rawTargets(data);
14129
+ const exists2 = targets.some((t) => String(t.id ?? "").toUpperCase() === targetId.toUpperCase());
14130
+ if (!exists2) throw new DeprecationWriteError("NOT_FOUND", `Target "${targetId}" not found in ${planId}.`);
14131
+ 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));
14132
+ if (!opts.confirm) {
14133
+ return { removed: false, preview: { planId, targetId, dependents } };
14134
+ }
14135
+ data.targets = targets.filter((t) => String(t.id ?? "").toUpperCase() !== targetId.toUpperCase());
14136
+ atomicWrite4(filePath, serialize3(data, body));
14137
+ return { removed: true, path: `${DEPRECATION_PLANS_DIR}/${path5.basename(filePath)}` };
14138
+ }
14139
+
14140
+ // src/core/deprecation-runbook.ts
14141
+ import matter17 from "gray-matter";
14142
+ var PRODUCTION_RUNBOOK_ARTIFACT_TYPE = "production-runbook";
14143
+ var PRODUCTION_RUNBOOKS_DIR = "knowledge/delivery/runbooks";
14144
+ var RUNBOOK_SECTIONS = [
14145
+ "Purpose",
14146
+ "Preconditions",
14147
+ "Dependencies",
14148
+ "Backup/Recovery",
14149
+ "Impact",
14150
+ "Execution Order",
14151
+ "Commands",
14152
+ "Expected Results",
14153
+ "Validation",
14154
+ "Rollback",
14155
+ "Abort Conditions",
14156
+ "Observation Window",
14157
+ "Evidence",
14158
+ "Approval"
14159
+ ];
14160
+ var ProductionRunbookError = class extends Error {
14161
+ constructor(message) {
14162
+ super(message);
14163
+ this.name = "ProductionRunbookError";
14164
+ }
14165
+ };
14166
+ function stringValue(value) {
14167
+ return typeof value === "string" && value.trim() ? value.trim() : null;
14168
+ }
14169
+ function slug5(value) {
14170
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "production-change";
14171
+ }
14172
+ function nextRunbookNumber(dir) {
14173
+ const root = join(dir, PRODUCTION_RUNBOOKS_DIR);
14174
+ return readDir(root).reduce((highest, name) => {
14175
+ const match = name.match(/^RB-(\d+)-.+\.md$/i);
14176
+ return match ? Math.max(highest, Number(match[1])) : highest;
14177
+ }, 0) + 1;
14178
+ }
14179
+ function runbookPath(dir, target) {
14180
+ const id = `RB-${String(nextRunbookNumber(dir)).padStart(3, "0")}`;
14181
+ return `${PRODUCTION_RUNBOOKS_DIR}/${id}-${slug5(target.title ?? target.id)}.md`;
14182
+ }
14183
+ function parseApproval(value) {
14184
+ const data = value && typeof value === "object" && !Array.isArray(value) ? value : {};
14185
+ const status = data.status === "approved" ? "approved" : "pending";
14186
+ return {
14187
+ required: data.required === true,
14188
+ status,
14189
+ approvedBy: stringValue(data.approved_by),
14190
+ approvedAt: stringValue(data.approved_at)
14191
+ };
14192
+ }
14193
+ function sectionPresent(body, section2) {
14194
+ const escaped = section2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace("/", "\\/");
14195
+ return new RegExp(`^##\\s+${escaped}\\s*$`, "mi").test(body);
14196
+ }
14197
+ function destructiveCommands(body) {
14198
+ const lines = body.split(/\r?\n/);
14199
+ return lines.filter((line) => /\b(drop|truncate|delete\s+from|alter\s+(table|database|schema)|create\s+or\s+replace)\b/i.test(line));
14200
+ }
14201
+ function relatedTargets(plan, target) {
14202
+ const ids = new Set(target.dependsOnRemoval);
14203
+ return plan.targets.filter((candidate) => ids.has(candidate.id));
14204
+ }
14205
+ function buildProductionRunbookContext(dir, planId, targetId) {
14206
+ const plan = getDeprecationPlan(dir, planId);
14207
+ if (!plan) throw new ProductionRunbookError(`Deprecation Plan "${planId}" not found.`);
14208
+ const target = plan.targets.find((candidate) => candidate.id === targetId);
14209
+ if (!target) throw new ProductionRunbookError(`Target "${targetId}" not found in ${plan.id}.`);
14210
+ const environment = environmentSummary(target);
14211
+ const dependencies = relatedTargets(plan, target);
14212
+ const blockers = [];
14213
+ if (!environment.removedInDevTest) blockers.push("Development and test must both be removed before preparing a production runbook.");
14214
+ if (target.lifecycle !== "production-ready") blockers.push(`Target lifecycle must be production-ready (current: ${target.lifecycle}).`);
14215
+ for (const dependency of dependencies) {
14216
+ if (!["completed", "deprecated-retained"].includes(String(dependency.lifecycle))) {
14217
+ blockers.push(`Dependency ${dependency.id} is not retired (current: ${dependency.lifecycle}).`);
14218
+ }
14219
+ }
14220
+ const path6 = runbookPath(dir, target);
14221
+ return {
14222
+ eligible: blockers.length === 0,
14223
+ plan: { id: plan.id, title: plan.title, purpose: plan.purpose },
14224
+ target,
14225
+ resource: target.resource ? getResource(dir, target.resource) : null,
14226
+ dependencies,
14227
+ blockers,
14228
+ nextPath: path6,
14229
+ 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."
14230
+ };
14231
+ }
14232
+ function renderRunbook(context) {
14233
+ const target = context.target;
14234
+ const resource = context.resource;
14235
+ const dependencies = context.dependencies.length > 0 ? context.dependencies.map((item) => `- ${item.id}: ${item.title ?? item.locator ?? item.id}`).join("\n") : "- None declared.";
14236
+ 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.";
14237
+ const observation = observationStatus(target);
14238
+ const resourceBoundary = resource ? `- Resource: ${resource.id} (${resource.title})
14239
+ - Production boundary: ${(resource.boundaries.production ?? []).join(", ") || "not declared"}
14240
+ - Interfaces: ${resource.interfaces.map((item) => item.type).join(", ") || "not declared"}` : "- No Project Resource is linked to this target.";
14241
+ return [
14242
+ "# Production Runbook",
14243
+ "",
14244
+ "## Purpose",
14245
+ "",
14246
+ `Safely apply the approved production change for ${target.id} (${target.title ?? target.locator ?? target.id}) in ${context.plan.id}.`,
14247
+ "",
14248
+ "## Preconditions",
14249
+ "",
14250
+ "- [ ] Development and test are removed and verified.",
14251
+ "- [ ] A human has reviewed this proposal and explicitly approved the production window.",
14252
+ "- [ ] Required backups/recovery points are verified before any change.",
14253
+ "",
14254
+ "## Dependencies",
14255
+ "",
14256
+ dependencies,
14257
+ "",
14258
+ "## Backup/Recovery",
14259
+ "",
14260
+ "- [ ] Record the backup, snapshot, export, or recovery point identifier before execution.",
14261
+ "- [ ] Confirm the restoration owner and recovery procedure.",
14262
+ "",
14263
+ "## Impact",
14264
+ "",
14265
+ `- Target: ${target.type} at ${target.locator ?? "not declared"}.`,
14266
+ `- Assessment: blast radius=${target.assessment.blastRadius ?? "not evaluated"}; reversibility=${target.assessment.reversibility ?? "not evaluated"}.`,
14267
+ resourceBoundary,
14268
+ "",
14269
+ "## Execution Order",
14270
+ "",
14271
+ "1. Confirm approval and the production change window.",
14272
+ "2. Verify the backup/recovery point.",
14273
+ "3. Execute the reviewed command manually.",
14274
+ "4. Capture actual results and validate before continuing.",
14275
+ "",
14276
+ "## Commands",
14277
+ "",
14278
+ "> Kaddo never executes production commands. Add only human-reviewed commands here after approval; do not place unattended automation in this runbook.",
14279
+ "",
14280
+ "## Expected Results",
14281
+ "",
14282
+ "- The approved target changes only in production.",
14283
+ "- No unrelated dependency or resource boundary is changed.",
14284
+ "",
14285
+ "## Validation",
14286
+ "",
14287
+ "- [ ] Validate the expected result using the linked resource/interface.",
14288
+ "- [ ] Confirm no unexpected errors or consumer regressions.",
14289
+ "",
14290
+ "## Rollback",
14291
+ "",
14292
+ "- [ ] Stop the change and apply the documented recovery procedure if validation fails.",
14293
+ "- [ ] Record the rollback result in Evidence.",
14294
+ "",
14295
+ "## Abort Conditions",
14296
+ "",
14297
+ "- Abort if the backup/recovery point is missing or cannot be restored.",
14298
+ "- Abort if approval is absent, the production window changes, or validation reveals unexpected impact.",
14299
+ "",
14300
+ "## Observation Window",
14301
+ "",
14302
+ `- ${observation.declared ? `Existing observation: ${observation.reasons.join(" ")}` : "After the production change, declare the observation window and exit criteria."}`,
14303
+ "- 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.",
14304
+ "",
14305
+ "## Evidence",
14306
+ "",
14307
+ evidence,
14308
+ "",
14309
+ "## Approval",
14310
+ "",
14311
+ "- Required: human approval before manual execution.",
14312
+ "- Status: pending.",
14313
+ "- Approved by: not recorded.",
14314
+ "- Approved at: not recorded.",
14315
+ ""
14316
+ ].join("\n");
14317
+ }
14318
+ function createProductionRunbook(dir, planId, targetId) {
14319
+ const context = buildProductionRunbookContext(dir, planId, targetId);
14320
+ if (!context.eligible) throw new ProductionRunbookError(context.blockers.join(" "));
14321
+ const path6 = context.nextPath;
14322
+ const id = path6.split("/").pop()?.match(/^(RB-\d+)-/)?.[1] ?? "";
14323
+ const content = matter17.stringify(renderRunbook(context), {
14324
+ id,
14325
+ type: PRODUCTION_RUNBOOK_ARTIFACT_TYPE,
14326
+ title: `Production runbook \u2014 ${context.target.title ?? context.target.id}`,
14327
+ deprecation_plan: context.plan.id,
14328
+ deprecation_target: context.target.id,
14329
+ resource: context.target.resource,
14330
+ approval: { required: true, status: "pending", approved_by: null, approved_at: null }
14331
+ });
14332
+ const absolute = join(dir, path6);
14333
+ if (exists(absolute)) throw new ProductionRunbookError(`Runbook already exists: ${path6}`);
14334
+ writeFile(absolute, content);
14335
+ return {
14336
+ id,
14337
+ title: `Production runbook \u2014 ${context.target.title ?? context.target.id}`,
14338
+ path: path6,
14339
+ planId: context.plan.id,
14340
+ targetId: context.target.id,
14341
+ approval: { required: true, status: "pending", approvedBy: null, approvedAt: null },
14342
+ markdownBody: renderRunbook(context)
14343
+ };
14344
+ }
14345
+ function getProductionRunbook(dir, id) {
14346
+ const root = join(dir, PRODUCTION_RUNBOOKS_DIR);
14347
+ for (const name of readDir(root)) {
14348
+ if (!name.toLowerCase().startsWith(`${id.toLowerCase()}-`) || !name.endsWith(".md")) continue;
14349
+ const path6 = `${PRODUCTION_RUNBOOKS_DIR}/${name}`;
14350
+ const parsed = matter17(readFile(join(dir, path6)));
14351
+ const data = parsed.data;
14352
+ if (data.type !== PRODUCTION_RUNBOOK_ARTIFACT_TYPE) continue;
14353
+ return {
14354
+ id: stringValue(data.id) ?? id,
14355
+ title: stringValue(data.title) ?? id,
14356
+ path: path6,
14357
+ planId: stringValue(data.deprecation_plan) ?? "",
14358
+ targetId: stringValue(data.deprecation_target) ?? "",
14359
+ approval: parseApproval(data.approval),
14360
+ markdownBody: parsed.content.trim()
14361
+ };
14362
+ }
14363
+ return null;
14364
+ }
14365
+ function validateProductionRunbook(runbook) {
14366
+ const findings = [];
14367
+ for (const section2 of RUNBOOK_SECTIONS) {
14368
+ if (!sectionPresent(runbook.markdownBody, section2)) findings.push({ level: "error", message: `Missing required section: ${section2}.` });
14369
+ }
14370
+ if (!runbook.approval.required) findings.push({ level: "error", message: "Human approval must be required for a production runbook." });
14371
+ const destructive = destructiveCommands(runbook.markdownBody);
14372
+ if (destructive.length > 0 && (runbook.approval.status !== "approved" || !runbook.approval.approvedBy || !runbook.approval.approvedAt)) {
14373
+ findings.push({ level: "error", message: "Destructive production commands require explicit human approval with approver and timestamp." });
14374
+ }
14375
+ if (destructive.length > 0) findings.push({ level: "warning", message: "Destructive commands are documentation only; Kaddo will never execute them." });
14376
+ return findings;
14377
+ }
13312
14378
  export {
14379
+ CANDIDATE_DISCOVERY_GUIDANCE,
13313
14380
  CURRENT_CONSENT_VERSION,
14381
+ DEPRECATION_ARTIFACT_TYPE,
14382
+ DEPRECATION_PLANS_DIR,
14383
+ DeprecationWriteError,
14384
+ ENVIRONMENTS,
14385
+ ENVIRONMENT_STATES,
14386
+ EVIDENCE_QUALITIES,
14387
+ EVIDENCE_SIGNALS,
13314
14388
  INITIATIVES_DIR,
13315
14389
  INITIATIVE_STATES,
13316
14390
  INITIATIVE_TRANSITIONS,
@@ -13320,20 +14394,30 @@ export {
13320
14394
  InitiativeWriteError,
13321
14395
  IntegrationError,
13322
14396
  IntegrationServiceError,
14397
+ LIFECYCLE_STATES2 as LIFECYCLE_STATES,
14398
+ LIFECYCLE_TRANSITIONS,
13323
14399
  POC_ARTIFACT_PATH,
13324
14400
  POC_REPORT_PREFIX,
14401
+ PRODUCTION_RUNBOOKS_DIR,
14402
+ PRODUCTION_RUNBOOK_ARTIFACT_TYPE,
14403
+ ProductionRunbookError,
13325
14404
  RESOURCE_ARTIFACT_TYPE,
13326
14405
  RESOURCE_ROLES,
13327
14406
  RESOURCE_TYPES,
14407
+ RUNBOOK_SECTIONS,
13328
14408
  ResourceWriteError,
14409
+ SOFT_DEPRECATION_STRATEGIES,
14410
+ TARGET_TYPES,
13329
14411
  TOPOLOGY_FILE,
13330
14412
  TopologyWriteError,
14413
+ USAGE_STATUSES,
13331
14414
  WorkItemNotFoundError,
13332
14415
  WorkItemNotInProgressError,
13333
14416
  WorkItemNotReadyError,
13334
14417
  WorkItemWriteError,
13335
14418
  addCandidate,
13336
14419
  addExternalLink,
14420
+ addTarget,
13337
14421
  analyzeCrossRepoEvidence,
13338
14422
  analyzeInitiative,
13339
14423
  analyzeScopeCoverage,
@@ -13342,6 +14426,7 @@ export {
13342
14426
  buildImplementationHandoff,
13343
14427
  buildImportIndex,
13344
14428
  buildPocReportContext,
14429
+ buildProductionRunbookContext,
13345
14430
  buildProjectExplanation,
13346
14431
  buildProjectRoute,
13347
14432
  buildReadinessReport,
@@ -13354,12 +14439,16 @@ export {
13354
14439
  consentNotice,
13355
14440
  createInitiative,
13356
14441
  createIntegration,
14442
+ createPlan,
14443
+ createProductionRunbook,
13357
14444
  createResource,
13358
14445
  createWorkItem,
13359
14446
  cwd,
13360
14447
  deferConsent,
13361
14448
  deleteIntegration,
13362
14449
  deleteResource,
14450
+ deriveRemovalWaves,
14451
+ deriveUnusedConfidence,
13363
14452
  detectFormat,
13364
14453
  disableIntegration,
13365
14454
  discoverExternalWorkItems,
@@ -13367,6 +14456,7 @@ export {
13367
14456
  discoverKnowledge,
13368
14457
  discoverWorkItems,
13369
14458
  enableIntegration,
14459
+ environmentSummary,
13370
14460
  evaluateCompletion,
13371
14461
  evaluateInitiativeCompletion,
13372
14462
  exists,
@@ -13377,6 +14467,8 @@ export {
13377
14467
  findSystemPaths,
13378
14468
  getAvailableIntegrationTypes,
13379
14469
  getConsentState,
14470
+ getDeprecationPlan,
14471
+ getDeprecationPlans,
13380
14472
  getExternalWorkItem,
13381
14473
  getImpactCandidates,
13382
14474
  getInitiative,
@@ -13384,6 +14476,7 @@ export {
13384
14476
  getIntegration,
13385
14477
  getIntegrationFilters,
13386
14478
  getIntegrationSecretStatus,
14479
+ getProductionRunbook,
13387
14480
  getResource,
13388
14481
  getResourceReferences,
13389
14482
  getResources,
@@ -13403,9 +14496,15 @@ export {
13403
14496
  isDeferralActive,
13404
14497
  isInteractive,
13405
14498
  isModule,
14499
+ isRetainedOutcome,
14500
+ isRetiredLifecycle,
13406
14501
  isEnabled as isTelemetryEnabled,
14502
+ isValidEnvironmentState,
13407
14503
  isValidInitiativeStatus,
13408
14504
  isValidInitiativeTransition,
14505
+ isValidLifecycleState,
14506
+ isValidLifecycleTransition,
14507
+ isValidTargetType,
13409
14508
  join,
13410
14509
  knowledgeLayers,
13411
14510
  lifecycleCounts,
@@ -13418,23 +14517,36 @@ export {
13418
14517
  materializeCandidate,
13419
14518
  materializeRoadmapInitiative,
13420
14519
  nextInitiativeId,
14520
+ nextPlanId,
14521
+ nextTargetId,
14522
+ observationStatus,
13421
14523
  parseContent,
13422
14524
  parseInitiative,
13423
14525
  parseScope,
14526
+ parseSoftDeprecation,
13424
14527
  parseSuccessCriteria,
14528
+ parseTarget,
14529
+ parseTargets,
14530
+ parseUsageEvidence,
14531
+ parseWorkItemDeprecationTargets,
13425
14532
  parseWorkItemResources,
13426
14533
  persistConsent,
13427
14534
  persistPocReport,
14535
+ planIntelligence,
13428
14536
  previewImport,
13429
14537
  projectMode,
14538
+ proposeWorkItemCandidates,
13430
14539
  readFile,
13431
14540
  readPocSummary,
13432
14541
  redactSecrets,
13433
14542
  removeIntegrationSecret,
14543
+ removeTarget,
13434
14544
  searchSystemNodes,
13435
14545
  setIntegrationSecret,
13436
14546
  setProjectMode,
13437
14547
  suggestInitiativesForExternalItem,
14548
+ targetsEligibleForRemoval,
14549
+ targetsPastObservation,
13438
14550
  topologyRevision,
13439
14551
  transitionInitiative,
13440
14552
  transitionWorkItem,
@@ -13442,10 +14554,15 @@ export {
13442
14554
  updateIntegration,
13443
14555
  updateIntegrationFilters,
13444
14556
  updateResource,
14557
+ updateTarget,
13445
14558
  updateWorkItem,
13446
14559
  validateConfigAgainstSchema,
14560
+ validatePlan,
14561
+ validateProductionRunbook,
13447
14562
  validateResource,
13448
14563
  validateSystemTopology,
14564
+ validateTarget,
14565
+ validateTargetInput,
13449
14566
  validateTopologyProposal,
13450
14567
  validateWorkItem,
13451
14568
  verifyIntegration,