@kaddo/cli 3.89.0 → 3.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/core.js +201 -3
  2. package/dist/index.js +825 -0
  3. package/package.json +1 -1
package/dist/core.js CHANGED
@@ -6570,6 +6570,7 @@ var VALID_SOURCES = [
6570
6570
  "csv",
6571
6571
  "api",
6572
6572
  "external",
6573
+ "chat",
6573
6574
  "unknown"
6574
6575
  ];
6575
6576
  function isValidSource(s) {
@@ -9395,8 +9396,199 @@ function buildRefinementHandoff(dir, workItemId) {
9395
9396
  };
9396
9397
  }
9397
9398
 
9398
- // src/services/integrations.ts
9399
+ // src/core/work-item-import.ts
9400
+ import crypto3 from "crypto";
9399
9401
  import matter8 from "gray-matter";
9402
+ var MAX_INPUT_BYTES = 102400;
9403
+ function detectFormat(raw) {
9404
+ const trimmed = raw.trim();
9405
+ if (!trimmed) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
9406
+ if (trimmed.startsWith("---")) {
9407
+ try {
9408
+ const { data } = matter8(trimmed);
9409
+ if (data && typeof data === "object" && Object.keys(data).length > 0) {
9410
+ const d = data;
9411
+ if (d.type === "work-item" || d.id && typeof d.id === "string" && /^WI-\d+/.test(d.id)) {
9412
+ return "kaddo-frontmatter";
9413
+ }
9414
+ return "markdown-frontmatter";
9415
+ }
9416
+ } catch {
9417
+ }
9418
+ }
9419
+ if (/^#{1,2}\s+/m.test(trimmed)) return "markdown";
9420
+ return "plain-text";
9421
+ }
9422
+ function parseContent(raw) {
9423
+ const trimmed = raw.trim();
9424
+ if (!trimmed) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
9425
+ const format = detectFormat(trimmed);
9426
+ let frontmatterFields = {};
9427
+ let bodyText = trimmed;
9428
+ if (format === "kaddo-frontmatter" || format === "markdown-frontmatter") {
9429
+ try {
9430
+ const parsed = matter8(trimmed);
9431
+ frontmatterFields = parsed.data ?? {};
9432
+ bodyText = parsed.content.trim();
9433
+ } catch {
9434
+ }
9435
+ }
9436
+ const title = extractTitle(frontmatterFields, bodyText);
9437
+ const candidateType = extractType(frontmatterFields);
9438
+ const sections = extractSections(bodyText);
9439
+ const summary = bodyText || title;
9440
+ return {
9441
+ format,
9442
+ title,
9443
+ type: candidateType,
9444
+ summary,
9445
+ body: bodyText,
9446
+ candidateFields: frontmatterFields,
9447
+ sections
9448
+ };
9449
+ }
9450
+ function extractTitle(fields, body) {
9451
+ if (typeof fields.title === "string" && fields.title.trim()) {
9452
+ return fields.title.trim().slice(0, 120);
9453
+ }
9454
+ const h1Match = body.match(/^#\s+(.+)$/m);
9455
+ if (h1Match) return h1Match[1].trim().slice(0, 120);
9456
+ const firstLine = body.split(/\r?\n/).find((l) => l.trim());
9457
+ return (firstLine?.trim() ?? "Untitled Work Item").slice(0, 120);
9458
+ }
9459
+ function extractType(fields) {
9460
+ const raw = typeof fields.work_type === "string" && fields.work_type.trim() ? fields.work_type.trim() : typeof fields.type === "string" && fields.type.trim() && fields.type !== "work-item" ? fields.type.trim() : void 0;
9461
+ if (!raw) return void 0;
9462
+ return normalizeType(raw) ?? void 0;
9463
+ }
9464
+ function extractSections(body) {
9465
+ const sections = /* @__PURE__ */ new Map();
9466
+ const lines = body.split(/\r?\n/);
9467
+ let currentHeading = null;
9468
+ let buffer = [];
9469
+ const flush = () => {
9470
+ if (currentHeading) {
9471
+ sections.set(currentHeading.toLowerCase(), buffer.join("\n").trim());
9472
+ }
9473
+ buffer = [];
9474
+ };
9475
+ for (const line of lines) {
9476
+ const match = line.match(/^##\s+(.+)$/);
9477
+ if (match) {
9478
+ flush();
9479
+ currentHeading = match[1].trim();
9480
+ } else if (currentHeading) {
9481
+ buffer.push(line);
9482
+ }
9483
+ }
9484
+ flush();
9485
+ return sections;
9486
+ }
9487
+ function normalizeImportFields(parsed, opts) {
9488
+ const type = opts.userType ? normalizeType(opts.userType) ?? "feature" : parsed.type ?? "feature";
9489
+ const intent = parsed.body && parsed.body !== parsed.title ? `${parsed.title}
9490
+
9491
+ ${parsed.body}` : parsed.title;
9492
+ const source = {
9493
+ type: opts.importSource === "chat" ? "chat" : "external",
9494
+ imported_at: (/* @__PURE__ */ new Date()).toISOString().split("T")[0]
9495
+ };
9496
+ source.source_format = opts.sourceFormat;
9497
+ source.source_hash = opts.sourceHash;
9498
+ const snapshot = { title: parsed.title };
9499
+ if (parsed.summary !== parsed.title) snapshot.description = parsed.summary;
9500
+ if (typeof parsed.candidateFields.type === "string") snapshot.type = parsed.candidateFields.type;
9501
+ if (typeof parsed.candidateFields.status === "string") snapshot.status = parsed.candidateFields.status;
9502
+ if (Array.isArray(parsed.candidateFields.labels)) {
9503
+ const labels = parsed.candidateFields.labels.filter((l) => typeof l === "string");
9504
+ if (labels.length > 0) snapshot.labels = labels;
9505
+ }
9506
+ return { type, intent, source, snapshot };
9507
+ }
9508
+ function computeContentHash(raw) {
9509
+ return crypto3.createHash("sha256").update(raw.trim(), "utf-8").digest("hex");
9510
+ }
9511
+ function findDuplicateByHash(dir, hash) {
9512
+ const items = discoverWorkItems(dir);
9513
+ for (const item of items) {
9514
+ const raw = readFile(item.filePath);
9515
+ if (!raw) continue;
9516
+ try {
9517
+ const { data } = matter8(raw);
9518
+ const source = data?.source;
9519
+ if (source && typeof source === "object" && !Array.isArray(source)) {
9520
+ const s = source;
9521
+ if (s.source_hash === hash) {
9522
+ return { workItemId: data.id ?? item.id ?? item.title, path: item.relPath };
9523
+ }
9524
+ }
9525
+ } catch {
9526
+ }
9527
+ }
9528
+ return void 0;
9529
+ }
9530
+ function importWorkItem(dir, opts) {
9531
+ const content = opts.content;
9532
+ if (!content?.trim()) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
9533
+ if (Buffer.byteLength(content, "utf-8") > MAX_INPUT_BYTES) {
9534
+ throw new ImportError("OVERSIZED_INPUT", `Import content exceeds the ${MAX_INPUT_BYTES / 1024}KB limit.`);
9535
+ }
9536
+ const parsed = parseContent(content);
9537
+ const sourceHash = computeContentHash(content);
9538
+ const duplicate = findDuplicateByHash(dir, sourceHash);
9539
+ if (duplicate) {
9540
+ return {
9541
+ created: false,
9542
+ workItemId: duplicate.workItemId,
9543
+ path: duplicate.path,
9544
+ status: "draft",
9545
+ source: opts.source,
9546
+ sourceFormat: parsed.format,
9547
+ sourceHash,
9548
+ duplicateOf: duplicate.workItemId,
9549
+ executed: false
9550
+ };
9551
+ }
9552
+ const normalized = normalizeImportFields(parsed, {
9553
+ userType: opts.type,
9554
+ importSource: opts.source,
9555
+ sourceHash,
9556
+ sourceFormat: parsed.format
9557
+ });
9558
+ const result = createWorkItem(dir, {
9559
+ intent: normalized.intent,
9560
+ type: normalized.type,
9561
+ source: normalized.source,
9562
+ originalSnapshot: normalized.snapshot
9563
+ });
9564
+ let refinementHandoff;
9565
+ try {
9566
+ refinementHandoff = buildRefinementHandoff(dir, result.id);
9567
+ } catch {
9568
+ }
9569
+ return {
9570
+ created: true,
9571
+ workItemId: result.id,
9572
+ path: result.path,
9573
+ status: "draft",
9574
+ source: opts.source,
9575
+ sourceFormat: parsed.format,
9576
+ sourceHash,
9577
+ executed: false,
9578
+ refinementHandoff
9579
+ };
9580
+ }
9581
+ var ImportError = class extends Error {
9582
+ constructor(code, message) {
9583
+ super(message);
9584
+ this.code = code;
9585
+ this.name = "ImportError";
9586
+ }
9587
+ code;
9588
+ };
9589
+
9590
+ // src/services/integrations.ts
9591
+ import matter9 from "gray-matter";
9400
9592
  import { parse as parseYaml9, stringify as stringifyYaml5 } from "yaml";
9401
9593
 
9402
9594
  // ../integrations/src/errors.ts
@@ -10738,7 +10930,7 @@ function findLinkedWorkItem(dir, integrationId, externalId) {
10738
10930
  for (const art of discoverWorkItems(dir)) {
10739
10931
  let data;
10740
10932
  try {
10741
- data = matter8(readFile(art.filePath)).data;
10933
+ data = matter9(readFile(art.filePath)).data;
10742
10934
  } catch {
10743
10935
  continue;
10744
10936
  }
@@ -10754,7 +10946,7 @@ function buildImportIndex(dir) {
10754
10946
  for (const art of discoverWorkItems(dir)) {
10755
10947
  let data;
10756
10948
  try {
10757
- data = matter8(readFile(art.filePath)).data;
10949
+ data = matter9(readFile(art.filePath)).data;
10758
10950
  } catch {
10759
10951
  continue;
10760
10952
  }
@@ -10819,6 +11011,7 @@ ${item.description}` : item.title;
10819
11011
  }
10820
11012
  export {
10821
11013
  INTEGRATIONS_FILE,
11014
+ ImportError,
10822
11015
  IntegrationError,
10823
11016
  IntegrationServiceError,
10824
11017
  TOPOLOGY_FILE,
@@ -10834,17 +11027,20 @@ export {
10834
11027
  buildReadinessReport,
10835
11028
  buildRefinementHandoff,
10836
11029
  buildTopologyEnrichmentHandoff,
11030
+ computeContentHash,
10837
11031
  computeRefinementStatus,
10838
11032
  createIntegration,
10839
11033
  createWorkItem,
10840
11034
  cwd,
10841
11035
  deleteIntegration,
11036
+ detectFormat,
10842
11037
  disableIntegration,
10843
11038
  discoverExternalWorkItems,
10844
11039
  discoverKnowledge,
10845
11040
  discoverWorkItems,
10846
11041
  enableIntegration,
10847
11042
  exists,
11043
+ findDuplicateByHash,
10848
11044
  findLinkedWorkItem,
10849
11045
  findSystemPaths,
10850
11046
  getAvailableIntegrationTypes,
@@ -10862,6 +11058,7 @@ export {
10862
11058
  getWorkItems,
10863
11059
  getWorkItemsSummary,
10864
11060
  importExternalWorkItem,
11061
+ importWorkItem,
10865
11062
  integrationRegistry,
10866
11063
  isActiveState,
10867
11064
  isModule,
@@ -10874,6 +11071,7 @@ export {
10874
11071
  loadConfig,
10875
11072
  loadMappedModules,
10876
11073
  loadSystemTopology,
11074
+ parseContent,
10877
11075
  previewImport,
10878
11076
  readFile,
10879
11077
  removeIntegrationSecret,
package/dist/index.js CHANGED
@@ -12710,6 +12710,7 @@ var VALID_SOURCES = [
12710
12710
  "csv",
12711
12711
  "api",
12712
12712
  "external",
12713
+ "chat",
12713
12714
  "unknown"
12714
12715
  ];
12715
12716
  function isValidSource(s) {
@@ -20288,6 +20289,826 @@ async function runAdmin(opts = {}) {
20288
20289
  process.on("SIGTERM", shutdown);
20289
20290
  }
20290
20291
 
20292
+ // src/core/work-item-import.ts
20293
+ import crypto3 from "crypto";
20294
+ import matter15 from "gray-matter";
20295
+
20296
+ // src/core/work-items.ts
20297
+ import matter14 from "gray-matter";
20298
+ function computeRefinementStatus(wi) {
20299
+ const aspects = {
20300
+ outcome: Boolean(wi.currentBehavior?.trim() || wi.targetBehavior?.trim()),
20301
+ journey: Boolean(wi.entryPoints?.trim() || wi.endToEndFlow?.trim()),
20302
+ modules: wi.affectedModules.length > 0 || wi.moduleCoverage.length > 0,
20303
+ impact: wi.impactAnalysis.length > 0,
20304
+ acceptance: wi.acceptanceCriteria.length > 0
20305
+ };
20306
+ const refined = aspects.outcome && aspects.modules && aspects.acceptance;
20307
+ return { status: refined ? "refined" : "needs-refinement", aspects };
20308
+ }
20309
+ var WorkItemNotFoundError = class extends Error {
20310
+ constructor(workItemId) {
20311
+ super(`Work Item "${workItemId}" was not found.`);
20312
+ this.workItemId = workItemId;
20313
+ this.name = "WorkItemNotFoundError";
20314
+ }
20315
+ workItemId;
20316
+ };
20317
+ function toListItem(a) {
20318
+ return {
20319
+ id: a.id || a.title,
20320
+ title: a.title || a.id,
20321
+ type: a.type,
20322
+ status: lifecycleStateOf({ status: a.status, filePath: a.filePath }),
20323
+ implementationStatus: a.implementationStatus || null,
20324
+ validationStatus: a.validationStatus || null,
20325
+ releaseStatus: a.releaseStatus || null,
20326
+ affectedModules: a.affectedModules,
20327
+ scopeConfidenceLevel: a.scopeConfidence?.level ?? null,
20328
+ initiative: a.initiative || null
20329
+ };
20330
+ }
20331
+ function getWorkItem(dir, workItemId) {
20332
+ const artifacts = discoverWorkItems(dir);
20333
+ const match = artifacts.find((a) => (a.id || a.title) === workItemId);
20334
+ if (!match) throw new WorkItemNotFoundError(workItemId);
20335
+ const base = toListItem(match);
20336
+ const body = readBody(match.filePath);
20337
+ const sections = splitSections(body);
20338
+ const fm2 = match.rawFrontmatter;
20339
+ const knowledge = discoverKnowledge(dir).filter((a) => !a.isWorkItem);
20340
+ const knowledgeById = new Map(knowledge.filter((k) => k.id).map((k) => [k.id, k]));
20341
+ const detail = {
20342
+ ...base,
20343
+ summary: match.summary?.trim() || null,
20344
+ actor: sectionText(sections, ["actor"]),
20345
+ outcome: sectionText(sections, ["actor and outcome", "outcome", "expected result"]),
20346
+ currentBehavior: sectionText(sections, ["current behavior", "current behaviour"]),
20347
+ targetBehavior: sectionText(sections, ["target behavior", "target behaviour"]),
20348
+ entryPoints: sectionText(sections, ["entry points"]),
20349
+ endToEndFlow: sectionText(sections, ["end-to-end flow", "end to end flow", "flow"]),
20350
+ scopeConfidence: match.scopeConfidence,
20351
+ scopeUnknowns: sectionBullets(sections, ["scope unknowns", "open scope questions"]),
20352
+ moduleCoverage: normalizeCoverage(match.moduleCoverage),
20353
+ impactAnalysis: normalizeImpact(match.impactAnalysis),
20354
+ acceptanceCriteria: parseAcceptanceCriteria(sections),
20355
+ implementationEvidence: parseEvidence(fm2),
20356
+ releaseGates: parseReleaseGates(fm2),
20357
+ completionExceptions: parseExceptions(fm2),
20358
+ decisions: parseDecisions(match.decisions, knowledgeById),
20359
+ relatedKnowledge: parseRelatedKnowledge(fm2, knowledgeById),
20360
+ source: parseWorkItemSource(fm2),
20361
+ originalSnapshot: parseOriginalSnapshot(fm2),
20362
+ path: match.relPath,
20363
+ ...parseSystemImpact(dir, fm2)
20364
+ };
20365
+ return { ...detail, refinement: computeRefinementStatus(detail) };
20366
+ }
20367
+ function parseGraphReason(v) {
20368
+ if (!v || typeof v !== "object") return null;
20369
+ const o = v;
20370
+ const relationship = typeof o.relationship === "string" && o.relationship.trim() ? o.relationship.trim() : null;
20371
+ const path11 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
20372
+ return relationship || path11.length ? { relationship, path: path11 } : null;
20373
+ }
20374
+ function parseExplain(o) {
20375
+ const refs = Array.isArray(o.evidence) ? o.evidence : Array.isArray(o.evidence_refs) ? o.evidence_refs : [];
20376
+ return {
20377
+ reason: typeof o.reason === "string" && o.reason.trim() ? o.reason.trim() : null,
20378
+ graphReason: parseGraphReason(o.graph_reason),
20379
+ evidenceRefs: refs.map(String).filter(Boolean),
20380
+ evidenceSummary: typeof o.evidence_summary === "string" && o.evidence_summary.trim() ? o.evidence_summary.trim() : null
20381
+ };
20382
+ }
20383
+ function emptyExplain() {
20384
+ return { reason: null, graphReason: null, evidenceRefs: [], evidenceSummary: null };
20385
+ }
20386
+ function parseSystemImpact(dir, fm2) {
20387
+ const topology = loadSystemTopology(dir);
20388
+ const byId = new Map(topology.entities.map((e) => [e.id, e]));
20389
+ const resolve = (id) => {
20390
+ const e = byId.get(id);
20391
+ return { id, nodeId: `sys:${id}`, label: e?.label ?? id, kind: e?.kind ?? "unknown", moduleId: e?.moduleId ?? null };
20392
+ };
20393
+ const affected = Array.isArray(fm2.affected_system_entities) ? fm2.affected_system_entities.map((raw) => {
20394
+ if (typeof raw === "string") return raw ? { ...resolve(raw), ...emptyExplain() } : null;
20395
+ if (raw && typeof raw === "object") {
20396
+ const o = raw;
20397
+ const id = String(o.id ?? "");
20398
+ return id ? { ...resolve(id), ...parseExplain(o) } : null;
20399
+ }
20400
+ return null;
20401
+ }).filter((e) => e != null) : [];
20402
+ const reviewed = Array.isArray(fm2.reviewed_system_entities) ? fm2.reviewed_system_entities.filter((r) => Boolean(r) && typeof r === "object").map((r) => ({ ...resolve(String(r.id ?? "")), ...parseExplain(r), status: String(r.status ?? "unknown") })).filter((r) => r.id) : [];
20403
+ const graphRevision = typeof fm2.graph_revision === "string" && fm2.graph_revision.trim() ? fm2.graph_revision.trim() : null;
20404
+ const graphCoverage = topology.entities.length === 0 ? "unavailable" : topology.relationships.length > 0 ? "available" : "partial";
20405
+ return { affectedSystemEntities: affected, reviewedSystemEntities: reviewed, graphRevision, graphCoverage };
20406
+ }
20407
+ function parseOriginalSnapshot(fm2) {
20408
+ const raw = fm2.original_snapshot;
20409
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
20410
+ const o = raw;
20411
+ const title = typeof o.title === "string" ? o.title : void 0;
20412
+ if (!title) return null;
20413
+ return {
20414
+ title,
20415
+ description: typeof o.description === "string" ? o.description : void 0,
20416
+ type: typeof o.type === "string" ? o.type : void 0,
20417
+ status: typeof o.status === "string" ? o.status : void 0,
20418
+ labels: Array.isArray(o.labels) ? o.labels.map(String) : void 0,
20419
+ assignee: typeof o.assignee === "string" ? o.assignee : void 0,
20420
+ created_at: typeof o.created_at === "string" ? o.created_at : void 0,
20421
+ updated_at: typeof o.updated_at === "string" ? o.updated_at : void 0
20422
+ };
20423
+ }
20424
+ function readBody(filePath) {
20425
+ try {
20426
+ const raw = readFile(filePath);
20427
+ return matter14(raw).content;
20428
+ } catch {
20429
+ return "";
20430
+ }
20431
+ }
20432
+ function splitSections(body) {
20433
+ const sections = /* @__PURE__ */ new Map();
20434
+ const lines = body.split(/\r?\n/);
20435
+ let current = null;
20436
+ let buffer = [];
20437
+ const flush = () => {
20438
+ if (current !== null) sections.set(current, buffer.join("\n").trim());
20439
+ buffer = [];
20440
+ };
20441
+ for (const line of lines) {
20442
+ const m = line.match(/^#{1,6}\s+(.*?)\s*$/);
20443
+ if (m) {
20444
+ flush();
20445
+ current = m[1].toLowerCase().replace(/[`*_]/g, "").trim();
20446
+ } else if (current !== null) {
20447
+ buffer.push(line);
20448
+ }
20449
+ }
20450
+ flush();
20451
+ return sections;
20452
+ }
20453
+ function isPlaceholder(text3) {
20454
+ const t = text3.trim();
20455
+ if (!t) return true;
20456
+ if (/^tbd$/i.test(t)) return true;
20457
+ if (/^_[^_]*_$/.test(t) && !t.includes("\n")) return true;
20458
+ return false;
20459
+ }
20460
+ function sectionText(sections, headings2) {
20461
+ for (const h of headings2) {
20462
+ const body = sections.get(h);
20463
+ if (body != null && !isPlaceholder(body)) return body.trim();
20464
+ }
20465
+ return null;
20466
+ }
20467
+ function sectionBullets(sections, headings2) {
20468
+ for (const h of headings2) {
20469
+ const body = sections.get(h);
20470
+ if (body == null || isPlaceholder(body)) continue;
20471
+ const bullets = extractBullets(body);
20472
+ if (bullets.length > 0) return bullets.map((b) => b.text);
20473
+ }
20474
+ return [];
20475
+ }
20476
+ function extractBullets(body) {
20477
+ const out = [];
20478
+ for (const line of body.split(/\r?\n/)) {
20479
+ const m = line.match(/^\s*[-*+]\s+(.*)$/);
20480
+ if (!m) continue;
20481
+ let text3 = m[1].trim();
20482
+ let checked = null;
20483
+ const cb = text3.match(/^\[([ xX])\]\s*(.*)$/);
20484
+ if (cb) {
20485
+ checked = cb[1].toLowerCase() === "x";
20486
+ text3 = cb[2].trim();
20487
+ }
20488
+ if (!text3 || isPlaceholder(text3)) continue;
20489
+ out.push({ text: text3, checked });
20490
+ }
20491
+ return out;
20492
+ }
20493
+ function parseAcceptanceCriteria(sections) {
20494
+ const body = sections.get("acceptance criteria");
20495
+ if (body == null || isPlaceholder(body)) return [];
20496
+ return extractBullets(body).map((b) => ({ text: b.text, checked: b.checked }));
20497
+ }
20498
+ function normalizeCoverage(mc) {
20499
+ if (!mc) return [];
20500
+ return Object.entries(mc).map(([id, v]) => ({ id, status: v.status, ...v.reason ? { reason: v.reason } : {} }));
20501
+ }
20502
+ function normalizeImpact(ia) {
20503
+ if (!ia) return [];
20504
+ return Object.entries(ia).map(([surface, v]) => ({
20505
+ surface,
20506
+ status: v.status,
20507
+ ...v.reason ? { reason: v.reason } : {},
20508
+ ...v.question ? { question: v.question } : {}
20509
+ }));
20510
+ }
20511
+ function optStr2(v) {
20512
+ if (typeof v === "string" && v.trim()) return v.trim();
20513
+ return void 0;
20514
+ }
20515
+ function parseEvidence(fm2) {
20516
+ const evidence = fm2.implementation_evidence;
20517
+ const repos = evidence?.repositories;
20518
+ if (!repos || typeof repos !== "object" || Array.isArray(repos)) return [];
20519
+ const out = [];
20520
+ for (const [module, val] of Object.entries(repos)) {
20521
+ if (!val || typeof val !== "object" || Array.isArray(val)) continue;
20522
+ const d = val;
20523
+ const validations = Array.isArray(d.validations) ? d.validations.map((v) => ({
20524
+ command: String(v.command ?? ""),
20525
+ status: String(v.status ?? "unknown"),
20526
+ ...optStr2(v.reason) ? { reason: optStr2(v.reason) } : {}
20527
+ })) : [];
20528
+ const migrations = Array.isArray(d.migrations) ? d.migrations.map((m) => ({
20529
+ id: String(m.id ?? ""),
20530
+ environment: String(m.environment ?? ""),
20531
+ status: String(m.status ?? "unknown"),
20532
+ ...optStr2(m.reason) ? { reason: optStr2(m.reason) } : {}
20533
+ })) : [];
20534
+ out.push({
20535
+ module,
20536
+ role: String(d.role ?? (module === "core" ? "core" : "module")),
20537
+ status: String(d.status ?? "unknown"),
20538
+ changedPaths: Array.isArray(d.changed_paths) ? d.changed_paths.map(String).filter(Boolean) : [],
20539
+ validations,
20540
+ migrations
20541
+ });
20542
+ }
20543
+ return out;
20544
+ }
20545
+ function parseReleaseGates(fm2) {
20546
+ if (!Array.isArray(fm2.release_gates)) return [];
20547
+ return fm2.release_gates.filter((g) => g && typeof g === "object").map((g) => ({
20548
+ id: String(g.id ?? ""),
20549
+ status: String(g.status ?? "pending"),
20550
+ ...optStr2(g.reason) ? { reason: optStr2(g.reason) } : {},
20551
+ ...optStr2(g.required_for) ? { requiredFor: optStr2(g.required_for) } : {}
20552
+ }));
20553
+ }
20554
+ function parseExceptions(fm2) {
20555
+ if (!Array.isArray(fm2.completion_exceptions)) return [];
20556
+ return fm2.completion_exceptions.filter((e) => e && typeof e === "object").map((e) => ({
20557
+ id: String(e.id ?? ""),
20558
+ status: String(e.status ?? "proposed"),
20559
+ ...optStr2(e.reason) ? { reason: optStr2(e.reason) } : {},
20560
+ ...optStr2(e.category) ? { category: optStr2(e.category) } : {},
20561
+ ...optStr2(e.impact) ? { impact: optStr2(e.impact) } : {}
20562
+ }));
20563
+ }
20564
+ function parseDecisions(decisions, knowledgeById) {
20565
+ return decisions.map((id) => {
20566
+ const k = knowledgeById.get(id);
20567
+ return {
20568
+ id,
20569
+ ...k?.title ? { title: k.title } : {},
20570
+ ...k ? { knowledgeId: k.id, knowledgeLayer: k.layer } : {}
20571
+ };
20572
+ });
20573
+ }
20574
+ function parseRelatedKnowledge(fm2, knowledgeById) {
20575
+ const refs = /* @__PURE__ */ new Set();
20576
+ for (const field of ["related_knowledge", "knowledge", "related"]) {
20577
+ const v = fm2[field];
20578
+ if (Array.isArray(v)) {
20579
+ for (const r of v) if (typeof r === "string" && r.trim()) refs.add(r.trim());
20580
+ }
20581
+ }
20582
+ const out = [];
20583
+ for (const ref of refs) {
20584
+ const k = knowledgeById.get(ref);
20585
+ if (k && k.id) out.push({ id: k.id, title: k.title || k.id, layer: k.layer });
20586
+ }
20587
+ return out;
20588
+ }
20589
+
20590
+ // src/core/system-map.ts
20591
+ function dimensionOf(type) {
20592
+ switch (type) {
20593
+ case "module":
20594
+ case "application":
20595
+ case "service":
20596
+ case "component":
20597
+ case "api":
20598
+ case "interface":
20599
+ case "database":
20600
+ case "queue":
20601
+ case "job":
20602
+ case "external-system":
20603
+ return "system";
20604
+ case "business":
20605
+ case "product":
20606
+ case "tech":
20607
+ case "delivery":
20608
+ case "capability":
20609
+ case "decision":
20610
+ case "project":
20611
+ case "knowledge-capsule":
20612
+ return "knowledge";
20613
+ case "work-item":
20614
+ case "initiative":
20615
+ case "roadmap-candidate":
20616
+ case "release":
20617
+ return "delivery";
20618
+ case "code-glob":
20619
+ case "file":
20620
+ case "directory":
20621
+ case "migration":
20622
+ case "configuration-artifact":
20623
+ return "implementation";
20624
+ default:
20625
+ return "unknown";
20626
+ }
20627
+ }
20628
+ var EDGE_LABELS = {
20629
+ informs: "informs",
20630
+ belongs_to: "belongs to",
20631
+ materialized_as: "materialized as",
20632
+ owns: "owns",
20633
+ implements: "implements",
20634
+ depends_on: "depends on",
20635
+ governs: "governs",
20636
+ provides_external_context: "provides external context",
20637
+ uses_external_knowledge: "uses external knowledge"
20638
+ };
20639
+ function emptyDimensions() {
20640
+ return { system: 0, knowledge: 0, delivery: 0, implementation: 0, unknown: 0 };
20641
+ }
20642
+ function emptyProjection(name, structure) {
20643
+ return {
20644
+ system: { name },
20645
+ nodes: [],
20646
+ relationships: [],
20647
+ groups: [],
20648
+ metadata: {
20649
+ projectName: name,
20650
+ structure,
20651
+ nodeCount: 0,
20652
+ relationshipCount: 0,
20653
+ coverage: "empty",
20654
+ available: false,
20655
+ dimensions: emptyDimensions(),
20656
+ topologyAvailable: false,
20657
+ topologyStatus: "unavailable",
20658
+ semanticEntityCount: 0,
20659
+ technicalRelationshipCount: 0,
20660
+ topologyFindings: []
20661
+ }
20662
+ };
20663
+ }
20664
+ function getSystemMapProjection(dir) {
20665
+ const config = loadConfig(dir);
20666
+ if (!config) return emptyProjection("unknown", "unknown");
20667
+ const graph = buildGraph(dir, config, { scope: "all" });
20668
+ const hints = buildGraphHints(dir, graph);
20669
+ const knowledgeByPath = /* @__PURE__ */ new Map();
20670
+ for (const a of discoverKnowledge(dir).filter((a2) => !a2.isWorkItem)) {
20671
+ const id = a.id || a.relPath.replace(/[/\\]/g, "-").replace(/\.md$/, "");
20672
+ const layer2 = a.layer === "module" ? "tech" : a.layer;
20673
+ knowledgeByPath.set(a.relPath, { id, layer: layer2 });
20674
+ }
20675
+ const wiModules = /* @__PURE__ */ new Map();
20676
+ for (const wi of discoverWorkItems(dir)) wiModules.set(wi.id || wi.title, wi.affectedModules);
20677
+ const mapped = loadMappedModules(dir);
20678
+ const groupIds = /* @__PURE__ */ new Set(["core", ...mapped.map((m) => m.id)]);
20679
+ const nodes = graph.nodes.map((n) => toNode(n, knowledgeByPath, wiModules, groupIds));
20680
+ const relationships = graph.edges.map((e) => ({
20681
+ id: `${e.from}~${e.type}~${e.to}`,
20682
+ source: e.from,
20683
+ target: e.to,
20684
+ type: e.type,
20685
+ label: EDGE_LABELS[e.type] ?? e.type.replace(/_/g, " ")
20686
+ }));
20687
+ const knowledgeById = /* @__PURE__ */ new Map();
20688
+ for (const ref of knowledgeByPath.values()) knowledgeById.set(ref.id, ref);
20689
+ const topology = loadSystemTopology(dir);
20690
+ const existingIds = new Set(nodes.map((n) => n.id));
20691
+ for (const e of topology.entities) {
20692
+ const nodeId = `sys:${e.id}`;
20693
+ const node = {
20694
+ id: nodeId,
20695
+ type: e.kind,
20696
+ label: e.label,
20697
+ dimension: "system",
20698
+ implementationRefs: e.implementationRefs,
20699
+ knowledgeRefs: e.knowledgeRefs.map((k) => knowledgeById.get(k)).filter(Boolean),
20700
+ evidence: e.evidence
20701
+ };
20702
+ if (e.purpose) node.purpose = e.purpose;
20703
+ if (e.moduleId) node.moduleId = e.moduleId;
20704
+ if (e.provenance) node.provenance = e.provenance;
20705
+ nodes.push(node);
20706
+ existingIds.add(nodeId);
20707
+ for (const ref of e.implementationRefs) {
20708
+ const fileId = `file:${ref}`;
20709
+ if (!existingIds.has(fileId)) {
20710
+ nodes.push({ id: fileId, type: "file", label: ref.split("/").pop() || ref, dimension: "implementation", path: ref });
20711
+ existingIds.add(fileId);
20712
+ }
20713
+ relationships.push({ id: `${nodeId}~implemented-by~${fileId}`, source: nodeId, target: fileId, type: "implemented-by", label: "implemented by" });
20714
+ }
20715
+ }
20716
+ for (const r of topology.relationships) {
20717
+ relationships.push({ id: `sys:${r.from}~${r.type}~sys:${r.to}`, source: `sys:${r.from}`, target: `sys:${r.to}`, type: r.type, label: r.type.replace(/-/g, " ") });
20718
+ }
20719
+ const usedGroups = new Set(nodes.map((n) => n.moduleId).filter(Boolean));
20720
+ const allGroups = [
20721
+ { id: "core", label: "core", repositoryId: "core", available: true },
20722
+ // A mapped module is available when its repository path resolves relative to the project.
20723
+ ...mapped.map((m) => ({ id: m.id, label: m.id, repositoryId: m.id, available: m.repoPath ? exists(join(dir, m.repoPath)) : false }))
20724
+ ];
20725
+ const groups = allGroups.filter((g) => usedGroups.has(g.id) || g.available === false);
20726
+ const dimensions = emptyDimensions();
20727
+ for (const n of nodes) dimensions[n.dimension]++;
20728
+ const semanticEntityCount = topology.entities.length;
20729
+ const technicalRelationshipCount = relationships.filter((r) => TECHNICAL_RELATIONSHIP_TYPES.has(r.type)).length;
20730
+ const topologyStatus = semanticEntityCount === 0 ? "unavailable" : topology.relationships.length > 0 ? "available" : "partial";
20731
+ return {
20732
+ system: { name: config.project.name },
20733
+ nodes,
20734
+ relationships,
20735
+ groups,
20736
+ metadata: {
20737
+ projectName: config.project.name,
20738
+ structure: config.project.structure,
20739
+ nodeCount: nodes.length,
20740
+ relationshipCount: relationships.length,
20741
+ coverage: hints.quality,
20742
+ available: nodes.length > 0,
20743
+ dimensions,
20744
+ topologyAvailable: dimensions.system > 0,
20745
+ topologyStatus,
20746
+ semanticEntityCount,
20747
+ technicalRelationshipCount,
20748
+ topologyFindings: topology.findings
20749
+ }
20750
+ };
20751
+ }
20752
+ function toNode(n, knowledgeByPath, wiModules, groupIds) {
20753
+ const node = { id: n.id, type: n.type, label: n.label, dimension: dimensionOf(n.type) };
20754
+ if (n.status) node.status = n.status;
20755
+ if (n.path && !/^([a-zA-Z]:[\\/]|\/)/.test(n.path)) node.path = n.path;
20756
+ if (n.type === "work-item") {
20757
+ const wiId = n.id.startsWith("wi:") ? n.id.slice(3) : n.id;
20758
+ node.workItemRef = wiId;
20759
+ const affected = (wiModules.get(wiId) ?? []).filter((m) => groupIds.has(m));
20760
+ if (affected.length === 1) node.moduleId = affected[0];
20761
+ }
20762
+ if (n.path) {
20763
+ const ref = knowledgeByPath.get(n.path);
20764
+ if (ref) node.knowledgeRef = ref;
20765
+ }
20766
+ return node;
20767
+ }
20768
+
20769
+ // src/core/work-item-refinement.ts
20770
+ var RECOMMENDED_AGENT = "work-item-agent";
20771
+ var RECOMMENDED_SKILL = "work-item-refinement";
20772
+ function buildRefinementHandoff(dir, workItemId) {
20773
+ const wi = getWorkItem(dir, workItemId);
20774
+ const config = loadConfig(dir);
20775
+ const projectName = config?.project.name ?? "this project";
20776
+ const mappedModules = loadMappedModules(dir).map((m) => m.id);
20777
+ const multirepo = mappedModules.length > 0;
20778
+ const lines = [
20779
+ `Refine Work Item ${wi.id} \u2014 "${wi.title}" \u2014 in project "${projectName}" using Kaddo.`,
20780
+ "",
20781
+ `Use the canonical ${RECOMMENDED_AGENT} and the ${RECOMMENDED_SKILL} skill (via Kaddo MCP or skills),`,
20782
+ "with access to this repository.",
20783
+ "",
20784
+ "Inspect the actual implementation and the relevant mapped modules before defining the final scope \u2014",
20785
+ "do not guess affected modules from the Work Item title. Read the current behavior in the code first,",
20786
+ "then classify."
20787
+ ];
20788
+ if (multirepo) {
20789
+ lines.push(
20790
+ "",
20791
+ `This is a multirepo project. Evaluate the scope across all relevant mapped modules (${mappedModules.join(", ")})`,
20792
+ "before finalizing affected_modules and module_coverage."
20793
+ );
20794
+ }
20795
+ const topology = getSystemMapProjection(dir).metadata.topologyStatus;
20796
+ if (topology !== "unavailable") {
20797
+ lines.push(
20798
+ "",
20799
+ `The semantic system Graph is ${topology}. When semantic system topology is available:`,
20800
+ "1. identify the relevant system entry points;",
20801
+ "2. query the Kaddo Graph (search / neighbors / paths) for connected entities;",
20802
+ "3. treat Graph results as IMPACT CANDIDATES, not confirmed scope;",
20803
+ "4. inspect the actual implementation in the repository for each relevant candidate;",
20804
+ "5. classify each candidate as affected, reviewed-not-affected or unknown;",
20805
+ "6. preserve the evidence and reasons behind each classification.",
20806
+ "",
20807
+ "A missing Graph relationship does not mean no impact, especially when Graph coverage is partial \u2014",
20808
+ "keep inspecting the repository beyond the Graph candidates when the task requires it."
20809
+ );
20810
+ } else {
20811
+ lines.push(
20812
+ "",
20813
+ "The semantic system Graph is unavailable. Continue repository-driven refinement normally, using the",
20814
+ "repository, Knowledge and mapped modules \u2014 the Graph is enrichment, not a prerequisite."
20815
+ );
20816
+ }
20817
+ lines.push(
20818
+ "",
20819
+ `Update the canonical Work Item ${wi.id} with:`,
20820
+ "- current and target behavior;",
20821
+ "- the end-to-end flow (journey);",
20822
+ "- affected modules;",
20823
+ "- affected system entities (affected_system_entities) and reviewed_system_entities;",
20824
+ "- module coverage;",
20825
+ "- impact analysis across the relevant surfaces;",
20826
+ "- scope confidence and open unknowns;",
20827
+ "- acceptance criteria;",
20828
+ "- relevant Knowledge / ADR relationships.",
20829
+ "",
20830
+ "Do not implement the Work Item. Do not run mutating Git operations."
20831
+ );
20832
+ return {
20833
+ workItemId: wi.id,
20834
+ title: wi.title,
20835
+ projectName,
20836
+ refinement: wi.refinement,
20837
+ recommendedAgent: RECOMMENDED_AGENT,
20838
+ recommendedSkill: RECOMMENDED_SKILL,
20839
+ text: lines.join("\n")
20840
+ };
20841
+ }
20842
+
20843
+ // src/core/work-item-import.ts
20844
+ var MAX_INPUT_BYTES = 102400;
20845
+ function detectFormat(raw) {
20846
+ const trimmed = raw.trim();
20847
+ if (!trimmed) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
20848
+ if (trimmed.startsWith("---")) {
20849
+ try {
20850
+ const { data } = matter15(trimmed);
20851
+ if (data && typeof data === "object" && Object.keys(data).length > 0) {
20852
+ const d = data;
20853
+ if (d.type === "work-item" || d.id && typeof d.id === "string" && /^WI-\d+/.test(d.id)) {
20854
+ return "kaddo-frontmatter";
20855
+ }
20856
+ return "markdown-frontmatter";
20857
+ }
20858
+ } catch {
20859
+ }
20860
+ }
20861
+ if (/^#{1,2}\s+/m.test(trimmed)) return "markdown";
20862
+ return "plain-text";
20863
+ }
20864
+ function parseContent(raw) {
20865
+ const trimmed = raw.trim();
20866
+ if (!trimmed) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
20867
+ const format = detectFormat(trimmed);
20868
+ let frontmatterFields = {};
20869
+ let bodyText = trimmed;
20870
+ if (format === "kaddo-frontmatter" || format === "markdown-frontmatter") {
20871
+ try {
20872
+ const parsed = matter15(trimmed);
20873
+ frontmatterFields = parsed.data ?? {};
20874
+ bodyText = parsed.content.trim();
20875
+ } catch {
20876
+ }
20877
+ }
20878
+ const title = extractTitle(frontmatterFields, bodyText);
20879
+ const candidateType = extractType(frontmatterFields);
20880
+ const sections = extractSections(bodyText);
20881
+ const summary = bodyText || title;
20882
+ return {
20883
+ format,
20884
+ title,
20885
+ type: candidateType,
20886
+ summary,
20887
+ body: bodyText,
20888
+ candidateFields: frontmatterFields,
20889
+ sections
20890
+ };
20891
+ }
20892
+ function extractTitle(fields, body) {
20893
+ if (typeof fields.title === "string" && fields.title.trim()) {
20894
+ return fields.title.trim().slice(0, 120);
20895
+ }
20896
+ const h1Match = body.match(/^#\s+(.+)$/m);
20897
+ if (h1Match) return h1Match[1].trim().slice(0, 120);
20898
+ const firstLine = body.split(/\r?\n/).find((l) => l.trim());
20899
+ return (firstLine?.trim() ?? "Untitled Work Item").slice(0, 120);
20900
+ }
20901
+ function extractType(fields) {
20902
+ const raw = typeof fields.work_type === "string" && fields.work_type.trim() ? fields.work_type.trim() : typeof fields.type === "string" && fields.type.trim() && fields.type !== "work-item" ? fields.type.trim() : void 0;
20903
+ if (!raw) return void 0;
20904
+ return normalizeType(raw) ?? void 0;
20905
+ }
20906
+ function extractSections(body) {
20907
+ const sections = /* @__PURE__ */ new Map();
20908
+ const lines = body.split(/\r?\n/);
20909
+ let currentHeading = null;
20910
+ let buffer = [];
20911
+ const flush = () => {
20912
+ if (currentHeading) {
20913
+ sections.set(currentHeading.toLowerCase(), buffer.join("\n").trim());
20914
+ }
20915
+ buffer = [];
20916
+ };
20917
+ for (const line of lines) {
20918
+ const match = line.match(/^##\s+(.+)$/);
20919
+ if (match) {
20920
+ flush();
20921
+ currentHeading = match[1].trim();
20922
+ } else if (currentHeading) {
20923
+ buffer.push(line);
20924
+ }
20925
+ }
20926
+ flush();
20927
+ return sections;
20928
+ }
20929
+ function normalizeImportFields(parsed, opts) {
20930
+ const type = opts.userType ? normalizeType(opts.userType) ?? "feature" : parsed.type ?? "feature";
20931
+ const intent = parsed.body && parsed.body !== parsed.title ? `${parsed.title}
20932
+
20933
+ ${parsed.body}` : parsed.title;
20934
+ const source = {
20935
+ type: opts.importSource === "chat" ? "chat" : "external",
20936
+ imported_at: (/* @__PURE__ */ new Date()).toISOString().split("T")[0]
20937
+ };
20938
+ source.source_format = opts.sourceFormat;
20939
+ source.source_hash = opts.sourceHash;
20940
+ const snapshot = { title: parsed.title };
20941
+ if (parsed.summary !== parsed.title) snapshot.description = parsed.summary;
20942
+ if (typeof parsed.candidateFields.type === "string") snapshot.type = parsed.candidateFields.type;
20943
+ if (typeof parsed.candidateFields.status === "string") snapshot.status = parsed.candidateFields.status;
20944
+ if (Array.isArray(parsed.candidateFields.labels)) {
20945
+ const labels = parsed.candidateFields.labels.filter((l) => typeof l === "string");
20946
+ if (labels.length > 0) snapshot.labels = labels;
20947
+ }
20948
+ return { type, intent, source, snapshot };
20949
+ }
20950
+ function computeContentHash(raw) {
20951
+ return crypto3.createHash("sha256").update(raw.trim(), "utf-8").digest("hex");
20952
+ }
20953
+ function findDuplicateByHash(dir, hash) {
20954
+ const items = discoverWorkItems(dir);
20955
+ for (const item of items) {
20956
+ const raw = readFile(item.filePath);
20957
+ if (!raw) continue;
20958
+ try {
20959
+ const { data } = matter15(raw);
20960
+ const source = data?.source;
20961
+ if (source && typeof source === "object" && !Array.isArray(source)) {
20962
+ const s = source;
20963
+ if (s.source_hash === hash) {
20964
+ return { workItemId: data.id ?? item.id ?? item.title, path: item.relPath };
20965
+ }
20966
+ }
20967
+ } catch {
20968
+ }
20969
+ }
20970
+ return void 0;
20971
+ }
20972
+ function importWorkItem(dir, opts) {
20973
+ const content = opts.content;
20974
+ if (!content?.trim()) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
20975
+ if (Buffer.byteLength(content, "utf-8") > MAX_INPUT_BYTES) {
20976
+ throw new ImportError("OVERSIZED_INPUT", `Import content exceeds the ${MAX_INPUT_BYTES / 1024}KB limit.`);
20977
+ }
20978
+ const parsed = parseContent(content);
20979
+ const sourceHash = computeContentHash(content);
20980
+ const duplicate = findDuplicateByHash(dir, sourceHash);
20981
+ if (duplicate) {
20982
+ return {
20983
+ created: false,
20984
+ workItemId: duplicate.workItemId,
20985
+ path: duplicate.path,
20986
+ status: "draft",
20987
+ source: opts.source,
20988
+ sourceFormat: parsed.format,
20989
+ sourceHash,
20990
+ duplicateOf: duplicate.workItemId,
20991
+ executed: false
20992
+ };
20993
+ }
20994
+ const normalized = normalizeImportFields(parsed, {
20995
+ userType: opts.type,
20996
+ importSource: opts.source,
20997
+ sourceHash,
20998
+ sourceFormat: parsed.format
20999
+ });
21000
+ const result = createWorkItem(dir, {
21001
+ intent: normalized.intent,
21002
+ type: normalized.type,
21003
+ source: normalized.source,
21004
+ originalSnapshot: normalized.snapshot
21005
+ });
21006
+ let refinementHandoff;
21007
+ try {
21008
+ refinementHandoff = buildRefinementHandoff(dir, result.id);
21009
+ } catch {
21010
+ }
21011
+ return {
21012
+ created: true,
21013
+ workItemId: result.id,
21014
+ path: result.path,
21015
+ status: "draft",
21016
+ source: opts.source,
21017
+ sourceFormat: parsed.format,
21018
+ sourceHash,
21019
+ executed: false,
21020
+ refinementHandoff
21021
+ };
21022
+ }
21023
+ var ImportError = class extends Error {
21024
+ constructor(code, message) {
21025
+ super(message);
21026
+ this.code = code;
21027
+ this.name = "ImportError";
21028
+ }
21029
+ code;
21030
+ };
21031
+
21032
+ // src/commands/work-item.ts
21033
+ function requireProject3(dir) {
21034
+ if (!loadConfig(dir)) {
21035
+ log2.error("No Kaddo project was found in the current directory.");
21036
+ process.exit(1);
21037
+ }
21038
+ }
21039
+ async function runWorkItemImport(dir, fileOrText, opts) {
21040
+ requireProject3(dir);
21041
+ let content;
21042
+ if (opts.text) {
21043
+ content = opts.text;
21044
+ } else if (fileOrText) {
21045
+ if (!exists(fileOrText)) {
21046
+ log2.error(`File not found: ${fileOrText}`);
21047
+ process.exit(1);
21048
+ }
21049
+ content = readFile(fileOrText) ?? void 0;
21050
+ if (!content?.trim()) {
21051
+ log2.error(`File is empty: ${fileOrText}`);
21052
+ process.exit(1);
21053
+ }
21054
+ } else if (!process.stdin.isTTY) {
21055
+ const chunks = [];
21056
+ for await (const chunk of process.stdin) chunks.push(chunk);
21057
+ content = Buffer.concat(chunks).toString("utf-8");
21058
+ }
21059
+ if (!content?.trim()) {
21060
+ log2.error("No content provided. Use a file path, --text, or pipe content via stdin.");
21061
+ process.exit(1);
21062
+ }
21063
+ try {
21064
+ intro2("Import external Work Item");
21065
+ const parsed = parseContent(content);
21066
+ const hash = computeContentHash(content);
21067
+ const duplicate = findDuplicateByHash(dir, hash);
21068
+ if (duplicate) {
21069
+ log2.warn(`Already imported as ${duplicate.workItemId}.`);
21070
+ outro2("No duplicate was created.");
21071
+ return;
21072
+ }
21073
+ log2.info(`Format: ${parsed.format}`);
21074
+ log2.info(`Title: ${parsed.title}`);
21075
+ log2.message(`Type: ${opts.type ?? parsed.type ?? "feature"}`);
21076
+ log2.message("Will create: a Draft Work Item (needs refinement).");
21077
+ log2.message("No project files have been modified yet.");
21078
+ if (!opts.yes) {
21079
+ const ok = await confirm2({ message: "Import this content as a Draft Work Item?" });
21080
+ if (ok !== true) {
21081
+ cancel2("Import cancelled. No files were changed.");
21082
+ process.exit(0);
21083
+ }
21084
+ }
21085
+ const result = importWorkItem(dir, {
21086
+ content,
21087
+ source: "cli",
21088
+ type: opts.type,
21089
+ filePath: fileOrText
21090
+ });
21091
+ if (!result.created) {
21092
+ log2.warn(`Already imported as ${result.duplicateOf}.`);
21093
+ outro2("No duplicate was created.");
21094
+ return;
21095
+ }
21096
+ log2.info(`Created ${result.workItemId} (Draft, needs refinement).`);
21097
+ log2.info(`Path: ${result.path}`);
21098
+ log2.message("executed = false \u2014 the Work Item has NOT been implemented.");
21099
+ if (result.refinementHandoff) {
21100
+ log2.step("Refinement handoff");
21101
+ log2.message(`Agent: ${result.refinementHandoff.recommendedAgent}`);
21102
+ log2.message(`Skill: ${result.refinementHandoff.recommendedSkill}`);
21103
+ }
21104
+ outro2("Done. Refine it next with the Work Item refinement handoff.");
21105
+ } catch (err) {
21106
+ if (err instanceof ImportError) log2.error(`[${err.code}] ${err.message}`);
21107
+ else log2.error("The import operation failed.");
21108
+ process.exit(1);
21109
+ }
21110
+ }
21111
+
20291
21112
  // src/index.ts
20292
21113
  var require2 = createRequire(import.meta.url);
20293
21114
  var { version } = require2("../package.json");
@@ -20343,6 +21164,10 @@ integrationsCmd.command("work-item <id> <external-id>").description("Read a sing
20343
21164
  integrationsCmd.command("import <id> <external-id>").description("Preview and, after confirmation, import an external work item as a Draft Work Item").option("--type <type>", "Kaddo Work Item type (required to create; never inferred from the external type)").option("-y, --yes", "Skip the confirmation prompt (for already-approved automation)").action(async (id, externalId, opts) => {
20344
21165
  await runIntegrationsImport(cwd(), id, externalId, opts);
20345
21166
  });
21167
+ var workItemCmd = program.command("work-item").description("Work Item operations");
21168
+ workItemCmd.command("import [file]").description("Import a Work Item from text or file into Kaddo as a Draft (import \u2260 execute)").option("--text <content>", "Import from inline text instead of a file").option("--type <type>", "Kaddo Work Item type (feature/bugfix/hotfix/spike/chore)").option("-y, --yes", "Skip the confirmation prompt").action(async (file, opts) => {
21169
+ await runWorkItemImport(cwd(), file, opts);
21170
+ });
20346
21171
  var reportCmd = program.command("report").description("Generate Kaddo reports");
20347
21172
  reportCmd.command("impact").description("Knowledge Impact Report: knowledge health, coverage, traceability, readiness (deterministic, no LLM)").option("--json", "Output JSON instead of Markdown").option("--scope <scope>", "Scope: all (default \u2014 accumulated impact) or active").option("--output <path>", "Write the report to a file (e.g. .kaddo/reports/impact-report.md)").action((opts) => {
20348
21173
  runReportImpact(opts);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaddo/cli",
3
- "version": "3.89.0",
3
+ "version": "3.90.0",
4
4
  "description": "Knowledge Driven Development toolkit",
5
5
  "license": "MIT",
6
6
  "repository": {