@kaddo/cli 3.88.4 → 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.
@@ -5,7 +5,7 @@
5
5
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>admin</title>
8
- <script type="module" crossorigin src="/assets/index-CoK1pkwA.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-vkZSMwVO.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/assets/index-DNkI-1xG.css">
10
10
  </head>
11
11
  <body>
@@ -1115,10 +1115,18 @@ async function createAdminServer(opts) {
1115
1115
  if (q.labels) filters.labels = q.labels.split(",");
1116
1116
  if (q.assignees) filters.assignees = q.assignees.split(",");
1117
1117
  if (q.search) filters.search = q.search;
1118
+ let cursors;
1119
+ if (q.cursors) {
1120
+ try {
1121
+ cursors = JSON.parse(q.cursors);
1122
+ } catch {
1123
+ }
1124
+ }
1118
1125
  return asyncCore(reply, () => discoverExternalWorkItemsAdmin(projectDir, {
1119
1126
  filters: Object.keys(filters).length ? filters : void 0,
1120
1127
  pageSize: q.pageSize ? Number.parseInt(q.pageSize, 10) : void 0,
1121
- integrationIds: q.integrationIds ? q.integrationIds.split(",") : void 0
1128
+ integrationIds: q.integrationIds ? q.integrationIds.split(",") : void 0,
1129
+ cursors
1122
1130
  }));
1123
1131
  }
