@swarmcraftai/cli 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.cjs CHANGED
@@ -366,18 +366,18 @@ var require_packetFile = __commonJS({
366
366
  };
367
367
  Object.defineProperty(exports2, "__esModule", { value: true });
368
368
  exports2.PacketFileContractError = exports2.PROVISIONAL_TASK_ID_PREFIX = exports2.PACKET_FILE_ROOT = exports2.WORKFLOW_STATES = exports2.CHECKLIST_STAGES = void 0;
369
- exports2.renderPacketFile = renderPacketFile2;
369
+ exports2.renderPacketFile = renderPacketFile;
370
370
  exports2.renderProvisionalPacketFile = renderProvisionalPacketFile;
371
371
  exports2.renderChecklistSection = renderChecklistSection;
372
- exports2.resolvePacketFilePath = resolvePacketFilePath3;
373
- exports2.parsePacketFile = parsePacketFile5;
372
+ exports2.resolvePacketFilePath = resolvePacketFilePath2;
373
+ exports2.parsePacketFile = parsePacketFile4;
374
374
  exports2.rewritePacketFileMetadata = rewritePacketFileMetadata2;
375
375
  exports2.rewriteProvisionalPacketFileMetadata = rewriteProvisionalPacketFileMetadata;
376
376
  exports2.rewritePacketFile = rewritePacketFile;
377
377
  exports2.markChecklistStageComplete = markChecklistStageComplete;
378
378
  exports2.appendAgentUpdateLines = appendAgentUpdateLines;
379
379
  exports2.composeTaskNotes = composeTaskNotes2;
380
- exports2.ensurePacketFileIdentity = ensurePacketFileIdentity2;
380
+ exports2.ensurePacketFileIdentity = ensurePacketFileIdentity;
381
381
  exports2.ensurePacketMatches = ensurePacketMatches;
382
382
  exports2.isProvisionalPacketFile = isProvisionalPacketFile;
383
383
  exports2.assertProvisionalPacketFile = assertProvisionalPacketFile;
@@ -399,7 +399,7 @@ var require_packetFile = __commonJS({
399
399
  exports2.PACKET_FILE_ROOT = ".swarmcraft/projects/";
400
400
  exports2.PROVISIONAL_TASK_ID_PREFIX = "provisional:";
401
401
  var CHECKLIST_SYNC_COMMENT = "<!-- Checklist scope is owner-controlled. Record intentional edits and completion evidence in Notes or Agent Update; optional board sync reconciles changes. -->";
402
- var PacketFileContractError2 = class extends Error {
402
+ var PacketFileContractError = class extends Error {
403
403
  code;
404
404
  constructor(code, message) {
405
405
  super(message);
@@ -407,9 +407,9 @@ var require_packetFile = __commonJS({
407
407
  this.code = code;
408
408
  }
409
409
  };
410
- exports2.PacketFileContractError = PacketFileContractError2;
411
- function renderPacketFile2(project, task, syncedAt, existingContents = null) {
412
- const existingPacket = existingContents ? parsePacketFile5(existingContents) : null;
410
+ exports2.PacketFileContractError = PacketFileContractError;
411
+ function renderPacketFile(project, task, syncedAt, existingContents = null) {
412
+ const existingPacket = existingContents ? parsePacketFile4(existingContents) : null;
413
413
  const storedSections = existingPacket ? existingPacket.sections : splitStoredTaskNotes(task.notes ?? null);
414
414
  const goal = task.summary?.trim() ? task.summary.trim() : "Describe the outcome in one short paragraph.";
415
415
  return preservePacketLineEndings(existingContents ?? "", () => [
@@ -520,32 +520,32 @@ var require_packetFile = __commonJS({
520
520
  }
521
521
  return normalizedItems.map((item) => `- [ ] ${item}`).join("\n");
522
522
  }
523
- function resolvePacketFilePath3(project, task, packetLink = task.packetLink) {
523
+ function resolvePacketFilePath2(project, task, packetLink = task.packetLink) {
524
524
  if (packetLink) {
525
525
  return packetLink.packetFilePath;
526
526
  }
527
527
  return node_path_1.default.posix.join(".swarmcraft", "projects", slugify(project.title || project.projectTitle || project.id), `${task.recommendedOrder}-${slugify(task.title || "task")}.md`);
528
528
  }
529
- function parsePacketFile5(contents) {
529
+ function parsePacketFile4(contents) {
530
530
  const { frontmatter, body } = parsePacketFileDocument(contents);
531
531
  const sections = parseSections(body);
532
532
  const requiredSections = ["Goal", "Notes", "Agent Update"];
533
533
  for (const section of requiredSections) {
534
534
  if (!(section in sections)) {
535
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", `The packet file is missing the required ${section} section.`);
535
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", `The packet file is missing the required ${section} section.`);
536
536
  }
537
537
  }
538
538
  const lane = parseLane(frontmatter.lane);
539
539
  const syncRevision = Number(frontmatter.syncRevision ?? (Number(frontmatter.swarmcraftVersion) >= 3 ? "0" : "NaN"));
540
540
  if (!Number.isInteger(syncRevision) || syncRevision < 0) {
541
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "The packet file is missing a valid syncRevision frontmatter value.");
541
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "The packet file is missing a valid syncRevision frontmatter value.");
542
542
  }
543
543
  const swarmcraftVersion = Number(frontmatter.swarmcraftVersion);
544
544
  if (!Number.isInteger(swarmcraftVersion) || ![2, 3, 4].includes(swarmcraftVersion)) {
545
- throw new PacketFileContractError2("PACKET_FILE_UNSUPPORTED_VERSION", "The packet file must declare supported swarmcraftVersion: 2, 3 or 4. Upgrade the client; do not regenerate the packet.");
545
+ throw new PacketFileContractError("PACKET_FILE_UNSUPPORTED_VERSION", "The packet file must declare supported swarmcraftVersion: 2, 3 or 4. Upgrade the client; do not regenerate the packet.");
546
546
  }
547
547
  if (swarmcraftVersion >= 3 && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(frontmatter.packetId ?? "")) {
548
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "V3 packets require a UUID packetId.");
548
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "V3 packets require a UUID packetId.");
549
549
  }
550
550
  const order = frontmatter.recommendedOrder === void 0 ? void 0 : Number(frontmatter.recommendedOrder);
551
551
  let ordered;
@@ -561,7 +561,7 @@ var require_packetFile = __commonJS({
561
561
  if (swarmcraftVersion < 4 && ordered.execution)
562
562
  throw new Error("Execution policy requires V4.");
563
563
  } catch (error) {
564
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", String(error));
564
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", String(error));
565
565
  }
566
566
  return {
567
567
  frontmatter: {
@@ -616,8 +616,8 @@ ${key}: ${value}`;
616
616
  function rewritePacketFile(input) {
617
617
  let rewritten = rewritePacketFileMetadata2(input.contents, {
618
618
  lane: input.lane,
619
- syncRevision: parsePacketFile5(input.contents).frontmatter.syncRevision,
620
- lastSyncedAt: input.syncedAt ?? parsePacketFile5(input.contents).frontmatter.lastSyncedAt
619
+ syncRevision: parsePacketFile4(input.contents).frontmatter.syncRevision,
620
+ lastSyncedAt: input.syncedAt ?? parsePacketFile4(input.contents).frontmatter.lastSyncedAt
621
621
  });
622
622
  rewritten = markChecklistStageComplete(rewritten, input.completeStage);
623
623
  return appendAgentUpdateLines(rewritten, input.agentUpdateLines);
@@ -655,15 +655,15 @@ ${key}: ${value}`;
655
655
  }
656
656
  return ["## Notes", "", normalizedNotes, "", "## Agent Update", "", normalizedAgentUpdate].join("\n");
657
657
  }
658
- function ensurePacketFileIdentity2(contents, projectId, taskId) {
658
+ function ensurePacketFileIdentity(contents, projectId, taskId) {
659
659
  const { frontmatter } = parsePacketFileDocument(contents);
660
660
  if (frontmatter.projectId !== projectId || frontmatter.taskId !== taskId) {
661
- throw new PacketFileContractError2("PACKET_FILE_MISMATCH", `The existing packet file is linked to ${frontmatter.taskId ?? "another task"} and cannot be reused for ${taskId}.`);
661
+ throw new PacketFileContractError("PACKET_FILE_MISMATCH", `The existing packet file is linked to ${frontmatter.taskId ?? "another task"} and cannot be reused for ${taskId}.`);
662
662
  }
663
663
  }
664
664
  function ensurePacketMatches(packet, projectId, taskId) {
665
665
  if (packet.frontmatter.projectId !== projectId || packet.frontmatter.taskId !== taskId) {
666
- throw new PacketFileContractError2("PACKET_FILE_MISMATCH", `The packet file belongs to ${packet.frontmatter.taskId} and cannot sync into ${taskId}.`);
666
+ throw new PacketFileContractError("PACKET_FILE_MISMATCH", `The packet file belongs to ${packet.frontmatter.taskId} and cannot sync into ${taskId}.`);
667
667
  }
668
668
  }
669
669
  function isProvisionalPacketFile(packet) {
@@ -671,19 +671,19 @@ ${key}: ${value}`;
671
671
  }
672
672
  function assertProvisionalPacketFile(packet) {
673
673
  if (!isProvisionalPacketFile(packet)) {
674
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "Provisional packets must use provisional: true, taskId: provisional:<slug>, lane: todo, and syncRevision: 0.");
674
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Provisional packets must use provisional: true, taskId: provisional:<slug>, lane: todo, and syncRevision: 0.");
675
675
  }
676
676
  const title = packet.frontmatter.title?.trim();
677
677
  if (!title) {
678
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "Provisional packets must include a title frontmatter value.");
678
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Provisional packets must include a title frontmatter value.");
679
679
  }
680
680
  if (!packet.sections.goal.trim()) {
681
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "Provisional packets must include a Goal section.");
681
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Provisional packets must include a Goal section.");
682
682
  }
683
683
  for (const checklistStage of exports2.CHECKLIST_STAGES) {
684
684
  for (const checklistItem of packet.sections.checklists[checklistStage]) {
685
685
  if (checklistItem.completed) {
686
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "Provisional packet checklist items must start unchecked.");
686
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Provisional packet checklist items must start unchecked.");
687
687
  }
688
688
  }
689
689
  }
@@ -714,7 +714,7 @@ ${key}: ${value}`;
714
714
  function assertChecklistShape(currentChecklistItems, parsedChecklistItemsByStage) {
715
715
  const problem = findChecklistShapeProblem2(currentChecklistItems, parsedChecklistItemsByStage);
716
716
  if (problem) {
717
- throw new PacketFileContractError2("PACKET_FILE_UNSUPPORTED_CHECKLIST", problem.message);
717
+ throw new PacketFileContractError("PACKET_FILE_UNSUPPORTED_CHECKLIST", problem.message);
718
718
  }
719
719
  }
720
720
  function listChecklistItemsForStage2(checklistItems, checklistStage) {
@@ -762,7 +762,7 @@ ${key}: ${value}`;
762
762
  const contents = normalizePacketText(original);
763
763
  const match = contents.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
764
764
  if (!match) {
765
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "The packet file is missing SwarmCraft frontmatter.");
765
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "The packet file is missing SwarmCraft frontmatter.");
766
766
  }
767
767
  const frontmatterBlock = match[1] ?? "";
768
768
  return {
@@ -804,7 +804,7 @@ ${key}: ${value}`;
804
804
  index++;
805
805
  }
806
806
  if (!dependencies.length)
807
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "dependsOn must be an array of packet UUIDs; use [] for no prerequisites.");
807
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "dependsOn must be an array of packet UUIDs; use [] for no prerequisites.");
808
808
  value = JSON.stringify(dependencies);
809
809
  } else if (key === "dependsOn") {
810
810
  const flow = value.replace(/\s+#.*$/, "").match(/^\[(.*)\]$/);
@@ -895,7 +895,7 @@ ${key}: ${value}`;
895
895
  }
896
896
  const match = line.match(/^- \[([ xX])\] (.+)$/);
897
897
  if (!match) {
898
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "Checklist entries must use the markdown checkbox form '- [ ] item'.");
898
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Checklist entries must use the markdown checkbox form '- [ ] item'.");
899
899
  }
900
900
  entries.push({
901
901
  completed: match[1].toLowerCase() === "x",
@@ -908,11 +908,11 @@ ${key}: ${value}`;
908
908
  if (exports2.WORKFLOW_STATES.includes(value)) {
909
909
  return value;
910
910
  }
911
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", "The packet file lane frontmatter must be one of todo, doing, checking, reviewing, or done.");
911
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", "The packet file lane frontmatter must be one of todo, doing, checking, reviewing, or done.");
912
912
  }
913
913
  function requireFrontmatterValue(value, key) {
914
914
  if (!value) {
915
- throw new PacketFileContractError2("PACKET_FILE_MALFORMED", `The packet file is missing the required ${key} frontmatter value.`);
915
+ throw new PacketFileContractError("PACKET_FILE_MALFORMED", `The packet file is missing the required ${key} frontmatter value.`);
916
916
  }
917
917
  return value;
918
918
  }
@@ -1247,7 +1247,7 @@ var require_localPacket = __commonJS({
1247
1247
  exports2.packetSnapshot = packetSnapshot3;
1248
1248
  exports2.newPacketId = newPacketId;
1249
1249
  exports2.localPacketId = localPacketId2;
1250
- exports2.migrateLocalPacket = migrateLocalPacket2;
1250
+ exports2.migrateLocalPacket = migrateLocalPacket;
1251
1251
  exports2.duplicatePacketIds = duplicatePacketIds;
1252
1252
  exports2.validateLocalPacket = validateLocalPacket2;
1253
1253
  exports2.validatePacketCompletion = validatePacketCompletion2;
@@ -1280,7 +1280,7 @@ var require_localPacket = __commonJS({
1280
1280
  const hex = (0, node_crypto_1.createHash)("sha256").update(JSON.stringify([packet.frontmatter.projectId, packet.frontmatter.taskId])).digest("hex");
1281
1281
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
1282
1282
  }
1283
- function migrateLocalPacket2(original) {
1283
+ function migrateLocalPacket(original) {
1284
1284
  const packet = (0, packetFile_js_1.parsePacketFile)(original);
1285
1285
  if (packet.frontmatter.swarmcraftVersion >= 3)
1286
1286
  return original;
@@ -1333,7 +1333,7 @@ packetId: ${localPacketId2(packet)}`);
1333
1333
  return { snapshot, conflicts };
1334
1334
  }
1335
1335
  function applyPacketSnapshot2(contents, snapshot, link) {
1336
- return (0, packetFile_js_1.preservePacketLineEndings)(migrateLocalPacket2(contents), (migrated) => {
1336
+ return (0, packetFile_js_1.preservePacketLineEndings)(migrateLocalPacket(contents), (migrated) => {
1337
1337
  let result = migrated;
1338
1338
  const before = packetSnapshot3((0, packetFile_js_1.parsePacketFile)(result));
1339
1339
  const metadata = (key, value, rendered = `${key}: ${value}`) => {
@@ -1396,7 +1396,7 @@ ${body}
1396
1396
  return fields.join("\n");
1397
1397
  }
1398
1398
  function migrateOrderedPacket(contents, filename, hostedOrder, dependsOn) {
1399
- const migrated = migrateLocalPacket2(contents);
1399
+ const migrated = migrateLocalPacket(contents);
1400
1400
  const packet = (0, packetFile_js_1.parsePacketFile)(migrated);
1401
1401
  if (packet.frontmatter.swarmcraftVersion === 4)
1402
1402
  return migrated;
@@ -1411,6 +1411,67 @@ ${body}
1411
1411
  }
1412
1412
  });
1413
1413
 
1414
+ // ../../packages/packet-workflow/dist/packetSync.js
1415
+ var require_packetSync = __commonJS({
1416
+ "../../packages/packet-workflow/dist/packetSync.js"(exports2) {
1417
+ "use strict";
1418
+ Object.defineProperty(exports2, "__esModule", { value: true });
1419
+ exports2.planPacketSync = planPacketSync3;
1420
+ exports2.summarisePacketSync = summarisePacketSync2;
1421
+ var packetFile_js_1 = require_packetFile();
1422
+ var localPacket_js_1 = require_localPacket();
1423
+ async function planPacketSync3(input) {
1424
+ const entries = [];
1425
+ const ordered = [...input.tasks].sort((left, right) => left.recommendedOrder - right.recommendedOrder);
1426
+ for (const task of ordered) {
1427
+ if (task.workflowState === "done" && !input.includeDone) {
1428
+ entries.push({ action: "skip", taskId: task.id, title: task.title, relativePath: null, reason: "completed on the board" });
1429
+ continue;
1430
+ }
1431
+ if (task.packetLink && task.packetLink.workspaceFolder !== input.workspaceFolder) {
1432
+ entries.push({ action: "skip", taskId: task.id, title: task.title, relativePath: task.packetLink.packetFilePath, reason: `linked to workspace ${task.packetLink.workspaceFolder}` });
1433
+ continue;
1434
+ }
1435
+ const relativePath = (0, packetFile_js_1.resolvePacketFilePath)(input.project, task, task.packetLink);
1436
+ const needsLink = !(task.packetLink && task.packetLink.packetFilePath === relativePath);
1437
+ const existing = await input.readExisting(relativePath);
1438
+ if (existing === null) {
1439
+ entries.push({ action: "create", taskId: task.id, title: task.title, relativePath, contents: (0, localPacket_js_1.migrateLocalPacket)((0, packetFile_js_1.renderPacketFile)(input.project, task, input.syncedAt)), needsLink });
1440
+ continue;
1441
+ }
1442
+ try {
1443
+ (0, packetFile_js_1.ensurePacketFileIdentity)(existing, input.project.id, task.id);
1444
+ (0, packetFile_js_1.parsePacketFile)(existing);
1445
+ } catch (error) {
1446
+ if (error instanceof packetFile_js_1.PacketFileContractError && (error.code === "PACKET_FILE_MALFORMED" || error.code === "PACKET_FILE_MISMATCH")) {
1447
+ entries.push({
1448
+ action: "skip",
1449
+ taskId: task.id,
1450
+ title: task.title,
1451
+ relativePath,
1452
+ reason: error.code === "PACKET_FILE_MISMATCH" ? "existing file belongs to another task" : "existing packet is malformed"
1453
+ });
1454
+ continue;
1455
+ }
1456
+ throw error;
1457
+ }
1458
+ const migrated = (0, localPacket_js_1.migrateLocalPacket)(existing);
1459
+ entries.push({ action: migrated === existing ? "unchanged" : "refresh", taskId: task.id, title: task.title, relativePath, contents: migrated, needsLink });
1460
+ }
1461
+ return entries;
1462
+ }
1463
+ function summarisePacketSync2(entries) {
1464
+ const counts = { create: 0, refresh: 0, unchanged: 0, skip: 0, links: 0 };
1465
+ for (const entry of entries) {
1466
+ counts[entry.action] += 1;
1467
+ if (entry.action !== "skip" && entry.needsLink)
1468
+ counts.links += 1;
1469
+ }
1470
+ return counts;
1471
+ }
1472
+ }
1473
+ });
1474
+
1414
1475
  // ../../packages/packet-workflow/dist/deliveryPolicy.js
1415
1476
  var require_deliveryPolicy = __commonJS({
1416
1477
  "../../packages/packet-workflow/dist/deliveryPolicy.js"(exports2) {
@@ -1465,6 +1526,7 @@ var require_dist = __commonJS({
1465
1526
  __exportStar(require_workflowContract(), exports2);
1466
1527
  __exportStar(require_localPacket(), exports2);
1467
1528
  __exportStar(require_executionMetadata(), exports2);
1529
+ __exportStar(require_packetSync(), exports2);
1468
1530
  var deliveryPolicy_1 = require_deliveryPolicy();
1469
1531
  Object.defineProperty(exports2, "parseDeliveryMode", { enumerable: true, get: function() {
1470
1532
  return deliveryPolicy_1.parseDeliveryMode;
@@ -45689,8 +45751,8 @@ var require_graceful_fs = __commonJS({
45689
45751
  fs2.createReadStream = createReadStream;
45690
45752
  fs2.createWriteStream = createWriteStream2;
45691
45753
  var fs$readFile = fs2.readFile;
45692
- fs2.readFile = readFile13;
45693
- function readFile13(path16, options, cb) {
45754
+ fs2.readFile = readFile14;
45755
+ function readFile14(path16, options, cb) {
45694
45756
  if (typeof options === "function")
45695
45757
  cb = options, options = null;
45696
45758
  return go$readFile(path16, options, cb);
@@ -66284,6 +66346,10 @@ Read **docs/discovery/README.md**, the nine curated discovery documents, and **.
66284
66346
 
66285
66347
  Never skip directly to package preparation merely because files exist.
66286
66348
 
66349
+ ## Generated project context is not owner evidence
66350
+
66351
+ Files such as **.swarmcraft/project.context.md**, **.swarmcraft/project.seed-summary.md**, and SwarmCraft-managed sections of **AGENTS.md** or **CLAUDE.md** are generated from a server-side project record, not from this owner. Never present their actors, systems, dependencies, or constraints as things the owner mentioned, and never record them in a curated document or source manifest as confirmed. Evidence comes only from the owner's own answers and the sources they select. If generated context names a different business, product, or project from the one the owner describes, stop and tell the owner the repository may be bound to the wrong SwarmCraft project before continuing.
66352
+
66287
66353
  ## Stage 1: gather sources
66288
66354
 
66289
66355
  When the source manifest is absent or has **GATHERING** status:
@@ -66362,6 +66428,12 @@ Use this manifest shape (repeat source entries as needed):
66362
66428
  }
66363
66429
  \`\`\`
66364
66430
 
66431
+ Set \`kind\` to exactly one of these values; any other value blocks package preparation:
66432
+
66433
+ - \`TEXT\`: a Markdown, text, or CSV file (\`.md\`, \`.txt\`, \`.csv\`) used directly as evidence.
66434
+ - \`BINARY_WITH_SIDECAR\`: a PDF, image, Office, archive, audio, or video original with a current Markdown sidecar.
66435
+ - \`UNSUPPORTED_BINARY\`: every other inventoried file, including HTML, code, stylesheets, SVG, JSON, and binaries without a sidecar. Always record it with \`selected: false\`.
66436
+
66365
66437
  For \`BINARY_WITH_SIDECAR\`, the source entry names and digests the binary and includes a \`sidecar\` object with \`logicalPath\`, \`digest\`, \`bytes\`, \`originalDigest\`, \`extractionMethod\`, \`extractedAt\`, \`coverageSummary\`, and \`requiresVisualReview\`. Preserve optional owner-authored \`visualReviewEvidence\` containing \`completedAt\` and \`confirmationSummary\`; it is valid only when \`requiresVisualReview\` is false. Keep unselected and unsupported inventory entries with \`selected: false\` so the aggregate decision remains auditable. Create and select \`docs/discovery/sources/owner-interview.md\` for every discovery; record the progressive opening answers, research references, proposed direction, owner corrections, material choices, and dates there.
66366
66438
 
66367
66439
  ## Binary and sidecar rules
@@ -66566,7 +66638,7 @@ var require_seedDiscoveryFiles = __commonJS({
66566
66638
  var renderPrototype_1 = require_renderPrototype();
66567
66639
  var renderDesign_1 = require_renderDesign();
66568
66640
  var renderReports_1 = require_renderReports();
66569
- exports2.DISCOVERY_SEED_VERSION = 16;
66641
+ exports2.DISCOVERY_SEED_VERSION = 18;
66570
66642
  exports2.DISCOVERY_SEED_STATE_PATH = ".swarmcraft/discovery.seed-state.json";
66571
66643
  var LEGACY_UNCHANGED_DISCOVERY_GUIDE_HASHES = /* @__PURE__ */ new Set([
66572
66644
  "810536d02524e6a11b4b93d1828d5e799380de2619dc481e91c6a02eb487984b",
@@ -68727,6 +68799,16 @@ var require_discoveryWorkflow = __commonJS({
68727
68799
  confirmedAt: selectionEvidenceValue.confirmedAt,
68728
68800
  confirmationSummary: selectionEvidenceValue.confirmationSummary
68729
68801
  };
68802
+ const invalidEntries = value.sources.flatMap((source, index) => {
68803
+ const problem = sourceEntryProblem(source);
68804
+ return problem ? [{ index, source, problem }] : [];
68805
+ });
68806
+ if (invalidEntries.length > 0) {
68807
+ const [first] = invalidEntries;
68808
+ const path16 = isRecord(first.source) && typeof first.source.logicalPath === "string" ? ` (${first.source.logicalPath})` : "";
68809
+ const others = invalidEntries.length > 1 ? ` ${invalidEntries.length - 1} more source entr${invalidEntries.length === 2 ? "y is" : "ies are"} also invalid.` : "";
68810
+ throw new Error(`Discovery source entry ${first.index + 1}${path16} in ${exports2.DISCOVERY_SOURCE_MANIFEST_PATH} is invalid: ${first.problem}.${others}`);
68811
+ }
68730
68812
  const sources = value.sources.map(parseSelectedSource);
68731
68813
  const paths = /* @__PURE__ */ new Set();
68732
68814
  for (const source of sources) {
@@ -68819,12 +68901,12 @@ var require_discoveryWorkflow = __commonJS({
68819
68901
  return manifest.sources.filter((source) => source.selected).map((source) => source.kind === "TEXT" ? source.logicalPath : source.sidecar?.logicalPath).filter((value) => Boolean(value));
68820
68902
  }
68821
68903
  function parseSelectedSource(value) {
68822
- if (!isRecord(value) || typeof value.logicalPath !== "string" || !isSafeDiscoveryPath(value.logicalPath) || !isSourceKind(value.kind) || typeof value.digest !== "string" || !DIGEST.test(value.digest) || typeof value.bytes !== "number" || !Number.isSafeInteger(value.bytes) || value.bytes < 0 || typeof value.selected !== "boolean" || typeof value.rationale !== "string") {
68904
+ if (!isRecord(value) || typeof value.logicalPath !== "string" || !isSourceKind(value.kind) || typeof value.digest !== "string" || typeof value.bytes !== "number" || typeof value.selected !== "boolean" || typeof value.rationale !== "string") {
68823
68905
  throw new Error("A discovery source entry is invalid.");
68824
68906
  }
68825
68907
  if (value.kind === "TEXT" && !TEXT_PATH.test(value.logicalPath))
68826
68908
  throw new Error(`Text discovery source must be Markdown, text or CSV: ${value.logicalPath}`);
68827
- if (value.kind !== "TEXT" && !BINARY_PATH.test(value.logicalPath))
68909
+ if (value.kind === "BINARY_WITH_SIDECAR" && !BINARY_PATH.test(value.logicalPath))
68828
68910
  throw new Error(`Binary discovery source has an unsupported format: ${value.logicalPath}`);
68829
68911
  let sidecar;
68830
68912
  if (value.sidecar !== void 0) {
@@ -68844,6 +68926,25 @@ var require_discoveryWorkflow = __commonJS({
68844
68926
  throw new Error(`Unsupported binary source cannot be selected: ${value.logicalPath}`);
68845
68927
  return { logicalPath: value.logicalPath, kind: value.kind, digest: value.digest, bytes: value.bytes, selected: value.selected, rationale: value.rationale, sidecar };
68846
68928
  }
68929
+ function sourceEntryProblem(value) {
68930
+ if (!isRecord(value))
68931
+ return "expected an object";
68932
+ if (typeof value.logicalPath !== "string")
68933
+ return "logicalPath must be a string";
68934
+ if (!isSafeDiscoveryPath(value.logicalPath))
68935
+ return 'logicalPath must be inside docs/discovery/sources/ without ".." segments';
68936
+ if (!isSourceKind(value.kind))
68937
+ return `kind ${JSON.stringify(value.kind)} must be one of TEXT, BINARY_WITH_SIDECAR or UNSUPPORTED_BINARY`;
68938
+ if (typeof value.digest !== "string" || !DIGEST.test(value.digest))
68939
+ return "digest must be sha256: followed by 64 lowercase hex characters";
68940
+ if (typeof value.bytes !== "number" || !Number.isSafeInteger(value.bytes) || value.bytes < 0)
68941
+ return "bytes must be a non-negative integer";
68942
+ if (typeof value.selected !== "boolean")
68943
+ return "selected must be true or false";
68944
+ if (typeof value.rationale !== "string")
68945
+ return "rationale must be a string";
68946
+ return null;
68947
+ }
68847
68948
  function isSafeDiscoveryPath(value) {
68848
68949
  return value.startsWith("docs/discovery/sources/") && !value.startsWith("/") && !value.split(/[\\/]/).includes("..");
68849
68950
  }
@@ -68901,7 +69002,7 @@ __export(main_exports, {
68901
69002
  runAuthLogin: () => runAuthLogin
68902
69003
  });
68903
69004
  module.exports = __toCommonJS(main_exports);
68904
- var import_packet_workflow9 = __toESM(require_dist(), 1);
69005
+ var import_packet_workflow10 = __toESM(require_dist(), 1);
68905
69006
 
68906
69007
  // src/browserAuth.ts
68907
69008
  var import_node_crypto = require("node:crypto");
@@ -69016,6 +69117,20 @@ var SwarmCraftClient = class {
69016
69117
  loadBoard(projectId, accessToken, delegationId) {
69017
69118
  return this.requestJson(`/projects/${encodeURIComponent(projectId)}/board`, { method: "GET" }, accessToken, void 0, delegationId);
69018
69119
  }
69120
+ /** Removes a task's packet link when it still names the expected workspace folder; a missing link is a no-op. */
69121
+ removeTaskPacketLink(projectId, taskId, workspaceFolder, accessToken, delegationId) {
69122
+ return this.requestJson(
69123
+ `/projects/${encodeURIComponent(projectId)}/tasks/${encodeURIComponent(taskId)}/packet-link?workspaceFolder=${encodeURIComponent(workspaceFolder)}`,
69124
+ { method: "DELETE" },
69125
+ accessToken,
69126
+ void 0,
69127
+ delegationId
69128
+ );
69129
+ }
69130
+ /** Loads an owned Discovery Workspace, including the project its package created once generation completes. */
69131
+ loadDiscoveryWorkspace(workspaceId, accessToken) {
69132
+ return this.requestJson(`/discovery/workspaces/${encodeURIComponent(workspaceId)}`, { method: "GET" }, accessToken);
69133
+ }
69019
69134
  upsertTaskPacketLink(projectId, taskId, request, accessToken, delegationId) {
69020
69135
  return this.requestJson(
69021
69136
  `/projects/${encodeURIComponent(projectId)}/tasks/${encodeURIComponent(taskId)}/packet-link`,
@@ -69869,14 +69984,14 @@ Implementation complete. Checking: ${options.checking ? "completed" : "explicitl
69869
69984
  }
69870
69985
 
69871
69986
  // src/main.ts
69872
- var import_promises15 = require("node:fs/promises");
69987
+ var import_promises16 = require("node:fs/promises");
69873
69988
  var import_node_path15 = __toESM(require("node:path"), 1);
69874
- var import_packet_workflow10 = __toESM(require_dist(), 1);
69989
+ var import_packet_workflow11 = __toESM(require_dist(), 1);
69875
69990
 
69876
69991
  // package.json
69877
69992
  var package_default = {
69878
69993
  name: "@swarmcraftai/cli",
69879
- version: "0.9.1",
69994
+ version: "0.9.2",
69880
69995
  description: "Prepare repositories and run packet-based SwarmCraft agent workflows from the terminal.",
69881
69996
  license: "SEE LICENSE IN LICENSE.txt",
69882
69997
  type: "module",
@@ -69961,81 +70076,149 @@ async function ensureWorkspaceTracking(workspace) {
69961
70076
  // src/bootstrap.ts
69962
70077
  var import_packet_workflow4 = __toESM(require_dist(), 1);
69963
70078
  var import_repo_seed3 = __toESM(require_dist4(), 1);
70079
+
70080
+ // src/workspaceBinding.ts
70081
+ var import_promises7 = require("node:fs/promises");
70082
+ var SEED_STATE_PATH = ".swarmcraft/project.seed-state.json";
70083
+ var DISCOVERY_BINDING_PATH = ".swarmcraft/discovery.binding.json";
70084
+ var ProjectBindingMismatchError = class extends Error {
70085
+ constructor(message) {
70086
+ super(message);
70087
+ this.name = "ProjectBindingMismatchError";
70088
+ }
70089
+ };
70090
+ async function readWorkspaceProjectBinding(workspacePath, client, accessToken) {
70091
+ const seedState = await readJson(workspacePath, SEED_STATE_PATH);
70092
+ const seedStateProjectId = typeof seedState?.projectId === "string" ? seedState.projectId : null;
70093
+ const discoveryBinding = await readJson(workspacePath, DISCOVERY_BINDING_PATH);
70094
+ if (!discoveryBinding) return { seedStateProjectId, discovery: null };
70095
+ const workspaceId = typeof discoveryBinding.workspaceId === "string" ? discoveryBinding.workspaceId : "";
70096
+ const apiId = decodeDiscoveryWorkspaceId(workspaceId);
70097
+ if (!apiId) return { seedStateProjectId, discovery: { workspaceId, resultingProjectId: null, unverifiedReason: "the discovery binding has an invalid workspace id" } };
70098
+ try {
70099
+ const workspace = await client.loadDiscoveryWorkspace(apiId, accessToken);
70100
+ return { seedStateProjectId, discovery: { workspaceId, resultingProjectId: workspace.resultingProjectId ?? null, unverifiedReason: null } };
70101
+ } catch (error) {
70102
+ const reason = error instanceof Error && error.message ? error.message : "the Discovery Workspace could not be loaded";
70103
+ return { seedStateProjectId, discovery: { workspaceId, resultingProjectId: null, unverifiedReason: reason } };
70104
+ }
70105
+ }
70106
+ function checkProjectBinding(project, binding) {
70107
+ const requested = `"${project.title}" (${project.id})`;
70108
+ const discovery = binding.discovery;
70109
+ if (discovery) {
70110
+ if (discovery.unverifiedReason) {
70111
+ return { status: "mismatch", message: `This workspace is bound to Deep Discovery workspace ${discovery.workspaceId}, but its project could not be verified (${discovery.unverifiedReason}). Requested project: ${requested}.` };
70112
+ }
70113
+ if (!discovery.resultingProjectId) {
70114
+ return { status: "mismatch", message: `This workspace's Deep Discovery (${discovery.workspaceId}) has not created a project yet, so it cannot be bound to ${requested}.` };
70115
+ }
70116
+ if (discovery.resultingProjectId !== project.id) {
70117
+ return { status: "mismatch", message: `This workspace's Deep Discovery (${discovery.workspaceId}) created project ${discovery.resultingProjectId}, not the requested project ${requested}.` };
70118
+ }
70119
+ if (binding.seedStateProjectId && binding.seedStateProjectId !== project.id) {
70120
+ return { status: "rebind", message: `Rebinding this workspace from project ${binding.seedStateProjectId} to ${requested}, the project its Deep Discovery created.` };
70121
+ }
70122
+ return { status: "match", message: null };
70123
+ }
70124
+ if (!binding.seedStateProjectId) {
70125
+ return { status: "unbound", message: `Binding this workspace to ${requested}.` };
70126
+ }
70127
+ if (binding.seedStateProjectId !== project.id) {
70128
+ return { status: "mismatch", message: `This workspace is bound to project ${binding.seedStateProjectId} in ${SEED_STATE_PATH}, not the requested project ${requested}.` };
70129
+ }
70130
+ return { status: "match", message: null };
70131
+ }
70132
+ function assertProjectBinding(project, binding, force) {
70133
+ const check = checkProjectBinding(project, binding);
70134
+ if (check.status === "mismatch" && !force) {
70135
+ throw new ProjectBindingMismatchError(`${check.message} Nothing was written. Check the project ID, or pass --force to write packets and packet links for this project anyway. Use --dry-run to preview.`);
70136
+ }
70137
+ return check;
70138
+ }
70139
+ function decodeDiscoveryWorkspaceId(bindingId) {
70140
+ const compact = bindingId.replace(/^dws_/, "");
70141
+ if (!/^[a-f0-9]{32}$/i.test(compact)) return null;
70142
+ return `${compact.slice(0, 8)}-${compact.slice(8, 12)}-${compact.slice(12, 16)}-${compact.slice(16, 20)}-${compact.slice(20)}`;
70143
+ }
70144
+ async function readJson(workspacePath, relativePath) {
70145
+ let contents;
70146
+ try {
70147
+ contents = await (0, import_promises7.readFile)(resolveContainedWorkspacePath(workspacePath, relativePath), "utf8");
70148
+ } catch (error) {
70149
+ if (error.code === "ENOENT") return null;
70150
+ throw error;
70151
+ }
70152
+ try {
70153
+ return JSON.parse(contents);
70154
+ } catch {
70155
+ throw new Error(`${relativePath} is not valid JSON; repair it before writing packets.`);
70156
+ }
70157
+ }
70158
+
70159
+ // src/bootstrap.ts
69964
70160
  async function runBootstrap(client, accessToken, options) {
69965
- await validateWorkspace(options.workspacePath);
69966
- await ensureWorkspaceTracking(options.workspacePath);
69967
- const workspace = await validateWorkspace(options.workspacePath);
70161
+ const dryRun = options.dryRun ?? false;
70162
+ const preflight = await validateWorkspace(options.workspacePath);
69968
70163
  const project = await client.loadProject(options.projectId, accessToken, options.delegationId);
69969
70164
  if (project.boardState !== "READY") {
69970
70165
  throw new Error(`Project ${project.id} is ${project.boardState}; wait for the board to be ready before bootstrapping a workspace.`);
69971
70166
  }
70167
+ const projectTitle = project.title || project.projectTitle || project.id;
70168
+ const binding = await readWorkspaceProjectBinding(preflight.workspacePath, client, accessToken);
70169
+ const bindingCheck = dryRun ? checkProjectBinding({ id: project.id, title: projectTitle }, binding) : assertProjectBinding({ id: project.id, title: projectTitle }, binding, options.force ?? false);
70170
+ if (!dryRun) await ensureWorkspaceTracking(options.workspacePath);
70171
+ const workspace = dryRun ? preflight : await validateWorkspace(options.workspacePath);
69972
70172
  const board = await client.loadBoard(project.id, accessToken, options.delegationId);
69973
- const seedResult = await seedWorkspace(project, workspace.workspacePath, options.agentProvider);
70173
+ const seedResult = dryRun ? null : await seedWorkspace(project, workspace.workspacePath, options.agentProvider);
69974
70174
  const selectedTasks = selectBootstrapTasks(board, options);
69975
70175
  const packetFilesCreated = [];
69976
70176
  const packetFilesRefreshed = [];
69977
70177
  const linkedPackets = [];
69978
70178
  const skippedTasks = [];
69979
70179
  const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
69980
- for (const task of selectedTasks) {
69981
- if (task.packetLink && task.packetLink.workspaceFolder !== workspace.workspaceFolderName) {
69982
- skippedTasks.push({
69983
- taskId: task.id,
69984
- title: task.title,
69985
- reason: `already linked to workspace ${task.packetLink.workspaceFolder}`
69986
- });
70180
+ const plan = await (0, import_packet_workflow4.planPacketSync)({
70181
+ project,
70182
+ tasks: selectedTasks,
70183
+ workspaceFolder: workspace.workspaceFolderName,
70184
+ // Task selection already removed completed tasks; the planner must not drop explicitly requested ones.
70185
+ includeDone: true,
70186
+ syncedAt,
70187
+ readExisting: async (relativePath) => await fileExists(resolveContainedWorkspacePath(workspace.workspacePath, relativePath)) ? readWorkspaceFile(workspace.workspacePath, relativePath) : null
70188
+ });
70189
+ for (const entry of plan) {
70190
+ if (entry.action === "skip") {
70191
+ skippedTasks.push({ taskId: entry.taskId, title: entry.title, reason: entry.relativePath ? `${entry.reason} at ${entry.relativePath}` : entry.reason });
69987
70192
  continue;
69988
70193
  }
69989
- const relativePacketPath = (0, import_packet_workflow4.resolvePacketFilePath)(project, task, task.packetLink);
69990
- const absolutePacketPath = resolveContainedWorkspacePath(workspace.workspacePath, relativePacketPath);
69991
- let packetContents;
69992
- if (await fileExists(absolutePacketPath)) {
69993
- const existingContents = await readWorkspaceFile(workspace.workspacePath, relativePacketPath);
69994
- try {
69995
- (0, import_packet_workflow4.ensurePacketFileIdentity)(existingContents, project.id, task.id);
69996
- (0, import_packet_workflow4.parsePacketFile)(existingContents);
69997
- packetContents = (0, import_packet_workflow4.migrateLocalPacket)(existingContents);
69998
- } catch (error) {
69999
- if (error instanceof import_packet_workflow4.PacketFileContractError && error.code === "PACKET_FILE_MALFORMED") {
70000
- skippedTasks.push({
70001
- taskId: task.id,
70002
- title: task.title,
70003
- reason: `existing packet is malformed at ${relativePacketPath}`
70004
- });
70005
- continue;
70006
- }
70007
- throw error;
70008
- }
70009
- if (packetContents !== existingContents) {
70010
- await writeWorkspaceFile(workspace.workspacePath, relativePacketPath, packetContents);
70011
- packetFilesRefreshed.push(relativePacketPath);
70012
- }
70013
- } else {
70014
- packetContents = (0, import_packet_workflow4.migrateLocalPacket)((0, import_packet_workflow4.renderPacketFile)(project, task, syncedAt));
70015
- await writeWorkspaceFile(workspace.workspacePath, relativePacketPath, packetContents);
70016
- packetFilesCreated.push(relativePacketPath);
70017
- }
70018
- const packetLinkMatches = task.packetLink && task.packetLink.workspaceFolder === workspace.workspaceFolderName && task.packetLink.packetFilePath === relativePacketPath;
70019
- if (!packetLinkMatches) {
70020
- await client.upsertTaskPacketLink(project.id, task.id, {
70021
- workspaceFolder: workspace.workspaceFolderName,
70022
- packetFilePath: relativePacketPath,
70023
- expectedRevision: task.revision,
70024
- lastSyncedTaskRevision: task.revision,
70025
- lastSyncedAt: syncedAt
70026
- }, accessToken, options.delegationId);
70027
- linkedPackets.push(relativePacketPath);
70028
- }
70194
+ if (entry.action !== "unchanged") {
70195
+ if (!dryRun) await writeWorkspaceFile(workspace.workspacePath, entry.relativePath, entry.contents);
70196
+ (entry.action === "create" ? packetFilesCreated : packetFilesRefreshed).push(entry.relativePath);
70197
+ }
70198
+ if (!entry.needsLink) continue;
70199
+ linkedPackets.push(entry.relativePath);
70200
+ if (dryRun) continue;
70201
+ const task = selectedTasks.find(({ id }) => id === entry.taskId);
70202
+ await client.upsertTaskPacketLink(project.id, task.id, {
70203
+ workspaceFolder: workspace.workspaceFolderName,
70204
+ packetFilePath: entry.relativePath,
70205
+ expectedRevision: task.revision,
70206
+ lastSyncedTaskRevision: task.revision,
70207
+ lastSyncedAt: syncedAt
70208
+ }, accessToken, options.delegationId);
70029
70209
  }
70030
70210
  return {
70031
- projectTitle: project.title || project.projectTitle || project.id,
70211
+ projectId: project.id,
70212
+ projectTitle,
70213
+ dryRun,
70214
+ binding: bindingCheck,
70032
70215
  workspacePath: workspace.workspacePath,
70033
70216
  dirtyFileCount: workspace.dirtyFileCount,
70034
- seedFilesWritten: seedResult.written,
70035
- seedFilesUpdated: seedResult.updated,
70036
- seedFilesRemoved: seedResult.removed,
70037
- seedConflicts: seedResult.conflicts,
70038
- seedTemplateSetVersion: seedResult.targetTemplateSetVersion,
70217
+ seedFilesWritten: seedResult?.written ?? [],
70218
+ seedFilesUpdated: seedResult?.updated ?? [],
70219
+ seedFilesRemoved: seedResult?.removed ?? [],
70220
+ seedConflicts: seedResult?.conflicts ?? [],
70221
+ seedTemplateSetVersion: seedResult?.targetTemplateSetVersion ?? 0,
70039
70222
  packetFilesCreated,
70040
70223
  packetFilesRefreshed,
70041
70224
  linkedPackets,
@@ -70075,7 +70258,7 @@ async function seedWorkspace(project, workspacePath, provider) {
70075
70258
 
70076
70259
  // src/oneShot.ts
70077
70260
  var import_packet_workflow6 = __toESM(require_dist(), 1);
70078
- var import_promises7 = require("node:fs/promises");
70261
+ var import_promises8 = require("node:fs/promises");
70079
70262
  var import_node_path7 = __toESM(require("node:path"), 1);
70080
70263
  var import_packet_workflow7 = __toESM(require_dist(), 1);
70081
70264
 
@@ -70179,7 +70362,8 @@ async function runOneShot(client, accessTokenProvider, options) {
70179
70362
  taskIds: options.taskIds,
70180
70363
  taskLimit: options.taskLimit,
70181
70364
  delegationId: options.delegation?.id ?? null,
70182
- agentProvider: options.agentProvider === "custom" || options.agentProvider === "managed" ? "codex" : options.agentProvider
70365
+ agentProvider: options.agentProvider === "custom" || options.agentProvider === "managed" ? "codex" : options.agentProvider,
70366
+ force: options.forceProjectBinding ?? false
70183
70367
  });
70184
70368
  }
70185
70369
  const project = await client.loadProject(options.projectId, await getAccessToken(), options.delegation?.id ?? null);
@@ -70415,7 +70599,7 @@ async function runStageAndSync(context) {
70415
70599
  printProgress(`Running ${context.stage} stage for ${context.task.title}.`);
70416
70600
  printProgress(`Agent log: ${stageOutcome.logPath}`);
70417
70601
  const costOutputPath = import_node_path7.default.join(import_node_path7.default.dirname(context.manifestPath), "agent-cost", `${String(agentRequestNumber).padStart(4, "0")}-${context.stage}.json`);
70418
- await (0, import_promises7.mkdir)(import_node_path7.default.dirname(costOutputPath), { recursive: true });
70602
+ await (0, import_promises8.mkdir)(import_node_path7.default.dirname(costOutputPath), { recursive: true });
70419
70603
  const managedStage = context.options.agentProvider === "managed" ? await context.client.prepareManagedAiStage(
70420
70604
  context.manifest.managedAi?.runId ?? "",
70421
70605
  context.task.id,
@@ -70592,7 +70776,7 @@ function formatDuration(elapsedMs) {
70592
70776
  }
70593
70777
 
70594
70778
  // src/sessionStore.ts
70595
- var import_promises8 = require("node:fs/promises");
70779
+ var import_promises9 = require("node:fs/promises");
70596
70780
  var import_node_os = __toESM(require("node:os"), 1);
70597
70781
  var import_node_path8 = __toESM(require("node:path"), 1);
70598
70782
  function resolveSessionPath() {
@@ -70600,7 +70784,7 @@ function resolveSessionPath() {
70600
70784
  }
70601
70785
  async function readStoredSession() {
70602
70786
  try {
70603
- return JSON.parse(await (0, import_promises8.readFile)(resolveSessionPath(), "utf8"));
70787
+ return JSON.parse(await (0, import_promises9.readFile)(resolveSessionPath(), "utf8"));
70604
70788
  } catch (error) {
70605
70789
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
70606
70790
  return null;
@@ -70610,10 +70794,10 @@ async function readStoredSession() {
70610
70794
  }
70611
70795
  async function writeStoredSession(session) {
70612
70796
  const sessionPath = resolveSessionPath();
70613
- await (0, import_promises8.mkdir)(import_node_path8.default.dirname(sessionPath), { recursive: true, mode: 448 });
70614
- await (0, import_promises8.writeFile)(sessionPath, `${JSON.stringify(session, null, 2)}
70797
+ await (0, import_promises9.mkdir)(import_node_path8.default.dirname(sessionPath), { recursive: true, mode: 448 });
70798
+ await (0, import_promises9.writeFile)(sessionPath, `${JSON.stringify(session, null, 2)}
70615
70799
  `, { mode: 384 });
70616
- await (0, import_promises8.chmod)(sessionPath, 384);
70800
+ await (0, import_promises9.chmod)(sessionPath, 384);
70617
70801
  }
70618
70802
  function toStoredSession(apiBaseUrl, tokenResponse) {
70619
70803
  return {
@@ -70631,7 +70815,7 @@ function sessionExpiresSoon(session) {
70631
70815
  }
70632
70816
 
70633
70817
  // src/commands/support-bundle-command.ts
70634
- var import_promises9 = require("node:fs/promises");
70818
+ var import_promises10 = require("node:fs/promises");
70635
70819
  var import_node_path9 = __toESM(require("node:path"), 1);
70636
70820
 
70637
70821
  // src/supportBundle.ts
@@ -70678,12 +70862,12 @@ function redactSupportBundleValue(value) {
70678
70862
  async function createRunSupportBundle(workspacePathValue, runId) {
70679
70863
  const workspacePath = import_node_path9.default.resolve(workspacePathValue);
70680
70864
  const manifestPath = resolveManifestPath(workspacePath, runId);
70681
- const manifest = JSON.parse(await (0, import_promises9.readFile)(manifestPath, "utf8"));
70865
+ const manifest = JSON.parse(await (0, import_promises10.readFile)(manifestPath, "utf8"));
70682
70866
  const bundleDir = resolveRunArtifactPath(workspacePath, runId, "support-bundle");
70683
- await (0, import_promises9.mkdir)(bundleDir, { recursive: true });
70684
- await (0, import_promises9.writeFile)(import_node_path9.default.join(bundleDir, "manifest.redacted.json"), `${JSON.stringify(redactSupportBundleValue(manifest), null, 2)}
70867
+ await (0, import_promises10.mkdir)(bundleDir, { recursive: true });
70868
+ await (0, import_promises10.writeFile)(import_node_path9.default.join(bundleDir, "manifest.redacted.json"), `${JSON.stringify(redactSupportBundleValue(manifest), null, 2)}
70685
70869
  `, { encoding: "utf8", mode: 384 });
70686
- await (0, import_promises9.writeFile)(import_node_path9.default.join(bundleDir, "summary.json"), `${JSON.stringify({
70870
+ await (0, import_promises10.writeFile)(import_node_path9.default.join(bundleDir, "summary.json"), `${JSON.stringify({
70687
70871
  runId,
70688
70872
  manifestPath: ".swarmcraft/runs/<run-id>/manifest.json",
70689
70873
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -70740,12 +70924,12 @@ function addOption(options, key, value) {
70740
70924
 
70741
70925
  // src/discovery.ts
70742
70926
  var import_node_crypto5 = require("node:crypto");
70743
- var import_promises11 = require("node:fs/promises");
70927
+ var import_promises12 = require("node:fs/promises");
70744
70928
  var import_node_path11 = __toESM(require("node:path"), 1);
70745
70929
  var import_operation_contract = __toESM(require_dist2(), 1);
70746
70930
 
70747
70931
  // src/operation/filesystem.ts
70748
- var import_promises10 = require("node:fs/promises");
70932
+ var import_promises11 = require("node:fs/promises");
70749
70933
  var import_node_path10 = __toESM(require("node:path"), 1);
70750
70934
  var OperateCommandError = class extends Error {
70751
70935
  constructor(code, exitCode, message) {
@@ -70766,7 +70950,7 @@ var OperationFiles = class {
70766
70950
  async target(relative2) {
70767
70951
  checkCancelled(this.signal);
70768
70952
  try {
70769
- const rootEntry = await (0, import_promises10.lstat)(this.root);
70953
+ const rootEntry = await (0, import_promises11.lstat)(this.root);
70770
70954
  if (!rootEntry.isDirectory() || rootEntry.isSymbolicLink()) {
70771
70955
  throw new OperateCommandError("OPERATE_PATH_UNSAFE", 4, "The selected workspace changed during the command.");
70772
70956
  }
@@ -70784,7 +70968,7 @@ var OperationFiles = class {
70784
70968
  for (let i = 0; i < components.length; i++) {
70785
70969
  current = import_node_path10.default.join(current, components[i]);
70786
70970
  try {
70787
- const entry = await (0, import_promises10.lstat)(current);
70971
+ const entry = await (0, import_promises11.lstat)(current);
70788
70972
  if (entry.isSymbolicLink() || entry.isFile() && entry.nlink > 1 || i < components.length - 1 && !entry.isDirectory()) {
70789
70973
  throw new OperateCommandError("OPERATE_PATH_UNSAFE", 4, "An operation path uses an unsafe filesystem link.");
70790
70974
  }
@@ -70798,11 +70982,11 @@ var OperationFiles = class {
70798
70982
  async read(relative2) {
70799
70983
  const target = await this.target(relative2);
70800
70984
  try {
70801
- const entry = await (0, import_promises10.lstat)(target);
70985
+ const entry = await (0, import_promises11.lstat)(target);
70802
70986
  if (!entry.isFile() || entry.size > 2e6) {
70803
70987
  throw new OperateCommandError("OPERATE_FILE_UNSUPPORTED", 4, "An operation file is not a supported bounded text file.");
70804
70988
  }
70805
- return await (0, import_promises10.readFile)(target, "utf8");
70989
+ return await (0, import_promises11.readFile)(target, "utf8");
70806
70990
  } catch (error) {
70807
70991
  if (isMissing(error)) return void 0;
70808
70992
  throw error;
@@ -70816,23 +71000,23 @@ var OperationFiles = class {
70816
71000
  /** Reads bounded local binary evidence through the same containment checks. */
70817
71001
  async bytes(relative2) {
70818
71002
  const target = await this.target(relative2);
70819
- const entry = await (0, import_promises10.lstat)(target);
71003
+ const entry = await (0, import_promises11.lstat)(target);
70820
71004
  if (!entry.isFile() || entry.size > 1e7) throw new OperateCommandError("OPERATE_FILE_UNSUPPORTED", 4, "Select bounded local evidence.");
70821
- return (0, import_promises10.readFile)(target);
71005
+ return (0, import_promises11.readFile)(target);
70822
71006
  }
70823
71007
  /** Creates an immutable snapshot; an existing file is never overwritten. */
70824
71008
  async create(relative2, contents) {
70825
71009
  const target = await this.target(relative2);
70826
- await (0, import_promises10.mkdir)(import_node_path10.default.dirname(target), { recursive: true });
71010
+ await (0, import_promises11.mkdir)(import_node_path10.default.dirname(target), { recursive: true });
70827
71011
  await this.target(relative2);
70828
- await (0, import_promises10.writeFile)(target, contents, { flag: "wx", mode: 384 });
71012
+ await (0, import_promises11.writeFile)(target, contents, { flag: "wx", mode: 384 });
70829
71013
  }
70830
71014
  /** Inventories only regular files; links are rejected rather than treated as available assets. */
70831
71015
  async fileInventory() {
70832
71016
  const result = [];
70833
71017
  for (const file of await this.inventory()) {
70834
71018
  const target = await this.target(file);
70835
- if ((await (0, import_promises10.lstat)(target)).isFile()) result.push(file);
71019
+ if ((await (0, import_promises11.lstat)(target)).isFile()) result.push(file);
70836
71020
  }
70837
71021
  return result;
70838
71022
  }
@@ -70840,7 +71024,7 @@ var OperationFiles = class {
70840
71024
  async removeEmptyDirectory(relative2) {
70841
71025
  const target = await this.target(relative2);
70842
71026
  try {
70843
- await (0, import_promises10.rmdir)(target);
71027
+ await (0, import_promises11.rmdir)(target);
70844
71028
  } catch (error) {
70845
71029
  if (isMissing(error) || ["ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) return;
70846
71030
  throw error;
@@ -70848,7 +71032,7 @@ var OperationFiles = class {
70848
71032
  }
70849
71033
  /** Removes only a checked individual file selected by seed reconciliation. */
70850
71034
  async remove(relative2) {
70851
- await (0, import_promises10.unlink)(await this.target(relative2));
71035
+ await (0, import_promises11.unlink)(await this.target(relative2));
70852
71036
  }
70853
71037
  /** Inventories paths without reading contents or following links; skips runtime dependency trees. */
70854
71038
  async inventory() {
@@ -70856,7 +71040,7 @@ var OperationFiles = class {
70856
71040
  const skip = /* @__PURE__ */ new Set([".git", "node_modules", ".venv", "dist", "build", "target"]);
70857
71041
  const walk = async (relative2) => {
70858
71042
  checkCancelled(this.signal);
70859
- for (const entry of await (0, import_promises10.readdir)(import_node_path10.default.join(this.root, relative2), { withFileTypes: true })) {
71043
+ for (const entry of await (0, import_promises11.readdir)(import_node_path10.default.join(this.root, relative2), { withFileTypes: true })) {
70860
71044
  if (skip.has(entry.name)) continue;
70861
71045
  const file = relative2 ? relative2 + "/" + entry.name : entry.name;
70862
71046
  result.push(file);
@@ -70881,13 +71065,13 @@ async function resolveOperationRoot(input) {
70881
71065
  const missing = [];
70882
71066
  while (true) {
70883
71067
  try {
70884
- const entry = await (0, import_promises10.lstat)(cursor);
71068
+ const entry = await (0, import_promises11.lstat)(cursor);
70885
71069
  if (!entry.isDirectory()) throw new OperateCommandError(
70886
71070
  "OPERATE_WORKSPACE_INVALID",
70887
71071
  4,
70888
71072
  "Select a directory for the operation workspace."
70889
71073
  );
70890
- return import_node_path10.default.join(await (0, import_promises10.realpath)(cursor), ...missing.reverse());
71074
+ return import_node_path10.default.join(await (0, import_promises11.realpath)(cursor), ...missing.reverse());
70891
71075
  } catch (error) {
70892
71076
  if (!isMissing(error)) throw error;
70893
71077
  missing.push(import_node_path10.default.basename(cursor));
@@ -70903,7 +71087,7 @@ async function inspectGit(root) {
70903
71087
  let existing = root;
70904
71088
  while (true) {
70905
71089
  try {
70906
- await (0, import_promises10.lstat)(existing);
71090
+ await (0, import_promises11.lstat)(existing);
70907
71091
  break;
70908
71092
  } catch (error) {
70909
71093
  if (!isMissing(error)) throw error;
@@ -70916,7 +71100,7 @@ async function inspectGit(root) {
70916
71100
  if (available.exitCode !== 0) throw new OperateCommandError("OPERATE_GIT_UNAVAILABLE", 4, "Install Git before initializing Operate.");
70917
71101
  return false;
70918
71102
  }
70919
- if (await (0, import_promises10.realpath)(result.stdout.trim()) !== root) {
71103
+ if (await (0, import_promises11.realpath)(result.stdout.trim()) !== root) {
70920
71104
  throw new OperateCommandError("OPERATE_GIT_ROOT_MISMATCH", 4, "Select the repository root, or a directory outside an existing repository.");
70921
71105
  }
70922
71106
  const unmerged = await operationGit(root, ["diff", "--name-only", "--diff-filter=U", "-z"]);
@@ -70933,7 +71117,7 @@ async function operationIgnored(root, relative2) {
70933
71117
  return result.exitCode === 0;
70934
71118
  }
70935
71119
  async function createOperationRoot(root) {
70936
- await (0, import_promises10.mkdir)(root, { recursive: true });
71120
+ await (0, import_promises11.mkdir)(root, { recursive: true });
70937
71121
  }
70938
71122
  function isMissing(error) {
70939
71123
  return !!error && typeof error === "object" && "code" in error && error.code === "ENOENT";
@@ -70965,7 +71149,7 @@ async function prepareDiscoveryBundle(options, dependencies = defaultDiscoveryDe
70965
71149
  const feedbackPath = resolveRunArtifactPath(workspacePath, runId, "discovery-feedback.md");
70966
71150
  const diagnosticsPath = resolveRunArtifactPath(workspacePath, runId, "diagnostics.json");
70967
71151
  const previewPath = resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery-package-preview.md");
70968
- await (0, import_promises11.mkdir)(runDirectory, { recursive: true });
71152
+ await (0, import_promises12.mkdir)(runDirectory, { recursive: true });
70969
71153
  const startedAt = dependencies.now().toISOString();
70970
71154
  const previousManifest = options.resumeRunId ? await loadManifest(manifestPath) : null;
70971
71155
  let manifest = {
@@ -71061,7 +71245,7 @@ async function validateCurrentDiscoveryBundle(workspacePathValue) {
71061
71245
  const currentPath = resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery-packages/current.json");
71062
71246
  let discoveryPackage;
71063
71247
  try {
71064
- discoveryPackage = (0, import_discovery_package_contract2.parseDiscoveryPackage)(JSON.parse(await (0, import_promises11.readFile)(currentPath, "utf8")));
71248
+ discoveryPackage = (0, import_discovery_package_contract2.parseDiscoveryPackage)(JSON.parse(await (0, import_promises12.readFile)(currentPath, "utf8")));
71065
71249
  } catch {
71066
71250
  throw new Error("No current Discovery Package exists. Run discovery prepare first.");
71067
71251
  }
@@ -71076,7 +71260,7 @@ async function validateCurrentDiscoveryBundle(workspacePathValue) {
71076
71260
  findings.push(...assessment.findings);
71077
71261
  for (const document3 of discoveryPackage.documents) {
71078
71262
  try {
71079
- const content = await (0, import_promises11.readFile)(resolveContainedWorkspacePath(workspacePath, document3.logicalPath), "utf8");
71263
+ const content = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, document3.logicalPath), "utf8");
71080
71264
  if ((0, import_discovery_package_contract2.discoveryDocumentDigest)(content) !== document3.digest) findings.push({ ruleId: "DP_SOURCE_CHANGED", path: document3.logicalPath, message: "The local document changed after package preparation." });
71081
71265
  } catch {
71082
71266
  findings.push({ ruleId: "DP_SOURCE_MISSING", path: document3.logicalPath, message: "A packaged local document is missing." });
@@ -71094,7 +71278,7 @@ async function createDiscoverySupportBundle(workspacePathValue, runId) {
71094
71278
  const manifest = await loadManifest(import_node_path11.default.join(runDirectory, "manifest.json"));
71095
71279
  let diagnostics = null;
71096
71280
  try {
71097
- diagnostics = JSON.parse(await (0, import_promises11.readFile)(import_node_path11.default.join(runDirectory, "diagnostics.json"), "utf8"));
71281
+ diagnostics = JSON.parse(await (0, import_promises12.readFile)(import_node_path11.default.join(runDirectory, "diagnostics.json"), "utf8"));
71098
71282
  } catch {
71099
71283
  diagnostics = { errorClass: "DIAGNOSTICS_MISSING" };
71100
71284
  }
@@ -71117,7 +71301,7 @@ async function createDiscoverySupportBundle(workspacePathValue, runId) {
71117
71301
  async function loadDiscoveryPreflight(workspacePath) {
71118
71302
  let serialized;
71119
71303
  try {
71120
- serialized = await (0, import_promises11.readFile)(resolveContainedWorkspacePath(workspacePath, import_discovery_package_contract.DISCOVERY_SOURCE_MANIFEST_PATH), "utf8");
71304
+ serialized = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, import_discovery_package_contract.DISCOVERY_SOURCE_MANIFEST_PATH), "utf8");
71121
71305
  } catch {
71122
71306
  throw new DiscoveryPreparationError("DP_SOURCE_MANIFEST_MISSING", "DISCOVERY_INCOMPLETE", "The owner-confirmed source-selection manifest is missing.");
71123
71307
  }
@@ -71143,7 +71327,7 @@ async function loadDiscoveryPreflight(workspacePath) {
71143
71327
  const documentReviews = /* @__PURE__ */ new Map();
71144
71328
  for (const logicalPath of import_discovery_package_contract.DISCOVERY_CURATED_DOCUMENTS) {
71145
71329
  try {
71146
- const content = await (0, import_promises11.readFile)(resolveContainedWorkspacePath(workspacePath, logicalPath), "utf8");
71330
+ const content = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, logicalPath), "utf8");
71147
71331
  documentReviews.set(logicalPath, (0, import_discovery_package_contract.parseDiscoveryDocumentReview)(logicalPath, content));
71148
71332
  } catch (error) {
71149
71333
  if (error instanceof DiscoveryPreparationError) throw error;
@@ -71172,7 +71356,7 @@ async function freezeDocuments(workspacePath, manifest, reviews) {
71172
71356
  if (source.kind === "BINARY_WITH_SIDECAR" && source.sidecar) {
71173
71357
  const content = await readText(workspacePath, source.sidecar.logicalPath);
71174
71358
  assertDigest(source.sidecar.logicalPath, content, source.sidecar.digest);
71175
- const original = await (0, import_promises11.readFile)(resolveContainedWorkspacePath(workspacePath, source.logicalPath));
71359
+ const original = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, source.logicalPath));
71176
71360
  const originalDigest = digestBytes(original);
71177
71361
  if (originalDigest !== source.digest || source.sidecar.originalDigest !== source.digest) {
71178
71362
  throw new DiscoveryPreparationError("DP_SIDECAR_STALE", "STALE_INPUT", `The selected sidecar is stale for ${source.logicalPath}.`);
@@ -71180,7 +71364,7 @@ async function freezeDocuments(workspacePath, manifest, reviews) {
71180
71364
  documents.push(document2(source.sidecar.logicalPath, "SIDECAR", content, "SUPPORTING", { logicalPath: source.logicalPath, digest: originalDigest }));
71181
71365
  }
71182
71366
  }
71183
- const selectionManifest = await (0, import_promises11.readFile)(resolveContainedWorkspacePath(workspacePath, import_discovery_package_contract.DISCOVERY_SOURCE_MANIFEST_PATH));
71367
+ const selectionManifest = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, import_discovery_package_contract.DISCOVERY_SOURCE_MANIFEST_PATH));
71184
71368
  return { documents: documents.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath)), selectionManifestDigest: digestBytes(selectionManifest) };
71185
71369
  }
71186
71370
  function document2(logicalPath, role, content, reviewState, original) {
@@ -71201,7 +71385,7 @@ async function publishPackage(workspacePath, discoveryPackage, assessment, previ
71201
71385
  const packagePath = import_node_path11.default.join(directory, "package.json");
71202
71386
  const assessmentPath = import_node_path11.default.join(directory, "assessment.json");
71203
71387
  const currentPath = resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery-packages/current.json");
71204
- await (0, import_promises11.mkdir)(directory, { recursive: true });
71388
+ await (0, import_promises12.mkdir)(directory, { recursive: true });
71205
71389
  await writeJsonAtomic(packagePath, discoveryPackage);
71206
71390
  await writeJsonAtomic(assessmentPath, assessment);
71207
71391
  await writeFileAtomic(previewPath, renderPreview(discoveryPackage, assessment));
@@ -71266,7 +71450,7 @@ function classify(error, signal) {
71266
71450
  }
71267
71451
  async function readDiscoveryWorkspaceId(workspacePath) {
71268
71452
  try {
71269
- const binding = JSON.parse(await (0, import_promises11.readFile)(resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery.binding.json"), "utf8"));
71453
+ const binding = JSON.parse(await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery.binding.json"), "utf8"));
71270
71454
  if (!binding.workspaceId) throw new Error("missing id");
71271
71455
  const compact = binding.workspaceId.replace(/^dws_/, "");
71272
71456
  if (!/^[a-f0-9]{32}$/i.test(compact)) throw new Error("invalid id");
@@ -71277,40 +71461,40 @@ async function readDiscoveryWorkspaceId(workspacePath) {
71277
71461
  }
71278
71462
  async function readText(workspacePath, logicalPath) {
71279
71463
  try {
71280
- return await (0, import_promises11.readFile)(resolveContainedWorkspacePath(workspacePath, logicalPath), "utf8");
71464
+ return await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, logicalPath), "utf8");
71281
71465
  } catch {
71282
71466
  throw new DiscoveryPreparationError("DP_SOURCE_MISSING", "STALE_INPUT", `The selected document is missing: ${logicalPath}`);
71283
71467
  }
71284
71468
  }
71285
71469
  async function loadManifest(manifestPath) {
71286
- return JSON.parse(await (0, import_promises11.readFile)(manifestPath, "utf8"));
71470
+ return JSON.parse(await (0, import_promises12.readFile)(manifestPath, "utf8"));
71287
71471
  }
71288
71472
  function diagnosticsRecord(startedAt, finishedAt) {
71289
71473
  return { schemaVersion: 2, phase: "preflight", errorClass: null, startedAt, finishedAt, documentCount: 0, bytes: 0, estimatedTokens: 0, supportCode: null };
71290
71474
  }
71291
71475
  async function writeFeedback(feedbackPath, findings) {
71292
- await (0, import_promises11.mkdir)(import_node_path11.default.dirname(feedbackPath), { recursive: true });
71476
+ await (0, import_promises12.mkdir)(import_node_path11.default.dirname(feedbackPath), { recursive: true });
71293
71477
  const body = findings.length === 0 ? "# Discovery Package feedback\n\nThe deterministic package is ready for preview and upload authorization.\n" : `# Discovery Package feedback
71294
71478
 
71295
71479
  Preparation needs attention. No package was uploaded.
71296
71480
 
71297
71481
  ${findings.map((item) => `- **${item.ruleId}** at \`${item.path}\`: ${item.message}`).join("\n")}
71298
71482
  `;
71299
- await (0, import_promises11.writeFile)(feedbackPath, body, "utf8");
71483
+ await (0, import_promises12.writeFile)(feedbackPath, body, "utf8");
71300
71484
  }
71301
71485
  async function writeJson(filePath, value) {
71302
- await (0, import_promises11.mkdir)(import_node_path11.default.dirname(filePath), { recursive: true });
71303
- await (0, import_promises11.writeFile)(filePath, JSON.stringify(value, null, 2) + "\n", "utf8");
71486
+ await (0, import_promises12.mkdir)(import_node_path11.default.dirname(filePath), { recursive: true });
71487
+ await (0, import_promises12.writeFile)(filePath, JSON.stringify(value, null, 2) + "\n", "utf8");
71304
71488
  }
71305
71489
  async function writeJsonAtomic(filePath, value) {
71306
71490
  await writeFileAtomic(filePath, JSON.stringify(value, null, 2) + "\n");
71307
71491
  }
71308
71492
  async function writeFileAtomic(filePath, contents) {
71309
- await (0, import_promises11.mkdir)(import_node_path11.default.dirname(filePath), { recursive: true });
71493
+ await (0, import_promises12.mkdir)(import_node_path11.default.dirname(filePath), { recursive: true });
71310
71494
  const temporaryPath = `${filePath}.${process.pid}.tmp`;
71311
- await (0, import_promises11.writeFile)(temporaryPath, contents, "utf8");
71312
- await (0, import_promises11.rename)(temporaryPath, filePath);
71313
- await (0, import_promises11.rm)(temporaryPath, { force: true });
71495
+ await (0, import_promises12.writeFile)(temporaryPath, contents, "utf8");
71496
+ await (0, import_promises12.rename)(temporaryPath, filePath);
71497
+ await (0, import_promises12.rm)(temporaryPath, { force: true });
71314
71498
  }
71315
71499
  function digestBytes(value) {
71316
71500
  return `sha256:${(0, import_node_crypto5.createHash)("sha256").update(value).digest("hex")}`;
@@ -71450,6 +71634,18 @@ var COMMANDS = [
71450
71634
  summary: "List SwarmCraft projects available to the signed-in user.",
71451
71635
  implemented: true
71452
71636
  },
71637
+ {
71638
+ name: "packets sync",
71639
+ usage: "swarmcraft packets sync --workspace <path> [--project <project-id>] [--include-done] [--link] [--dry-run] [--yes] [--delegation <id>]",
71640
+ summary: "Pull every task on the workspace's bound project into local packet files for inspection.",
71641
+ implemented: true
71642
+ },
71643
+ {
71644
+ name: "packets links",
71645
+ usage: "swarmcraft packets links --project <project-id> --workspace-folder <name> [--remove [--yes]] [--delegation <id>]",
71646
+ summary: "List, then optionally remove, a project's remote packet links that name one workspace folder.",
71647
+ implemented: true
71648
+ },
71453
71649
  {
71454
71650
  name: "discovery prepare",
71455
71651
  usage: "swarmcraft discovery prepare --workspace <path> [--source <owner-selected-relative-md-or-txt> ...] [--discovery-workspace <id>] [--run-id <id>|--resume-run <id>]",
@@ -71470,13 +71666,13 @@ var COMMANDS = [
71470
71666
  },
71471
71667
  {
71472
71668
  name: "init",
71473
- usage: "swarmcraft init --project <project-id> --workspace <path> --agent-provider codex|copilot|claude [--task <task-id>] [--task-limit <n|all>] [--delegation <id>]",
71669
+ usage: "swarmcraft init --project <project-id> --workspace <path> --agent-provider codex|copilot|claude [--task <task-id>] [--task-limit <n|all>] [--delegation <id>] [--dry-run] [--force]",
71474
71670
  summary: "Prepare a repository with SwarmCraft packet and agent guidance files.",
71475
71671
  implemented: true
71476
71672
  },
71477
71673
  {
71478
71674
  name: "one-shot",
71479
- usage: `swarmcraft one-shot (--project <project-id> | --plan <path> | --packet <path>) [--phase <anchor>] [--preview] --workspace <path> --agent-provider ${import_packet_workflow8.EXTERNAL_AGENT_PROVIDERS.join("|")}|managed [--agent-command <template>] [--delegation <id>] [--run-id <id>] [--delivery branch|direct] [--checking on|off] [--reviewing on|off] [--task <id>] [--task-limit <n|all>] [--max-checking-attempts <n>] [--done-policy stop|auto] [--commit-policy none|done] [--max-agent-requests <n>] [--allow-dirty]`,
71675
+ usage: `swarmcraft one-shot (--project <project-id> | --plan <path> | --packet <path>) [--phase <anchor>] [--preview] --workspace <path> --agent-provider ${import_packet_workflow8.EXTERNAL_AGENT_PROVIDERS.join("|")}|managed [--agent-command <template>] [--delegation <id>] [--run-id <id>] [--delivery branch|direct] [--checking on|off] [--reviewing on|off] [--task <id>] [--task-limit <n|all>] [--max-checking-attempts <n>] [--done-policy stop|auto] [--commit-policy none|done] [--max-agent-requests <n>] [--allow-dirty] [--force]`,
71480
71676
  summary: "Run the project board packet loop with your own AI or incrementally metered Managed AI.",
71481
71677
  implemented: true
71482
71678
  },
@@ -71507,7 +71703,7 @@ var COMMANDS = [
71507
71703
  ];
71508
71704
  function findCommand(positionals) {
71509
71705
  if (positionals.length === 0) return void 0;
71510
- const commandKey = positionals[0] === "auth" || positionals[0] === "projects" || positionals[0] === "delegation" || positionals[0] === "discovery" || positionals[0] === "operate" ? positionals.slice(0, 2).join(" ") : positionals[0];
71706
+ const commandKey = positionals[0] === "auth" || positionals[0] === "projects" || positionals[0] === "packets" || positionals[0] === "delegation" || positionals[0] === "discovery" || positionals[0] === "operate" ? positionals.slice(0, 2).join(" ") : positionals[0];
71511
71707
  return COMMANDS.find((command) => command.name === commandKey);
71512
71708
  }
71513
71709
  var COMMAND_INSTRUCTIONS = {
@@ -71521,15 +71717,17 @@ var COMMAND_INSTRUCTIONS = {
71521
71717
  init: {
71522
71718
  requirements: ["Signed-in CLI session, accessible READY project, network, and a local Git workspace."],
71523
71719
  effects: ["Creates initial guidance or reconciles an existing repo. Updates unchanged managed files; preserves edited managed files as conflicts and existing owner files such as CLAUDE.md.", "Creates or migrates selected unfinished board packets while preserving local progress. Completed board tasks and repo-only provisional packets are untouched. May create/update remote packet links.", "The explicit provider selects generated guidance; it does not change the extension preference. No agents run or Git commit is made. For an existing repo's offline upgrade use swarmcraft upgrade."],
71524
- options: ["--project, --workspace and --agent-provider are required.", "--task <id>: repeat to select tasks; --task-limit <positive integer|all> defaults to all unfinished tasks.", "--delegation <id>: use authorised operator access."],
71720
+ options: ["--project, --workspace and --agent-provider are required.", "--task <id>: repeat to select tasks; --task-limit <positive integer|all> defaults to all unfinished tasks.", "--delegation <id>: use authorised operator access.", "--dry-run: print the project name and ID, binding check, and packets and links that would change; writes nothing.", "Before writing, --project must match the project the workspace's Deep Discovery created, or the project in .swarmcraft/project.seed-state.json when there is no discovery binding. A mismatch, or a discovery that cannot be verified, stops with nothing written; --force writes anyway."],
71525
71721
  result: "Prints seed/packet changes, conflicts and skipped tasks. Exit 0 on completion, 1 on error; inspect conflicts and git diff before committing.",
71526
71722
  example: "swarmcraft init --project <id> --workspace . --agent-provider claude"
71527
71723
  },
71528
71724
  "auth login": { requirements: ["Network and a SwarmCraft account; opens browser approval by default (Google, GitHub, passkey or password)."], effects: ["Authenticates and stores a private local CLI session. Does not seed a repo."], options: ["--api-base-url overrides SWARMCRAFT_API_BASE_URL; default https://swarmcraft.ai/api.", "--no-browser prints the approval link without opening a browser. Ctrl+C cancels waiting.", "--method password prompts for SwarmCraft credentials; existing credential flags/environment variables retain password login. Google passwords are never accepted here.", "Prefer interactive prompts to --password/--mfa-code flags to avoid shell history exposure."], result: "Exit 0 when the session is stored; 1 on failure.", example: "swarmcraft auth login" },
71725
+ "packets sync": { requirements: ["Signed-in session, network, a local Git workspace, and a workspace bound to a READY project by Deep Discovery or project seeding."], effects: ["Creates packet files for board tasks that have none and migrates existing packets to the current format. Local packet progress and edits are kept; tasks are never moved; guidance files are not reseeded.", "Completed tasks, tasks linked to another workspace folder, malformed packets and files owned by another task are skipped and listed. Repo-only packets are untouched. Remote packet links are written only with --link."], options: ["--workspace is required. The project defaults to the workspace binding: the project its Deep Discovery created, otherwise .swarmcraft/project.seed-state.json. --project must match that binding; an unbound or mismatched workspace stops with nothing written.", "--include-done also materialises completed tasks. --link creates or refreshes remote packet links.", "--dry-run prints the preview only. Without --yes, the CLI shows the preview and asks before writing; non-interactive runs need --yes. --delegation selects authorised operator access."], result: "Prints the project name and ID, counts to create, refresh, keep and skip, and each change. Exit 0 when synced, previewed, cancelled or already current; 1 on error.", example: "swarmcraft packets sync --workspace . --dry-run" },
71726
+ "packets links": { requirements: ["Signed-in session, network, and access to the project."], effects: ["Without --remove, only reads the board. With --remove, deletes the listed remote packet links after confirmation; tasks, lanes, checklists, notes and local packet files are untouched.", "Each removal re-checks that the link still names the workspace folder, so links re-pointed since the listing are kept and reported as conflicts. Removals are audited."], options: ["--project and --workspace-folder are required; the folder name must match the link exactly, as shown in the listing.", "--remove prompts you to type the project ID; --yes skips the prompt for non-interactive use after you have reviewed the list.", "--delegation selects authorised operator access."], result: "Prints the project name and ID and every matching link; with --remove, prints removed, conflict and failed counts. Exit 0 on success, 1 when any removal fails.", example: "swarmcraft packets links --project <id> --workspace-folder my-repo" },
71529
71727
  "projects list": { requirements: ["Signed-in session and network."], effects: ["Lists accessible projects. May refresh the local session; optional on-behalf-of access starts an audited delegation."], options: ["--delegation selects existing access; --on-behalf-of requires --delegation-reason."], result: "Prints project ID, state, progress and title; exit 0 on success, 1 on failure.", example: "swarmcraft projects list" },
71530
71728
  "delegation start": { requirements: ["Signed-in authorised operator and network."], effects: ["Creates audited, temporary server-side access for the named user."], options: ["--user and --reason required; --support-ticket optional; --expires-in-minutes bounds 5\u2013600 (server default when omitted)."], result: "Prints delegation details; exit 0 on success, 1 on failure.", example: "swarmcraft delegation start --user <user> --reason <reason>" },
71531
71729
  "delegation end": { requirements: ["Signed-in authorised operator and network."], effects: ["Revokes the specified server-side delegation; local repo files are untouched."], options: ["--delegation <id> required."], result: "Prints the ended delegation; exit 0 on success, 1 on failure.", example: "swarmcraft delegation end --delegation <id>" },
71532
- "one-shot": { requirements: ["Hosted mode requires signed-in project access and network. Local --plan/--packet mode needs only Git and the external provider; Managed AI requires hosted mode and credits."], effects: ["Runs agents, changes repository files and board state, and writes run artifacts under .swarmcraft/runs/<run-id>. Managed AI is metered; external providers use their own access.", "This executes delivery, not a guidance upgrade. Commit policy can create local commits; review outputs."], options: ["--workspace and --agent-provider required; choose hosted --project or local --plan / repeatable --packet. Local --phase narrows a plan; --preview resolves selection without execution. Local mode rejects mixed hosted selectors. custom uses --agent-command or SWARMCRAFT_AGENT_COMMAND; managed rejects custom credentials/commands.", "--delivery branch|direct defaults to branch. Direct runs on the current branch without source/target branch or merge prerequisites; checking and reviewing remain independent. Neither mode pushes or merges automatically.", "Local defaults: --checking on; --reviewing on; --commit-policy none. Local mode does not accept --done-policy: reviewing on stops for human review; reviewing off permits completion after required stages. --task-limit and --max-checking-attempts are hosted-only.", "Hosted defaults: --checking off; --done-policy auto; --reviewing on only when done-policy is stop; --commit-policy none; --task-limit all; --max-checking-attempts 2.", "--max-agent-requests and --max-agent-spend-usd bound usage; --require-cost-telemetry requires cost evidence. --allow-dirty opts into existing changes.", "The resume command freezes local scope and policy. Its --accept-packet-changes explicitly reconciles owner edits; --retry-interrupted permits retry after inspecting an interrupted stage. Local outcomes exit 0 complete, 2 blocked/review-required, 1 execution error. --run-id selects artifacts; --task selects tasks; --agent-env-file and --agent-api-key-env-name configure external providers; --delegation selects authorised access."], result: "Prints run/task outcomes. Exit 0 means command completion, not that every task succeeded; inspect outcomes. Execution errors exit 1.", example: "swarmcraft one-shot --project <id> --workspace . --agent-provider claude --done-policy stop --max-agent-requests 3" },
71730
+ "one-shot": { requirements: ["Hosted mode requires signed-in project access and network. Local --plan/--packet mode needs only Git and the external provider; Managed AI requires hosted mode and credits."], effects: ["Runs agents, changes repository files and board state, and writes run artifacts under .swarmcraft/runs/<run-id>. Managed AI is metered; external providers use their own access.", "This executes delivery, not a guidance upgrade. Commit policy can create local commits; review outputs."], options: ["--workspace and --agent-provider required; choose hosted --project or local --plan / repeatable --packet. Local --phase narrows a plan; --preview resolves selection without execution. Local mode rejects mixed hosted selectors. custom uses --agent-command or SWARMCRAFT_AGENT_COMMAND; managed rejects custom credentials/commands.", "--delivery branch|direct defaults to branch. Direct runs on the current branch without source/target branch or merge prerequisites; checking and reviewing remain independent. Neither mode pushes or merges automatically.", "Local defaults: --checking on; --reviewing on; --commit-policy none. Local mode does not accept --done-policy: reviewing on stops for human review; reviewing off permits completion after required stages. --task-limit and --max-checking-attempts are hosted-only.", "Hosted defaults: --checking off; --done-policy auto; --reviewing on only when done-policy is stop; --commit-policy none; --task-limit all; --max-checking-attempts 2.", "--max-agent-requests and --max-agent-spend-usd bound usage; --require-cost-telemetry requires cost evidence. --allow-dirty opts into existing changes.", "Hosted --project must match the workspace's Deep Discovery project or seed-state binding before bootstrap writes packets or links; --force overrides a mismatch.", "The resume command freezes local scope and policy. Its --accept-packet-changes explicitly reconciles owner edits; --retry-interrupted permits retry after inspecting an interrupted stage. Local outcomes exit 0 complete, 2 blocked/review-required, 1 execution error. --run-id selects artifacts; --task selects tasks; --agent-env-file and --agent-api-key-env-name configure external providers; --delegation selects authorised access."], result: "Prints run/task outcomes. Exit 0 means command completion, not that every task succeeded; inspect outcomes. Execution errors exit 1.", example: "swarmcraft one-shot --project <id> --workspace . --agent-provider claude --done-policy stop --max-agent-requests 3" },
71533
71731
  resume: { requirements: ["Existing run manifest and original provider prerequisites. Hosted runs also require signed-in project access and network."], effects: ["Continues the recorded execution, including agent writes and board updates. Uses the saved run policies."], options: ["--run and --workspace required; --max-agent-requests can extend the request limit. Hosted-only: --allow-dirty and --delegation. Local-only: --accept-packet-changes reconciles inspected owner edits; --retry-interrupted authorizes retry of an inspected interrupted stage. Selection and execution policies remain frozen."], result: "Prints resumed run outcomes; inspect task failures even when command exits 0. Errors exit 1.", example: "swarmcraft resume --run <id> --workspace ." },
71534
71732
  status: { requirements: ["Existing local run manifest; no sign-in or API required."], effects: ["Reads the recorded run summary without continuing execution or writing files."], options: ["--run and --workspace required. Delegation is not used for this local read."], result: "Prints local run/task outcomes; exit 0 on success, 1 when unreadable.", example: "swarmcraft status --run <id> --workspace ." },
71535
71733
  doctor: { requirements: ["No session required for local checks; an existing session enables an API reachability check."], effects: ["Checks Node, session, optional Git workspace and provider executable. May refresh session or use explicitly requested delegation; does not upgrade guidance."], options: ["--workspace and --agent-provider optional; custom skips provider executable lookup."], result: "Diagnostic text reports missing prerequisites; a completed diagnostic may exit 0 despite reported problems. Read the output.", example: "swarmcraft doctor --workspace . --agent-provider claude" },
@@ -71572,11 +71770,11 @@ Help is local and read-only; no authentication or command execution occurs.
71572
71770
 
71573
71771
  // src/terminalPrompt.ts
71574
71772
  var import_node_process = require("node:process");
71575
- var import_promises12 = require("node:readline/promises");
71773
+ var import_promises13 = require("node:readline/promises");
71576
71774
  var import_node_stream = require("node:stream");
71577
71775
  var DEFAULT_STREAMS = { input: import_node_process.stdin, output: import_node_process.stdout };
71578
71776
  async function promptLine(prompt, streams = DEFAULT_STREAMS) {
71579
- const readline = (0, import_promises12.createInterface)({ input: streams.input, output: streams.output });
71777
+ const readline = (0, import_promises13.createInterface)({ input: streams.input, output: streams.output });
71580
71778
  try {
71581
71779
  return (await readline.question(prompt)).trim();
71582
71780
  } finally {
@@ -71598,7 +71796,7 @@ async function promptSecret(prompt, streams = DEFAULT_STREAMS) {
71598
71796
  });
71599
71797
  concealedOutput.isTTY = true;
71600
71798
  concealedOutput.columns = streams.output.columns ?? 80;
71601
- const readline = (0, import_promises12.createInterface)({ input: streams.input, output: concealedOutput, terminal: true });
71799
+ const readline = (0, import_promises13.createInterface)({ input: streams.input, output: concealedOutput, terminal: true });
71602
71800
  try {
71603
71801
  const answer = readline.question(prompt);
71604
71802
  muted = true;
@@ -71636,7 +71834,7 @@ function formatProjectUpgrade(result) {
71636
71834
  }
71637
71835
 
71638
71836
  // src/operation/upgrade.ts
71639
- var import_promises13 = require("node:fs/promises");
71837
+ var import_promises14 = require("node:fs/promises");
71640
71838
  var import_node_path12 = __toESM(require("node:path"), 1);
71641
71839
  var import_node_crypto6 = require("node:crypto");
71642
71840
  var import_repo_seed6 = __toESM(require_dist4(), 1);
@@ -71822,7 +72020,7 @@ async function checkOperationUpgrade(workspace) {
71822
72020
  const result = (state) => ({ protocol: 1, state, valid: true });
71823
72021
  const git3 = await operationGit(root, ["rev-parse", "--absolute-git-dir"]);
71824
72022
  if (!git3.exitCode) try {
71825
- await (0, import_promises13.lstat)(import_node_path12.default.join(git3.stdout.trim(), JOURNAL));
72023
+ await (0, import_promises14.lstat)(import_node_path12.default.join(git3.stdout.trim(), JOURNAL));
71826
72024
  return result("INTERRUPTED");
71827
72025
  } catch (error) {
71828
72026
  if (!isMissing(error)) throw error;
@@ -71850,15 +72048,15 @@ async function upgradeOperation(workspace, signal) {
71850
72048
  const files = new OperationFiles(root);
71851
72049
  let pending;
71852
72050
  try {
71853
- const info = await (0, import_promises13.lstat)(journalPath);
72051
+ const info = await (0, import_promises14.lstat)(journalPath);
71854
72052
  if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > 5e7) fail("OPERATE_RECOVERY_REVIEW_REQUIRED", "Upgrade recovery state is not a supported bounded local file.");
71855
- pending = JSON.parse(await (0, import_promises13.readFile)(journalPath, "utf8"));
72053
+ pending = JSON.parse(await (0, import_promises14.readFile)(journalPath, "utf8"));
71856
72054
  } catch (error) {
71857
72055
  if (!isMissing(error)) throw error;
71858
72056
  }
71859
72057
  if (pending) {
71860
72058
  await recover(root, files, pending);
71861
- await (0, import_promises13.unlink)(journalPath);
72059
+ await (0, import_promises14.unlink)(journalPath);
71862
72060
  }
71863
72061
  const check = await checkOperationUpgrade(root);
71864
72062
  if (check.state === "CURRENT") return { valid: true, state: "CURRENT", codes: [] };
@@ -71948,18 +72146,18 @@ async function upgradeOperation(workspace, signal) {
71948
72146
  if ((await git2(root, ["rev-parse", "HEAD"])).trim() !== journal.checkpoint) fail("OPERATE_CONCURRENT_EDIT", "Git history changed during upgrade. Review recovery before retrying.");
71949
72147
  await git2(root, ["commit", "--only", "-m", "Upgrade Operate repository", "-m", "Operate-Upgrade-Checkpoint: " + journal.checkpoint, "--", ...changes.map((change) => change.path)]);
71950
72148
  await verifyCommitted(root, journal);
71951
- await (0, import_promises13.unlink)(journalPath);
72149
+ await (0, import_promises14.unlink)(journalPath);
71952
72150
  return { valid: true, state: "UPDATED", codes: status.codes, checkpoint: journal.checkpoint };
71953
72151
  } catch (error) {
71954
72152
  try {
71955
72153
  await recover(root, files, journal);
71956
- await (0, import_promises13.unlink)(journalPath);
72154
+ await (0, import_promises14.unlink)(journalPath);
71957
72155
  } catch {
71958
72156
  }
71959
72157
  throw error;
71960
72158
  }
71961
72159
  } finally {
71962
- await (0, import_promises13.unlink)(lock);
72160
+ await (0, import_promises14.unlink)(lock);
71963
72161
  }
71964
72162
  }
71965
72163
  function upgradeFailureMessage(code) {
@@ -71979,7 +72177,7 @@ async function requireClean(root) {
71979
72177
  for (const name of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply", "sequencer"]) {
71980
72178
  const location = (await git2(root, ["rev-parse", "--git-path", name])).trim();
71981
72179
  try {
71982
- await (0, import_promises13.lstat)(import_node_path12.default.resolve(root, location));
72180
+ await (0, import_promises14.lstat)(import_node_path12.default.resolve(root, location));
71983
72181
  fail("OPERATE_GIT_IN_PROGRESS", "Finish the current Git operation before upgrading.");
71984
72182
  } catch (error) {
71985
72183
  if (!isMissing(error)) throw error;
@@ -71988,12 +72186,12 @@ async function requireClean(root) {
71988
72186
  }
71989
72187
  async function acquire(lock) {
71990
72188
  try {
71991
- const handle = await (0, import_promises13.open)(lock, "wx", 384);
72189
+ const handle = await (0, import_promises14.open)(lock, "wx", 384);
71992
72190
  await handle.writeFile(String(process.pid));
71993
72191
  await handle.close();
71994
72192
  } catch (error) {
71995
72193
  if (!(error && typeof error === "object" && "code" in error && error.code === "EEXIST")) throw error;
71996
- const pid = Number(await (0, import_promises13.readFile)(lock, "utf8"));
72194
+ const pid = Number(await (0, import_promises14.readFile)(lock, "utf8"));
71997
72195
  if (!Number.isSafeInteger(pid) || pid < 1) fail("OPERATE_UPGRADE_LOCKED", "Upgrade lock needs review before retrying.");
71998
72196
  try {
71999
72197
  process.kill(pid, 0);
@@ -72003,17 +72201,17 @@ async function acquire(lock) {
72003
72201
  }
72004
72202
  let reaper;
72005
72203
  try {
72006
- reaper = await (0, import_promises13.open)(lock + ".recovery", "wx", 384);
72204
+ reaper = await (0, import_promises14.open)(lock + ".recovery", "wx", 384);
72007
72205
  } catch {
72008
72206
  fail("OPERATE_UPGRADE_LOCKED", "Another process is recovering the upgrade lock. Retry after it finishes.");
72009
72207
  }
72010
72208
  try {
72011
- if (Number(await (0, import_promises13.readFile)(lock, "utf8")) !== pid) fail("OPERATE_UPGRADE_LOCKED", "The upgrade lock changed. Retry after the active process finishes.");
72012
- await (0, import_promises13.unlink)(lock);
72209
+ if (Number(await (0, import_promises14.readFile)(lock, "utf8")) !== pid) fail("OPERATE_UPGRADE_LOCKED", "The upgrade lock changed. Retry after the active process finishes.");
72210
+ await (0, import_promises14.unlink)(lock);
72013
72211
  await acquire(lock);
72014
72212
  } finally {
72015
72213
  await reaper.close();
72016
- await (0, import_promises13.unlink)(lock + ".recovery");
72214
+ await (0, import_promises14.unlink)(lock + ".recovery");
72017
72215
  }
72018
72216
  }
72019
72217
  }
@@ -72066,7 +72264,7 @@ async function verifyCommitted(root, journal) {
72066
72264
  }
72067
72265
  async function writeJournal(destination, journal) {
72068
72266
  const temporary = destination + "." + (0, import_node_crypto6.randomUUID)() + ".tmp";
72069
- const handle = await (0, import_promises13.open)(temporary, "wx", 384);
72267
+ const handle = await (0, import_promises14.open)(temporary, "wx", 384);
72070
72268
  try {
72071
72269
  await handle.writeFile(JSON.stringify(journal));
72072
72270
  await handle.sync();
@@ -72074,9 +72272,9 @@ async function writeJournal(destination, journal) {
72074
72272
  await handle.close();
72075
72273
  }
72076
72274
  try {
72077
- await (0, import_promises13.rename)(temporary, destination);
72275
+ await (0, import_promises14.rename)(temporary, destination);
72078
72276
  } catch (error) {
72079
- await (0, import_promises13.unlink)(temporary);
72277
+ await (0, import_promises14.unlink)(temporary);
72080
72278
  throw error;
72081
72279
  }
72082
72280
  }
@@ -72379,7 +72577,7 @@ async function generateOperationHandbook(options, signal, processRunner = runPro
72379
72577
  }
72380
72578
 
72381
72579
  // src/operation/intake.ts
72382
- var import_promises14 = require("node:fs/promises");
72580
+ var import_promises15 = require("node:fs/promises");
72383
72581
  var import_node_path14 = __toESM(require("node:path"), 1);
72384
72582
  var import_operation_contract7 = __toESM(require_dist2(), 1);
72385
72583
  async function intakeOperationSource(options, signal) {
@@ -72406,9 +72604,9 @@ async function intakeOperationSource(options, signal) {
72406
72604
  extension = import_node_path14.default.extname(previous.locator);
72407
72605
  if ((0, import_operation_contract7.artifactDigest)(bytes) !== previous.source_digest) throw new OperateCommandError("OPERATE_SOURCE_CHANGED", 3, "The original differs from its registered snapshot; import a new version with a new source ID.");
72408
72606
  } else if (options.input) {
72409
- const entry = await (0, import_promises14.lstat)(options.input);
72607
+ const entry = await (0, import_promises15.lstat)(options.input);
72410
72608
  if (!entry.isFile() || entry.isSymbolicLink() || entry.size > 1e7) throw new OperateCommandError("OPERATE_SOURCE_UNSUPPORTED", 4, "Select a regular source file of at most 10 MB.");
72411
- bytes = await (0, import_promises14.readFile)(options.input);
72609
+ bytes = await (0, import_promises15.readFile)(options.input);
72412
72610
  extension = import_node_path14.default.extname(options.input).toLowerCase();
72413
72611
  }
72414
72612
  const digest = bytes ? (0, import_operation_contract7.artifactDigest)(bytes) : "";
@@ -72622,6 +72820,96 @@ function safeOperateError(error) {
72622
72820
  return new OperateCommandError("OPERATE_COMMAND_FAILED", 4, "Operate could not complete. Check command options, workspace permissions, and local operation files.");
72623
72821
  }
72624
72822
 
72823
+ // src/commands/packet-link-commands.ts
72824
+ function findWorkspacePacketLinks(board, workspaceFolder) {
72825
+ return board.columns.flatMap((column) => column.tasks).filter((task) => task.packetLink?.workspaceFolder === workspaceFolder).map((task) => ({
72826
+ taskId: task.id,
72827
+ title: task.title,
72828
+ workflowState: task.workflowState,
72829
+ packetFilePath: task.packetLink.packetFilePath
72830
+ }));
72831
+ }
72832
+ async function removeWorkspacePacketLinks(client, accessToken, projectId, workspaceFolder, links, delegationId) {
72833
+ const result = { removed: [], conflicts: [], failed: [] };
72834
+ for (const link of links) {
72835
+ try {
72836
+ await client.removeTaskPacketLink(projectId, link.taskId, workspaceFolder, accessToken, delegationId);
72837
+ result.removed.push(link.taskId);
72838
+ } catch (error) {
72839
+ if (error instanceof SwarmCraftApiError && error.code === "PROJECT_TASK_PACKET_LINK_CONFLICT") {
72840
+ result.conflicts.push(link.taskId);
72841
+ } else {
72842
+ result.failed.push({ taskId: link.taskId, message: error instanceof Error ? error.message : "Unknown error" });
72843
+ }
72844
+ }
72845
+ }
72846
+ return result;
72847
+ }
72848
+
72849
+ // src/packetSync.ts
72850
+ var import_packet_workflow9 = __toESM(require_dist(), 1);
72851
+ async function runPacketSync(client, accessToken, options) {
72852
+ const workspace = await validateWorkspace(options.workspacePath);
72853
+ const binding = await readWorkspaceProjectBinding(workspace.workspacePath, client, accessToken);
72854
+ if (binding.discovery && !binding.discovery.resultingProjectId) {
72855
+ throw new Error(binding.discovery.unverifiedReason ? `This workspace's Deep Discovery binding could not be verified (${binding.discovery.unverifiedReason}). Nothing was written.` : "This workspace's Deep Discovery has not created a project yet. Nothing was written.");
72856
+ }
72857
+ const boundProjectId = binding.discovery?.resultingProjectId ?? binding.seedStateProjectId;
72858
+ const targetProjectId = options.projectId ?? boundProjectId;
72859
+ if (!targetProjectId || !boundProjectId) {
72860
+ throw new Error("This workspace is not bound to a SwarmCraft project. Bind it with `swarmcraft init --project <id>` or the VS Code extension before syncing packets.");
72861
+ }
72862
+ const project = await client.loadProject(targetProjectId, accessToken, options.delegationId);
72863
+ const projectTitle = project.title || project.projectTitle || project.id;
72864
+ const check = checkProjectBinding({ id: project.id, title: projectTitle }, binding);
72865
+ if (check.status === "mismatch") throw new Error(`${check.message} Nothing was written.`);
72866
+ if (project.boardState !== "READY") throw new Error(`Project "${projectTitle}" (${project.id}) is ${project.boardState}; wait for the board to be ready.`);
72867
+ const board = await client.loadBoard(project.id, accessToken, options.delegationId);
72868
+ const tasks = board.columns.flatMap((column) => column.tasks);
72869
+ const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
72870
+ const entries = await (0, import_packet_workflow9.planPacketSync)({
72871
+ project,
72872
+ tasks,
72873
+ workspaceFolder: workspace.workspaceFolderName,
72874
+ includeDone: options.includeDone,
72875
+ syncedAt,
72876
+ readExisting: async (relativePath) => await fileExists(resolveContainedWorkspacePath(workspace.workspacePath, relativePath)) ? readWorkspaceFile(workspace.workspacePath, relativePath) : null
72877
+ });
72878
+ const preview = {
72879
+ projectId: project.id,
72880
+ projectTitle,
72881
+ workspacePath: workspace.workspacePath,
72882
+ link: options.link,
72883
+ counts: (0, import_packet_workflow9.summarisePacketSync)(entries),
72884
+ entries,
72885
+ bindingNotice: check.status === "rebind" ? check.message : null
72886
+ };
72887
+ if (options.dryRun) return { ...preview, status: "dry-run", linkedPackets: [] };
72888
+ const writes = entries.filter((entry) => entry.action === "create" || entry.action === "refresh");
72889
+ const links = options.link ? entries.filter((entry) => entry.action !== "skip" && entry.needsLink) : [];
72890
+ if (writes.length === 0 && links.length === 0) return { ...preview, status: "nothing-to-do", linkedPackets: [] };
72891
+ if (!await options.confirm(preview)) return { ...preview, status: "cancelled", linkedPackets: [] };
72892
+ await ensureWorkspaceTracking(workspace.workspacePath);
72893
+ for (const entry of writes) {
72894
+ if (entry.action === "skip") continue;
72895
+ await writeWorkspaceFile(workspace.workspacePath, entry.relativePath, entry.contents);
72896
+ }
72897
+ const linkedPackets = [];
72898
+ for (const entry of links) {
72899
+ if (entry.action === "skip") continue;
72900
+ const task = tasks.find(({ id }) => id === entry.taskId);
72901
+ await client.upsertTaskPacketLink(project.id, task.id, {
72902
+ workspaceFolder: workspace.workspaceFolderName,
72903
+ packetFilePath: entry.relativePath,
72904
+ expectedRevision: task.revision,
72905
+ lastSyncedTaskRevision: task.revision,
72906
+ lastSyncedAt: syncedAt
72907
+ }, accessToken, options.delegationId);
72908
+ linkedPackets.push(entry.relativePath);
72909
+ }
72910
+ return { ...preview, status: "synced", linkedPackets };
72911
+ }
72912
+
72625
72913
  // src/main.ts
72626
72914
  var VERSION = package_default.version;
72627
72915
  var DEFAULT_API_BASE_URL = "https://swarmcraft.ai/api";
@@ -72638,7 +72926,7 @@ async function main(argv) {
72638
72926
  if (command) {
72639
72927
  printCommandHelp(command);
72640
72928
  } else {
72641
- if (parsed.positionals.length && !["auth", "projects", "delegation", "discovery", "operate"].includes(parsed.positionals.join(" "))) throw new Error("Unknown help command. Run swarmcraft --help.");
72929
+ if (parsed.positionals.length && !["auth", "projects", "packets", "delegation", "discovery", "operate"].includes(parsed.positionals.join(" "))) throw new Error("Unknown help command. Run swarmcraft --help.");
72642
72930
  printGeneralHelp();
72643
72931
  }
72644
72932
  return 0;
@@ -72649,7 +72937,7 @@ async function main(argv) {
72649
72937
  printCommandHelp(helpCommand);
72650
72938
  } else {
72651
72939
  const requested = parsed.positionals.slice(1).join(" ");
72652
- if (requested && !["auth", "projects", "delegation", "discovery", "operate"].includes(requested)) throw new Error("Unknown help command. Run swarmcraft --help.");
72940
+ if (requested && !["auth", "projects", "packets", "delegation", "discovery", "operate"].includes(requested)) throw new Error("Unknown help command. Run swarmcraft --help.");
72653
72941
  printGeneralHelp();
72654
72942
  }
72655
72943
  return 0;
@@ -72687,6 +72975,10 @@ Run "swarmcraft --help" for available commands.`);
72687
72975
  case "projects list":
72688
72976
  await runProjectsList(parsed);
72689
72977
  return 0;
72978
+ case "packets links":
72979
+ return runPacketLinks(parsed);
72980
+ case "packets sync":
72981
+ return runPacketSyncCommand(parsed);
72690
72982
  case "discovery prepare":
72691
72983
  await runDiscoveryPrepare(parsed);
72692
72984
  return 0;
@@ -72782,6 +73074,71 @@ async function runProjectsList(parsed) {
72782
73074
  console.log(`${project.id} ${project.boardState} ${done}/${total} done ${project.title}`);
72783
73075
  }
72784
73076
  }
73077
+ async function runPacketSyncCommand(parsed) {
73078
+ const workspacePath = requireOption(parsed, "workspace");
73079
+ const { client, session, delegation } = await resolveProjectCommandContext(parsed);
73080
+ printDelegationContext(delegation);
73081
+ const result = await runPacketSync(client, session.accessToken, {
73082
+ workspacePath,
73083
+ projectId: getOption(parsed, "project") ?? null,
73084
+ includeDone: hasFlag(parsed, "include-done"),
73085
+ link: hasFlag(parsed, "link"),
73086
+ dryRun: hasFlag(parsed, "dry-run"),
73087
+ delegationId: delegation?.id ?? null,
73088
+ confirm: async (preview) => {
73089
+ printPacketSyncPreview(preview);
73090
+ if (hasFlag(parsed, "yes")) return true;
73091
+ if (!process.stdin.isTTY) throw new Error("Writing packets needs confirmation. Re-run in a terminal, or pass --yes after reviewing the preview with --dry-run.");
73092
+ return (await promptLine("Write these packet files? [y/N] ")).toLowerCase() === "y";
73093
+ }
73094
+ });
73095
+ if (result.status === "dry-run" || result.status === "nothing-to-do") printPacketSyncPreview(result);
73096
+ if (result.status === "nothing-to-do") console.log("Local packets already match the board. Nothing was written.");
73097
+ if (result.status === "cancelled") console.log("Cancelled. Nothing was written.");
73098
+ if (result.status === "synced") {
73099
+ console.log(`Packet files written: ${result.counts.create + result.counts.refresh}`);
73100
+ if (result.link) console.log(`Packet links upserted: ${result.linkedPackets.length}`);
73101
+ }
73102
+ return 0;
73103
+ }
73104
+ function printPacketSyncPreview(preview) {
73105
+ console.log(`Project: "${preview.projectTitle}" (${preview.projectId})`);
73106
+ if (preview.bindingNotice) console.log(`Binding: ${preview.bindingNotice}`);
73107
+ console.log(`Workspace: ${preview.workspacePath}`);
73108
+ const { create, refresh, unchanged, skip, links } = preview.counts;
73109
+ console.log(`To create: ${create} To refresh: ${refresh} Kept as is: ${unchanged} Skipped: ${skip}`);
73110
+ console.log(preview.link ? `Packet links to upsert: ${links}` : "Remote packet links: not changed (use --link to create them)");
73111
+ for (const entry of preview.entries) {
73112
+ if (entry.action === "create") console.log(` + ${entry.relativePath}`);
73113
+ else if (entry.action === "refresh") console.log(` ~ ${entry.relativePath}`);
73114
+ else if (entry.action === "skip") console.log(` - ${entry.taskId} ${entry.title}: ${entry.reason}`);
73115
+ }
73116
+ }
73117
+ async function runPacketLinks(parsed) {
73118
+ const projectId = requireOption(parsed, "project");
73119
+ const workspaceFolder = requireOption(parsed, "workspace-folder");
73120
+ const { client, session, delegation } = await resolveProjectCommandContext(parsed);
73121
+ printDelegationContext(delegation);
73122
+ const delegationId = delegation?.id ?? null;
73123
+ const project = await client.loadProject(projectId, session.accessToken, delegationId);
73124
+ const links = findWorkspacePacketLinks(await client.loadBoard(project.id, session.accessToken, delegationId), workspaceFolder);
73125
+ console.log(`Project: "${project.title || project.projectTitle || project.id}" (${project.id})`);
73126
+ console.log(`Packet links naming workspace folder "${workspaceFolder}": ${links.length}`);
73127
+ for (const link of links) console.log(` ${link.taskId} ${link.workflowState} ${link.title} ${link.packetFilePath}`);
73128
+ if (!hasFlag(parsed, "remove") || links.length === 0) return 0;
73129
+ if (!hasFlag(parsed, "yes")) {
73130
+ if (!process.stdin.isTTY) throw new Error("Removing packet links needs confirmation. Re-run in a terminal, or pass --yes after reviewing the list.");
73131
+ if (await promptLine(`Type the project ID to remove these ${links.length} packet link(s): `) !== project.id) {
73132
+ console.log("Cancelled. No packet links were removed.");
73133
+ return 0;
73134
+ }
73135
+ }
73136
+ const result = await removeWorkspacePacketLinks(client, session.accessToken, project.id, workspaceFolder, links, delegationId);
73137
+ console.log(`Removed: ${result.removed.length}`);
73138
+ if (result.conflicts.length > 0) console.log(`Kept because the link now names another workspace folder: ${result.conflicts.join(", ")}`);
73139
+ for (const failure2 of result.failed) console.log(`Failed: ${failure2.taskId}: ${failure2.message}`);
73140
+ return result.failed.length > 0 ? 1 : 0;
73141
+ }
72785
73142
  async function runInit(parsed) {
72786
73143
  const projectId = requireOption(parsed, "project");
72787
73144
  const workspacePath = requireOption(parsed, "workspace");
@@ -72794,12 +73151,14 @@ async function runInit(parsed) {
72794
73151
  taskIds: getOptions(parsed, "task"),
72795
73152
  taskLimit,
72796
73153
  delegationId: delegation?.id ?? null,
72797
- agentProvider: parseChoice(requireOption(parsed, "agent-provider"), ["codex", "copilot", "claude"], "--agent-provider")
73154
+ agentProvider: parseChoice(requireOption(parsed, "agent-provider"), ["codex", "copilot", "claude"], "--agent-provider"),
73155
+ force: hasFlag(parsed, "force"),
73156
+ dryRun: hasFlag(parsed, "dry-run")
72798
73157
  });
72799
73158
  printBootstrapSummary(summary);
72800
73159
  }
72801
73160
  async function runOneShotCommand(parsed) {
72802
- rejectUnsupportedOptions(parsed, ["api-base-url", "workspace", "agent-provider", "agent-command", "agent-env-file", "agent-api-key-env-name", "project", "plan", "packet", "phase", "preview", "task", "task-limit", "delegation", "delivery", "checking", "reviewing", "done-policy", "commit-policy", "max-checking-attempts", "max-agent-requests", "max-agent-spend-usd", "require-cost-telemetry", "allow-dirty", "run-id"]);
73161
+ rejectUnsupportedOptions(parsed, ["api-base-url", "workspace", "agent-provider", "agent-command", "agent-env-file", "agent-api-key-env-name", "project", "plan", "packet", "phase", "preview", "task", "task-limit", "delegation", "delivery", "checking", "reviewing", "done-policy", "commit-policy", "max-checking-attempts", "max-agent-requests", "max-agent-spend-usd", "require-cost-telemetry", "allow-dirty", "run-id", "force"]);
72803
73162
  if (getOption(parsed, "plan") || getOptions(parsed, "packet").length) {
72804
73163
  for (const key of ["api-base-url", "project", "task", "delegation", "task-limit", "done-policy", "max-checking-attempts"]) if (getOption(parsed, key)) throw new Error(`Local selection cannot combine with --${key}.`);
72805
73164
  const options2 = { ...parseOneShotOptions(parsed, true), delegation: null };
@@ -72909,7 +73268,7 @@ async function runDoctor(parsed) {
72909
73268
  }
72910
73269
  const provider = getOption(parsed, "agent-provider");
72911
73270
  if (provider && provider !== "custom") {
72912
- const commandName = (0, import_packet_workflow10.parseExternalAgentProvider)(provider);
73271
+ const commandName = (0, import_packet_workflow11.parseExternalAgentProvider)(provider);
72913
73272
  const result = await runProcess(process.platform === "win32" ? "where.exe" : "which", [commandName], process.cwd());
72914
73273
  console.log(`${commandName}: ${result.exitCode === 0 ? result.stdout.trim() : "not found"}`);
72915
73274
  }
@@ -73016,15 +73375,24 @@ function toDelegationContext(delegation) {
73016
73375
  };
73017
73376
  }
73018
73377
  function printBootstrapSummary(summary) {
73019
- console.log(`Bootstrapped ${summary.projectTitle}`);
73378
+ console.log(summary.dryRun ? `Dry run for "${summary.projectTitle}" (${summary.projectId}). Nothing was written.` : `Bootstrapped "${summary.projectTitle}" (${summary.projectId})`);
73379
+ if (summary.binding.message) console.log(`${summary.binding.status === "mismatch" ? "Binding mismatch" : "Binding"}: ${summary.binding.message}`);
73020
73380
  console.log(`Workspace: ${summary.workspacePath}`);
73021
73381
  if (summary.dirtyFileCount > 0) {
73022
73382
  console.log(`Workspace had ${summary.dirtyFileCount} pre-existing changed file(s).`);
73023
73383
  }
73024
- console.log(`Seed files written or updated: ${summary.seedFilesWritten.length}`);
73025
- console.log(`Packet files created: ${summary.packetFilesCreated.length}`);
73026
- console.log(`Packet files refreshed: ${summary.packetFilesRefreshed.length}`);
73027
- console.log(`Packet links upserted: ${summary.linkedPackets.length}`);
73384
+ if (summary.dryRun) {
73385
+ console.log(`Packet files to create: ${summary.packetFilesCreated.length}`);
73386
+ console.log(`Packet files to refresh: ${summary.packetFilesRefreshed.length}`);
73387
+ console.log(`Packet links to upsert: ${summary.linkedPackets.length}`);
73388
+ for (const packetPath of summary.packetFilesCreated) console.log(` + ${packetPath}`);
73389
+ for (const packetPath of summary.packetFilesRefreshed) console.log(` ~ ${packetPath}`);
73390
+ } else {
73391
+ console.log(`Seed files written or updated: ${summary.seedFilesWritten.length}`);
73392
+ console.log(`Packet files created: ${summary.packetFilesCreated.length}`);
73393
+ console.log(`Packet files refreshed: ${summary.packetFilesRefreshed.length}`);
73394
+ console.log(`Packet links upserted: ${summary.linkedPackets.length}`);
73395
+ }
73028
73396
  if (summary.skippedTasks.length > 0) {
73029
73397
  console.log("Skipped tasks:");
73030
73398
  for (const skipped of summary.skippedTasks) {
@@ -73066,7 +73434,7 @@ function printRunSummary(manifest) {
73066
73434
  }
73067
73435
  function parseOneShotOptions(parsed, local = false) {
73068
73436
  const providerValue = requireOption(parsed, "agent-provider");
73069
- const agentProvider = providerValue === "managed" ? "managed" : (0, import_packet_workflow10.parseExternalAgentProvider)(providerValue);
73437
+ const agentProvider = providerValue === "managed" ? "managed" : (0, import_packet_workflow11.parseExternalAgentProvider)(providerValue);
73070
73438
  if (agentProvider === "managed" && (getOption(parsed, "agent-command") || getOption(parsed, "agent-env-file") || getOption(parsed, "agent-api-key-env-name"))) {
73071
73439
  throw new Error("Managed AI does not accept custom commands or provider credentials.");
73072
73440
  }
@@ -73079,7 +73447,7 @@ function parseOneShotOptions(parsed, local = false) {
73079
73447
  workspacePath: requireOption(parsed, "workspace"),
73080
73448
  agentProvider,
73081
73449
  agentCommand: getOption(parsed, "agent-command") ?? process.env.SWARMCRAFT_AGENT_COMMAND ?? null,
73082
- delivery: (0, import_packet_workflow9.parseDeliveryMode)(getOption(parsed, "delivery")),
73450
+ delivery: (0, import_packet_workflow10.parseDeliveryMode)(getOption(parsed, "delivery")),
73083
73451
  checking: parseOnOff(getOption(parsed, "checking") ?? (local ? "on" : "off"), "--checking"),
73084
73452
  reviewing: explicitReviewing ? parseOnOff(explicitReviewing, "--reviewing") : local || donePolicy === "stop",
73085
73453
  maxCheckingAttempts: parsePositiveInteger(getOption(parsed, "max-checking-attempts") ?? "2", "--max-checking-attempts"),
@@ -73089,6 +73457,7 @@ function parseOneShotOptions(parsed, local = false) {
73089
73457
  maxAgentSpendUsd: getOption(parsed, "max-agent-spend-usd") ? parseNonNegativeNumber(getOption(parsed, "max-agent-spend-usd"), "--max-agent-spend-usd") : null,
73090
73458
  requireCostTelemetry: hasFlag(parsed, "require-cost-telemetry"),
73091
73459
  allowDirty: hasFlag(parsed, "allow-dirty"),
73460
+ forceProjectBinding: hasFlag(parsed, "force"),
73092
73461
  agentEnvFilePath: getOption(parsed, "agent-env-file") ?? null,
73093
73462
  agentApiKeyEnvName: getOption(parsed, "agent-api-key-env-name") ?? null,
73094
73463
  taskIds: getOptions(parsed, "task"),
@@ -73098,10 +73467,10 @@ function parseOneShotOptions(parsed, local = false) {
73098
73467
  };
73099
73468
  }
73100
73469
  async function readRunManifest(workspacePath, runId) {
73101
- return JSON.parse(await (0, import_promises15.readFile)(resolveManifestPath(import_node_path15.default.resolve(workspacePath), runId), "utf8"));
73470
+ return JSON.parse(await (0, import_promises16.readFile)(resolveManifestPath(import_node_path15.default.resolve(workspacePath), runId), "utf8"));
73102
73471
  }
73103
73472
  function commandGroup(name) {
73104
- if (["init", "upgrade"].includes(name)) return "Setup and upgrade";
73473
+ if (["init", "upgrade"].includes(name) || name.startsWith("packets ")) return "Setup and upgrade";
73105
73474
  if (["one-shot", "resume", "status"].includes(name)) return "Delivery";
73106
73475
  if (name.startsWith("operate ")) return "Operate";
73107
73476
  if (name.startsWith("discovery ")) return "Discovery";