@swarmcraftai/cli 0.9.0 → 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/CHANGELOG.md +17 -0
- package/README.md +21 -1
- package/dist/main.cjs +742 -270
- package/package.json +1 -1
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 =
|
|
369
|
+
exports2.renderPacketFile = renderPacketFile;
|
|
370
370
|
exports2.renderProvisionalPacketFile = renderProvisionalPacketFile;
|
|
371
371
|
exports2.renderChecklistSection = renderChecklistSection;
|
|
372
|
-
exports2.resolvePacketFilePath =
|
|
373
|
-
exports2.parsePacketFile =
|
|
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 =
|
|
380
|
+
exports2.ensurePacketFileIdentity = ensurePacketFileIdentity;
|
|
381
381
|
exports2.ensurePacketMatches = ensurePacketMatches;
|
|
382
382
|
exports2.isProvisionalPacketFile = isProvisionalPacketFile;
|
|
383
383
|
exports2.assertProvisionalPacketFile = assertProvisionalPacketFile;
|
|
@@ -389,6 +389,8 @@ var require_packetFile = __commonJS({
|
|
|
389
389
|
exports2.normalizeSectionText = normalizeSectionText;
|
|
390
390
|
exports2.previewText = previewText;
|
|
391
391
|
exports2.slugify = slugify;
|
|
392
|
+
exports2.preservePacketLineEndings = preservePacketLineEndings;
|
|
393
|
+
exports2.renderDependsOnFrontmatter = renderDependsOnFrontmatter;
|
|
392
394
|
var node_path_1 = __importDefault(require("node:path"));
|
|
393
395
|
var node_crypto_1 = require("node:crypto");
|
|
394
396
|
var executionMetadata_js_1 = require_executionMetadata();
|
|
@@ -397,7 +399,7 @@ var require_packetFile = __commonJS({
|
|
|
397
399
|
exports2.PACKET_FILE_ROOT = ".swarmcraft/projects/";
|
|
398
400
|
exports2.PROVISIONAL_TASK_ID_PREFIX = "provisional:";
|
|
399
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. -->";
|
|
400
|
-
var
|
|
402
|
+
var PacketFileContractError = class extends Error {
|
|
401
403
|
code;
|
|
402
404
|
constructor(code, message) {
|
|
403
405
|
super(message);
|
|
@@ -405,17 +407,17 @@ var require_packetFile = __commonJS({
|
|
|
405
407
|
this.code = code;
|
|
406
408
|
}
|
|
407
409
|
};
|
|
408
|
-
exports2.PacketFileContractError =
|
|
409
|
-
function
|
|
410
|
-
const existingPacket = existingContents ?
|
|
410
|
+
exports2.PacketFileContractError = PacketFileContractError;
|
|
411
|
+
function renderPacketFile(project, task, syncedAt, existingContents = null) {
|
|
412
|
+
const existingPacket = existingContents ? parsePacketFile4(existingContents) : null;
|
|
411
413
|
const storedSections = existingPacket ? existingPacket.sections : splitStoredTaskNotes(task.notes ?? null);
|
|
412
414
|
const goal = task.summary?.trim() ? task.summary.trim() : "Describe the outcome in one short paragraph.";
|
|
413
|
-
return [
|
|
415
|
+
return preservePacketLineEndings(existingContents ?? "", () => [
|
|
414
416
|
"---",
|
|
415
417
|
"swarmcraftVersion: 4",
|
|
416
418
|
`packetId: ${existingPacket?.frontmatter.packetId ?? legacyPacketUuid(project.id, task.id)}`,
|
|
417
419
|
`recommendedOrder: ${existingPacket?.frontmatter.recommendedOrder ?? task.recommendedOrder}`,
|
|
418
|
-
...existingPacket?.frontmatter.dependsOn !== void 0 ? [
|
|
420
|
+
...existingPacket?.frontmatter.dependsOn !== void 0 ? [renderDependsOnFrontmatter(existingPacket.frontmatter.dependsOn)] : [],
|
|
419
421
|
...existingPacket?.frontmatter.execution !== void 0 ? [`execution: ${JSON.stringify(existingPacket.frontmatter.execution)}`] : [],
|
|
420
422
|
`projectId: ${project.id}`,
|
|
421
423
|
`taskId: ${task.id}`,
|
|
@@ -455,7 +457,7 @@ var require_packetFile = __commonJS({
|
|
|
455
457
|
"",
|
|
456
458
|
storedSections.agentUpdate || "<!-- Short structured summary of what changed, what is blocked, and what still needs review. -->",
|
|
457
459
|
""
|
|
458
|
-
].join("\n");
|
|
460
|
+
].join("\n"));
|
|
459
461
|
}
|
|
460
462
|
function renderProvisionalPacketFile(input) {
|
|
461
463
|
const title = input.title.trim();
|
|
@@ -518,32 +520,32 @@ var require_packetFile = __commonJS({
|
|
|
518
520
|
}
|
|
519
521
|
return normalizedItems.map((item) => `- [ ] ${item}`).join("\n");
|
|
520
522
|
}
|
|
521
|
-
function
|
|
523
|
+
function resolvePacketFilePath2(project, task, packetLink = task.packetLink) {
|
|
522
524
|
if (packetLink) {
|
|
523
525
|
return packetLink.packetFilePath;
|
|
524
526
|
}
|
|
525
527
|
return node_path_1.default.posix.join(".swarmcraft", "projects", slugify(project.title || project.projectTitle || project.id), `${task.recommendedOrder}-${slugify(task.title || "task")}.md`);
|
|
526
528
|
}
|
|
527
|
-
function
|
|
529
|
+
function parsePacketFile4(contents) {
|
|
528
530
|
const { frontmatter, body } = parsePacketFileDocument(contents);
|
|
529
531
|
const sections = parseSections(body);
|
|
530
532
|
const requiredSections = ["Goal", "Notes", "Agent Update"];
|
|
531
533
|
for (const section of requiredSections) {
|
|
532
534
|
if (!(section in sections)) {
|
|
533
|
-
throw new
|
|
535
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", `The packet file is missing the required ${section} section.`);
|
|
534
536
|
}
|
|
535
537
|
}
|
|
536
538
|
const lane = parseLane(frontmatter.lane);
|
|
537
539
|
const syncRevision = Number(frontmatter.syncRevision ?? (Number(frontmatter.swarmcraftVersion) >= 3 ? "0" : "NaN"));
|
|
538
540
|
if (!Number.isInteger(syncRevision) || syncRevision < 0) {
|
|
539
|
-
throw new
|
|
541
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "The packet file is missing a valid syncRevision frontmatter value.");
|
|
540
542
|
}
|
|
541
543
|
const swarmcraftVersion = Number(frontmatter.swarmcraftVersion);
|
|
542
544
|
if (!Number.isInteger(swarmcraftVersion) || ![2, 3, 4].includes(swarmcraftVersion)) {
|
|
543
|
-
throw new
|
|
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.");
|
|
544
546
|
}
|
|
545
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 ?? "")) {
|
|
546
|
-
throw new
|
|
548
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "V3 packets require a UUID packetId.");
|
|
547
549
|
}
|
|
548
550
|
const order = frontmatter.recommendedOrder === void 0 ? void 0 : Number(frontmatter.recommendedOrder);
|
|
549
551
|
let ordered;
|
|
@@ -559,7 +561,7 @@ var require_packetFile = __commonJS({
|
|
|
559
561
|
if (swarmcraftVersion < 4 && ordered.execution)
|
|
560
562
|
throw new Error("Execution policy requires V4.");
|
|
561
563
|
} catch (error) {
|
|
562
|
-
throw new
|
|
564
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", String(error));
|
|
563
565
|
}
|
|
564
566
|
return {
|
|
565
567
|
frontmatter: {
|
|
@@ -595,25 +597,27 @@ var require_packetFile = __commonJS({
|
|
|
595
597
|
provisional: null
|
|
596
598
|
});
|
|
597
599
|
}
|
|
598
|
-
function patchPacketFrontmatter(
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
const
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
600
|
+
function patchPacketFrontmatter(original, updates) {
|
|
601
|
+
return preservePacketLineEndings(original, (contents) => {
|
|
602
|
+
parsePacketFileDocument(contents);
|
|
603
|
+
const boundary = contents.indexOf("\n---", 4);
|
|
604
|
+
let header = contents.slice(0, boundary);
|
|
605
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
606
|
+
const pattern = new RegExp(`^${key}:[^\\n]*`, "m");
|
|
607
|
+
if (value === null)
|
|
608
|
+
header = header.replace(new RegExp(`^${key}:[^\\n]*\\n?`, "m"), "").trimEnd();
|
|
609
|
+
else
|
|
610
|
+
header = pattern.test(header) ? header.replace(pattern, () => `${key}: ${value}`) : `${header}
|
|
608
611
|
${key}: ${value}`;
|
|
609
|
-
|
|
610
|
-
|
|
612
|
+
}
|
|
613
|
+
return header + contents.slice(boundary);
|
|
614
|
+
});
|
|
611
615
|
}
|
|
612
616
|
function rewritePacketFile(input) {
|
|
613
617
|
let rewritten = rewritePacketFileMetadata2(input.contents, {
|
|
614
618
|
lane: input.lane,
|
|
615
|
-
syncRevision:
|
|
616
|
-
lastSyncedAt: input.syncedAt ??
|
|
619
|
+
syncRevision: parsePacketFile4(input.contents).frontmatter.syncRevision,
|
|
620
|
+
lastSyncedAt: input.syncedAt ?? parsePacketFile4(input.contents).frontmatter.lastSyncedAt
|
|
617
621
|
});
|
|
618
622
|
rewritten = markChecklistStageComplete(rewritten, input.completeStage);
|
|
619
623
|
return appendAgentUpdateLines(rewritten, input.agentUpdateLines);
|
|
@@ -621,21 +625,21 @@ ${key}: ${value}`;
|
|
|
621
625
|
function markChecklistStageComplete(contents, checklistStage) {
|
|
622
626
|
const heading = checklistSectionHeading(checklistStage);
|
|
623
627
|
const sectionPattern = new RegExp(`(## ${escapeRegExp(heading)}\\n\\n)([\\s\\S]*?)(?=\\n## |$)`);
|
|
624
|
-
return contents.replace(sectionPattern, (_match, prefix, body) => {
|
|
628
|
+
return preservePacketLineEndings(contents, (lf) => lf.replace(sectionPattern, (_match, prefix, body) => {
|
|
625
629
|
const updatedBody = body.split("\n").map((line) => line.replace(/^- \[ \] /, "- [x] ")).join("\n");
|
|
626
630
|
return `${prefix}${updatedBody}`;
|
|
627
|
-
});
|
|
631
|
+
}));
|
|
628
632
|
}
|
|
629
633
|
function appendAgentUpdateLines(contents, lines) {
|
|
630
634
|
if (lines.length === 0) {
|
|
631
635
|
return contents;
|
|
632
636
|
}
|
|
633
637
|
const sectionPattern = /(## Agent Update\n\n)([\s\S]*?)$/;
|
|
634
|
-
return contents.replace(sectionPattern, (_match, prefix, body) => {
|
|
638
|
+
return preservePacketLineEndings(contents, (lf) => lf.replace(sectionPattern, (_match, prefix, body) => {
|
|
635
639
|
const normalizedBody = normalizeSectionText(body);
|
|
636
640
|
return `${prefix}${[normalizedBody, ...lines].filter(Boolean).join("\n")}
|
|
637
641
|
`;
|
|
638
|
-
});
|
|
642
|
+
}));
|
|
639
643
|
}
|
|
640
644
|
function composeTaskNotes2(notes, agentUpdate) {
|
|
641
645
|
const normalizedNotes = normalizeSectionText(notes);
|
|
@@ -651,15 +655,15 @@ ${key}: ${value}`;
|
|
|
651
655
|
}
|
|
652
656
|
return ["## Notes", "", normalizedNotes, "", "## Agent Update", "", normalizedAgentUpdate].join("\n");
|
|
653
657
|
}
|
|
654
|
-
function
|
|
658
|
+
function ensurePacketFileIdentity(contents, projectId, taskId) {
|
|
655
659
|
const { frontmatter } = parsePacketFileDocument(contents);
|
|
656
660
|
if (frontmatter.projectId !== projectId || frontmatter.taskId !== taskId) {
|
|
657
|
-
throw new
|
|
661
|
+
throw new PacketFileContractError("PACKET_FILE_MISMATCH", `The existing packet file is linked to ${frontmatter.taskId ?? "another task"} and cannot be reused for ${taskId}.`);
|
|
658
662
|
}
|
|
659
663
|
}
|
|
660
664
|
function ensurePacketMatches(packet, projectId, taskId) {
|
|
661
665
|
if (packet.frontmatter.projectId !== projectId || packet.frontmatter.taskId !== taskId) {
|
|
662
|
-
throw new
|
|
666
|
+
throw new PacketFileContractError("PACKET_FILE_MISMATCH", `The packet file belongs to ${packet.frontmatter.taskId} and cannot sync into ${taskId}.`);
|
|
663
667
|
}
|
|
664
668
|
}
|
|
665
669
|
function isProvisionalPacketFile(packet) {
|
|
@@ -667,19 +671,19 @@ ${key}: ${value}`;
|
|
|
667
671
|
}
|
|
668
672
|
function assertProvisionalPacketFile(packet) {
|
|
669
673
|
if (!isProvisionalPacketFile(packet)) {
|
|
670
|
-
throw new
|
|
674
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Provisional packets must use provisional: true, taskId: provisional:<slug>, lane: todo, and syncRevision: 0.");
|
|
671
675
|
}
|
|
672
676
|
const title = packet.frontmatter.title?.trim();
|
|
673
677
|
if (!title) {
|
|
674
|
-
throw new
|
|
678
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Provisional packets must include a title frontmatter value.");
|
|
675
679
|
}
|
|
676
680
|
if (!packet.sections.goal.trim()) {
|
|
677
|
-
throw new
|
|
681
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Provisional packets must include a Goal section.");
|
|
678
682
|
}
|
|
679
683
|
for (const checklistStage of exports2.CHECKLIST_STAGES) {
|
|
680
684
|
for (const checklistItem of packet.sections.checklists[checklistStage]) {
|
|
681
685
|
if (checklistItem.completed) {
|
|
682
|
-
throw new
|
|
686
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Provisional packet checklist items must start unchecked.");
|
|
683
687
|
}
|
|
684
688
|
}
|
|
685
689
|
}
|
|
@@ -710,7 +714,7 @@ ${key}: ${value}`;
|
|
|
710
714
|
function assertChecklistShape(currentChecklistItems, parsedChecklistItemsByStage) {
|
|
711
715
|
const problem = findChecklistShapeProblem2(currentChecklistItems, parsedChecklistItemsByStage);
|
|
712
716
|
if (problem) {
|
|
713
|
-
throw new
|
|
717
|
+
throw new PacketFileContractError("PACKET_FILE_UNSUPPORTED_CHECKLIST", problem.message);
|
|
714
718
|
}
|
|
715
719
|
}
|
|
716
720
|
function listChecklistItemsForStage2(checklistItems, checklistStage) {
|
|
@@ -746,10 +750,19 @@ ${key}: ${value}`;
|
|
|
746
750
|
function slugify(value) {
|
|
747
751
|
return String(value).normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "packet";
|
|
748
752
|
}
|
|
749
|
-
function
|
|
753
|
+
function preservePacketLineEndings(contents, edit) {
|
|
754
|
+
const result = edit(normalizePacketText(contents));
|
|
755
|
+
const withLineEndings = contents.includes("\r\n") ? result.replace(/\r?\n/g, "\r\n") : result;
|
|
756
|
+
return contents.startsWith("\uFEFF") && !withLineEndings.startsWith("\uFEFF") ? `\uFEFF${withLineEndings}` : withLineEndings;
|
|
757
|
+
}
|
|
758
|
+
function normalizePacketText(contents) {
|
|
759
|
+
return contents.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
|
|
760
|
+
}
|
|
761
|
+
function parsePacketFileDocument(original) {
|
|
762
|
+
const contents = normalizePacketText(original);
|
|
750
763
|
const match = contents.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
|
|
751
764
|
if (!match) {
|
|
752
|
-
throw new
|
|
765
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "The packet file is missing SwarmCraft frontmatter.");
|
|
753
766
|
}
|
|
754
767
|
const frontmatterBlock = match[1] ?? "";
|
|
755
768
|
return {
|
|
@@ -768,6 +781,14 @@ ${key}: ${value}`;
|
|
|
768
781
|
continue;
|
|
769
782
|
const key = line.slice(0, separatorIndex).trim();
|
|
770
783
|
let value = line.slice(separatorIndex + 1).trim();
|
|
784
|
+
const structured = key === "dependsOn" || key === "execution";
|
|
785
|
+
if (structured && !value && /^[[{]/.test(lines[index + 1]?.trim() ?? ""))
|
|
786
|
+
value = lines[++index].trim();
|
|
787
|
+
if (structured && /^[[{]/.test(value)) {
|
|
788
|
+
while (!isBalancedFlow(value) && index + 1 < lines.length)
|
|
789
|
+
value += ` ${lines[++index].trim()}`;
|
|
790
|
+
value = value.replace(/,\s*([\]}])/g, "$1");
|
|
791
|
+
}
|
|
771
792
|
if (key === "dependsOn" && (!value || value.startsWith("#"))) {
|
|
772
793
|
const dependencies = [];
|
|
773
794
|
while (index + 1 < lines.length) {
|
|
@@ -779,13 +800,16 @@ ${key}: ${value}`;
|
|
|
779
800
|
const item = next.match(/^\s*-\s+(.+?)\s*$/);
|
|
780
801
|
if (!item)
|
|
781
802
|
break;
|
|
782
|
-
|
|
783
|
-
dependencies.push(scalar.startsWith("'") && scalar.endsWith("'") ? scalar.slice(1, -1) : parseFrontmatterValue(scalar));
|
|
803
|
+
dependencies.push(parseDependencyScalar(item[1].replace(/\s+#.*$/, "")));
|
|
784
804
|
index++;
|
|
785
805
|
}
|
|
786
806
|
if (!dependencies.length)
|
|
787
|
-
throw new
|
|
807
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "dependsOn must be an array of packet UUIDs; use [] for no prerequisites.");
|
|
788
808
|
value = JSON.stringify(dependencies);
|
|
809
|
+
} else if (key === "dependsOn") {
|
|
810
|
+
const flow = value.replace(/\s+#.*$/, "").match(/^\[(.*)\]$/);
|
|
811
|
+
if (flow)
|
|
812
|
+
value = isJsonArray(flow[0]) ? flow[0] : JSON.stringify(flow[1].trim() ? flow[1].split(",").map(parseDependencyScalar) : []);
|
|
789
813
|
}
|
|
790
814
|
entries[key] = parseFrontmatterValue(value);
|
|
791
815
|
}
|
|
@@ -801,6 +825,23 @@ ${key}: ${value}`;
|
|
|
801
825
|
}
|
|
802
826
|
return value;
|
|
803
827
|
}
|
|
828
|
+
function parseDependencyScalar(raw) {
|
|
829
|
+
const scalar = raw.trim();
|
|
830
|
+
return scalar.startsWith("'") && scalar.endsWith("'") ? scalar.slice(1, -1) : parseFrontmatterValue(scalar);
|
|
831
|
+
}
|
|
832
|
+
function isBalancedFlow(value) {
|
|
833
|
+
return (value.match(/[[{]/g)?.length ?? 0) <= (value.match(/[\]}]/g)?.length ?? 0);
|
|
834
|
+
}
|
|
835
|
+
function renderDependsOnFrontmatter(dependencies) {
|
|
836
|
+
return dependencies.length ? ["dependsOn:", ...dependencies.map((id) => ` - ${id}`)].join("\n") : "dependsOn: []";
|
|
837
|
+
}
|
|
838
|
+
function isJsonArray(value) {
|
|
839
|
+
try {
|
|
840
|
+
return Array.isArray(JSON.parse(value));
|
|
841
|
+
} catch {
|
|
842
|
+
return false;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
804
845
|
function parseNullableFrontmatterValue(value) {
|
|
805
846
|
if (!value || value === "null") {
|
|
806
847
|
return null;
|
|
@@ -854,7 +895,7 @@ ${key}: ${value}`;
|
|
|
854
895
|
}
|
|
855
896
|
const match = line.match(/^- \[([ xX])\] (.+)$/);
|
|
856
897
|
if (!match) {
|
|
857
|
-
throw new
|
|
898
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "Checklist entries must use the markdown checkbox form '- [ ] item'.");
|
|
858
899
|
}
|
|
859
900
|
entries.push({
|
|
860
901
|
completed: match[1].toLowerCase() === "x",
|
|
@@ -867,11 +908,11 @@ ${key}: ${value}`;
|
|
|
867
908
|
if (exports2.WORKFLOW_STATES.includes(value)) {
|
|
868
909
|
return value;
|
|
869
910
|
}
|
|
870
|
-
throw new
|
|
911
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", "The packet file lane frontmatter must be one of todo, doing, checking, reviewing, or done.");
|
|
871
912
|
}
|
|
872
913
|
function requireFrontmatterValue(value, key) {
|
|
873
914
|
if (!value) {
|
|
874
|
-
throw new
|
|
915
|
+
throw new PacketFileContractError("PACKET_FILE_MALFORMED", `The packet file is missing the required ${key} frontmatter value.`);
|
|
875
916
|
}
|
|
876
917
|
return value;
|
|
877
918
|
}
|
|
@@ -1206,9 +1247,10 @@ var require_localPacket = __commonJS({
|
|
|
1206
1247
|
exports2.packetSnapshot = packetSnapshot3;
|
|
1207
1248
|
exports2.newPacketId = newPacketId;
|
|
1208
1249
|
exports2.localPacketId = localPacketId2;
|
|
1209
|
-
exports2.migrateLocalPacket =
|
|
1250
|
+
exports2.migrateLocalPacket = migrateLocalPacket;
|
|
1210
1251
|
exports2.duplicatePacketIds = duplicatePacketIds;
|
|
1211
|
-
exports2.validateLocalPacket =
|
|
1252
|
+
exports2.validateLocalPacket = validateLocalPacket2;
|
|
1253
|
+
exports2.validatePacketCompletion = validatePacketCompletion2;
|
|
1212
1254
|
exports2.reconcilePacketSnapshots = reconcilePacketSnapshots;
|
|
1213
1255
|
exports2.applyPacketSnapshot = applyPacketSnapshot2;
|
|
1214
1256
|
exports2.renderLocalPacket = renderLocalPacket;
|
|
@@ -1238,16 +1280,18 @@ var require_localPacket = __commonJS({
|
|
|
1238
1280
|
const hex = (0, node_crypto_1.createHash)("sha256").update(JSON.stringify([packet.frontmatter.projectId, packet.frontmatter.taskId])).digest("hex");
|
|
1239
1281
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
1240
1282
|
}
|
|
1241
|
-
function
|
|
1242
|
-
const packet = (0, packetFile_js_1.parsePacketFile)(
|
|
1283
|
+
function migrateLocalPacket(original) {
|
|
1284
|
+
const packet = (0, packetFile_js_1.parsePacketFile)(original);
|
|
1243
1285
|
if (packet.frontmatter.swarmcraftVersion >= 3)
|
|
1244
|
-
return
|
|
1245
|
-
|
|
1286
|
+
return original;
|
|
1287
|
+
return (0, packetFile_js_1.preservePacketLineEndings)(original, (contents) => {
|
|
1288
|
+
let result = contents.replace(/^swarmcraftVersion: 2$/m, `swarmcraftVersion: 3
|
|
1246
1289
|
packetId: ${localPacketId2(packet)}`);
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1290
|
+
if (packet.frontmatter.provisional || packet.frontmatter.taskId.startsWith("provisional:")) {
|
|
1291
|
+
result = result.replace(/^taskId:.*\n/m, "").replace(/^provisional:.*\n/m, "");
|
|
1292
|
+
}
|
|
1293
|
+
return result;
|
|
1294
|
+
});
|
|
1251
1295
|
}
|
|
1252
1296
|
function duplicatePacketIds(packets) {
|
|
1253
1297
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -1260,10 +1304,13 @@ packetId: ${localPacketId2(packet)}`);
|
|
|
1260
1304
|
}
|
|
1261
1305
|
return [...duplicates];
|
|
1262
1306
|
}
|
|
1263
|
-
function
|
|
1307
|
+
function validateLocalPacket2(snapshot) {
|
|
1264
1308
|
if (!snapshot.title.trim() || !snapshot.goal.trim())
|
|
1265
1309
|
throw new packetFile_js_1.PacketFileContractError("PACKET_FILE_MALFORMED", "Packets require a title and goal.");
|
|
1266
1310
|
(0, executionMetadata_js_1.validateExecutionMetadata)(snapshot);
|
|
1311
|
+
}
|
|
1312
|
+
function validatePacketCompletion2(snapshot) {
|
|
1313
|
+
validateLocalPacket2(snapshot);
|
|
1267
1314
|
const required = (stage) => stage === "doing" || snapshot.execution?.[stage] !== "skipped";
|
|
1268
1315
|
const incomplete = (stage) => required(stage) && snapshot[stage].some((item) => !item.completed);
|
|
1269
1316
|
const prior = snapshot.lane === "checking" ? ["doing"] : snapshot.lane === "reviewing" ? ["doing", "checking"] : [];
|
|
@@ -1286,65 +1333,70 @@ packetId: ${localPacketId2(packet)}`);
|
|
|
1286
1333
|
return { snapshot, conflicts };
|
|
1287
1334
|
}
|
|
1288
1335
|
function applyPacketSnapshot2(contents, snapshot, link) {
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
const
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
const
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
metadata("
|
|
1314
|
-
metadata("
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
const
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1336
|
+
return (0, packetFile_js_1.preservePacketLineEndings)(migrateLocalPacket(contents), (migrated) => {
|
|
1337
|
+
let result = migrated;
|
|
1338
|
+
const before = packetSnapshot3((0, packetFile_js_1.parsePacketFile)(result));
|
|
1339
|
+
const metadata = (key, value, rendered = `${key}: ${value}`) => {
|
|
1340
|
+
const boundary = result.indexOf("\n---", 4);
|
|
1341
|
+
let header = result.slice(0, boundary);
|
|
1342
|
+
const wrapped = key === "dependsOn" || key === "execution" ? `[ ]*(?:\\n[ ]*)?(?:\\[[^\\]]*\\]|\\{[^}]*\\})[^\\n]*|` : "";
|
|
1343
|
+
const block = key === "dependsOn" ? "(?:\\n(?:[ ]*-[ ]+[^\\n]*|[ ]*#[^\\n]*|[ ]*(?=\\n|$)))*" : "";
|
|
1344
|
+
const pattern = new RegExp(`^${key}:(?:${wrapped}.*${block})`, "m");
|
|
1345
|
+
header = pattern.test(header) ? header.replace(pattern, (matched) => {
|
|
1346
|
+
const comments = key === "dependsOn" ? matched.split("\n").slice(1).filter((line) => line.trimStart().startsWith("#")) : [];
|
|
1347
|
+
return [rendered, ...comments].join("\n");
|
|
1348
|
+
}) : `${header}
|
|
1349
|
+
${rendered}`;
|
|
1350
|
+
result = header + result.slice(boundary);
|
|
1351
|
+
};
|
|
1352
|
+
if (snapshot.recommendedOrder !== void 0) {
|
|
1353
|
+
metadata("swarmcraftVersion", "4");
|
|
1354
|
+
metadata("recommendedOrder", String(snapshot.recommendedOrder));
|
|
1355
|
+
}
|
|
1356
|
+
if (snapshot.dependsOn !== void 0)
|
|
1357
|
+
metadata("dependsOn", "", (0, packetFile_js_1.renderDependsOnFrontmatter)(snapshot.dependsOn));
|
|
1358
|
+
if (snapshot.execution !== void 0)
|
|
1359
|
+
metadata("execution", JSON.stringify(snapshot.execution));
|
|
1360
|
+
metadata("title", JSON.stringify(snapshot.title));
|
|
1361
|
+
metadata("lane", snapshot.lane);
|
|
1362
|
+
if (link) {
|
|
1363
|
+
metadata("taskId", link.taskId);
|
|
1364
|
+
metadata("syncRevision", String(link.revision));
|
|
1365
|
+
metadata("lastSyncedAt", link.syncedAt);
|
|
1366
|
+
}
|
|
1367
|
+
const fields = [["goal", "Goal"], ["notes", "Notes"], ["agentUpdate", "Agent Update"], ["doing", "Doing Checklist"], ["checking", "Checking Checklist"], ["reviewing", "Reviewing Checklist"]];
|
|
1368
|
+
for (const [field, heading] of fields) {
|
|
1369
|
+
if (JSON.stringify(before[field]) === JSON.stringify(snapshot[field]))
|
|
1370
|
+
continue;
|
|
1371
|
+
const value = snapshot[field];
|
|
1372
|
+
const body = Array.isArray(value) ? value.map((item) => `- [${item.completed ? "x" : " "}] ${item.body}`).join("\n") : value;
|
|
1373
|
+
const pattern = new RegExp(`^## ${heading}\\s*\\n[\\s\\S]*?(?=^## |$(?![\\s\\S]))`, "m");
|
|
1374
|
+
if (pattern.test(result))
|
|
1375
|
+
result = result.replace(pattern, () => `## ${heading}
|
|
1325
1376
|
|
|
1326
1377
|
${body}
|
|
1327
1378
|
|
|
1328
1379
|
`);
|
|
1329
|
-
|
|
1330
|
-
|
|
1380
|
+
else
|
|
1381
|
+
result += `
|
|
1331
1382
|
## ${heading}
|
|
1332
1383
|
|
|
1333
1384
|
${body}
|
|
1334
1385
|
`;
|
|
1335
|
-
|
|
1336
|
-
|
|
1386
|
+
}
|
|
1387
|
+
return result;
|
|
1388
|
+
});
|
|
1337
1389
|
}
|
|
1338
1390
|
function renderLocalPacket(snapshot, projectId) {
|
|
1339
|
-
|
|
1340
|
-
const fields = ["---", snapshot.recommendedOrder === void 0 ? "swarmcraftVersion: 3" : "swarmcraftVersion: 4", ...snapshot.recommendedOrder === void 0 ? [] : [`recommendedOrder: ${snapshot.recommendedOrder}`], ...snapshot.dependsOn === void 0 ? [] : [
|
|
1391
|
+
validateLocalPacket2(snapshot);
|
|
1392
|
+
const fields = ["---", snapshot.recommendedOrder === void 0 ? "swarmcraftVersion: 3" : "swarmcraftVersion: 4", ...snapshot.recommendedOrder === void 0 ? [] : [`recommendedOrder: ${snapshot.recommendedOrder}`], ...snapshot.dependsOn === void 0 ? [] : [(0, packetFile_js_1.renderDependsOnFrontmatter)(snapshot.dependsOn)], ...snapshot.execution === void 0 ? [] : [`execution: ${JSON.stringify(snapshot.execution)}`], `packetId: ${newPacketId()}`, ...projectId ? [`projectId: ${projectId}`] : [], `title: ${JSON.stringify(snapshot.title)}`, `lane: ${snapshot.lane}`, "---", ""];
|
|
1341
1393
|
for (const [heading, value] of [["Goal", snapshot.goal], ["Doing Checklist", snapshot.doing], ["Checking Checklist", snapshot.checking], ["Reviewing Checklist", snapshot.reviewing], ["Notes", snapshot.notes], ["Agent Update", snapshot.agentUpdate]]) {
|
|
1342
1394
|
fields.push(`## ${heading}`, "", typeof value === "string" ? value : value.map((item) => `- [${item.completed ? "x" : " "}] ${item.body}`).join("\n"), "");
|
|
1343
1395
|
}
|
|
1344
1396
|
return fields.join("\n");
|
|
1345
1397
|
}
|
|
1346
1398
|
function migrateOrderedPacket(contents, filename, hostedOrder, dependsOn) {
|
|
1347
|
-
const migrated =
|
|
1399
|
+
const migrated = migrateLocalPacket(contents);
|
|
1348
1400
|
const packet = (0, packetFile_js_1.parsePacketFile)(migrated);
|
|
1349
1401
|
if (packet.frontmatter.swarmcraftVersion === 4)
|
|
1350
1402
|
return migrated;
|
|
@@ -1359,6 +1411,67 @@ ${body}
|
|
|
1359
1411
|
}
|
|
1360
1412
|
});
|
|
1361
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
|
+
|
|
1362
1475
|
// ../../packages/packet-workflow/dist/deliveryPolicy.js
|
|
1363
1476
|
var require_deliveryPolicy = __commonJS({
|
|
1364
1477
|
"../../packages/packet-workflow/dist/deliveryPolicy.js"(exports2) {
|
|
@@ -1413,6 +1526,7 @@ var require_dist = __commonJS({
|
|
|
1413
1526
|
__exportStar(require_workflowContract(), exports2);
|
|
1414
1527
|
__exportStar(require_localPacket(), exports2);
|
|
1415
1528
|
__exportStar(require_executionMetadata(), exports2);
|
|
1529
|
+
__exportStar(require_packetSync(), exports2);
|
|
1416
1530
|
var deliveryPolicy_1 = require_deliveryPolicy();
|
|
1417
1531
|
Object.defineProperty(exports2, "parseDeliveryMode", { enumerable: true, get: function() {
|
|
1418
1532
|
return deliveryPolicy_1.parseDeliveryMode;
|
|
@@ -2051,6 +2165,8 @@ var require_renderAssistantActionSkills = __commonJS({
|
|
|
2051
2165
|
"",
|
|
2052
2166
|
`Generate packetId once using a UUID generator (for example node -e "console.log(require('node:crypto').randomUUID())"). Preserve it across renames and edits. Include projectId when existing context explicitly binds this repository to the authorised project. Omit projectId when no authorised project binding exists; local work does not require it. Never invent hosted task IDs. Separate copied work needs a new packetId and explicit project binding.`,
|
|
2053
2167
|
"",
|
|
2168
|
+
"All six packet sections must be top-level `##` headings. Do not nest `### Agent Update` under Notes; subheadings such as `### Plan Context` belong within Notes.",
|
|
2169
|
+
"",
|
|
2054
2170
|
"A local packet must include:",
|
|
2055
2171
|
"",
|
|
2056
2172
|
...(0, packet_workflow_1.renderBullets)([
|
|
@@ -2064,10 +2180,54 @@ var require_renderAssistantActionSkills = __commonJS({
|
|
|
2064
2180
|
"",
|
|
2065
2181
|
"New checklist items start unchecked. As evidence is obtained, complete them and advance lanes locally, even without SwarmCraft, an account, or an extension. Connected packets sync automatically; Sync Packet is only a retry/conflict recovery action. Set swarmcraft.packetSync.enabled to false in VS Code to remain local-only.",
|
|
2066
2182
|
"",
|
|
2183
|
+
"List prerequisites one per line as a YAML list under `dependsOn:`, each line ` - <packet-UUID>`, as in the example below. This is the form SwarmCraft sync writes and editor formatters leave intact. Use `dependsOn: []` only for no prerequisites. Do not write inline arrays such as `[uuid-a, uuid-b]`.",
|
|
2184
|
+
"",
|
|
2185
|
+
"Complete packet example (replace example identities and content; the dependency must identify a real prerequisite packet):",
|
|
2186
|
+
"",
|
|
2187
|
+
"```markdown",
|
|
2188
|
+
"---",
|
|
2189
|
+
"swarmcraftVersion: 4",
|
|
2190
|
+
"packetId: 9827f492-b15b-437b-a94c-9556680fabf1",
|
|
2191
|
+
"recommendedOrder: 2",
|
|
2192
|
+
"dependsOn:",
|
|
2193
|
+
" - 2006de45-e236-4221-970e-5445ed0b3b0b",
|
|
2194
|
+
'title: "Document the agreed workflow"',
|
|
2195
|
+
"lane: todo",
|
|
2196
|
+
"syncRevision: 0",
|
|
2197
|
+
"lastSyncedAt: null",
|
|
2198
|
+
"---",
|
|
2199
|
+
"",
|
|
2200
|
+
"## Goal",
|
|
2201
|
+
"",
|
|
2202
|
+
"Record the agreed workflow and its exceptions.",
|
|
2203
|
+
"",
|
|
2204
|
+
"## Doing Checklist",
|
|
2205
|
+
"",
|
|
2206
|
+
"- [ ] Document the workflow from the agreed requirements.",
|
|
2207
|
+
"",
|
|
2208
|
+
"## Checking Checklist",
|
|
2209
|
+
"",
|
|
2210
|
+
"- [ ] Compare the documented workflow against the requirements.",
|
|
2211
|
+
"",
|
|
2212
|
+
"## Reviewing Checklist",
|
|
2213
|
+
"",
|
|
2214
|
+
"- [ ] Ask the owner to review the workflow.",
|
|
2215
|
+
"",
|
|
2216
|
+
"## Notes",
|
|
2217
|
+
"",
|
|
2218
|
+
"### Plan Context",
|
|
2219
|
+
"",
|
|
2220
|
+
"Link the owning plan and phase here for initiative work.",
|
|
2221
|
+
"",
|
|
2222
|
+
"## Agent Update",
|
|
2223
|
+
"",
|
|
2224
|
+
"Not started.",
|
|
2225
|
+
"```",
|
|
2226
|
+
"",
|
|
2067
2227
|
"Before handing off a local packet, validate that:",
|
|
2068
2228
|
"",
|
|
2069
2229
|
...(0, packet_workflow_1.renderBullets)([
|
|
2070
|
-
"`packetId` is a stable random UUID and `swarmcraftVersion` is `
|
|
2230
|
+
"`packetId` is a stable random UUID and `swarmcraftVersion` is `4`",
|
|
2071
2231
|
"`projectId` is optional; when present it comes from an explicit authorised binding",
|
|
2072
2232
|
"`lane` reflects current work rather than registration status",
|
|
2073
2233
|
"all six required packet sections are present",
|
|
@@ -45591,8 +45751,8 @@ var require_graceful_fs = __commonJS({
|
|
|
45591
45751
|
fs2.createReadStream = createReadStream;
|
|
45592
45752
|
fs2.createWriteStream = createWriteStream2;
|
|
45593
45753
|
var fs$readFile = fs2.readFile;
|
|
45594
|
-
fs2.readFile =
|
|
45595
|
-
function
|
|
45754
|
+
fs2.readFile = readFile14;
|
|
45755
|
+
function readFile14(path16, options, cb) {
|
|
45596
45756
|
if (typeof options === "function")
|
|
45597
45757
|
cb = options, options = null;
|
|
45598
45758
|
return go$readFile(path16, options, cb);
|
|
@@ -66186,6 +66346,10 @@ Read **docs/discovery/README.md**, the nine curated discovery documents, and **.
|
|
|
66186
66346
|
|
|
66187
66347
|
Never skip directly to package preparation merely because files exist.
|
|
66188
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
|
+
|
|
66189
66353
|
## Stage 1: gather sources
|
|
66190
66354
|
|
|
66191
66355
|
When the source manifest is absent or has **GATHERING** status:
|
|
@@ -66264,6 +66428,12 @@ Use this manifest shape (repeat source entries as needed):
|
|
|
66264
66428
|
}
|
|
66265
66429
|
\`\`\`
|
|
66266
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
|
+
|
|
66267
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.
|
|
66268
66438
|
|
|
66269
66439
|
## Binary and sidecar rules
|
|
@@ -66468,7 +66638,7 @@ var require_seedDiscoveryFiles = __commonJS({
|
|
|
66468
66638
|
var renderPrototype_1 = require_renderPrototype();
|
|
66469
66639
|
var renderDesign_1 = require_renderDesign();
|
|
66470
66640
|
var renderReports_1 = require_renderReports();
|
|
66471
|
-
exports2.DISCOVERY_SEED_VERSION =
|
|
66641
|
+
exports2.DISCOVERY_SEED_VERSION = 18;
|
|
66472
66642
|
exports2.DISCOVERY_SEED_STATE_PATH = ".swarmcraft/discovery.seed-state.json";
|
|
66473
66643
|
var LEGACY_UNCHANGED_DISCOVERY_GUIDE_HASHES = /* @__PURE__ */ new Set([
|
|
66474
66644
|
"810536d02524e6a11b4b93d1828d5e799380de2619dc481e91c6a02eb487984b",
|
|
@@ -68629,6 +68799,16 @@ var require_discoveryWorkflow = __commonJS({
|
|
|
68629
68799
|
confirmedAt: selectionEvidenceValue.confirmedAt,
|
|
68630
68800
|
confirmationSummary: selectionEvidenceValue.confirmationSummary
|
|
68631
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
|
+
}
|
|
68632
68812
|
const sources = value.sources.map(parseSelectedSource);
|
|
68633
68813
|
const paths = /* @__PURE__ */ new Set();
|
|
68634
68814
|
for (const source of sources) {
|
|
@@ -68721,12 +68901,12 @@ var require_discoveryWorkflow = __commonJS({
|
|
|
68721
68901
|
return manifest.sources.filter((source) => source.selected).map((source) => source.kind === "TEXT" ? source.logicalPath : source.sidecar?.logicalPath).filter((value) => Boolean(value));
|
|
68722
68902
|
}
|
|
68723
68903
|
function parseSelectedSource(value) {
|
|
68724
|
-
if (!isRecord(value) || typeof value.logicalPath !== "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") {
|
|
68725
68905
|
throw new Error("A discovery source entry is invalid.");
|
|
68726
68906
|
}
|
|
68727
68907
|
if (value.kind === "TEXT" && !TEXT_PATH.test(value.logicalPath))
|
|
68728
68908
|
throw new Error(`Text discovery source must be Markdown, text or CSV: ${value.logicalPath}`);
|
|
68729
|
-
if (value.kind
|
|
68909
|
+
if (value.kind === "BINARY_WITH_SIDECAR" && !BINARY_PATH.test(value.logicalPath))
|
|
68730
68910
|
throw new Error(`Binary discovery source has an unsupported format: ${value.logicalPath}`);
|
|
68731
68911
|
let sidecar;
|
|
68732
68912
|
if (value.sidecar !== void 0) {
|
|
@@ -68746,6 +68926,25 @@ var require_discoveryWorkflow = __commonJS({
|
|
|
68746
68926
|
throw new Error(`Unsupported binary source cannot be selected: ${value.logicalPath}`);
|
|
68747
68927
|
return { logicalPath: value.logicalPath, kind: value.kind, digest: value.digest, bytes: value.bytes, selected: value.selected, rationale: value.rationale, sidecar };
|
|
68748
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
|
+
}
|
|
68749
68948
|
function isSafeDiscoveryPath(value) {
|
|
68750
68949
|
return value.startsWith("docs/discovery/sources/") && !value.startsWith("/") && !value.split(/[\\/]/).includes("..");
|
|
68751
68950
|
}
|
|
@@ -68803,7 +69002,7 @@ __export(main_exports, {
|
|
|
68803
69002
|
runAuthLogin: () => runAuthLogin
|
|
68804
69003
|
});
|
|
68805
69004
|
module.exports = __toCommonJS(main_exports);
|
|
68806
|
-
var
|
|
69005
|
+
var import_packet_workflow10 = __toESM(require_dist(), 1);
|
|
68807
69006
|
|
|
68808
69007
|
// src/browserAuth.ts
|
|
68809
69008
|
var import_node_crypto = require("node:crypto");
|
|
@@ -68918,6 +69117,20 @@ var SwarmCraftClient = class {
|
|
|
68918
69117
|
loadBoard(projectId, accessToken, delegationId) {
|
|
68919
69118
|
return this.requestJson(`/projects/${encodeURIComponent(projectId)}/board`, { method: "GET" }, accessToken, void 0, delegationId);
|
|
68920
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
|
+
}
|
|
68921
69134
|
upsertTaskPacketLink(projectId, taskId, request, accessToken, delegationId) {
|
|
68922
69135
|
return this.requestJson(
|
|
68923
69136
|
`/projects/${encodeURIComponent(projectId)}/tasks/${encodeURIComponent(taskId)}/packet-link`,
|
|
@@ -69513,7 +69726,12 @@ async function selectLocalPackets(root, selectors) {
|
|
|
69513
69726
|
const paths = /* @__PURE__ */ new Map();
|
|
69514
69727
|
for (const name of await discover(root, ".swarmcraft/projects")) {
|
|
69515
69728
|
const contents = await readContainedLocal(root, name);
|
|
69516
|
-
|
|
69729
|
+
let parsed;
|
|
69730
|
+
try {
|
|
69731
|
+
parsed = (0, import_packet_workflow2.parsePacketFile)(contents);
|
|
69732
|
+
} catch (error) {
|
|
69733
|
+
throw new Error(`Unreadable packet ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
69734
|
+
}
|
|
69517
69735
|
const id = (0, import_packet_workflow2.localPacketId)(parsed);
|
|
69518
69736
|
if (records.has(id)) throw new Error(`Duplicate packet identity: ${name}`);
|
|
69519
69737
|
records.set(id, { path: name, contents, parsed });
|
|
@@ -69728,7 +69946,7 @@ async function executeLocalRun(manifest, resume) {
|
|
|
69728
69946
|
if (snapshot.lane === "doing" || snapshot.checking.some((item) => !item.completed)) throw new LocalRunBlocked(`Checking requires more work: ${selected.path}`);
|
|
69729
69947
|
}
|
|
69730
69948
|
snapshot.lane = options.reviewing && snapshot.lane !== "done" ? "reviewing" : "done";
|
|
69731
|
-
(0, import_packet_workflow3.
|
|
69949
|
+
(0, import_packet_workflow3.validatePacketCompletion)(snapshot);
|
|
69732
69950
|
if (snapshot.lane === "done") {
|
|
69733
69951
|
const entry = `### One-shot completion (${manifest.runId})
|
|
69734
69952
|
Implementation complete. Checking: ${options.checking ? "completed" : "explicitly skipped"}. Reviewing: ${options.reviewing ? "approved" : "explicitly skipped"}.`;
|
|
@@ -69766,14 +69984,14 @@ Implementation complete. Checking: ${options.checking ? "completed" : "explicitl
|
|
|
69766
69984
|
}
|
|
69767
69985
|
|
|
69768
69986
|
// src/main.ts
|
|
69769
|
-
var
|
|
69987
|
+
var import_promises16 = require("node:fs/promises");
|
|
69770
69988
|
var import_node_path15 = __toESM(require("node:path"), 1);
|
|
69771
|
-
var
|
|
69989
|
+
var import_packet_workflow11 = __toESM(require_dist(), 1);
|
|
69772
69990
|
|
|
69773
69991
|
// package.json
|
|
69774
69992
|
var package_default = {
|
|
69775
69993
|
name: "@swarmcraftai/cli",
|
|
69776
|
-
version: "0.9.
|
|
69994
|
+
version: "0.9.2",
|
|
69777
69995
|
description: "Prepare repositories and run packet-based SwarmCraft agent workflows from the terminal.",
|
|
69778
69996
|
license: "SEE LICENSE IN LICENSE.txt",
|
|
69779
69997
|
type: "module",
|
|
@@ -69858,81 +70076,149 @@ async function ensureWorkspaceTracking(workspace) {
|
|
|
69858
70076
|
// src/bootstrap.ts
|
|
69859
70077
|
var import_packet_workflow4 = __toESM(require_dist(), 1);
|
|
69860
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
|
|
69861
70160
|
async function runBootstrap(client, accessToken, options) {
|
|
69862
|
-
|
|
69863
|
-
await
|
|
69864
|
-
const workspace = await validateWorkspace(options.workspacePath);
|
|
70161
|
+
const dryRun = options.dryRun ?? false;
|
|
70162
|
+
const preflight = await validateWorkspace(options.workspacePath);
|
|
69865
70163
|
const project = await client.loadProject(options.projectId, accessToken, options.delegationId);
|
|
69866
70164
|
if (project.boardState !== "READY") {
|
|
69867
70165
|
throw new Error(`Project ${project.id} is ${project.boardState}; wait for the board to be ready before bootstrapping a workspace.`);
|
|
69868
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);
|
|
69869
70172
|
const board = await client.loadBoard(project.id, accessToken, options.delegationId);
|
|
69870
|
-
const seedResult = await seedWorkspace(project, workspace.workspacePath, options.agentProvider);
|
|
70173
|
+
const seedResult = dryRun ? null : await seedWorkspace(project, workspace.workspacePath, options.agentProvider);
|
|
69871
70174
|
const selectedTasks = selectBootstrapTasks(board, options);
|
|
69872
70175
|
const packetFilesCreated = [];
|
|
69873
70176
|
const packetFilesRefreshed = [];
|
|
69874
70177
|
const linkedPackets = [];
|
|
69875
70178
|
const skippedTasks = [];
|
|
69876
70179
|
const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
69877
|
-
|
|
69878
|
-
|
|
69879
|
-
|
|
69880
|
-
|
|
69881
|
-
|
|
69882
|
-
|
|
69883
|
-
|
|
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 });
|
|
69884
70192
|
continue;
|
|
69885
70193
|
}
|
|
69886
|
-
|
|
69887
|
-
|
|
69888
|
-
|
|
69889
|
-
|
|
69890
|
-
|
|
69891
|
-
|
|
69892
|
-
|
|
69893
|
-
|
|
69894
|
-
|
|
69895
|
-
|
|
69896
|
-
|
|
69897
|
-
|
|
69898
|
-
|
|
69899
|
-
|
|
69900
|
-
|
|
69901
|
-
});
|
|
69902
|
-
continue;
|
|
69903
|
-
}
|
|
69904
|
-
throw error;
|
|
69905
|
-
}
|
|
69906
|
-
if (packetContents !== existingContents) {
|
|
69907
|
-
await writeWorkspaceFile(workspace.workspacePath, relativePacketPath, packetContents);
|
|
69908
|
-
packetFilesRefreshed.push(relativePacketPath);
|
|
69909
|
-
}
|
|
69910
|
-
} else {
|
|
69911
|
-
packetContents = (0, import_packet_workflow4.migrateLocalPacket)((0, import_packet_workflow4.renderPacketFile)(project, task, syncedAt));
|
|
69912
|
-
await writeWorkspaceFile(workspace.workspacePath, relativePacketPath, packetContents);
|
|
69913
|
-
packetFilesCreated.push(relativePacketPath);
|
|
69914
|
-
}
|
|
69915
|
-
const packetLinkMatches = task.packetLink && task.packetLink.workspaceFolder === workspace.workspaceFolderName && task.packetLink.packetFilePath === relativePacketPath;
|
|
69916
|
-
if (!packetLinkMatches) {
|
|
69917
|
-
await client.upsertTaskPacketLink(project.id, task.id, {
|
|
69918
|
-
workspaceFolder: workspace.workspaceFolderName,
|
|
69919
|
-
packetFilePath: relativePacketPath,
|
|
69920
|
-
expectedRevision: task.revision,
|
|
69921
|
-
lastSyncedTaskRevision: task.revision,
|
|
69922
|
-
lastSyncedAt: syncedAt
|
|
69923
|
-
}, accessToken, options.delegationId);
|
|
69924
|
-
linkedPackets.push(relativePacketPath);
|
|
69925
|
-
}
|
|
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);
|
|
69926
70209
|
}
|
|
69927
70210
|
return {
|
|
69928
|
-
|
|
70211
|
+
projectId: project.id,
|
|
70212
|
+
projectTitle,
|
|
70213
|
+
dryRun,
|
|
70214
|
+
binding: bindingCheck,
|
|
69929
70215
|
workspacePath: workspace.workspacePath,
|
|
69930
70216
|
dirtyFileCount: workspace.dirtyFileCount,
|
|
69931
|
-
seedFilesWritten: seedResult
|
|
69932
|
-
seedFilesUpdated: seedResult
|
|
69933
|
-
seedFilesRemoved: seedResult
|
|
69934
|
-
seedConflicts: seedResult
|
|
69935
|
-
seedTemplateSetVersion: seedResult
|
|
70217
|
+
seedFilesWritten: seedResult?.written ?? [],
|
|
70218
|
+
seedFilesUpdated: seedResult?.updated ?? [],
|
|
70219
|
+
seedFilesRemoved: seedResult?.removed ?? [],
|
|
70220
|
+
seedConflicts: seedResult?.conflicts ?? [],
|
|
70221
|
+
seedTemplateSetVersion: seedResult?.targetTemplateSetVersion ?? 0,
|
|
69936
70222
|
packetFilesCreated,
|
|
69937
70223
|
packetFilesRefreshed,
|
|
69938
70224
|
linkedPackets,
|
|
@@ -69972,7 +70258,7 @@ async function seedWorkspace(project, workspacePath, provider) {
|
|
|
69972
70258
|
|
|
69973
70259
|
// src/oneShot.ts
|
|
69974
70260
|
var import_packet_workflow6 = __toESM(require_dist(), 1);
|
|
69975
|
-
var
|
|
70261
|
+
var import_promises8 = require("node:fs/promises");
|
|
69976
70262
|
var import_node_path7 = __toESM(require("node:path"), 1);
|
|
69977
70263
|
var import_packet_workflow7 = __toESM(require_dist(), 1);
|
|
69978
70264
|
|
|
@@ -70076,7 +70362,8 @@ async function runOneShot(client, accessTokenProvider, options) {
|
|
|
70076
70362
|
taskIds: options.taskIds,
|
|
70077
70363
|
taskLimit: options.taskLimit,
|
|
70078
70364
|
delegationId: options.delegation?.id ?? null,
|
|
70079
|
-
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
|
|
70080
70367
|
});
|
|
70081
70368
|
}
|
|
70082
70369
|
const project = await client.loadProject(options.projectId, await getAccessToken(), options.delegation?.id ?? null);
|
|
@@ -70312,7 +70599,7 @@ async function runStageAndSync(context) {
|
|
|
70312
70599
|
printProgress(`Running ${context.stage} stage for ${context.task.title}.`);
|
|
70313
70600
|
printProgress(`Agent log: ${stageOutcome.logPath}`);
|
|
70314
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`);
|
|
70315
|
-
await (0,
|
|
70602
|
+
await (0, import_promises8.mkdir)(import_node_path7.default.dirname(costOutputPath), { recursive: true });
|
|
70316
70603
|
const managedStage = context.options.agentProvider === "managed" ? await context.client.prepareManagedAiStage(
|
|
70317
70604
|
context.manifest.managedAi?.runId ?? "",
|
|
70318
70605
|
context.task.id,
|
|
@@ -70489,7 +70776,7 @@ function formatDuration(elapsedMs) {
|
|
|
70489
70776
|
}
|
|
70490
70777
|
|
|
70491
70778
|
// src/sessionStore.ts
|
|
70492
|
-
var
|
|
70779
|
+
var import_promises9 = require("node:fs/promises");
|
|
70493
70780
|
var import_node_os = __toESM(require("node:os"), 1);
|
|
70494
70781
|
var import_node_path8 = __toESM(require("node:path"), 1);
|
|
70495
70782
|
function resolveSessionPath() {
|
|
@@ -70497,7 +70784,7 @@ function resolveSessionPath() {
|
|
|
70497
70784
|
}
|
|
70498
70785
|
async function readStoredSession() {
|
|
70499
70786
|
try {
|
|
70500
|
-
return JSON.parse(await (0,
|
|
70787
|
+
return JSON.parse(await (0, import_promises9.readFile)(resolveSessionPath(), "utf8"));
|
|
70501
70788
|
} catch (error) {
|
|
70502
70789
|
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
70503
70790
|
return null;
|
|
@@ -70507,10 +70794,10 @@ async function readStoredSession() {
|
|
|
70507
70794
|
}
|
|
70508
70795
|
async function writeStoredSession(session) {
|
|
70509
70796
|
const sessionPath = resolveSessionPath();
|
|
70510
|
-
await (0,
|
|
70511
|
-
await (0,
|
|
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)}
|
|
70512
70799
|
`, { mode: 384 });
|
|
70513
|
-
await (0,
|
|
70800
|
+
await (0, import_promises9.chmod)(sessionPath, 384);
|
|
70514
70801
|
}
|
|
70515
70802
|
function toStoredSession(apiBaseUrl, tokenResponse) {
|
|
70516
70803
|
return {
|
|
@@ -70528,7 +70815,7 @@ function sessionExpiresSoon(session) {
|
|
|
70528
70815
|
}
|
|
70529
70816
|
|
|
70530
70817
|
// src/commands/support-bundle-command.ts
|
|
70531
|
-
var
|
|
70818
|
+
var import_promises10 = require("node:fs/promises");
|
|
70532
70819
|
var import_node_path9 = __toESM(require("node:path"), 1);
|
|
70533
70820
|
|
|
70534
70821
|
// src/supportBundle.ts
|
|
@@ -70575,12 +70862,12 @@ function redactSupportBundleValue(value) {
|
|
|
70575
70862
|
async function createRunSupportBundle(workspacePathValue, runId) {
|
|
70576
70863
|
const workspacePath = import_node_path9.default.resolve(workspacePathValue);
|
|
70577
70864
|
const manifestPath = resolveManifestPath(workspacePath, runId);
|
|
70578
|
-
const manifest = JSON.parse(await (0,
|
|
70865
|
+
const manifest = JSON.parse(await (0, import_promises10.readFile)(manifestPath, "utf8"));
|
|
70579
70866
|
const bundleDir = resolveRunArtifactPath(workspacePath, runId, "support-bundle");
|
|
70580
|
-
await (0,
|
|
70581
|
-
await (0,
|
|
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)}
|
|
70582
70869
|
`, { encoding: "utf8", mode: 384 });
|
|
70583
|
-
await (0,
|
|
70870
|
+
await (0, import_promises10.writeFile)(import_node_path9.default.join(bundleDir, "summary.json"), `${JSON.stringify({
|
|
70584
70871
|
runId,
|
|
70585
70872
|
manifestPath: ".swarmcraft/runs/<run-id>/manifest.json",
|
|
70586
70873
|
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -70637,12 +70924,12 @@ function addOption(options, key, value) {
|
|
|
70637
70924
|
|
|
70638
70925
|
// src/discovery.ts
|
|
70639
70926
|
var import_node_crypto5 = require("node:crypto");
|
|
70640
|
-
var
|
|
70927
|
+
var import_promises12 = require("node:fs/promises");
|
|
70641
70928
|
var import_node_path11 = __toESM(require("node:path"), 1);
|
|
70642
70929
|
var import_operation_contract = __toESM(require_dist2(), 1);
|
|
70643
70930
|
|
|
70644
70931
|
// src/operation/filesystem.ts
|
|
70645
|
-
var
|
|
70932
|
+
var import_promises11 = require("node:fs/promises");
|
|
70646
70933
|
var import_node_path10 = __toESM(require("node:path"), 1);
|
|
70647
70934
|
var OperateCommandError = class extends Error {
|
|
70648
70935
|
constructor(code, exitCode, message) {
|
|
@@ -70663,7 +70950,7 @@ var OperationFiles = class {
|
|
|
70663
70950
|
async target(relative2) {
|
|
70664
70951
|
checkCancelled(this.signal);
|
|
70665
70952
|
try {
|
|
70666
|
-
const rootEntry = await (0,
|
|
70953
|
+
const rootEntry = await (0, import_promises11.lstat)(this.root);
|
|
70667
70954
|
if (!rootEntry.isDirectory() || rootEntry.isSymbolicLink()) {
|
|
70668
70955
|
throw new OperateCommandError("OPERATE_PATH_UNSAFE", 4, "The selected workspace changed during the command.");
|
|
70669
70956
|
}
|
|
@@ -70681,7 +70968,7 @@ var OperationFiles = class {
|
|
|
70681
70968
|
for (let i = 0; i < components.length; i++) {
|
|
70682
70969
|
current = import_node_path10.default.join(current, components[i]);
|
|
70683
70970
|
try {
|
|
70684
|
-
const entry = await (0,
|
|
70971
|
+
const entry = await (0, import_promises11.lstat)(current);
|
|
70685
70972
|
if (entry.isSymbolicLink() || entry.isFile() && entry.nlink > 1 || i < components.length - 1 && !entry.isDirectory()) {
|
|
70686
70973
|
throw new OperateCommandError("OPERATE_PATH_UNSAFE", 4, "An operation path uses an unsafe filesystem link.");
|
|
70687
70974
|
}
|
|
@@ -70695,11 +70982,11 @@ var OperationFiles = class {
|
|
|
70695
70982
|
async read(relative2) {
|
|
70696
70983
|
const target = await this.target(relative2);
|
|
70697
70984
|
try {
|
|
70698
|
-
const entry = await (0,
|
|
70985
|
+
const entry = await (0, import_promises11.lstat)(target);
|
|
70699
70986
|
if (!entry.isFile() || entry.size > 2e6) {
|
|
70700
70987
|
throw new OperateCommandError("OPERATE_FILE_UNSUPPORTED", 4, "An operation file is not a supported bounded text file.");
|
|
70701
70988
|
}
|
|
70702
|
-
return await (0,
|
|
70989
|
+
return await (0, import_promises11.readFile)(target, "utf8");
|
|
70703
70990
|
} catch (error) {
|
|
70704
70991
|
if (isMissing(error)) return void 0;
|
|
70705
70992
|
throw error;
|
|
@@ -70713,23 +71000,23 @@ var OperationFiles = class {
|
|
|
70713
71000
|
/** Reads bounded local binary evidence through the same containment checks. */
|
|
70714
71001
|
async bytes(relative2) {
|
|
70715
71002
|
const target = await this.target(relative2);
|
|
70716
|
-
const entry = await (0,
|
|
71003
|
+
const entry = await (0, import_promises11.lstat)(target);
|
|
70717
71004
|
if (!entry.isFile() || entry.size > 1e7) throw new OperateCommandError("OPERATE_FILE_UNSUPPORTED", 4, "Select bounded local evidence.");
|
|
70718
|
-
return (0,
|
|
71005
|
+
return (0, import_promises11.readFile)(target);
|
|
70719
71006
|
}
|
|
70720
71007
|
/** Creates an immutable snapshot; an existing file is never overwritten. */
|
|
70721
71008
|
async create(relative2, contents) {
|
|
70722
71009
|
const target = await this.target(relative2);
|
|
70723
|
-
await (0,
|
|
71010
|
+
await (0, import_promises11.mkdir)(import_node_path10.default.dirname(target), { recursive: true });
|
|
70724
71011
|
await this.target(relative2);
|
|
70725
|
-
await (0,
|
|
71012
|
+
await (0, import_promises11.writeFile)(target, contents, { flag: "wx", mode: 384 });
|
|
70726
71013
|
}
|
|
70727
71014
|
/** Inventories only regular files; links are rejected rather than treated as available assets. */
|
|
70728
71015
|
async fileInventory() {
|
|
70729
71016
|
const result = [];
|
|
70730
71017
|
for (const file of await this.inventory()) {
|
|
70731
71018
|
const target = await this.target(file);
|
|
70732
|
-
if ((await (0,
|
|
71019
|
+
if ((await (0, import_promises11.lstat)(target)).isFile()) result.push(file);
|
|
70733
71020
|
}
|
|
70734
71021
|
return result;
|
|
70735
71022
|
}
|
|
@@ -70737,7 +71024,7 @@ var OperationFiles = class {
|
|
|
70737
71024
|
async removeEmptyDirectory(relative2) {
|
|
70738
71025
|
const target = await this.target(relative2);
|
|
70739
71026
|
try {
|
|
70740
|
-
await (0,
|
|
71027
|
+
await (0, import_promises11.rmdir)(target);
|
|
70741
71028
|
} catch (error) {
|
|
70742
71029
|
if (isMissing(error) || ["ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) return;
|
|
70743
71030
|
throw error;
|
|
@@ -70745,7 +71032,7 @@ var OperationFiles = class {
|
|
|
70745
71032
|
}
|
|
70746
71033
|
/** Removes only a checked individual file selected by seed reconciliation. */
|
|
70747
71034
|
async remove(relative2) {
|
|
70748
|
-
await (0,
|
|
71035
|
+
await (0, import_promises11.unlink)(await this.target(relative2));
|
|
70749
71036
|
}
|
|
70750
71037
|
/** Inventories paths without reading contents or following links; skips runtime dependency trees. */
|
|
70751
71038
|
async inventory() {
|
|
@@ -70753,7 +71040,7 @@ var OperationFiles = class {
|
|
|
70753
71040
|
const skip = /* @__PURE__ */ new Set([".git", "node_modules", ".venv", "dist", "build", "target"]);
|
|
70754
71041
|
const walk = async (relative2) => {
|
|
70755
71042
|
checkCancelled(this.signal);
|
|
70756
|
-
for (const entry of await (0,
|
|
71043
|
+
for (const entry of await (0, import_promises11.readdir)(import_node_path10.default.join(this.root, relative2), { withFileTypes: true })) {
|
|
70757
71044
|
if (skip.has(entry.name)) continue;
|
|
70758
71045
|
const file = relative2 ? relative2 + "/" + entry.name : entry.name;
|
|
70759
71046
|
result.push(file);
|
|
@@ -70778,13 +71065,13 @@ async function resolveOperationRoot(input) {
|
|
|
70778
71065
|
const missing = [];
|
|
70779
71066
|
while (true) {
|
|
70780
71067
|
try {
|
|
70781
|
-
const entry = await (0,
|
|
71068
|
+
const entry = await (0, import_promises11.lstat)(cursor);
|
|
70782
71069
|
if (!entry.isDirectory()) throw new OperateCommandError(
|
|
70783
71070
|
"OPERATE_WORKSPACE_INVALID",
|
|
70784
71071
|
4,
|
|
70785
71072
|
"Select a directory for the operation workspace."
|
|
70786
71073
|
);
|
|
70787
|
-
return import_node_path10.default.join(await (0,
|
|
71074
|
+
return import_node_path10.default.join(await (0, import_promises11.realpath)(cursor), ...missing.reverse());
|
|
70788
71075
|
} catch (error) {
|
|
70789
71076
|
if (!isMissing(error)) throw error;
|
|
70790
71077
|
missing.push(import_node_path10.default.basename(cursor));
|
|
@@ -70800,7 +71087,7 @@ async function inspectGit(root) {
|
|
|
70800
71087
|
let existing = root;
|
|
70801
71088
|
while (true) {
|
|
70802
71089
|
try {
|
|
70803
|
-
await (0,
|
|
71090
|
+
await (0, import_promises11.lstat)(existing);
|
|
70804
71091
|
break;
|
|
70805
71092
|
} catch (error) {
|
|
70806
71093
|
if (!isMissing(error)) throw error;
|
|
@@ -70813,7 +71100,7 @@ async function inspectGit(root) {
|
|
|
70813
71100
|
if (available.exitCode !== 0) throw new OperateCommandError("OPERATE_GIT_UNAVAILABLE", 4, "Install Git before initializing Operate.");
|
|
70814
71101
|
return false;
|
|
70815
71102
|
}
|
|
70816
|
-
if (await (0,
|
|
71103
|
+
if (await (0, import_promises11.realpath)(result.stdout.trim()) !== root) {
|
|
70817
71104
|
throw new OperateCommandError("OPERATE_GIT_ROOT_MISMATCH", 4, "Select the repository root, or a directory outside an existing repository.");
|
|
70818
71105
|
}
|
|
70819
71106
|
const unmerged = await operationGit(root, ["diff", "--name-only", "--diff-filter=U", "-z"]);
|
|
@@ -70830,7 +71117,7 @@ async function operationIgnored(root, relative2) {
|
|
|
70830
71117
|
return result.exitCode === 0;
|
|
70831
71118
|
}
|
|
70832
71119
|
async function createOperationRoot(root) {
|
|
70833
|
-
await (0,
|
|
71120
|
+
await (0, import_promises11.mkdir)(root, { recursive: true });
|
|
70834
71121
|
}
|
|
70835
71122
|
function isMissing(error) {
|
|
70836
71123
|
return !!error && typeof error === "object" && "code" in error && error.code === "ENOENT";
|
|
@@ -70862,7 +71149,7 @@ async function prepareDiscoveryBundle(options, dependencies = defaultDiscoveryDe
|
|
|
70862
71149
|
const feedbackPath = resolveRunArtifactPath(workspacePath, runId, "discovery-feedback.md");
|
|
70863
71150
|
const diagnosticsPath = resolveRunArtifactPath(workspacePath, runId, "diagnostics.json");
|
|
70864
71151
|
const previewPath = resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery-package-preview.md");
|
|
70865
|
-
await (0,
|
|
71152
|
+
await (0, import_promises12.mkdir)(runDirectory, { recursive: true });
|
|
70866
71153
|
const startedAt = dependencies.now().toISOString();
|
|
70867
71154
|
const previousManifest = options.resumeRunId ? await loadManifest(manifestPath) : null;
|
|
70868
71155
|
let manifest = {
|
|
@@ -70958,7 +71245,7 @@ async function validateCurrentDiscoveryBundle(workspacePathValue) {
|
|
|
70958
71245
|
const currentPath = resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery-packages/current.json");
|
|
70959
71246
|
let discoveryPackage;
|
|
70960
71247
|
try {
|
|
70961
|
-
discoveryPackage = (0, import_discovery_package_contract2.parseDiscoveryPackage)(JSON.parse(await (0,
|
|
71248
|
+
discoveryPackage = (0, import_discovery_package_contract2.parseDiscoveryPackage)(JSON.parse(await (0, import_promises12.readFile)(currentPath, "utf8")));
|
|
70962
71249
|
} catch {
|
|
70963
71250
|
throw new Error("No current Discovery Package exists. Run discovery prepare first.");
|
|
70964
71251
|
}
|
|
@@ -70973,7 +71260,7 @@ async function validateCurrentDiscoveryBundle(workspacePathValue) {
|
|
|
70973
71260
|
findings.push(...assessment.findings);
|
|
70974
71261
|
for (const document3 of discoveryPackage.documents) {
|
|
70975
71262
|
try {
|
|
70976
|
-
const content = await (0,
|
|
71263
|
+
const content = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, document3.logicalPath), "utf8");
|
|
70977
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." });
|
|
70978
71265
|
} catch {
|
|
70979
71266
|
findings.push({ ruleId: "DP_SOURCE_MISSING", path: document3.logicalPath, message: "A packaged local document is missing." });
|
|
@@ -70991,7 +71278,7 @@ async function createDiscoverySupportBundle(workspacePathValue, runId) {
|
|
|
70991
71278
|
const manifest = await loadManifest(import_node_path11.default.join(runDirectory, "manifest.json"));
|
|
70992
71279
|
let diagnostics = null;
|
|
70993
71280
|
try {
|
|
70994
|
-
diagnostics = JSON.parse(await (0,
|
|
71281
|
+
diagnostics = JSON.parse(await (0, import_promises12.readFile)(import_node_path11.default.join(runDirectory, "diagnostics.json"), "utf8"));
|
|
70995
71282
|
} catch {
|
|
70996
71283
|
diagnostics = { errorClass: "DIAGNOSTICS_MISSING" };
|
|
70997
71284
|
}
|
|
@@ -71014,7 +71301,7 @@ async function createDiscoverySupportBundle(workspacePathValue, runId) {
|
|
|
71014
71301
|
async function loadDiscoveryPreflight(workspacePath) {
|
|
71015
71302
|
let serialized;
|
|
71016
71303
|
try {
|
|
71017
|
-
serialized = await (0,
|
|
71304
|
+
serialized = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, import_discovery_package_contract.DISCOVERY_SOURCE_MANIFEST_PATH), "utf8");
|
|
71018
71305
|
} catch {
|
|
71019
71306
|
throw new DiscoveryPreparationError("DP_SOURCE_MANIFEST_MISSING", "DISCOVERY_INCOMPLETE", "The owner-confirmed source-selection manifest is missing.");
|
|
71020
71307
|
}
|
|
@@ -71040,7 +71327,7 @@ async function loadDiscoveryPreflight(workspacePath) {
|
|
|
71040
71327
|
const documentReviews = /* @__PURE__ */ new Map();
|
|
71041
71328
|
for (const logicalPath of import_discovery_package_contract.DISCOVERY_CURATED_DOCUMENTS) {
|
|
71042
71329
|
try {
|
|
71043
|
-
const content = await (0,
|
|
71330
|
+
const content = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, logicalPath), "utf8");
|
|
71044
71331
|
documentReviews.set(logicalPath, (0, import_discovery_package_contract.parseDiscoveryDocumentReview)(logicalPath, content));
|
|
71045
71332
|
} catch (error) {
|
|
71046
71333
|
if (error instanceof DiscoveryPreparationError) throw error;
|
|
@@ -71069,7 +71356,7 @@ async function freezeDocuments(workspacePath, manifest, reviews) {
|
|
|
71069
71356
|
if (source.kind === "BINARY_WITH_SIDECAR" && source.sidecar) {
|
|
71070
71357
|
const content = await readText(workspacePath, source.sidecar.logicalPath);
|
|
71071
71358
|
assertDigest(source.sidecar.logicalPath, content, source.sidecar.digest);
|
|
71072
|
-
const original = await (0,
|
|
71359
|
+
const original = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, source.logicalPath));
|
|
71073
71360
|
const originalDigest = digestBytes(original);
|
|
71074
71361
|
if (originalDigest !== source.digest || source.sidecar.originalDigest !== source.digest) {
|
|
71075
71362
|
throw new DiscoveryPreparationError("DP_SIDECAR_STALE", "STALE_INPUT", `The selected sidecar is stale for ${source.logicalPath}.`);
|
|
@@ -71077,7 +71364,7 @@ async function freezeDocuments(workspacePath, manifest, reviews) {
|
|
|
71077
71364
|
documents.push(document2(source.sidecar.logicalPath, "SIDECAR", content, "SUPPORTING", { logicalPath: source.logicalPath, digest: originalDigest }));
|
|
71078
71365
|
}
|
|
71079
71366
|
}
|
|
71080
|
-
const selectionManifest = await (0,
|
|
71367
|
+
const selectionManifest = await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, import_discovery_package_contract.DISCOVERY_SOURCE_MANIFEST_PATH));
|
|
71081
71368
|
return { documents: documents.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath)), selectionManifestDigest: digestBytes(selectionManifest) };
|
|
71082
71369
|
}
|
|
71083
71370
|
function document2(logicalPath, role, content, reviewState, original) {
|
|
@@ -71098,7 +71385,7 @@ async function publishPackage(workspacePath, discoveryPackage, assessment, previ
|
|
|
71098
71385
|
const packagePath = import_node_path11.default.join(directory, "package.json");
|
|
71099
71386
|
const assessmentPath = import_node_path11.default.join(directory, "assessment.json");
|
|
71100
71387
|
const currentPath = resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery-packages/current.json");
|
|
71101
|
-
await (0,
|
|
71388
|
+
await (0, import_promises12.mkdir)(directory, { recursive: true });
|
|
71102
71389
|
await writeJsonAtomic(packagePath, discoveryPackage);
|
|
71103
71390
|
await writeJsonAtomic(assessmentPath, assessment);
|
|
71104
71391
|
await writeFileAtomic(previewPath, renderPreview(discoveryPackage, assessment));
|
|
@@ -71163,7 +71450,7 @@ function classify(error, signal) {
|
|
|
71163
71450
|
}
|
|
71164
71451
|
async function readDiscoveryWorkspaceId(workspacePath) {
|
|
71165
71452
|
try {
|
|
71166
|
-
const binding = JSON.parse(await (0,
|
|
71453
|
+
const binding = JSON.parse(await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, ".swarmcraft/discovery.binding.json"), "utf8"));
|
|
71167
71454
|
if (!binding.workspaceId) throw new Error("missing id");
|
|
71168
71455
|
const compact = binding.workspaceId.replace(/^dws_/, "");
|
|
71169
71456
|
if (!/^[a-f0-9]{32}$/i.test(compact)) throw new Error("invalid id");
|
|
@@ -71174,40 +71461,40 @@ async function readDiscoveryWorkspaceId(workspacePath) {
|
|
|
71174
71461
|
}
|
|
71175
71462
|
async function readText(workspacePath, logicalPath) {
|
|
71176
71463
|
try {
|
|
71177
|
-
return await (0,
|
|
71464
|
+
return await (0, import_promises12.readFile)(resolveContainedWorkspacePath(workspacePath, logicalPath), "utf8");
|
|
71178
71465
|
} catch {
|
|
71179
71466
|
throw new DiscoveryPreparationError("DP_SOURCE_MISSING", "STALE_INPUT", `The selected document is missing: ${logicalPath}`);
|
|
71180
71467
|
}
|
|
71181
71468
|
}
|
|
71182
71469
|
async function loadManifest(manifestPath) {
|
|
71183
|
-
return JSON.parse(await (0,
|
|
71470
|
+
return JSON.parse(await (0, import_promises12.readFile)(manifestPath, "utf8"));
|
|
71184
71471
|
}
|
|
71185
71472
|
function diagnosticsRecord(startedAt, finishedAt) {
|
|
71186
71473
|
return { schemaVersion: 2, phase: "preflight", errorClass: null, startedAt, finishedAt, documentCount: 0, bytes: 0, estimatedTokens: 0, supportCode: null };
|
|
71187
71474
|
}
|
|
71188
71475
|
async function writeFeedback(feedbackPath, findings) {
|
|
71189
|
-
await (0,
|
|
71476
|
+
await (0, import_promises12.mkdir)(import_node_path11.default.dirname(feedbackPath), { recursive: true });
|
|
71190
71477
|
const body = findings.length === 0 ? "# Discovery Package feedback\n\nThe deterministic package is ready for preview and upload authorization.\n" : `# Discovery Package feedback
|
|
71191
71478
|
|
|
71192
71479
|
Preparation needs attention. No package was uploaded.
|
|
71193
71480
|
|
|
71194
71481
|
${findings.map((item) => `- **${item.ruleId}** at \`${item.path}\`: ${item.message}`).join("\n")}
|
|
71195
71482
|
`;
|
|
71196
|
-
await (0,
|
|
71483
|
+
await (0, import_promises12.writeFile)(feedbackPath, body, "utf8");
|
|
71197
71484
|
}
|
|
71198
71485
|
async function writeJson(filePath, value) {
|
|
71199
|
-
await (0,
|
|
71200
|
-
await (0,
|
|
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");
|
|
71201
71488
|
}
|
|
71202
71489
|
async function writeJsonAtomic(filePath, value) {
|
|
71203
71490
|
await writeFileAtomic(filePath, JSON.stringify(value, null, 2) + "\n");
|
|
71204
71491
|
}
|
|
71205
71492
|
async function writeFileAtomic(filePath, contents) {
|
|
71206
|
-
await (0,
|
|
71493
|
+
await (0, import_promises12.mkdir)(import_node_path11.default.dirname(filePath), { recursive: true });
|
|
71207
71494
|
const temporaryPath = `${filePath}.${process.pid}.tmp`;
|
|
71208
|
-
await (0,
|
|
71209
|
-
await (0,
|
|
71210
|
-
await (0,
|
|
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 });
|
|
71211
71498
|
}
|
|
71212
71499
|
function digestBytes(value) {
|
|
71213
71500
|
return `sha256:${(0, import_node_crypto5.createHash)("sha256").update(value).digest("hex")}`;
|
|
@@ -71347,6 +71634,18 @@ var COMMANDS = [
|
|
|
71347
71634
|
summary: "List SwarmCraft projects available to the signed-in user.",
|
|
71348
71635
|
implemented: true
|
|
71349
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
|
+
},
|
|
71350
71649
|
{
|
|
71351
71650
|
name: "discovery prepare",
|
|
71352
71651
|
usage: "swarmcraft discovery prepare --workspace <path> [--source <owner-selected-relative-md-or-txt> ...] [--discovery-workspace <id>] [--run-id <id>|--resume-run <id>]",
|
|
@@ -71367,13 +71666,13 @@ var COMMANDS = [
|
|
|
71367
71666
|
},
|
|
71368
71667
|
{
|
|
71369
71668
|
name: "init",
|
|
71370
|
-
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]",
|
|
71371
71670
|
summary: "Prepare a repository with SwarmCraft packet and agent guidance files.",
|
|
71372
71671
|
implemented: true
|
|
71373
71672
|
},
|
|
71374
71673
|
{
|
|
71375
71674
|
name: "one-shot",
|
|
71376
|
-
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]`,
|
|
71377
71676
|
summary: "Run the project board packet loop with your own AI or incrementally metered Managed AI.",
|
|
71378
71677
|
implemented: true
|
|
71379
71678
|
},
|
|
@@ -71404,7 +71703,7 @@ var COMMANDS = [
|
|
|
71404
71703
|
];
|
|
71405
71704
|
function findCommand(positionals) {
|
|
71406
71705
|
if (positionals.length === 0) return void 0;
|
|
71407
|
-
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];
|
|
71408
71707
|
return COMMANDS.find((command) => command.name === commandKey);
|
|
71409
71708
|
}
|
|
71410
71709
|
var COMMAND_INSTRUCTIONS = {
|
|
@@ -71418,15 +71717,17 @@ var COMMAND_INSTRUCTIONS = {
|
|
|
71418
71717
|
init: {
|
|
71419
71718
|
requirements: ["Signed-in CLI session, accessible READY project, network, and a local Git workspace."],
|
|
71420
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."],
|
|
71421
|
-
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."],
|
|
71422
71721
|
result: "Prints seed/packet changes, conflicts and skipped tasks. Exit 0 on completion, 1 on error; inspect conflicts and git diff before committing.",
|
|
71423
71722
|
example: "swarmcraft init --project <id> --workspace . --agent-provider claude"
|
|
71424
71723
|
},
|
|
71425
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" },
|
|
71426
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" },
|
|
71427
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>" },
|
|
71428
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>" },
|
|
71429
|
-
"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" },
|
|
71430
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 ." },
|
|
71431
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 ." },
|
|
71432
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" },
|
|
@@ -71469,11 +71770,11 @@ Help is local and read-only; no authentication or command execution occurs.
|
|
|
71469
71770
|
|
|
71470
71771
|
// src/terminalPrompt.ts
|
|
71471
71772
|
var import_node_process = require("node:process");
|
|
71472
|
-
var
|
|
71773
|
+
var import_promises13 = require("node:readline/promises");
|
|
71473
71774
|
var import_node_stream = require("node:stream");
|
|
71474
71775
|
var DEFAULT_STREAMS = { input: import_node_process.stdin, output: import_node_process.stdout };
|
|
71475
71776
|
async function promptLine(prompt, streams = DEFAULT_STREAMS) {
|
|
71476
|
-
const readline = (0,
|
|
71777
|
+
const readline = (0, import_promises13.createInterface)({ input: streams.input, output: streams.output });
|
|
71477
71778
|
try {
|
|
71478
71779
|
return (await readline.question(prompt)).trim();
|
|
71479
71780
|
} finally {
|
|
@@ -71495,7 +71796,7 @@ async function promptSecret(prompt, streams = DEFAULT_STREAMS) {
|
|
|
71495
71796
|
});
|
|
71496
71797
|
concealedOutput.isTTY = true;
|
|
71497
71798
|
concealedOutput.columns = streams.output.columns ?? 80;
|
|
71498
|
-
const readline = (0,
|
|
71799
|
+
const readline = (0, import_promises13.createInterface)({ input: streams.input, output: concealedOutput, terminal: true });
|
|
71499
71800
|
try {
|
|
71500
71801
|
const answer = readline.question(prompt);
|
|
71501
71802
|
muted = true;
|
|
@@ -71533,7 +71834,7 @@ function formatProjectUpgrade(result) {
|
|
|
71533
71834
|
}
|
|
71534
71835
|
|
|
71535
71836
|
// src/operation/upgrade.ts
|
|
71536
|
-
var
|
|
71837
|
+
var import_promises14 = require("node:fs/promises");
|
|
71537
71838
|
var import_node_path12 = __toESM(require("node:path"), 1);
|
|
71538
71839
|
var import_node_crypto6 = require("node:crypto");
|
|
71539
71840
|
var import_repo_seed6 = __toESM(require_dist4(), 1);
|
|
@@ -71719,7 +72020,7 @@ async function checkOperationUpgrade(workspace) {
|
|
|
71719
72020
|
const result = (state) => ({ protocol: 1, state, valid: true });
|
|
71720
72021
|
const git3 = await operationGit(root, ["rev-parse", "--absolute-git-dir"]);
|
|
71721
72022
|
if (!git3.exitCode) try {
|
|
71722
|
-
await (0,
|
|
72023
|
+
await (0, import_promises14.lstat)(import_node_path12.default.join(git3.stdout.trim(), JOURNAL));
|
|
71723
72024
|
return result("INTERRUPTED");
|
|
71724
72025
|
} catch (error) {
|
|
71725
72026
|
if (!isMissing(error)) throw error;
|
|
@@ -71747,15 +72048,15 @@ async function upgradeOperation(workspace, signal) {
|
|
|
71747
72048
|
const files = new OperationFiles(root);
|
|
71748
72049
|
let pending;
|
|
71749
72050
|
try {
|
|
71750
|
-
const info = await (0,
|
|
72051
|
+
const info = await (0, import_promises14.lstat)(journalPath);
|
|
71751
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.");
|
|
71752
|
-
pending = JSON.parse(await (0,
|
|
72053
|
+
pending = JSON.parse(await (0, import_promises14.readFile)(journalPath, "utf8"));
|
|
71753
72054
|
} catch (error) {
|
|
71754
72055
|
if (!isMissing(error)) throw error;
|
|
71755
72056
|
}
|
|
71756
72057
|
if (pending) {
|
|
71757
72058
|
await recover(root, files, pending);
|
|
71758
|
-
await (0,
|
|
72059
|
+
await (0, import_promises14.unlink)(journalPath);
|
|
71759
72060
|
}
|
|
71760
72061
|
const check = await checkOperationUpgrade(root);
|
|
71761
72062
|
if (check.state === "CURRENT") return { valid: true, state: "CURRENT", codes: [] };
|
|
@@ -71845,18 +72146,18 @@ async function upgradeOperation(workspace, signal) {
|
|
|
71845
72146
|
if ((await git2(root, ["rev-parse", "HEAD"])).trim() !== journal.checkpoint) fail("OPERATE_CONCURRENT_EDIT", "Git history changed during upgrade. Review recovery before retrying.");
|
|
71846
72147
|
await git2(root, ["commit", "--only", "-m", "Upgrade Operate repository", "-m", "Operate-Upgrade-Checkpoint: " + journal.checkpoint, "--", ...changes.map((change) => change.path)]);
|
|
71847
72148
|
await verifyCommitted(root, journal);
|
|
71848
|
-
await (0,
|
|
72149
|
+
await (0, import_promises14.unlink)(journalPath);
|
|
71849
72150
|
return { valid: true, state: "UPDATED", codes: status.codes, checkpoint: journal.checkpoint };
|
|
71850
72151
|
} catch (error) {
|
|
71851
72152
|
try {
|
|
71852
72153
|
await recover(root, files, journal);
|
|
71853
|
-
await (0,
|
|
72154
|
+
await (0, import_promises14.unlink)(journalPath);
|
|
71854
72155
|
} catch {
|
|
71855
72156
|
}
|
|
71856
72157
|
throw error;
|
|
71857
72158
|
}
|
|
71858
72159
|
} finally {
|
|
71859
|
-
await (0,
|
|
72160
|
+
await (0, import_promises14.unlink)(lock);
|
|
71860
72161
|
}
|
|
71861
72162
|
}
|
|
71862
72163
|
function upgradeFailureMessage(code) {
|
|
@@ -71876,7 +72177,7 @@ async function requireClean(root) {
|
|
|
71876
72177
|
for (const name of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply", "sequencer"]) {
|
|
71877
72178
|
const location = (await git2(root, ["rev-parse", "--git-path", name])).trim();
|
|
71878
72179
|
try {
|
|
71879
|
-
await (0,
|
|
72180
|
+
await (0, import_promises14.lstat)(import_node_path12.default.resolve(root, location));
|
|
71880
72181
|
fail("OPERATE_GIT_IN_PROGRESS", "Finish the current Git operation before upgrading.");
|
|
71881
72182
|
} catch (error) {
|
|
71882
72183
|
if (!isMissing(error)) throw error;
|
|
@@ -71885,12 +72186,12 @@ async function requireClean(root) {
|
|
|
71885
72186
|
}
|
|
71886
72187
|
async function acquire(lock) {
|
|
71887
72188
|
try {
|
|
71888
|
-
const handle = await (0,
|
|
72189
|
+
const handle = await (0, import_promises14.open)(lock, "wx", 384);
|
|
71889
72190
|
await handle.writeFile(String(process.pid));
|
|
71890
72191
|
await handle.close();
|
|
71891
72192
|
} catch (error) {
|
|
71892
72193
|
if (!(error && typeof error === "object" && "code" in error && error.code === "EEXIST")) throw error;
|
|
71893
|
-
const pid = Number(await (0,
|
|
72194
|
+
const pid = Number(await (0, import_promises14.readFile)(lock, "utf8"));
|
|
71894
72195
|
if (!Number.isSafeInteger(pid) || pid < 1) fail("OPERATE_UPGRADE_LOCKED", "Upgrade lock needs review before retrying.");
|
|
71895
72196
|
try {
|
|
71896
72197
|
process.kill(pid, 0);
|
|
@@ -71900,17 +72201,17 @@ async function acquire(lock) {
|
|
|
71900
72201
|
}
|
|
71901
72202
|
let reaper;
|
|
71902
72203
|
try {
|
|
71903
|
-
reaper = await (0,
|
|
72204
|
+
reaper = await (0, import_promises14.open)(lock + ".recovery", "wx", 384);
|
|
71904
72205
|
} catch {
|
|
71905
72206
|
fail("OPERATE_UPGRADE_LOCKED", "Another process is recovering the upgrade lock. Retry after it finishes.");
|
|
71906
72207
|
}
|
|
71907
72208
|
try {
|
|
71908
|
-
if (Number(await (0,
|
|
71909
|
-
await (0,
|
|
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);
|
|
71910
72211
|
await acquire(lock);
|
|
71911
72212
|
} finally {
|
|
71912
72213
|
await reaper.close();
|
|
71913
|
-
await (0,
|
|
72214
|
+
await (0, import_promises14.unlink)(lock + ".recovery");
|
|
71914
72215
|
}
|
|
71915
72216
|
}
|
|
71916
72217
|
}
|
|
@@ -71963,7 +72264,7 @@ async function verifyCommitted(root, journal) {
|
|
|
71963
72264
|
}
|
|
71964
72265
|
async function writeJournal(destination, journal) {
|
|
71965
72266
|
const temporary = destination + "." + (0, import_node_crypto6.randomUUID)() + ".tmp";
|
|
71966
|
-
const handle = await (0,
|
|
72267
|
+
const handle = await (0, import_promises14.open)(temporary, "wx", 384);
|
|
71967
72268
|
try {
|
|
71968
72269
|
await handle.writeFile(JSON.stringify(journal));
|
|
71969
72270
|
await handle.sync();
|
|
@@ -71971,9 +72272,9 @@ async function writeJournal(destination, journal) {
|
|
|
71971
72272
|
await handle.close();
|
|
71972
72273
|
}
|
|
71973
72274
|
try {
|
|
71974
|
-
await (0,
|
|
72275
|
+
await (0, import_promises14.rename)(temporary, destination);
|
|
71975
72276
|
} catch (error) {
|
|
71976
|
-
await (0,
|
|
72277
|
+
await (0, import_promises14.unlink)(temporary);
|
|
71977
72278
|
throw error;
|
|
71978
72279
|
}
|
|
71979
72280
|
}
|
|
@@ -72276,7 +72577,7 @@ async function generateOperationHandbook(options, signal, processRunner = runPro
|
|
|
72276
72577
|
}
|
|
72277
72578
|
|
|
72278
72579
|
// src/operation/intake.ts
|
|
72279
|
-
var
|
|
72580
|
+
var import_promises15 = require("node:fs/promises");
|
|
72280
72581
|
var import_node_path14 = __toESM(require("node:path"), 1);
|
|
72281
72582
|
var import_operation_contract7 = __toESM(require_dist2(), 1);
|
|
72282
72583
|
async function intakeOperationSource(options, signal) {
|
|
@@ -72303,9 +72604,9 @@ async function intakeOperationSource(options, signal) {
|
|
|
72303
72604
|
extension = import_node_path14.default.extname(previous.locator);
|
|
72304
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.");
|
|
72305
72606
|
} else if (options.input) {
|
|
72306
|
-
const entry = await (0,
|
|
72607
|
+
const entry = await (0, import_promises15.lstat)(options.input);
|
|
72307
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.");
|
|
72308
|
-
bytes = await (0,
|
|
72609
|
+
bytes = await (0, import_promises15.readFile)(options.input);
|
|
72309
72610
|
extension = import_node_path14.default.extname(options.input).toLowerCase();
|
|
72310
72611
|
}
|
|
72311
72612
|
const digest = bytes ? (0, import_operation_contract7.artifactDigest)(bytes) : "";
|
|
@@ -72519,6 +72820,96 @@ function safeOperateError(error) {
|
|
|
72519
72820
|
return new OperateCommandError("OPERATE_COMMAND_FAILED", 4, "Operate could not complete. Check command options, workspace permissions, and local operation files.");
|
|
72520
72821
|
}
|
|
72521
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
|
+
|
|
72522
72913
|
// src/main.ts
|
|
72523
72914
|
var VERSION = package_default.version;
|
|
72524
72915
|
var DEFAULT_API_BASE_URL = "https://swarmcraft.ai/api";
|
|
@@ -72535,7 +72926,7 @@ async function main(argv) {
|
|
|
72535
72926
|
if (command) {
|
|
72536
72927
|
printCommandHelp(command);
|
|
72537
72928
|
} else {
|
|
72538
|
-
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.");
|
|
72539
72930
|
printGeneralHelp();
|
|
72540
72931
|
}
|
|
72541
72932
|
return 0;
|
|
@@ -72546,7 +72937,7 @@ async function main(argv) {
|
|
|
72546
72937
|
printCommandHelp(helpCommand);
|
|
72547
72938
|
} else {
|
|
72548
72939
|
const requested = parsed.positionals.slice(1).join(" ");
|
|
72549
|
-
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.");
|
|
72550
72941
|
printGeneralHelp();
|
|
72551
72942
|
}
|
|
72552
72943
|
return 0;
|
|
@@ -72584,6 +72975,10 @@ Run "swarmcraft --help" for available commands.`);
|
|
|
72584
72975
|
case "projects list":
|
|
72585
72976
|
await runProjectsList(parsed);
|
|
72586
72977
|
return 0;
|
|
72978
|
+
case "packets links":
|
|
72979
|
+
return runPacketLinks(parsed);
|
|
72980
|
+
case "packets sync":
|
|
72981
|
+
return runPacketSyncCommand(parsed);
|
|
72587
72982
|
case "discovery prepare":
|
|
72588
72983
|
await runDiscoveryPrepare(parsed);
|
|
72589
72984
|
return 0;
|
|
@@ -72679,6 +73074,71 @@ async function runProjectsList(parsed) {
|
|
|
72679
73074
|
console.log(`${project.id} ${project.boardState} ${done}/${total} done ${project.title}`);
|
|
72680
73075
|
}
|
|
72681
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
|
+
}
|
|
72682
73142
|
async function runInit(parsed) {
|
|
72683
73143
|
const projectId = requireOption(parsed, "project");
|
|
72684
73144
|
const workspacePath = requireOption(parsed, "workspace");
|
|
@@ -72691,12 +73151,14 @@ async function runInit(parsed) {
|
|
|
72691
73151
|
taskIds: getOptions(parsed, "task"),
|
|
72692
73152
|
taskLimit,
|
|
72693
73153
|
delegationId: delegation?.id ?? null,
|
|
72694
|
-
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")
|
|
72695
73157
|
});
|
|
72696
73158
|
printBootstrapSummary(summary);
|
|
72697
73159
|
}
|
|
72698
73160
|
async function runOneShotCommand(parsed) {
|
|
72699
|
-
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"]);
|
|
72700
73162
|
if (getOption(parsed, "plan") || getOptions(parsed, "packet").length) {
|
|
72701
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}.`);
|
|
72702
73164
|
const options2 = { ...parseOneShotOptions(parsed, true), delegation: null };
|
|
@@ -72806,7 +73268,7 @@ async function runDoctor(parsed) {
|
|
|
72806
73268
|
}
|
|
72807
73269
|
const provider = getOption(parsed, "agent-provider");
|
|
72808
73270
|
if (provider && provider !== "custom") {
|
|
72809
|
-
const commandName = (0,
|
|
73271
|
+
const commandName = (0, import_packet_workflow11.parseExternalAgentProvider)(provider);
|
|
72810
73272
|
const result = await runProcess(process.platform === "win32" ? "where.exe" : "which", [commandName], process.cwd());
|
|
72811
73273
|
console.log(`${commandName}: ${result.exitCode === 0 ? result.stdout.trim() : "not found"}`);
|
|
72812
73274
|
}
|
|
@@ -72913,15 +73375,24 @@ function toDelegationContext(delegation) {
|
|
|
72913
73375
|
};
|
|
72914
73376
|
}
|
|
72915
73377
|
function printBootstrapSummary(summary) {
|
|
72916
|
-
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}`);
|
|
72917
73380
|
console.log(`Workspace: ${summary.workspacePath}`);
|
|
72918
73381
|
if (summary.dirtyFileCount > 0) {
|
|
72919
73382
|
console.log(`Workspace had ${summary.dirtyFileCount} pre-existing changed file(s).`);
|
|
72920
73383
|
}
|
|
72921
|
-
|
|
72922
|
-
|
|
72923
|
-
|
|
72924
|
-
|
|
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
|
+
}
|
|
72925
73396
|
if (summary.skippedTasks.length > 0) {
|
|
72926
73397
|
console.log("Skipped tasks:");
|
|
72927
73398
|
for (const skipped of summary.skippedTasks) {
|
|
@@ -72963,7 +73434,7 @@ function printRunSummary(manifest) {
|
|
|
72963
73434
|
}
|
|
72964
73435
|
function parseOneShotOptions(parsed, local = false) {
|
|
72965
73436
|
const providerValue = requireOption(parsed, "agent-provider");
|
|
72966
|
-
const agentProvider = providerValue === "managed" ? "managed" : (0,
|
|
73437
|
+
const agentProvider = providerValue === "managed" ? "managed" : (0, import_packet_workflow11.parseExternalAgentProvider)(providerValue);
|
|
72967
73438
|
if (agentProvider === "managed" && (getOption(parsed, "agent-command") || getOption(parsed, "agent-env-file") || getOption(parsed, "agent-api-key-env-name"))) {
|
|
72968
73439
|
throw new Error("Managed AI does not accept custom commands or provider credentials.");
|
|
72969
73440
|
}
|
|
@@ -72976,7 +73447,7 @@ function parseOneShotOptions(parsed, local = false) {
|
|
|
72976
73447
|
workspacePath: requireOption(parsed, "workspace"),
|
|
72977
73448
|
agentProvider,
|
|
72978
73449
|
agentCommand: getOption(parsed, "agent-command") ?? process.env.SWARMCRAFT_AGENT_COMMAND ?? null,
|
|
72979
|
-
delivery: (0,
|
|
73450
|
+
delivery: (0, import_packet_workflow10.parseDeliveryMode)(getOption(parsed, "delivery")),
|
|
72980
73451
|
checking: parseOnOff(getOption(parsed, "checking") ?? (local ? "on" : "off"), "--checking"),
|
|
72981
73452
|
reviewing: explicitReviewing ? parseOnOff(explicitReviewing, "--reviewing") : local || donePolicy === "stop",
|
|
72982
73453
|
maxCheckingAttempts: parsePositiveInteger(getOption(parsed, "max-checking-attempts") ?? "2", "--max-checking-attempts"),
|
|
@@ -72986,6 +73457,7 @@ function parseOneShotOptions(parsed, local = false) {
|
|
|
72986
73457
|
maxAgentSpendUsd: getOption(parsed, "max-agent-spend-usd") ? parseNonNegativeNumber(getOption(parsed, "max-agent-spend-usd"), "--max-agent-spend-usd") : null,
|
|
72987
73458
|
requireCostTelemetry: hasFlag(parsed, "require-cost-telemetry"),
|
|
72988
73459
|
allowDirty: hasFlag(parsed, "allow-dirty"),
|
|
73460
|
+
forceProjectBinding: hasFlag(parsed, "force"),
|
|
72989
73461
|
agentEnvFilePath: getOption(parsed, "agent-env-file") ?? null,
|
|
72990
73462
|
agentApiKeyEnvName: getOption(parsed, "agent-api-key-env-name") ?? null,
|
|
72991
73463
|
taskIds: getOptions(parsed, "task"),
|
|
@@ -72995,10 +73467,10 @@ function parseOneShotOptions(parsed, local = false) {
|
|
|
72995
73467
|
};
|
|
72996
73468
|
}
|
|
72997
73469
|
async function readRunManifest(workspacePath, runId) {
|
|
72998
|
-
return JSON.parse(await (0,
|
|
73470
|
+
return JSON.parse(await (0, import_promises16.readFile)(resolveManifestPath(import_node_path15.default.resolve(workspacePath), runId), "utf8"));
|
|
72999
73471
|
}
|
|
73000
73472
|
function commandGroup(name) {
|
|
73001
|
-
if (["init", "upgrade"].includes(name)) return "Setup and upgrade";
|
|
73473
|
+
if (["init", "upgrade"].includes(name) || name.startsWith("packets ")) return "Setup and upgrade";
|
|
73002
73474
|
if (["one-shot", "resume", "status"].includes(name)) return "Delivery";
|
|
73003
73475
|
if (name.startsWith("operate ")) return "Operate";
|
|
73004
73476
|
if (name.startsWith("discovery ")) return "Discovery";
|