1124
1132
  );
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
@@ -9435,6 +9627,8 @@ function defaultMessageFor(code) {
9435
9627
  return "The external provider is temporarily unavailable.";
9436
9628
  case "INTEGRATION_TIMEOUT":
9437
9629
  return "The external provider did not respond in time.";
9630
+ case "INTEGRATION_INVALID_QUERY":
9631
+ return "The query syntax is invalid. Check filter values or JQL.";
9438
9632
  case "INTEGRATION_PROVIDER_ERROR":
9439
9633
  return "The external provider returned an error.";
9440
9634
  case "UNSUPPORTED_CAPABILITY":
@@ -10146,13 +10340,19 @@ async function handleJiraResponse(res) {
10146
10340
  if (res.status >= 500) throw integrationError("INTEGRATION_UNAVAILABLE");
10147
10341
  if (!res.ok) {
10148
10342
  let detail = "";
10343
+ let isJqlError = false;
10149
10344
  try {
10150
10345
  const body = await res.json();
10151
10346
  const msgs = body.errorMessages?.filter(Boolean) ?? [];
10152
10347
  const fieldErrs = body.errors ? Object.entries(body.errors).map(([k, v]) => `${k}: ${v}`) : [];
10153
10348
  detail = [...msgs, ...fieldErrs].join("; ");
10349
+ if (res.status === 400) {
10350
+ const combined = detail.toLowerCase();
10351
+ isJqlError = combined.includes("jql") || combined.includes("query") || combined.includes("field") || combined.includes("clause");
10352
+ }
10154
10353
  } catch {
10155
10354
  }
10355
+ if (isJqlError) throw integrationError("INTEGRATION_INVALID_QUERY");
10156
10356
  throw integrationError("INTEGRATION_PROVIDER_ERROR", detail || `Jira responded with status ${res.status}.`);
10157
10357
  }
10158
10358
  return await res.json();
@@ -10678,8 +10878,9 @@ async function discoverExternalWorkItems(dir, opts = {}, env = process.env) {
10678
10878
  const adapter = resolveAdapter(integration);
10679
10879
  const { context } = await buildContextWithSecrets(dir, integration, env);
10680
10880
  const filters = mergeFilters(integration.filters, opts.filters);
10881
+ const cursor = opts.cursors?.[integration.id];
10681
10882
  const page = await withTimeout(
10682
- adapter.listWorkItems({ context, pageSize: opts.pageSize, filters }),
10883
+ adapter.listWorkItems({ context, cursor, pageSize: opts.pageSize, filters }),
10683
10884
  context.timeoutMs
10684
10885
  );
10685
10886
  return {
@@ -10729,7 +10930,7 @@ function findLinkedWorkItem(dir, integrationId, externalId) {
10729
10930
  for (const art of discoverWorkItems(dir)) {
10730
10931
  let data;
10731
10932
  try {
10732
- data = matter8(readFile(art.filePath)).data;
10933
+ data = matter9(readFile(art.filePath)).data;
10733
10934
  } catch {
10734
10935
  continue;
10735
10936
  }
@@ -10745,7 +10946,7 @@ function buildImportIndex(dir) {
10745
10946
  for (const art of discoverWorkItems(dir)) {
10746
10947
  let data;
10747
10948
  try {
10748
- data = matter8(readFile(art.filePath)).data;
10949
+ data = matter9(readFile(art.filePath)).data;
10749
10950
  } catch {
10750
10951
  continue;
10751
10952
  }
@@ -10756,48 +10957,61 @@ function buildImportIndex(dir) {
10756
10957
  }
10757
10958
  return index;
10758
10959
  }
10960
+ var importLocks = /* @__PURE__ */ new Set();
10759
10961
  async function previewImport(dir, id, externalId, opts = {}, env = process.env) {
10962
+ const { integration } = requireIntegration(dir, id);
10963
+ if (!integration.enabled) throw new IntegrationServiceError("INTEGRATION_DISABLED", `Integration "${id}" is disabled. Enable it before previewing imports.`);
10760
10964
  const item = await getExternalWorkItem(dir, id, externalId, env);
10761
10965
  if (!item) throw integrationError("INTEGRATION_NOT_FOUND", `External work item "${externalId}" was not found.`);
10762
10966
  const preview = buildImportPreview(item, { integrationId: id, type: opts.type });
10763
10967
  return { preview, duplicate: findLinkedWorkItem(dir, id, externalId) };
10764
10968
  }
10765
10969
  async function importExternalWorkItem(dir, id, externalId, opts, env = process.env) {
10766
- const item = await getExternalWorkItem(dir, id, externalId, env);
10767
- if (!item) throw integrationError("INTEGRATION_NOT_FOUND", `External work item "${externalId}" was not found.`);
10768
- const preview = buildImportPreview(item, { integrationId: id, type: opts.type });
10769
- const existing = findLinkedWorkItem(dir, id, externalId);
10770
- if (existing) return { workItemId: existing.workItemId, created: false, duplicateOf: existing.workItemId, preview };
10771
- const intent = item.description ? `${item.title}
10970
+ const { integration } = requireIntegration(dir, id);
10971
+ if (!integration.enabled) throw new IntegrationServiceError("INTEGRATION_DISABLED", `Integration "${id}" is disabled. Enable it before importing.`);
10972
+ const lockKey = `${id}#${externalId}`;
10973
+ if (importLocks.has(lockKey)) throw new IntegrationServiceError("INTEGRATION_INVALID_INPUT", "Import already in progress for this item.");
10974
+ importLocks.add(lockKey);
10975
+ try {
10976
+ const item = await getExternalWorkItem(dir, id, externalId, env);
10977
+ if (!item) throw integrationError("INTEGRATION_NOT_FOUND", `External work item "${externalId}" was not found.`);
10978
+ const preview = buildImportPreview(item, { integrationId: id, type: opts.type });
10979
+ const existing = findLinkedWorkItem(dir, id, externalId);
10980
+ if (existing) return { workItemId: existing.workItemId, created: false, duplicateOf: existing.workItemId, preview };
10981
+ const intent = item.description ? `${item.title}
10772
10982
 
10773
10983
  ${item.description}` : item.title;
10774
- const created = createWorkItem(dir, {
10775
- intent,
10776
- type: opts.type,
10777
- source: {
10778
- type: "external",
10779
- provider: item.provider,
10780
- integration: id,
10781
- id: externalId,
10782
- url: item.url,
10783
- imported_at: (/* @__PURE__ */ new Date()).toISOString(),
10784
- external_updated_at: item.updatedAt
10785
- },
10786
- originalSnapshot: {
10787
- title: item.title,
10788
- description: item.description,
10789
- type: item.type,
10790
- status: item.status,
10791
- labels: item.labels,
10792
- assignee: item.assignees?.[0]?.name,
10793
- created_at: item.createdAt,
10794
- updated_at: item.updatedAt
10795
- }
10796
- });
10797
- return { workItemId: created.id, created: true, preview, path: created.path };
10984
+ const created = createWorkItem(dir, {
10985
+ intent,
10986
+ type: opts.type,
10987
+ source: {
10988
+ type: "external",
10989
+ provider: item.provider,
10990
+ integration: id,
10991
+ id: externalId,
10992
+ url: item.url,
10993
+ imported_at: (/* @__PURE__ */ new Date()).toISOString(),
10994
+ external_updated_at: item.updatedAt
10995
+ },
10996
+ originalSnapshot: {
10997
+ title: item.title,
10998
+ description: item.description,
10999
+ type: item.type,
11000
+ status: item.status,
11001
+ labels: item.labels,
11002
+ assignee: item.assignees?.[0]?.name,
11003
+ created_at: item.createdAt,
11004
+ updated_at: item.updatedAt
11005
+ }
11006
+ });
11007
+ return { workItemId: created.id, created: true, preview, path: created.path };
11008
+ } finally {
11009
+ importLocks.delete(lockKey);
11010
+ }
10798
11011
  }
10799
11012
  export {
10800
11013
  INTEGRATIONS_FILE,
11014
+ ImportError,
10801
11015
  IntegrationError,
10802
11016
  IntegrationServiceError,
10803
11017
  TOPOLOGY_FILE,
@@ -10813,17 +11027,20 @@ export {
10813
11027
  buildReadinessReport,
10814
11028
  buildRefinementHandoff,
10815
11029
  buildTopologyEnrichmentHandoff,
11030
+ computeContentHash,
10816
11031
  computeRefinementStatus,
10817
11032
  createIntegration,
10818
11033
  createWorkItem,
10819
11034
  cwd,
10820
11035
  deleteIntegration,
11036
+ detectFormat,
10821
11037
  disableIntegration,
10822
11038
  discoverExternalWorkItems,
10823
11039
  discoverKnowledge,
10824
11040
  discoverWorkItems,
10825
11041
  enableIntegration,
10826
11042
  exists,
11043
+ findDuplicateByHash,
10827
11044
  findLinkedWorkItem,
10828
11045
  findSystemPaths,
10829
11046
  getAvailableIntegrationTypes,
@@ -10841,6 +11058,7 @@ export {
10841
11058
  getWorkItems,
10842
11059
  getWorkItemsSummary,
10843
11060
  importExternalWorkItem,
11061
+ importWorkItem,
10844
11062
  integrationRegistry,
10845
11063
  isActiveState,
10846
11064
  isModule,
@@ -10853,6 +11071,7 @@ export {
10853
11071
  loadConfig,
10854
11072
  loadMappedModules,
10855
11073
  loadSystemTopology,
11074
+ parseContent,
10856
11075
  previewImport,
10857
11076
  readFile,
10858
11077
  removeIntegrationSecret,