cadre-ai 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,20 +33,20 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
33
33
  // src/cadre-core.ts
34
34
  var cadre_core_exports = {};
35
35
  __export(cadre_core_exports, {
36
+ appendCadreEvent: () => appendCadreEvent,
37
+ appendCadreMessage: () => appendCadreMessage,
36
38
  artifactCatalog: () => artifactCatalog,
37
39
  artifactPacket: () => artifactPacket,
38
40
  artifactRender: () => artifactRender,
39
41
  artifactSchema: () => artifactSchema,
40
42
  artifactSync: () => artifactSync,
41
43
  availableWork: () => availableWork,
42
- beadsSummary: () => beadsSummary,
43
- beadsTaskWrite: () => beadsTaskWrite,
44
44
  claimTrack: () => claimTrack,
45
45
  collisionScan: () => collisionScan,
46
46
  completeTask: () => completeTask,
47
- createBeadsTree: () => createBeadsTree,
48
47
  dependencyGraph: () => dependencyGraph,
49
48
  doctor: () => doctor,
49
+ ensureNativeState: () => ensureNativeState,
50
50
  fleetStatus: () => fleetStatus,
51
51
  heartbeatTrack: () => heartbeatTrack,
52
52
  implementationPrep: () => implementationPrep,
@@ -60,6 +60,7 @@ __export(cadre_core_exports, {
60
60
  lspSetup: () => lspSetup,
61
61
  mcpReadiness: () => mcpReadiness,
62
62
  metadataPatch: () => metadataPatch,
63
+ nativeStateSummary: () => nativeStateSummary,
63
64
  parallelWorkflow: () => parallelWorkflow,
64
65
  parsePlanFile: () => parsePlanFile,
65
66
  parsePlanJson: () => parsePlanJson,
@@ -69,6 +70,8 @@ __export(cadre_core_exports, {
69
70
  polyrepoPreflight: () => polyrepoPreflight,
70
71
  prCiStatus: () => prCiStatus,
71
72
  providerEvidence: () => providerEvidence,
73
+ readCadreEvents: () => readCadreEvents,
74
+ readCadreMessages: () => readCadreMessages,
72
75
  recordParallelWorker: () => recordParallelWorker,
73
76
  recordReview: () => recordReview,
74
77
  recordTaskResult: () => recordTaskResult,
@@ -86,6 +89,7 @@ __export(cadre_core_exports, {
86
89
  testCoverage: () => testCoverage,
87
90
  testImpact: () => testImpact,
88
91
  trackContext: () => trackContext,
92
+ workflowFormula: () => workflowFormula,
89
93
  workflowPacket: () => workflowPacket,
90
94
  workspaceDiagnostics: () => workspaceDiagnostics,
91
95
  workspaceHealth: () => workspaceHealth,
@@ -94,7 +98,7 @@ __export(cadre_core_exports, {
94
98
  module.exports = __toCommonJS(cadre_core_exports);
95
99
 
96
100
  // src/core/application/runtime/artifact-actions.ts
97
- var import_node_fs13 = __toESM(require("node:fs"));
101
+ var import_node_fs14 = __toESM(require("node:fs"));
98
102
  var import_node_path28 = __toESM(require("node:path"));
99
103
 
100
104
  // src/guards.ts
@@ -130,7 +134,7 @@ function errorCode(error) {
130
134
  }
131
135
 
132
136
  // src/core/application/runtime/artifact-catalog.ts
133
- var import_node_fs12 = __toESM(require("node:fs"));
137
+ var import_node_fs13 = __toESM(require("node:fs"));
134
138
  var import_node_path27 = __toESM(require("node:path"));
135
139
 
136
140
  // src/core/infrastructure/runtime/json-store.ts
@@ -160,7 +164,6 @@ function isCadreProjectRoot(root) {
160
164
  "product.json",
161
165
  "tech-stack.json",
162
166
  "workflow.json",
163
- "beads.json",
164
167
  "config.json",
165
168
  "repos.json"
166
169
  ].some((name) => fileExists(import_node_path.default.join(cadreDir, name))) || fileExists(import_node_path.default.join(cadreDir, "tracks"));
@@ -237,7 +240,6 @@ function isControlPlaneFile(file) {
237
240
  const normalized = String(file || "").replace(/\\/g, "/").replace(/^\.\//, "");
238
241
  if (!normalized) return true;
239
242
  if (normalized.startsWith("cadre/")) return true;
240
- if (normalized.startsWith(".beads/")) return true;
241
243
  if (normalized === ".gitattributes" || normalized === ".gitmodules") return true;
242
244
  if (normalized === "cadre-merge-train.gitlab-ci.yml") return true;
243
245
  if (normalized === ".gitlab-ci.yml") return true;
@@ -597,8 +599,8 @@ function configuredProvider(root, args = {}) {
597
599
  const config = loadTopology(root).config || {};
598
600
  const detected = detectedProviderFromRemotes(root);
599
601
  const explicit = normalizeProviderMode(args.providerMode || args.provider_mode || args.provider);
600
- const configured = normalizeProviderMode(config.provider_mode) || normalizeProviderMode(config.pr_provider);
601
- const providerMode = explicit || configured || (detected.ambiguous ? null : normalizeProviderMode(detected.provider_mode));
602
+ const configured2 = normalizeProviderMode(config.provider_mode) || normalizeProviderMode(config.pr_provider);
603
+ const providerMode = explicit || configured2 || (detected.ambiguous ? null : normalizeProviderMode(detected.provider_mode));
602
604
  const remoteHostValue = args.remoteHost || args.remote_host || config.remote_host || detected.remote_host || null;
603
605
  const mode = providerMode || null;
604
606
  return {
@@ -607,7 +609,7 @@ function configuredProvider(root, args = {}) {
607
609
  provider_mcp_required: mode === "github" || mode === "gitlab",
608
610
  remote_host: remoteHostValue,
609
611
  detected,
610
- source: explicit ? "argument" : configured ? "config" : "detected",
612
+ source: explicit ? "argument" : configured2 ? "config" : "detected",
611
613
  requires_confirmation: !mode && detected.ambiguous === true
612
614
  };
613
615
  }
@@ -673,7 +675,7 @@ function parseCoveragePercent(text) {
673
675
  }
674
676
 
675
677
  // src/core/application/runtime/track-schedule.ts
676
- var import_node_fs11 = __toESM(require("node:fs"));
678
+ var import_node_fs12 = __toESM(require("node:fs"));
677
679
  var import_node_path24 = __toESM(require("node:path"));
678
680
 
679
681
  // src/core/infrastructure/runtime/coverage.ts
@@ -788,7 +790,6 @@ var DEFAULT_IGNORES = /* @__PURE__ */ new Set([
788
790
  ".git",
789
791
  ".hg",
790
792
  ".svn",
791
- ".beads",
792
793
  ".worktrees",
793
794
  ".agents",
794
795
  ".claude",
@@ -971,15 +972,6 @@ var import_node_path8 = __toESM(require("node:path"));
971
972
  function findTrack(root, trackId) {
972
973
  return listTracks(root).find((item) => item.track_id === trackId) || null;
973
974
  }
974
- function priorityRank(priority) {
975
- const ranks = {
976
- critical: 0,
977
- high: 1,
978
- medium: 2,
979
- low: 3
980
- };
981
- return ranks[String(priority || "medium").toLowerCase()] ?? 2;
982
- }
983
975
  function trackContext(root, trackId) {
984
976
  const track = findTrack(root, trackId);
985
977
  if (!track) return { ok: false, error: `Track not found: ${trackId}` };
@@ -1031,8 +1023,7 @@ function trackContext(root, trackId) {
1031
1023
  metadata_path: import_node_path8.default.relative(root, track.metadata_path || import_node_path8.default.join(track.dir, "metadata.json")),
1032
1024
  plan_path: import_node_path8.default.relative(root, track.plan_path),
1033
1025
  spec_path: import_node_path8.default.relative(root, track.spec_path),
1034
- beads_epic: track.metadata.beads_epic || null,
1035
- beads_tasks: track.metadata.beads_tasks || {},
1026
+ tags: asStringArray(track.metadata.tags),
1036
1027
  review: track.metadata.review || null,
1037
1028
  last_coverage: track.metadata.last_coverage ?? null
1038
1029
  },
@@ -1047,7 +1038,7 @@ function trackContext(root, trackId) {
1047
1038
  var import_node_path17 = __toESM(require("node:path"));
1048
1039
 
1049
1040
  // src/core/application/runtime/quality-gates.ts
1050
- var import_node_fs8 = __toESM(require("node:fs"));
1041
+ var import_node_fs9 = __toESM(require("node:fs"));
1051
1042
  var import_node_path16 = __toESM(require("node:path"));
1052
1043
 
1053
1044
  // src/core/application/runtime/mcp-readiness.ts
@@ -1064,7 +1055,7 @@ var OPTIONAL_CATEGORIES = [
1064
1055
  kind: "issue_tracker",
1065
1056
  label: "Issue tracker",
1066
1057
  aliases: ["issue_tracker", "issueTracker", "jira", "linear", "github_issues", "gitlab_issues"],
1067
- purpose: "Link tracks, Beads tasks, and provider issues without forcing agents through local CLI fallbacks.",
1058
+ purpose: "Link Cadre tracks, native workflow state, and provider issues without forcing agents through local CLI fallbacks.",
1068
1059
  required: false,
1069
1060
  recommended: true
1070
1061
  },
@@ -1434,7 +1425,7 @@ function isIgnoredRepoMapFile(file) {
1434
1425
  if (normalized.startsWith(".claude-plugin/")) return true;
1435
1426
  if (normalized.startsWith("plugins/cadre/")) return true;
1436
1427
  if (normalized.startsWith("plugins/cadre-claude/")) return true;
1437
- return normalized.split("/").some((part) => [".git", ".beads", "node_modules", "dist", "build", "coverage"].includes(part));
1428
+ return normalized.split("/").some((part) => [".git", "node_modules", "dist", "build", "coverage"].includes(part));
1438
1429
  }
1439
1430
  function selectedRepoNames(args = {}) {
1440
1431
  const values = [
@@ -1586,7 +1577,7 @@ function repoMap(root, args = {}) {
1586
1577
  }
1587
1578
 
1588
1579
  // src/core/application/runtime/track-mutations.ts
1589
- var import_node_fs7 = __toESM(require("node:fs"));
1580
+ var import_node_fs8 = __toESM(require("node:fs"));
1590
1581
  var import_node_path15 = __toESM(require("node:path"));
1591
1582
 
1592
1583
  // src/core/domain/track-status.ts
@@ -1599,835 +1590,342 @@ var STATUS_MARKERS = {
1599
1590
  };
1600
1591
  var VALID_STATUSES = new Set(Object.keys(STATUS_MARKERS));
1601
1592
 
1602
- // src/core/application/runtime/beads-tree.ts
1603
- var import_node_path14 = __toESM(require("node:path"));
1604
-
1605
- // src/core/application/runtime/spec-docs.ts
1606
- function normalizedSpecHeading(heading) {
1607
- return heading.toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, " ").trim();
1593
+ // src/core/application/runtime/native-state.ts
1594
+ var import_node_fs7 = __toESM(require("node:fs"));
1595
+ var import_node_path13 = __toESM(require("node:path"));
1596
+ function nativeStatePaths(root) {
1597
+ return {
1598
+ events: import_node_path13.default.join(root, "cadre", "events.jsonl"),
1599
+ formulas: import_node_path13.default.join(root, "cadre", "formulas"),
1600
+ operations: import_node_path13.default.join(root, "cadre", "operations"),
1601
+ messages: import_node_path13.default.join(root, "cadre", "messages"),
1602
+ inbox: import_node_path13.default.join(root, "cadre", "messages", "inbox.jsonl"),
1603
+ outbox: import_node_path13.default.join(root, "cadre", "messages", "outbox.jsonl"),
1604
+ wisps: import_node_path13.default.join(root, "cadre", "local", "wisps")
1605
+ };
1608
1606
  }
1609
- function specSectionKind(heading) {
1610
- const normalized = normalizedSpecHeading(heading);
1611
- if (["description", "summary", "overview", "goal", "goals", "objective", "objectives", "context", "problem"].includes(normalized)) {
1612
- return "description";
1613
- }
1614
- if ([
1615
- "functional requirements",
1616
- "functional requirement",
1617
- "fr",
1618
- "requirements",
1619
- "requirement",
1620
- "user facing behavior",
1621
- "user facing behaviours",
1622
- "user behavior",
1623
- "user behaviour",
1624
- "behavior",
1625
- "behaviour"
1626
- ].includes(normalized)) {
1627
- return "functional_requirements";
1628
- }
1629
- if ([
1630
- "non functional requirements",
1631
- "non functional requirement",
1632
- "nonfunctional requirements",
1633
- "nonfunctional requirement",
1634
- "nfr",
1635
- "constraints",
1636
- "constraint",
1637
- "quality attributes",
1638
- "quality attribute",
1639
- "performance requirements",
1640
- "security requirements"
1641
- ].includes(normalized)) {
1642
- return "non_functional_requirements";
1643
- }
1644
- if (["acceptance criteria", "acceptance criterion", "acceptance", "success criteria", "definition of done", "done"].includes(normalized)) {
1645
- return "acceptance_criteria";
1607
+ function compactStamp(value) {
1608
+ return value.replace(/[^0-9A-Za-z]+/g, "").slice(0, 16);
1609
+ }
1610
+ function nativeId(prefix, payload) {
1611
+ const recordedAt = asOptionalString(payload.recorded_at) || utcNow();
1612
+ return `${prefix}_${compactStamp(recordedAt)}_${textHash(JSON.stringify(payload)).slice(0, 12)}`;
1613
+ }
1614
+ function readJsonlObjects(file, limit = 200) {
1615
+ if (!fileExists(file)) return [];
1616
+ const lines = import_node_fs7.default.readFileSync(file, "utf8").split(/\r?\n/).filter(Boolean);
1617
+ const selected = limit > 0 ? lines.slice(-limit) : lines;
1618
+ const out = [];
1619
+ for (const line of selected) {
1620
+ try {
1621
+ out.push(asJsonObject(JSON.parse(line)));
1622
+ } catch {
1623
+ }
1646
1624
  }
1647
- if (["out of scope", "out scope", "out of scopes", "non goals", "non goal", "nongoals", "exclusions", "exclusion"].includes(normalized)) {
1648
- return "out_of_scope";
1625
+ return out;
1626
+ }
1627
+ function countJsonlLines(file) {
1628
+ if (!fileExists(file)) return 0;
1629
+ return import_node_fs7.default.readFileSync(file, "utf8").split(/\r?\n/).filter(Boolean).length;
1630
+ }
1631
+ function ensureCadreLocalIgnored(root) {
1632
+ const cadreDir = import_node_path13.default.join(root, "cadre");
1633
+ const ignorePath = import_node_path13.default.join(cadreDir, ".gitignore");
1634
+ import_node_fs7.default.mkdirSync(cadreDir, { recursive: true });
1635
+ const current = fileExists(ignorePath) ? import_node_fs7.default.readFileSync(ignorePath, "utf8") : "";
1636
+ const lines = current.split(/\r?\n/).filter(Boolean);
1637
+ if (!lines.includes("/local/")) {
1638
+ lines.push("/local/");
1639
+ import_node_fs7.default.writeFileSync(ignorePath, `${lines.join("\n")}
1640
+ `);
1641
+ return import_node_path13.default.relative(root, ignorePath);
1649
1642
  }
1650
1643
  return null;
1651
1644
  }
1652
- function cleanSpecItem(value) {
1653
- const heading = compactLines(asOptionalString(value.heading || value.title || value.name) || "", 240);
1654
- const body = normalizedText(asOptionalString(value.body || value.description || value.text) || "").trim();
1655
- if (!heading && !body) return null;
1656
- return { heading: heading || "Item", body };
1645
+ function ensureNativeState(root) {
1646
+ const paths = nativeStatePaths(root);
1647
+ for (const dir of [
1648
+ asOptionalString(paths.formulas),
1649
+ asOptionalString(paths.operations),
1650
+ asOptionalString(paths.messages),
1651
+ asOptionalString(paths.wisps)
1652
+ ].filter((value) => Boolean(value))) {
1653
+ import_node_fs7.default.mkdirSync(dir, { recursive: true });
1654
+ }
1655
+ const ignore_path = ensureCadreLocalIgnored(root);
1656
+ return {
1657
+ ok: true,
1658
+ paths: {
1659
+ events: import_node_path13.default.relative(root, String(paths.events)),
1660
+ formulas: import_node_path13.default.relative(root, String(paths.formulas)),
1661
+ operations: import_node_path13.default.relative(root, String(paths.operations)),
1662
+ messages: import_node_path13.default.relative(root, String(paths.messages)),
1663
+ wisps: import_node_path13.default.relative(root, String(paths.wisps))
1664
+ },
1665
+ ignore_path
1666
+ };
1657
1667
  }
1658
- function parseSpecListItem(line) {
1659
- const text = line.trim();
1660
- const bold = text.match(/^\*\*(.+?)\*\*:?\s*(.*)$/);
1661
- const keyed = !bold ? text.match(/^(.+?)\s*(?::|\s+-\s+|\s+--\s+|\s+—\s+)\s*(.+)$/) : null;
1662
- if (bold?.[1]) return { heading: bold[1].trim(), body: (bold[2] || "").trim() };
1663
- if (keyed?.[1]) return { heading: keyed[1].trim(), body: (keyed[2] || "").trim() };
1664
- return { heading: text, body: "" };
1668
+ function appendCadreEvent(root, event) {
1669
+ ensureNativeState(root);
1670
+ const recorded_at = asOptionalString(event.recorded_at) || utcNow();
1671
+ const kind = asOptionalString(event.kind || event.type) || "event";
1672
+ const actor = asOptionalString(event.actor) || gitIdentity(root) || null;
1673
+ const entry = {
1674
+ ...event,
1675
+ version: 1,
1676
+ schema: "cadre.event.v1",
1677
+ id: asOptionalString(event.id) || nativeId("evt", { ...event, recorded_at, kind }),
1678
+ kind,
1679
+ recorded_at,
1680
+ actor
1681
+ };
1682
+ const file = import_node_path13.default.join(root, "cadre", "events.jsonl");
1683
+ appendJsonl(file, entry);
1684
+ return { ok: true, path: import_node_path13.default.relative(root, file), event: entry };
1665
1685
  }
1666
- function parseSpecListItems(body, fallbackHeading) {
1667
- const lines = normalizedText(body).split("\n");
1668
- const items = [];
1669
- let current = null;
1670
- const pushCurrent = () => {
1671
- if (!current) return;
1672
- const cleaned = cleanSpecItem(current);
1673
- if (cleaned) items.push(cleaned);
1674
- current = null;
1686
+ function readCadreEvents(root, limit = 50) {
1687
+ return readJsonlObjects(import_node_path13.default.join(root, "cadre", "events.jsonl"), limit);
1688
+ }
1689
+ function appendCadreMessage(root, box, message) {
1690
+ ensureNativeState(root);
1691
+ const recorded_at = asOptionalString(message.recorded_at) || utcNow();
1692
+ const direction = box === "outbox" ? "outgoing" : "incoming";
1693
+ const entry = {
1694
+ ...message,
1695
+ version: 1,
1696
+ schema: "cadre.message.v1",
1697
+ id: asOptionalString(message.id) || nativeId(`msg_${box}`, { ...message, recorded_at, direction }),
1698
+ box,
1699
+ direction,
1700
+ status: asOptionalString(message.status) || "pending",
1701
+ recorded_at,
1702
+ from: asOptionalString(message.from) || gitIdentity(root) || null
1675
1703
  };
1676
- for (const rawLine of lines) {
1677
- const bullet = rawLine.match(/^\s*(?:[-*+]|\d+[.)])\s+(.+)$/);
1678
- if (bullet?.[1]) {
1679
- pushCurrent();
1680
- current = parseSpecListItem(bullet[1]);
1681
- continue;
1682
- }
1683
- const text = rawLine.trim();
1684
- if (!text) continue;
1685
- if (!current) {
1686
- current = { heading: fallbackHeading, body: text };
1687
- continue;
1688
- }
1689
- const existing = asOptionalString(current.body) || "";
1690
- current.body = existing ? `${existing}
1691
- ${text}` : text;
1692
- }
1693
- pushCurrent();
1694
- if (items.length > 0) return items;
1695
- const fallbackBody = normalizedText(body).trim();
1696
- return fallbackBody ? [{ heading: fallbackHeading, body: fallbackBody }] : [];
1704
+ const file = import_node_path13.default.join(root, "cadre", "messages", `${box}.jsonl`);
1705
+ appendJsonl(file, entry);
1706
+ return { ok: true, path: import_node_path13.default.relative(root, file), message: entry };
1697
1707
  }
1698
- function specItemsFromRaw(value) {
1699
- return asArray(value).map((entry) => {
1700
- if (typeof entry === "string") return cleanSpecItem({ heading: entry, body: "" });
1701
- return cleanSpecItem(asJsonObject(entry));
1702
- }).filter((entry) => Boolean(entry));
1708
+ function readCadreMessages(root, box, limit = 50) {
1709
+ return readJsonlObjects(import_node_path13.default.join(root, "cadre", "messages", `${box}.jsonl`), limit);
1703
1710
  }
1704
- function specJsonFromText(trackId, text) {
1705
- const parsed = splitMarkdownSections(text || `# Spec: ${trackId}
1706
- `);
1707
- const descriptionParts = [parsed.body].filter(Boolean);
1708
- const functionalRequirements = [];
1709
- const nonFunctionalRequirements = [];
1710
- const acceptanceCriteria = [];
1711
- const outOfScope = [];
1712
- for (const rawSection of parsed.sections) {
1713
- const section = asJsonObject(rawSection);
1714
- const heading = asOptionalString(section.heading) || "";
1715
- const body = asOptionalString(section.body) || "";
1716
- const kind = specSectionKind(heading);
1717
- if (kind === "description") descriptionParts.push(body);
1718
- else if (kind === "functional_requirements") functionalRequirements.push(...parseSpecListItems(body, heading));
1719
- else if (kind === "non_functional_requirements") nonFunctionalRequirements.push(...parseSpecListItems(body, heading));
1720
- else if (kind === "acceptance_criteria") acceptanceCriteria.push(...parseSpecListItems(body, heading));
1721
- else if (kind === "out_of_scope") outOfScope.push(...parseSpecListItems(body, heading));
1722
- else if (body) descriptionParts.push(`### ${heading}
1723
-
1724
- ${body}`);
1725
- }
1711
+ function nativeStateSummary(root) {
1712
+ const paths = nativeStatePaths(root);
1726
1713
  return {
1727
- version: 1,
1728
- schema: "cadre.spec.v1",
1729
- kind: "spec",
1730
- track_id: trackId,
1731
- title: parsed.title,
1732
- description: descriptionParts.join("\n\n").trim(),
1733
- functional_requirements: functionalRequirements,
1734
- non_functional_requirements: nonFunctionalRequirements,
1735
- acceptance_criteria: acceptanceCriteria,
1736
- out_of_scope: outOfScope,
1737
- updated_at: utcNow()
1714
+ ok: true,
1715
+ paths: {
1716
+ events: import_node_path13.default.relative(root, String(paths.events)),
1717
+ inbox: import_node_path13.default.relative(root, String(paths.inbox)),
1718
+ outbox: import_node_path13.default.relative(root, String(paths.outbox)),
1719
+ operations: import_node_path13.default.relative(root, String(paths.operations)),
1720
+ formulas: import_node_path13.default.relative(root, String(paths.formulas)),
1721
+ wisps: import_node_path13.default.relative(root, String(paths.wisps))
1722
+ },
1723
+ counts: {
1724
+ events: countJsonlLines(String(paths.events)),
1725
+ inbox: countJsonlLines(String(paths.inbox)),
1726
+ outbox: countJsonlLines(String(paths.outbox))
1727
+ },
1728
+ recent_events: readCadreEvents(root, 8),
1729
+ recent_inbox: readCadreMessages(root, "inbox", 8),
1730
+ recent_outbox: readCadreMessages(root, "outbox", 8)
1738
1731
  };
1739
1732
  }
1740
- function normalizedSpecFromRaw(raw) {
1741
- if (asOptionalString(raw.description) || asArray(raw.functional_requirements).length > 0 || asArray(raw.non_functional_requirements).length > 0 || asArray(raw.acceptance_criteria).length > 0 || asArray(raw.out_of_scope).length > 0) {
1733
+
1734
+ // src/core/application/runtime/commit-trace.ts
1735
+ var import_node_path14 = __toESM(require("node:path"));
1736
+ var DEFAULT_NOTES_REF = "refs/notes/cadre";
1737
+ function configured(root) {
1738
+ return fileExists(import_node_path14.default.join(root, "cadre", "config.json"));
1739
+ }
1740
+ function traceability(root) {
1741
+ return asJsonObject(loadTopology(root).config.traceability);
1742
+ }
1743
+ function traceEnabled(root, kind, args, force = false) {
1744
+ const mode = asOptionalString(args.commitMode || args.commit_mode)?.toLowerCase();
1745
+ if (["off", "none", "manual", "false"].includes(mode || "")) return false;
1746
+ if (force) return true;
1747
+ if (!configured(root)) return false;
1748
+ const trace = traceability(root);
1749
+ if (Object.keys(trace).length === 0) return false;
1750
+ if (trace.enabled === false) return false;
1751
+ if (kind === "product") return trace.auto_product_commits !== false;
1752
+ if (kind === "control") return trace.auto_control_commits !== false;
1753
+ return trace.auto_automation_commits !== false;
1754
+ }
1755
+ function notesRef(root, args = {}) {
1756
+ return asOptionalString(args.notesRef || args.notes_ref) || asOptionalString(traceability(root).notes_ref) || DEFAULT_NOTES_REF;
1757
+ }
1758
+ function notesEnabled(root) {
1759
+ const trace = traceability(root);
1760
+ return trace.git_notes !== false && trace.notes !== false;
1761
+ }
1762
+ function notesPushEnabled(root) {
1763
+ return traceability(root).push_notes !== false;
1764
+ }
1765
+ function statusEntries(cwd) {
1766
+ const result = runCommand("git", ["status", "--porcelain", "--untracked-files=all"], { cwd });
1767
+ if (!result.ok) return {};
1768
+ const entries = {};
1769
+ for (const line of result.stdout.split(/\r?\n/)) {
1770
+ if (!line.trim()) continue;
1771
+ const status = line.slice(0, 2);
1772
+ const rawPath = line.slice(3).trim();
1773
+ const file = rawPath.includes(" -> ") ? rawPath.split(" -> ").pop() || "" : rawPath;
1774
+ const normalized = file.replace(/^"|"$/g, "");
1775
+ if (normalized) entries[normalized] = status;
1776
+ }
1777
+ return entries;
1778
+ }
1779
+ function beginTrace(cwd) {
1780
+ const gitRoot = runCommand("git", ["rev-parse", "--show-toplevel"], { cwd });
1781
+ if (!gitRoot.ok) {
1742
1782
  return {
1743
- ...raw,
1744
- description: asOptionalString(raw.description || raw.summary) || "",
1745
- functional_requirements: specItemsFromRaw(raw.functional_requirements),
1746
- non_functional_requirements: specItemsFromRaw(raw.non_functional_requirements),
1747
- acceptance_criteria: specItemsFromRaw(raw.acceptance_criteria),
1748
- out_of_scope: specItemsFromRaw(raw.out_of_scope)
1783
+ ok: true,
1784
+ cwd,
1785
+ entries: {},
1786
+ dirty_files: [],
1787
+ skipped: true,
1788
+ reason: "not a git repository"
1749
1789
  };
1750
1790
  }
1751
- const title = asOptionalString(raw.title) || `Spec: ${asOptionalString(raw.track_id) || "track"}`;
1752
- const parts = [`# ${title}`, ""];
1753
- const summary = asOptionalString(raw.summary);
1754
- if (summary) parts.push(summary, "");
1755
- for (const rawSection of asArray(raw.sections)) {
1756
- const section = asJsonObject(rawSection);
1757
- const heading = asOptionalString(section.heading);
1758
- const body = asOptionalString(section.body);
1759
- if (heading && body) parts.push(`## ${heading}`, "", body, "");
1760
- }
1761
- return specJsonFromText(asOptionalString(raw.track_id) || "track", parts.join("\n"));
1791
+ const root = gitRoot.stdout.trim() || cwd;
1792
+ const entries = statusEntries(root);
1793
+ return {
1794
+ ok: true,
1795
+ cwd: root,
1796
+ git_root: root,
1797
+ entries,
1798
+ dirty_files: Object.keys(entries).sort()
1799
+ };
1762
1800
  }
1763
- function appendSpecItemSection(parts, heading, items) {
1764
- if (items.length === 0) return;
1765
- parts.push(`## ${heading}`, "");
1766
- for (const item of items) {
1767
- const itemHeading = asOptionalString(item.heading) || "Item";
1768
- const body = normalizedText(asOptionalString(item.body) || "").trim();
1769
- if (!body) {
1770
- parts.push(`- ${itemHeading}`);
1771
- continue;
1772
- }
1773
- if (!body.includes("\n")) {
1774
- parts.push(`- **${itemHeading}**: ${body}`);
1775
- continue;
1776
- }
1777
- parts.push(`- **${itemHeading}**`);
1778
- for (const line of body.split("\n")) {
1779
- parts.push(line.trim() ? ` ${line}` : "");
1780
- }
1781
- }
1782
- parts.push("");
1801
+ function isControlPlaneFile2(file) {
1802
+ const normalized = file.replace(/\\/g, "/").replace(/^\.\//, "");
1803
+ if (normalized.startsWith("cadre/local/")) return false;
1804
+ if (normalized.startsWith("cadre/.locks/")) return false;
1805
+ if (normalized.includes(".tmp")) return false;
1806
+ return normalized.startsWith("cadre/") || normalized === ".gitattributes" || normalized === ".gitmodules" || normalized === ".gitlab-ci.yml" || normalized === "cadre-merge-train.gitlab-ci.yml" || normalized.startsWith(".github/workflows/cadre-");
1783
1807
  }
1784
- function renderSpecMarkdown(raw) {
1785
- const spec = normalizedSpecFromRaw(raw);
1786
- const title = asOptionalString(spec.title) || `Spec: ${asOptionalString(spec.track_id) || "track"}`;
1787
- const parts = [`# ${title}`, ""];
1788
- const description = asOptionalString(spec.description);
1789
- if (description) parts.push("## Description", "", description, "");
1790
- appendSpecItemSection(parts, "Functional Requirements", specItemsFromRaw(spec.functional_requirements));
1791
- appendSpecItemSection(parts, "Non-Functional Requirements", specItemsFromRaw(spec.non_functional_requirements));
1792
- appendSpecItemSection(parts, "Acceptance Criteria", specItemsFromRaw(spec.acceptance_criteria));
1793
- appendSpecItemSection(parts, "Out Of Scope", specItemsFromRaw(spec.out_of_scope));
1794
- return normalizedText(parts.join("\n"));
1808
+ function changedAfter(before, after) {
1809
+ const beforeEntries = asJsonObject(before?.entries);
1810
+ return Object.entries(after).filter(([file, status]) => beforeEntries[file] !== status).map(([file]) => file).sort();
1795
1811
  }
1796
- function renderStyleGuideMarkdown(raw) {
1797
- const id = asOptionalString(raw.id) || "styleguide";
1798
- const title = asOptionalString(raw.title) || id;
1799
- const parts = [`# ${title}`, ""];
1800
- const summary = asOptionalString(raw.summary);
1801
- if (summary) parts.push(summary, "");
1802
- const rules = asArray(raw.rules);
1803
- if (rules.length > 0) {
1804
- parts.push("## Rules", "");
1805
- for (const rawRule of rules) {
1806
- const rule = asJsonObject(rawRule);
1807
- const severity = asOptionalString(rule.severity);
1808
- const suffix = severity ? ` (${severity})` : "";
1809
- parts.push(`- ${asOptionalString(rule.summary) || asOptionalString(rule.id) || "Rule"}${suffix}`);
1810
- const rationale = asOptionalString(rule.rationale);
1811
- if (rationale) parts.push(` Rationale: ${rationale}`);
1812
- }
1813
- parts.push("");
1814
- }
1815
- for (const rawSection of asArray(raw.sections)) {
1816
- const section = asJsonObject(rawSection);
1817
- const heading = asOptionalString(section.heading);
1818
- const body = asOptionalString(section.body);
1819
- if (heading && body) parts.push(`## ${heading}`, "", body, "");
1820
- }
1821
- return normalizedText(parts.join("\n"));
1812
+ function uniqueFiles(files) {
1813
+ return Array.from(new Set(files.map((file) => file.replace(/\\/g, "/").replace(/^\.\//, "")).filter(Boolean))).sort();
1822
1814
  }
1823
-
1824
- // src/core/application/runtime/beads-config.ts
1825
- var import_node_path13 = __toESM(require("node:path"));
1826
- var MAX_PREFIX_WORDS = 2;
1827
- function firstString(...values) {
1828
- for (const value of values) {
1829
- if (typeof value === "string") return value;
1830
- }
1831
- return void 0;
1832
- }
1833
- function words(value) {
1834
- return String(value || "").trim().split(/[\s_-]+/).map((word) => word.trim()).filter(Boolean);
1835
- }
1836
- function normalizeBeadsEpicPrefix(value) {
1837
- const raw = asOptionalString(value);
1838
- if (raw === void 0) return "";
1839
- const trimmed = raw.trim();
1840
- if (!trimmed) return "";
1841
- return safeName(trimmed.toLowerCase()).replace(/_+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
1842
- }
1843
- function prefixError(value) {
1844
- const raw = asOptionalString(value);
1845
- if (raw === void 0 || !raw.trim()) return "beadsEpicPrefix is required";
1846
- if (words(raw).length > MAX_PREFIX_WORDS) return "beadsEpicPrefix must be at most two words";
1847
- return null;
1815
+ function conventionalSubject(type, scope, subject) {
1816
+ const cleanType = type.replace(/[^a-z0-9-]/gi, "").toLowerCase() || "cadre";
1817
+ const cleanScope = scope.replace(/[^a-z0-9_.-]/gi, "-").toLowerCase() || "trace";
1818
+ return `${cleanType}(${cleanScope}): ${subject.trim() || "record trace"}`;
1848
1819
  }
1849
- function firstWordsSlug(value, fallback) {
1850
- const selected = words(value).slice(0, MAX_PREFIX_WORDS).join(" ") || fallback;
1851
- return normalizeBeadsEpicPrefix(selected);
1820
+ function messageBody(body, footers) {
1821
+ const footerText = Object.entries(footers).filter((entry) => Boolean(entry[1])).map(([key, value]) => `${key}: ${value}`).join("\n");
1822
+ return [body?.trim() || "", footerText].filter(Boolean).join("\n\n");
1852
1823
  }
1853
- function productTitle(args = {}) {
1854
- const product = asJsonObject(args.product);
1855
- return firstString(product.title, product.name, product.id);
1824
+ function commandOk(result) {
1825
+ return result.ok === true;
1856
1826
  }
1857
- function projectBeadsEpicPrefix(root) {
1858
- return firstWordsSlug(import_node_path13.default.basename(root), "project");
1859
- }
1860
- function productBeadsEpicPrefix(root, args = {}) {
1861
- return firstWordsSlug(productTitle(args), projectBeadsEpicPrefix(root));
1862
- }
1863
- function exampleFor(prefix) {
1864
- return `${prefix}-<track_id>`;
1865
- }
1866
- function recommendation(label, epicPrefix, reason, recommended = false) {
1867
- return {
1868
- label,
1869
- epic_prefix: epicPrefix,
1870
- example: exampleFor(epicPrefix),
1871
- recommended,
1872
- reason
1873
- };
1874
- }
1875
- function beadsPrefixRecommendations(root, args = {}) {
1876
- const seen = /* @__PURE__ */ new Set();
1877
- const out = [];
1878
- const add = (entry) => {
1879
- const prefix = asOptionalString(entry.epic_prefix);
1880
- if (!prefix || seen.has(prefix)) return;
1881
- seen.add(prefix);
1882
- out.push(entry);
1883
- };
1884
- const projectPrefix = projectBeadsEpicPrefix(root);
1885
- add(recommendation("Project", projectPrefix, "Derived from the project directory.", true));
1886
- const productPrefix = productBeadsEpicPrefix(root, args);
1887
- add(recommendation("Product", productPrefix, "Derived from the product title."));
1888
- return out;
1889
- }
1890
- function configuredPrefix(args) {
1891
- const rawArgs = args;
1892
- const inlineConfig = {
1893
- ...asJsonObject(rawArgs.beadsConfig),
1894
- ...asJsonObject(rawArgs.beads_config)
1895
- };
1896
- return firstString(rawArgs.beadsEpicPrefix, rawArgs.beads_epic_prefix, inlineConfig.epicPrefix, inlineConfig.epic_prefix);
1897
- }
1898
- function resolveBeadsEpicPrefix(root, args = {}) {
1899
- const recommendations = beadsPrefixRecommendations(root, args);
1900
- const directPrefix = configuredPrefix(args);
1901
- if (directPrefix !== void 0) {
1902
- const error = prefixError(directPrefix);
1903
- if (error) {
1904
- return {
1905
- selected: false,
1906
- required: true,
1907
- epic_prefix: "",
1908
- source: "invalid_argument",
1909
- example: exampleFor("<prefix>"),
1910
- max_words: MAX_PREFIX_WORDS,
1911
- missing_payload: ["beadsEpicPrefix"],
1912
- recommendations,
1913
- error
1914
- };
1915
- }
1916
- const epicPrefix = normalizeBeadsEpicPrefix(directPrefix);
1917
- return {
1918
- selected: true,
1919
- required: false,
1920
- epic_prefix: epicPrefix,
1921
- source: "arguments",
1922
- example: exampleFor(epicPrefix),
1923
- max_words: MAX_PREFIX_WORDS,
1924
- missing_payload: [],
1925
- recommendations
1926
- };
1927
- }
1928
- const diskConfig = readJson(import_node_path13.default.join(root, "cadre", "beads.json"), {});
1929
- const diskPrefix = firstString(diskConfig.epicPrefix, diskConfig.epic_prefix);
1930
- if (diskPrefix !== void 0) {
1931
- const error = prefixError(diskPrefix);
1932
- if (error) {
1933
- return {
1934
- selected: false,
1935
- required: true,
1936
- epic_prefix: asOptionalString(recommendations[0]?.epic_prefix) || projectBeadsEpicPrefix(root),
1937
- source: "invalid_cadre/beads.json",
1938
- example: exampleFor(asOptionalString(recommendations[0]?.epic_prefix) || projectBeadsEpicPrefix(root)),
1939
- max_words: MAX_PREFIX_WORDS,
1940
- missing_payload: ["beadsEpicPrefix"],
1941
- recommendations,
1942
- error
1943
- };
1944
- }
1945
- const epicPrefix = normalizeBeadsEpicPrefix(diskPrefix);
1946
- return {
1947
- selected: true,
1948
- required: false,
1949
- epic_prefix: epicPrefix,
1950
- source: "cadre/beads.json",
1951
- example: exampleFor(epicPrefix),
1952
- max_words: MAX_PREFIX_WORDS,
1953
- missing_payload: [],
1954
- recommendations
1955
- };
1956
- }
1957
- const defaultPrefix = asOptionalString(recommendations[0]?.epic_prefix) || projectBeadsEpicPrefix(root);
1958
- return {
1959
- selected: false,
1960
- required: true,
1961
- epic_prefix: defaultPrefix,
1962
- source: "setup_required",
1963
- example: exampleFor(defaultPrefix),
1964
- max_words: MAX_PREFIX_WORDS,
1965
- missing_payload: ["beadsEpicPrefix"],
1966
- recommendations
1967
- };
1968
- }
1969
- function beadsEpicIdForTrack(root, trackId, args = {}) {
1970
- const prefix = resolveBeadsEpicPrefix(root, args).epic_prefix;
1971
- return prefix ? `${prefix}-${trackId}` : trackId;
1972
- }
1973
-
1974
- // src/core/application/runtime/beads-tree.ts
1975
- function extractBeadsId(json, fallback = null) {
1976
- if (!isRecord(json)) return fallback;
1977
- for (const key of ["id", "issue_id", "issueId"]) {
1978
- const value = json[key];
1979
- if (typeof value === "string" && value.trim()) return value.trim();
1980
- }
1981
- const issue = json.issue;
1982
- if (isRecord(issue) && typeof issue.id === "string" && issue.id.trim()) return issue.id.trim();
1983
- return fallback;
1984
- }
1985
- function extractAssignee(json) {
1986
- if (Array.isArray(json)) {
1987
- for (const item of json) {
1988
- const nested = extractAssignee(item);
1989
- if (nested) return nested;
1990
- }
1991
- return null;
1992
- }
1993
- if (!isRecord(json)) return null;
1994
- const direct = json.assignee || json.assigned_to || json.owner || json.claimed_by;
1995
- if (typeof direct === "string" && direct.trim()) return direct.trim();
1996
- for (const key of ["issue", "task", "epic", "data"]) {
1997
- const nested = extractAssignee(json[key]);
1998
- if (nested) return nested;
1999
- }
2000
- return null;
2001
- }
2002
- function parseCommandJson(result) {
2003
- try {
2004
- return JSON.parse(asString(result.stdout) || "null");
2005
- } catch {
2006
- return null;
2007
- }
2008
- }
2009
- function beadsCommandPlanEntry(args) {
2010
- return { command: ["bd", ...args].join(" "), args };
2011
- }
2012
- function compactLines(value, limit = 1200) {
2013
- return String(value || "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean).join("\n").slice(0, limit);
1827
+ function commitSha(cwd) {
1828
+ const result = runCommand("git", ["rev-parse", "HEAD"], { cwd });
1829
+ return result.ok ? result.stdout.trim() || null : null;
2014
1830
  }
2015
- function specContextFromJson(raw) {
2016
- const spec = normalizeSpecJson(asOptionalString(asJsonObject(raw).track_id) || "track", raw);
2017
- const overview = compactLines([
2018
- asOptionalString(spec.description),
2019
- ...specItemsFromRaw(spec.functional_requirements).map((item) => `${asOptionalString(item.heading)}: ${asOptionalString(item.body)}`),
2020
- ...specItemsFromRaw(spec.non_functional_requirements).map((item) => `${asOptionalString(item.heading)}: ${asOptionalString(item.body)}`)
2021
- ].filter(Boolean).join("\n"), 1400);
2022
- const acceptance = compactLines(specItemsFromRaw(spec.acceptance_criteria).map((item) => `${asOptionalString(item.heading)}: ${asOptionalString(item.body)}`).filter(Boolean).join("\n"), 1e3);
2023
- return { overview, acceptance };
2024
- }
2025
- function taskDesignText(track, phase, task, specContext) {
2026
- return compactLines([
2027
- `Track: ${track.track_id}`,
2028
- `Phase: ${phase.title}`,
2029
- `Task: ${task.title}`,
2030
- task.files && task.files.length ? `Files: ${task.files.join(", ")}` : null,
2031
- task.depends && task.depends.length ? `Depends on: ${task.depends.join(", ")}` : null,
2032
- task.repo ? `Repo: ${task.repo}` : null,
2033
- specContext.overview ? `Spec context: ${specContext.overview}` : null
2034
- ].filter(Boolean).join("\n"), 1800);
2035
- }
2036
- function taskAcceptanceText(task, specContext) {
2037
- return compactLines([
2038
- `Complete when this task is implemented, tested, and committed.`,
2039
- task.files && task.files.length ? `Owned files changed only as needed: ${task.files.join(", ")}` : null,
2040
- specContext.acceptance ? `Track acceptance context: ${specContext.acceptance}` : null
2041
- ].filter(Boolean).join("\n"), 1600);
2042
- }
2043
- function addCreateContext(args, design, acceptance) {
2044
- if (design) args.push("--design", design);
2045
- if (acceptance) args.push("--acceptance", acceptance);
2046
- return args;
2047
- }
2048
- function createBeadsTree(root, args = {}) {
2049
- const markdownError = markdownPayloadError(args);
2050
- if (markdownError) return markdownError;
2051
- const trackId = args.trackId || args.track_id;
2052
- if (!trackId) return { ok: false, error: "trackId is required" };
2053
- const dryRun = args.dryRun === true;
2054
- const diskTrack = findTrack(root, trackId);
2055
- if (!diskTrack && !dryRun) return { ok: false, error: `Track not found: ${trackId}` };
2056
- if (!diskTrack && dryRun && !args.plan) {
2057
- return { ok: false, error: `Track not found: ${trackId}; dryRun without track files requires plan` };
2058
- }
2059
- const draftMetadata = {
2060
- track_id: trackId,
2061
- type: "feature",
2062
- status: "new",
2063
- priority: "medium",
2064
- description: trackId,
2065
- git_branch: `track/${trackId}`,
2066
- ...args.metadata && typeof args.metadata === "object" ? args.metadata : {}
2067
- };
2068
- const track = diskTrack || {
2069
- track_id: trackId,
2070
- dir: import_node_path14.default.join(root, "cadre", "tracks", safeName(trackId)),
2071
- metadata_path: import_node_path14.default.join(root, "cadre", "tracks", safeName(trackId), "metadata.json"),
2072
- plan_path: import_node_path14.default.join(root, "cadre", "tracks", safeName(trackId), "plan.md"),
2073
- spec_path: import_node_path14.default.join(root, "cadre", "tracks", safeName(trackId), "spec.md"),
2074
- plan_json_path: import_node_path14.default.join(root, "cadre", "tracks", safeName(trackId), "plan.json"),
2075
- spec_json_path: import_node_path14.default.join(root, "cadre", "tracks", safeName(trackId), "spec.json"),
2076
- learnings_jsonl_path: import_node_path14.default.join(root, "cadre", "tracks", safeName(trackId), "learnings.jsonl"),
2077
- handoff_json_path: import_node_path14.default.join(root, "cadre", "tracks", safeName(trackId), "handoff.json"),
2078
- metadata: draftMetadata
2079
- };
2080
- if (!dryRun && !commandExists("bd", root)) {
2081
- return { ok: false, available: false, reason: "Beads CLI (bd) is not installed or not on PATH" };
2082
- }
2083
- const identity = args.identity || gitIdentity(root);
2084
- const specJson = args.spec ? normalizeSpecJson(String(trackId), args.spec) : readJson(trackSpecJsonPath(track), null);
2085
- const plan = args.plan ? parsePlanJson(normalizePlanJson(String(trackId), args.plan, specJson)) : parsePlanFile(track.plan_path);
2086
- const specContext = specContextFromJson(specJson);
2087
- const beadsPrefix = resolveBeadsEpicPrefix(root, args);
2088
- if (!beadsPrefix.selected && beadsPrefix.error) {
2089
- return {
2090
- ok: false,
2091
- error: beadsPrefix.error,
2092
- missing_payload: beadsPrefix.missing_payload,
2093
- beads_prefix: beadsPrefix
2094
- };
2095
- }
2096
- const epicId = args.epicId || track.metadata.beads_epic || beadsEpicIdForTrack(root, String(track.track_id), args);
2097
- const commands = [];
2098
- const results = [];
2099
- const beadsTasks = {};
2100
- const runBd = (bdArgs) => {
2101
- commands.push(beadsCommandPlanEntry(bdArgs));
2102
- if (dryRun) {
2103
- const id = bdArgs[0] === "create" && bdArgs.includes("--id") ? epicId : `dry-${commands.length}`;
2104
- return { ok: true, status: 0, stdout: JSON.stringify({ id }), stderr: "", command: "bd", args: bdArgs };
2105
- }
2106
- const result = runCommand("bd", bdArgs, { cwd: root, maxBuffer: 10 * 1024 * 1024 });
2107
- results.push(result);
2108
- return result;
2109
- };
2110
- const showEpic = dryRun ? { ok: false } : runCommand("bd", ["show", epicId, "--json"], { cwd: root, maxBuffer: 10 * 1024 * 1024 });
2111
- if (showEpic.ok) {
2112
- if (track.metadata.beads_epic === epicId && track.metadata.beads_tasks && Object.keys(track.metadata.beads_tasks).length > 0) {
2113
- return {
2114
- ok: true,
2115
- available: true,
2116
- existing: true,
2117
- dry_run: false,
2118
- track_id: track.track_id,
2119
- beads_epic_prefix: beadsPrefix.epic_prefix,
2120
- beads_epic: epicId,
2121
- beads_tasks: track.metadata.beads_tasks,
2122
- commands,
2123
- results,
2124
- metadata_patch: {
2125
- beads_epic: epicId,
2126
- beads_tasks: track.metadata.beads_tasks
2127
- }
2128
- };
2129
- }
1831
+ function writeNote(cwd, ref, sha, note) {
1832
+ return runCommand("git", ["notes", "--ref", ref, "add", "-f", "-m", `${JSON.stringify(note, null, 2)}
1833
+ `, sha], { cwd });
1834
+ }
1835
+ function commitTrace(root, args, options) {
1836
+ if (!traceEnabled(root, options.kind, args, options.forceEnabled === true)) {
1837
+ return { ok: true, skipped: true, reason: "traceability disabled or unconfigured" };
1838
+ }
1839
+ const cwd = options.cwd || root;
1840
+ const snapshot = options.before || beginTrace(cwd);
1841
+ if (snapshot.skipped) return { ok: true, skipped: true, reason: snapshot.reason || "git unavailable" };
1842
+ const gitRoot = asOptionalString(snapshot.git_root) || cwd;
1843
+ const after = statusEntries(gitRoot);
1844
+ const requestedFiles = options.files ? uniqueFiles(options.files) : changedAfter(snapshot, after).filter((file) => options.kind === "product" ? !isControlPlaneFile2(file) : isControlPlaneFile2(file));
1845
+ const files = requestedFiles.filter((file) => after[file]);
1846
+ if (files.length === 0) return { ok: true, skipped: true, reason: "no changed files to commit" };
1847
+ const beforeEntries = asJsonObject(snapshot.entries);
1848
+ const preexisting = files.filter((file) => beforeEntries[file]);
1849
+ const allowDirty = options.allowDirty === true || args.allowDirty === true || args.allow_dirty === true;
1850
+ if (preexisting.length > 0 && !allowDirty) {
2130
1851
  return {
2131
1852
  ok: false,
2132
- available: true,
2133
- existing: true,
2134
- reason: `Beads epic ${epicId} already exists but metadata.beads_tasks is missing; reconcile existing children before creating new ones`,
2135
- commands,
2136
- results
1853
+ stage: "preexisting_dirty_files",
1854
+ reason: "Refusing to commit files that were dirty before this packet",
1855
+ files,
1856
+ preexisting_dirty_files: preexisting
2137
1857
  };
2138
- } else {
2139
- const epicArgs = addCreateContext([
2140
- "create",
2141
- `${track.track_id}: ${track.metadata.description || track.metadata.name || track.track_id}`,
2142
- "--id",
2143
- epicId,
2144
- "-t",
2145
- "epic",
2146
- "-p",
2147
- String(priorityRank(track.metadata.priority))
2148
- ], specContext.overview, specContext.acceptance);
2149
- epicArgs.push("--json");
2150
- if (identity) epicArgs.splice(epicArgs.length - 1, 0, "--assignee", identity);
2151
- const epicResult = runBd(epicArgs);
2152
- if (!epicResult.ok) return { ok: false, available: true, stage: "create_epic", commands, results };
2153
- }
2154
- const phaseIds = {};
2155
- for (const phase of plan.phases) {
2156
- const phaseKey = `phase${phase.phase_index}`;
2157
- const phaseResult = runBd(addCreateContext(
2158
- ["create", phase.title, "-t", "task", "--parent", epicId, "--labels", "cadre:phase"],
2159
- `Phase for Cadre track ${track.track_id}: ${phase.title}`,
2160
- `All tasks in this phase are complete or intentionally skipped.`
2161
- ).concat("--json"));
2162
- if (!phaseResult.ok) return { ok: false, available: true, stage: "create_phase", phase: phaseKey, commands, results };
2163
- const phaseId = extractBeadsId(parseCommandJson(phaseResult), dryRun ? `dry-${phaseKey}` : null);
2164
- if (!phaseId) return { ok: false, available: true, stage: "parse_phase_id", phase: phaseKey, commands, results };
2165
- phaseIds[phaseKey] = phaseId;
2166
- beadsTasks[phaseKey] = phaseId;
2167
- for (const task of phase.tasks) {
2168
- const taskKey = task.task_key || `phase${phase.phase_index}_task${task.task_index}`;
2169
- const taskResult = runBd(addCreateContext([
2170
- "create",
2171
- task.title,
2172
- "-t",
2173
- "task",
2174
- "--parent",
2175
- phaseId,
2176
- "--labels",
2177
- "cadre:task"
2178
- ], taskDesignText(track, phase, task, specContext), taskAcceptanceText(task, specContext)).concat("--json"));
2179
- if (!taskResult.ok) return { ok: false, available: true, stage: "create_task", task: taskKey, commands, results };
2180
- const taskId = extractBeadsId(parseCommandJson(taskResult), dryRun ? `dry-${taskKey}` : null);
2181
- if (!taskId) return { ok: false, available: true, stage: "parse_task_id", task: taskKey, commands, results };
2182
- beadsTasks[taskKey] = taskId;
2183
- }
2184
- }
2185
- for (const phase of plan.phases) {
2186
- const phaseKey = `phase${phase.phase_index}`;
2187
- const hasExplicitPhaseDepends = Object.prototype.hasOwnProperty.call(phase.annotations || {}, "depends");
2188
- if (!hasExplicitPhaseDepends && phase.phase_index > 1) {
2189
- const previousPhaseId = phaseIds[`phase${phase.phase_index - 1}`];
2190
- const currentPhaseId = phaseIds[phaseKey];
2191
- if (currentPhaseId && previousPhaseId) runBd(["dep", "add", currentPhaseId, previousPhaseId, "--json"]);
2192
- } else if (phase.annotations.depends) {
2193
- for (const dep of asString(phase.annotations.depends).split(",").map((item) => item.trim()).filter(Boolean)) {
2194
- const currentPhaseId = phaseIds[phaseKey];
2195
- const dependencyPhaseId = phaseIds[dep];
2196
- if (currentPhaseId && dependencyPhaseId) runBd(["dep", "add", currentPhaseId, dependencyPhaseId, "--json"]);
2197
- }
2198
- }
2199
- const execution = phase.annotations.execution || "sequential";
2200
- for (const task of phase.tasks) {
2201
- const taskKey = task.task_key || `phase${phase.phase_index}_task${task.task_index}`;
2202
- if (execution !== "parallel" && task.task_index > 1) {
2203
- const taskId = beadsTasks[taskKey];
2204
- const previousTask = phase.tasks.find((candidate) => candidate.task_index === task.task_index - 1);
2205
- const previousTaskKey = previousTask?.task_key || `phase${phase.phase_index}_task${task.task_index - 1}`;
2206
- const previousTaskId = beadsTasks[previousTaskKey];
2207
- if (taskId && previousTaskId) runBd(["dep", "add", taskId, previousTaskId, "--json"]);
2208
- }
2209
- if (execution === "parallel") {
2210
- for (const dep of task.depends || []) {
2211
- const taskDep = dep.match(/^task(\d+)$/);
2212
- const dependencyTask = taskDep ? phase.tasks.find((candidate) => candidate.task_index === Number(taskDep[1])) : null;
2213
- const depKey = dependencyTask?.task_key || (taskDep ? `phase${phase.phase_index}_task${taskDep[1]}` : dep);
2214
- const taskId = beadsTasks[taskKey];
2215
- const dependencyTaskId = beadsTasks[depKey];
2216
- if (taskId && dependencyTaskId) runBd(["dep", "add", taskId, dependencyTaskId, "--json"]);
2217
- }
2218
- }
2219
- }
2220
- }
2221
- runBd([
2222
- "note",
2223
- epicId,
2224
- [
2225
- `TRACK INITIALIZED: ${track.track_id}`,
2226
- `PHASES: ${plan.phases.length}`,
2227
- `BRANCH: ${track.metadata.git_branch || `track/${track.track_id}`}`
2228
- ].join("\n"),
2229
- "--json"
2230
- ]);
2231
- for (const phase of plan.phases) {
2232
- if ((phase.annotations.execution || "sequential") !== "parallel") continue;
2233
- for (const task of phase.tasks) {
2234
- const taskKey = `phase${phase.phase_index}_task${task.task_index}`;
2235
- const taskId = beadsTasks[taskKey];
2236
- if (!taskId) continue;
2237
- runBd([
2238
- "note",
2239
- taskId,
2240
- [
2241
- "PARALLEL_ENABLED: true",
2242
- `FILES_OWNED: ${(task.files || []).join(", ")}`,
2243
- `DEPENDS_ON: ${(task.depends || []).join(", ") || "none"}`,
2244
- task.repo ? `REPO: ${task.repo}` : null
2245
- ].filter(Boolean).join("\n"),
2246
- "--json"
2247
- ]);
2248
- }
2249
- }
2250
- let metadataPatch2 = null;
2251
- if (!dryRun) {
2252
- metadataPatch2 = patchJsonFile(track.metadata_path, (metadata) => ({
2253
- ...metadata,
2254
- beads_epic: epicId,
2255
- beads_tasks: beadsTasks
2256
- }), {
2257
- root,
2258
- lockName: trackLockName(track.track_id)
2259
- });
2260
- if (!metadataPatch2.ok) {
2261
- return { ok: false, available: true, stage: "metadata_patch", commands, results, metadata_patch: metadataPatch2 };
2262
- }
2263
1858
  }
2264
- return {
2265
- ok: true,
2266
- available: true,
2267
- dry_run: dryRun,
2268
- track_id: track.track_id,
2269
- beads_epic_prefix: beadsPrefix.epic_prefix,
2270
- beads_epic: epicId,
2271
- beads_tasks: beadsTasks,
2272
- commands,
2273
- results,
2274
- metadata_patch: {
2275
- beads_epic: epicId,
2276
- beads_tasks: beadsTasks
2277
- },
2278
- metadata_write: metadataPatch2
1859
+ const add = runCommand("git", ["add", "-A", "--", ...files], { cwd: gitRoot });
1860
+ if (!add.ok) return { ok: false, stage: "git_add", files, add };
1861
+ const staged = runCommand("git", ["diff", "--cached", "--quiet"], { cwd: gitRoot });
1862
+ if (staged.status === 0) return { ok: true, skipped: true, reason: "no staged changes", files };
1863
+ const traceId = `trace_${textHash(JSON.stringify({ root, files, now: utcNow(), workflow: options.workflow })).slice(0, 16)}`;
1864
+ const type = asOptionalString(args.commitType || args.commit_type) || options.type || (options.kind === "product" ? "feat" : "cadre");
1865
+ const scope = asOptionalString(args.commitScope || args.commit_scope) || options.scope || options.workflow;
1866
+ const subject = asOptionalString(args.commitSubject || args.commit_subject) || options.subject;
1867
+ const fullSubject = conventionalSubject(type, scope, subject);
1868
+ const body = asOptionalString(args.commitBody || args.commit_body) || options.body;
1869
+ const commitBody = messageBody(body, {
1870
+ "Cadre-Trace-Id": traceId,
1871
+ "Cadre-Workflow": options.workflow,
1872
+ "Cadre-Track": options.trackId || null,
1873
+ "Cadre-Repo": options.repo || null
1874
+ });
1875
+ const commit = runCommand("git", [
1876
+ "-c",
1877
+ "commit.gpgsign=false",
1878
+ "-c",
1879
+ "user.name=Cadre",
1880
+ "-c",
1881
+ "user.email=cadre@local.invalid",
1882
+ "commit",
1883
+ "-m",
1884
+ fullSubject,
1885
+ "-m",
1886
+ commitBody
1887
+ ], { cwd: gitRoot });
1888
+ if (!commit.ok) return { ok: false, stage: "git_commit", files, commit };
1889
+ const sha = commitSha(gitRoot);
1890
+ const notePayload = {
1891
+ version: 1,
1892
+ schema: "cadre.commit_trace.v1",
1893
+ trace_id: traceId,
1894
+ kind: options.kind,
1895
+ workflow: options.workflow,
1896
+ action: options.action || null,
1897
+ track_id: options.trackId || null,
1898
+ repo: options.repo || null,
1899
+ files,
1900
+ commit_sha: sha,
1901
+ recorded_at: utcNow(),
1902
+ ...asJsonObject(options.note)
1903
+ };
1904
+ if (options.kind === "product") notePayload.product_commit_sha = sha;
1905
+ if (options.kind === "control") notePayload.control_commit_sha = sha;
1906
+ const ref = notesRef(root, args);
1907
+ const note = sha && notesEnabled(root) ? writeNote(gitRoot, ref, sha, notePayload) : null;
1908
+ return {
1909
+ ok: !note || commandOk(note),
1910
+ trace_id: traceId,
1911
+ kind: options.kind,
1912
+ workflow: options.workflow,
1913
+ commit_sha: sha,
1914
+ subject: fullSubject,
1915
+ files,
1916
+ notes_ref: ref,
1917
+ note
2279
1918
  };
2280
1919
  }
2281
-
2282
- // src/core/application/runtime/beads-task-write.ts
2283
- function beadsTaskWrite(root, args = {}) {
2284
- if (!commandExists("bd", root)) {
2285
- return { ok: false, available: false, reason: "Beads CLI (bd) is not installed or not on PATH" };
2286
- }
2287
- const op = args.operation;
2288
- const id = args.id || args.taskId || args.issueId;
2289
- const commands = [];
2290
- const runBd = (bdArgs) => {
2291
- const result = runCommand("bd", bdArgs, { cwd: root, maxBuffer: 10 * 1024 * 1024 });
2292
- commands.push(result);
2293
- return result;
2294
- };
2295
- if (op === "ready") {
2296
- const bdArgs = ["ready", "--json"];
2297
- if (args.parent) bdArgs.push("--parent", String(args.parent));
2298
- runBd(bdArgs);
2299
- } else if (op === "list") {
2300
- const bdArgs = ["list", "--json"];
2301
- if (args.status) bdArgs.push("--status", String(args.status));
2302
- if (args.label) bdArgs.push("--label", String(args.label));
2303
- if (args.parent) bdArgs.push("--parent", String(args.parent));
2304
- runBd(bdArgs);
2305
- } else if (op === "show") {
2306
- if (!id) return { ok: false, available: true, error: "id is required for show" };
2307
- const bdArgs = ["show", String(id)];
2308
- if (args.long === true) bdArgs.push("--long");
2309
- bdArgs.push("--json");
2310
- runBd(bdArgs);
2311
- } else if (op === "update") {
2312
- if (!id) return { ok: false, available: true, error: "id is required for update" };
2313
- const bdArgs = ["update", String(id), "--json"];
2314
- if (args.status) bdArgs.push("--status", String(args.status));
2315
- if (Object.prototype.hasOwnProperty.call(args, "assignee")) bdArgs.push("--assignee", String(args.assignee || ""));
2316
- if (args.priority) bdArgs.push("--priority", String(args.priority));
2317
- if (args.notes) bdArgs.push("--notes", String(args.notes));
2318
- runBd(bdArgs);
2319
- } else if (op === "note") {
2320
- if (!id || !args.note) return { ok: false, available: true, error: "id and note are required for note" };
2321
- if (args.dedupKey) {
2322
- const show = runCommand("bd", ["show", String(id), "--long", "--json"], { cwd: root, maxBuffer: 10 * 1024 * 1024 });
2323
- commands.push(show);
2324
- if (show.ok && `${show.stdout}
2325
- ${show.stderr}`.includes(String(args.dedupKey))) {
2326
- return { ok: true, available: true, operation: op, skipped: true, reason: "dedupKey already present", commands, json: parseCommandJson(show) };
2327
- }
2328
- }
2329
- runBd(["note", String(id), String(args.note), "--json"]);
2330
- } else if (op === "close") {
2331
- if (!id) return { ok: false, available: true, error: "id is required for close" };
2332
- const bdArgs = ["close", String(id), "--reason", String(args.reason || "Task completed"), "--json"];
2333
- if (args.continue === true) bdArgs.splice(2, 0, "--continue");
2334
- runBd(bdArgs);
2335
- } else if (op === "label_add" || op === "label_remove") {
2336
- if (!id || !args.label) return { ok: false, available: true, error: "id and label are required for label operations" };
2337
- runBd(["label", op === "label_add" ? "add" : "remove", String(id), String(args.label), "--json"]);
2338
- } else if (op === "dep_add" || op === "dep_remove") {
2339
- if (!id || !args.dependsOn) return { ok: false, available: true, error: "id and dependsOn are required for dependency operations" };
2340
- runBd(["dep", op === "dep_add" ? "add" : "remove", String(id), String(args.dependsOn), "--json"]);
2341
- } else if (op === "create") {
2342
- if (!args.title) return { ok: false, available: true, error: "title is required for create" };
2343
- const bdArgs = ["create", String(args.title), "--json"];
2344
- if (args.id) bdArgs.push("--id", String(args.id));
2345
- if (args.type) bdArgs.push("-t", String(args.type));
2346
- if (args.parent) bdArgs.push("--parent", String(args.parent));
2347
- if (args.priority) bdArgs.push("-p", String(args.priority));
2348
- if (args.deps) bdArgs.push("--deps", String(args.deps));
2349
- if (args.labels) bdArgs.push("--labels", Array.isArray(args.labels) ? args.labels.join(",") : String(args.labels));
2350
- if (args.design) bdArgs.push("--design", String(args.design));
2351
- if (args.acceptance) bdArgs.push("--acceptance", String(args.acceptance));
2352
- if (args.ephemeral === true) bdArgs.push("--ephemeral");
2353
- runBd(bdArgs);
2354
- } else if (op === "mail_send") {
2355
- if (!args.to || !args.subject) return { ok: false, available: true, error: "to and subject are required for mail_send" };
2356
- const bdArgs = ["mail", "send", String(args.to), "--subject", String(args.subject), "--json"];
2357
- if (args.body) bdArgs.push("--body", String(args.body));
2358
- runBd(bdArgs);
2359
- } else if (op === "formula_list") {
2360
- runBd(["formula", "list", "--json"]);
2361
- } else if (op === "formula_show") {
2362
- if (!args.name) return { ok: false, available: true, error: "name is required for formula_show" };
2363
- runBd(["formula", "show", String(args.name), "--json"]);
2364
- } else if (op === "compact") {
2365
- if (args.all === true) runBd(["admin", "compact", "--auto", "--all"]);
2366
- else if (id) runBd(["admin", "compact", "--auto", "--id", String(id)]);
2367
- else return { ok: false, available: true, error: "id or all=true is required for compact" };
2368
- } else if (op === "rules_compact") {
2369
- runBd(["rules", "compact", "--auto"]);
2370
- } else if (op === "dolt_pull" || op === "dolt_push") {
2371
- runBd(["dolt", op === "dolt_pull" ? "pull" : "push"]);
2372
- } else if (op === "sql") {
2373
- if (!args.sql) return { ok: false, available: true, error: "sql is required for sql" };
2374
- runBd(["sql", String(args.sql)]);
2375
- } else if (op === "worktree_create") {
2376
- if (!args.path || !args.branch) return { ok: false, available: true, error: "path and branch are required for worktree_create" };
2377
- runBd(["worktree", "create", String(args.path), "--branch", String(args.branch)]);
2378
- } else if (op === "worktree_remove") {
2379
- if (!args.path) return { ok: false, available: true, error: "path is required for worktree_remove" };
2380
- const bdArgs = ["worktree", "remove", String(args.path)];
2381
- if (args.force === true) bdArgs.push("--force");
2382
- runBd(bdArgs);
2383
- } else {
2384
- return {
2385
- ok: false,
2386
- available: true,
2387
- error: `Unsupported Beads operation: ${op}`,
2388
- operations: [
2389
- "ready",
2390
- "list",
2391
- "show",
2392
- "update",
2393
- "note",
2394
- "close",
2395
- "label_add",
2396
- "label_remove",
2397
- "dep_add",
2398
- "dep_remove",
2399
- "create",
2400
- "mail_send",
2401
- "formula_list",
2402
- "formula_show",
2403
- "compact",
2404
- "rules_compact",
2405
- "dolt_pull",
2406
- "dolt_push",
2407
- "sql",
2408
- "worktree_create",
2409
- "worktree_remove"
2410
- ]
2411
- };
2412
- }
2413
- const ok = commands.every((cmd) => cmd.ok || op === "close" && /already|closed/i.test(`${cmd.stdout}
2414
- ${cmd.stderr}`));
2415
- let json = null;
2416
- const last = commands[commands.length - 1];
2417
- try {
2418
- json = JSON.parse(last && last.stdout ? last.stdout : "null");
2419
- } catch {
2420
- }
2421
- const rowsAffectedMatch = last ? `${last.stdout}
2422
- ${last.stderr}`.match(/(?:rows?\s+affected|affected\s+rows?)\D+(\d+)/i) : null;
2423
- return {
2424
- ok,
2425
- available: true,
2426
- operation: op,
2427
- commands,
2428
- json,
2429
- rows_affected: rowsAffectedMatch?.[1] ? Number(rowsAffectedMatch[1]) : null
2430
- };
1920
+ function notesPushAction(root, repo, cwd, remote = "origin") {
1921
+ return plannedGitAction(
1922
+ `notes-push-${repo.replace(/[^A-Za-z0-9_.-]+/g, "-") || "root"}`,
1923
+ "push_notes",
1924
+ repo,
1925
+ cwd,
1926
+ ["push", remote, `${notesRef(root)}:${notesRef(root)}`],
1927
+ `Push Cadre git notes for ${repo}`
1928
+ );
2431
1929
  }
2432
1930
 
2433
1931
  // src/core/application/runtime/track-mutations.ts
@@ -2497,7 +1995,15 @@ function metadataPatch(root, args = {}) {
2497
1995
  track_id: track.track_id,
2498
1996
  metadata_path: import_node_path15.default.relative(root, track.metadata_path),
2499
1997
  patch_keys: Object.keys(patch).sort(),
2500
- result
1998
+ result,
1999
+ event: result.ok ? appendCadreEvent(root, {
2000
+ kind: "metadata_updated",
2001
+ workflow: "metadata_patch",
2002
+ track_id: track.track_id,
2003
+ patch_keys: Object.keys(patch).sort(),
2004
+ tags: asStringArray(asJsonObject(patch).tags),
2005
+ depends_on: asStringArray(asJsonObject(patch).depends_on)
2006
+ }) : null
2501
2007
  };
2502
2008
  }
2503
2009
  function heartbeatTrack(root, args = {}) {
@@ -2532,19 +2038,13 @@ function heartbeatTrackUnlocked(root, track, args = {}) {
2532
2038
  last_updated: now
2533
2039
  }), { lock: false });
2534
2040
  }
2535
- let beads = null;
2536
- const epic = track.metadata.beads_epic;
2537
- if (epic && commandExists("bd", root)) {
2538
- beads = beadsTaskWrite(root, { operation: "update", id: epic, assignee: identity || "" });
2539
- }
2540
2041
  return {
2541
- ok: metadataResult.ok && (!stateResult || stateResult.ok) && (!beads || beads.ok),
2042
+ ok: metadataResult.ok && (!stateResult || stateResult.ok),
2542
2043
  track_id: track.track_id,
2543
2044
  owner: identity,
2544
2045
  heartbeat_at: now,
2545
2046
  metadata: metadataResult,
2546
- state: stateResult,
2547
- beads
2047
+ state: stateResult
2548
2048
  };
2549
2049
  }
2550
2050
  function claimTrack(root, trackId, options = {}) {
@@ -2562,41 +2062,6 @@ function claimTrackUnlocked(root, track, options = {}) {
2562
2062
  if (heldBy && heldBy !== identity && !stale && options.takeover !== true) {
2563
2063
  return { ok: false, claimed: false, reason: "foreign-held", held_by: heldBy, hold };
2564
2064
  }
2565
- const commands = [];
2566
- if (track.metadata.beads_epic) {
2567
- if (!commandExists("bd", root)) {
2568
- return { ok: false, claimed: false, error: "Beads CLI (bd) is required but was not found" };
2569
- }
2570
- const escapedIdentity = identity.replace(/'/g, "''");
2571
- const escapedEpic = String(track.metadata.beads_epic).replace(/'/g, "''");
2572
- const sql = `UPDATE issues SET assignee='${escapedIdentity}' WHERE id='${escapedEpic}' AND (assignee IS NULL OR assignee='' OR assignee='${escapedIdentity}' OR updated_at < datetime('now','-30 minutes'))`;
2573
- commands.push(runCommand("bd", ["sql", sql], { cwd: root }));
2574
- const last = commands[commands.length - 1];
2575
- if (!last || !last.ok) return { ok: false, claimed: false, error: "Beads claim failed", commands };
2576
- const verify = runCommand("bd", ["show", track.metadata.beads_epic, "--json"], { cwd: root, maxBuffer: 10 * 1024 * 1024 });
2577
- commands.push(verify);
2578
- if (!verify.ok) return { ok: false, claimed: false, error: "Beads claim verification failed", commands };
2579
- const assignedTo = extractAssignee(parseCommandJson(verify));
2580
- if (!assignedTo) {
2581
- return {
2582
- ok: false,
2583
- claimed: false,
2584
- reason: "claim-unverified",
2585
- error: "Beads claim verification did not expose an assignee",
2586
- commands
2587
- };
2588
- }
2589
- if (assignedTo !== identity) {
2590
- return {
2591
- ok: false,
2592
- claimed: false,
2593
- reason: "foreign-held",
2594
- held_by: assignedTo,
2595
- hold,
2596
- commands
2597
- };
2598
- }
2599
- }
2600
2065
  const topology = loadTopology(root);
2601
2066
  const metadataResult = patchJsonFile(track.metadata_path, (metadata) => {
2602
2067
  metadata.owner = identity;
@@ -2612,7 +2077,7 @@ function claimTrackUnlocked(root, track, options = {}) {
2612
2077
  }
2613
2078
  return metadata;
2614
2079
  }, { lock: false });
2615
- if (!metadataResult.ok) return { ok: false, claimed: false, error: "Metadata claim patch failed", metadata: metadataResult, commands };
2080
+ if (!metadataResult.ok) return { ok: false, claimed: false, error: "Metadata claim patch failed", metadata: metadataResult };
2616
2081
  const statePath = import_node_path15.default.join(track.dir, "implement_state.json");
2617
2082
  writeJson(statePath, {
2618
2083
  status: "starting",
@@ -2620,6 +2085,13 @@ function claimTrackUnlocked(root, track, options = {}) {
2620
2085
  track_id: track.track_id,
2621
2086
  last_updated: now
2622
2087
  });
2088
+ const event = appendCadreEvent(root, {
2089
+ kind: "track_claimed",
2090
+ workflow: "claim",
2091
+ track_id: track.track_id,
2092
+ owner: identity,
2093
+ previous_owner: heldBy || null
2094
+ });
2623
2095
  return {
2624
2096
  ok: true,
2625
2097
  claimed: true,
@@ -2627,10 +2099,10 @@ function claimTrackUnlocked(root, track, options = {}) {
2627
2099
  owner: identity,
2628
2100
  previous_hold: hold,
2629
2101
  metadata: metadataResult,
2630
- commands
2102
+ event
2631
2103
  };
2632
2104
  }
2633
- function setTrackStatus(root, trackId, status) {
2105
+ function setTrackStatus(root, trackId, status, args = {}) {
2634
2106
  if (!VALID_STATUSES.has(status)) {
2635
2107
  return {
2636
2108
  ok: false,
@@ -2643,6 +2115,7 @@ function setTrackStatus(root, trackId, status) {
2643
2115
  return { ok: false, error: `Track not found: ${trackId}` };
2644
2116
  }
2645
2117
  return withTrackLock(root, trackId, () => {
2118
+ const traceBefore = beginTrace(root);
2646
2119
  const metadata = patchJsonFile(track.metadata_path, (current) => ({
2647
2120
  ...current,
2648
2121
  status
@@ -2651,12 +2124,36 @@ function setTrackStatus(root, trackId, status) {
2651
2124
  return { ok: false, track_id: trackId, status, stage: "metadata_patch", metadata };
2652
2125
  }
2653
2126
  const regen = regenIndex(root);
2127
+ const event = appendCadreEvent(root, {
2128
+ kind: "status_changed",
2129
+ workflow: "set_status",
2130
+ track_id: trackId,
2131
+ status
2132
+ });
2133
+ const controlCommit = commitTrace(root, args, {
2134
+ kind: "control",
2135
+ workflow: "status",
2136
+ subject: `mark ${trackId} ${status}`,
2137
+ before: traceBefore,
2138
+ files: [
2139
+ import_node_path15.default.relative(root, track.metadata_path),
2140
+ "cadre/tracks.json",
2141
+ "cadre/events.jsonl"
2142
+ ],
2143
+ trackId,
2144
+ note: {
2145
+ event_id: asOptionalString(asJsonObject(event.event).id) || null,
2146
+ status
2147
+ }
2148
+ });
2654
2149
  return {
2655
- ok: Boolean(regen.ok),
2150
+ ok: Boolean(regen.ok) && controlCommit.ok !== false,
2656
2151
  track_id: trackId,
2657
2152
  status,
2658
2153
  metadata,
2659
- regen
2154
+ regen,
2155
+ event,
2156
+ control_commit: controlCommit
2660
2157
  };
2661
2158
  });
2662
2159
  }
@@ -2670,14 +2167,14 @@ function recordTaskResultUnlocked(root, args = {}) {
2670
2167
  const task = phase && (phase.tasks || []).find((item) => item.task_index === taskIndex);
2671
2168
  if (!task) return { ok: false, error: `Task not found: phase ${phaseIndex} task ${taskIndex}` };
2672
2169
  const planJsonPath = trackPlanJsonPath(track);
2673
- const commitSha = args.commitSha ? String(args.commitSha).trim() : "";
2170
+ const commitSha2 = args.commitSha ? String(args.commitSha).trim() : "";
2674
2171
  const recordedAt = utcNow();
2675
2172
  const lastTaskResult = {
2676
2173
  phase_index: phaseIndex,
2677
2174
  task_index: taskIndex,
2678
2175
  task_key: task.task_key,
2679
2176
  status: args.status || "completed",
2680
- commit_sha: commitSha || null,
2177
+ commit_sha: commitSha2 || null,
2681
2178
  repo: args.repo || task.repo || null,
2682
2179
  working_root: args.workingRoot || null,
2683
2180
  recorded_at: recordedAt
@@ -2704,7 +2201,7 @@ function recordTaskResultUnlocked(root, args = {}) {
2704
2201
  if (Number(currentTask.task_index || currentTask.index) !== taskIndex) return currentTask;
2705
2202
  const commitShas = Array.from(/* @__PURE__ */ new Set([
2706
2203
  ...asStringArray(currentTask.commit_shas),
2707
- ...commitSha ? [commitSha.slice(0, 12)] : []
2204
+ ...commitSha2 ? [commitSha2.slice(0, 12)] : []
2708
2205
  ]));
2709
2206
  return {
2710
2207
  ...currentTask,
@@ -2712,7 +2209,7 @@ function recordTaskResultUnlocked(root, args = {}) {
2712
2209
  commit_shas: commitShas,
2713
2210
  completion_evidence: {
2714
2211
  ...asJsonObject(currentTask.completion_evidence),
2715
- commit_sha: commitSha || null,
2212
+ commit_sha: commitSha2 || null,
2716
2213
  repo: args.repo || task.repo || null,
2717
2214
  working_root: args.workingRoot || null,
2718
2215
  coverage: typeof args.coverage === "number" ? args.coverage : null,
@@ -2729,20 +2226,28 @@ function recordTaskResultUnlocked(root, args = {}) {
2729
2226
  return { ok: false, track_id: track.track_id, stage: "plan_json_patch", metadata, plan_json: planPatch };
2730
2227
  }
2731
2228
  const nextPlan = asJsonObject(planPatch.value);
2732
- import_node_fs7.default.writeFileSync(
2229
+ import_node_fs8.default.writeFileSync(
2733
2230
  track.plan_path,
2734
2231
  withGeneratedMarker(import_node_path15.default.relative(root, planJsonPath), "cadre.plan.v1", renderPlanMarkdown(nextPlan))
2735
2232
  );
2736
- const metadataValue = asJsonObject(metadata.value);
2737
- const beadsTasks = asJsonObject(metadataValue.beads_tasks);
2738
2233
  return {
2739
2234
  ok: true,
2740
2235
  track_id: track.track_id,
2741
2236
  task_key: task.task_key,
2742
2237
  line: task.line,
2743
2238
  status: args.status || "completed",
2744
- commit_sha: commitSha || null,
2745
- beads_task_id: asOptionalString(beadsTasks[task.task_key]) || null,
2239
+ commit_sha: commitSha2 || null,
2240
+ event: appendCadreEvent(root, {
2241
+ kind: "task_result_recorded",
2242
+ workflow: "record_task_result",
2243
+ track_id: track.track_id,
2244
+ phase_index: phaseIndex,
2245
+ task_index: taskIndex,
2246
+ task_key: task.task_key,
2247
+ status: args.status || "completed",
2248
+ commit_sha: commitSha2 || null,
2249
+ repo: args.repo || task.repo || null
2250
+ }),
2746
2251
  metadata,
2747
2252
  plan_json: planPatch
2748
2253
  };
@@ -3053,12 +2558,12 @@ function scanReviewTodos(root, files, limit = 100) {
3053
2558
  if (!fileExists(abs)) continue;
3054
2559
  let stat;
3055
2560
  try {
3056
- stat = import_node_fs8.default.statSync(abs);
2561
+ stat = import_node_fs9.default.statSync(abs);
3057
2562
  } catch {
3058
2563
  continue;
3059
2564
  }
3060
2565
  if (stat.size > 1024 * 1024) continue;
3061
- const lines = import_node_fs8.default.readFileSync(abs, "utf8").split(/\r?\n/);
2566
+ const lines = import_node_fs9.default.readFileSync(abs, "utf8").split(/\r?\n/);
3062
2567
  for (let index = 0; index < lines.length && findings.length < limit; index += 1) {
3063
2568
  const line = lines[index] || "";
3064
2569
  if (patterns.some((pattern) => pattern.test(line))) {
@@ -3203,6 +2708,7 @@ function recordReview(root, args = {}) {
3203
2708
  return withTrackLock(root, track.track_id, () => recordReviewUnlocked(root, track, args));
3204
2709
  }
3205
2710
  function recordReviewUnlocked(root, track, args = {}) {
2711
+ const traceBefore = beginTrace(root);
3206
2712
  const verdict = args.verdict || "";
3207
2713
  if (!["approved", "changes_requested"].includes(verdict)) {
3208
2714
  return { ok: false, error: `Invalid review verdict: ${verdict}` };
@@ -3242,7 +2748,21 @@ function recordReviewUnlocked(root, track, args = {}) {
3242
2748
  };
3243
2749
  }
3244
2750
  const gate = reviewGate(root, track.track_id, args);
3245
- return { ok: true, track_id: track.track_id, review: asJsonObject(metadata.value).review, metadata, gate };
2751
+ const controlCommit = commitTrace(root, args, {
2752
+ kind: "control",
2753
+ workflow: "review",
2754
+ subject: `record ${track.track_id} review`,
2755
+ before: traceBefore,
2756
+ files: [
2757
+ import_node_path17.default.relative(root, track.metadata_path)
2758
+ ],
2759
+ trackId: track.track_id,
2760
+ note: {
2761
+ verdict,
2762
+ blocking_count: Number(args.blockingCount || 0)
2763
+ }
2764
+ });
2765
+ return { ok: controlCommit.ok !== false, track_id: track.track_id, review: asJsonObject(metadata.value).review, metadata, gate, control_commit: controlCommit };
3246
2766
  }
3247
2767
  function reviewEvidencePath(track) {
3248
2768
  return import_node_path17.default.join(track.dir, "review-evidence.json");
@@ -3268,6 +2788,7 @@ function providerEvidence(root, args = {}) {
3268
2788
  return withTrackLock(root, track.track_id, () => providerEvidenceUnlocked(root, track, args));
3269
2789
  }
3270
2790
  function providerEvidenceUnlocked(root, track, args = {}) {
2791
+ const traceBefore = beginTrace(root);
3271
2792
  const evidencePath = reviewEvidencePath(track);
3272
2793
  const existing = readJson(evidencePath, {
3273
2794
  track_id: track.track_id,
@@ -3322,12 +2843,32 @@ function providerEvidenceUnlocked(root, track, args = {}) {
3322
2843
  return current;
3323
2844
  }, { lock: false });
3324
2845
  if (!metadata.ok) return { ok: false, track_id: track.track_id, stage: "metadata_patch", metadata };
2846
+ const controlCommit = commitTrace(root, args, {
2847
+ kind: "control",
2848
+ workflow: "review",
2849
+ action: "provider_evidence",
2850
+ subject: `record ${track.track_id} evidence`,
2851
+ before: traceBefore,
2852
+ files: [
2853
+ import_node_path17.default.relative(root, evidencePath),
2854
+ import_node_path17.default.relative(root, import_node_path17.default.join(track.dir, "review-evidence.jsonl")),
2855
+ import_node_path17.default.relative(root, track.metadata_path)
2856
+ ],
2857
+ trackId: track.track_id,
2858
+ note: {
2859
+ provider,
2860
+ evidence_id: entry.id,
2861
+ blocking_count: entry.blocking_count,
2862
+ reviewed_sha: entry.reviewed_sha
2863
+ }
2864
+ });
3325
2865
  return {
3326
- ok: true,
2866
+ ok: controlCommit.ok !== false,
3327
2867
  track_id: track.track_id,
3328
2868
  path: import_node_path17.default.relative(root, evidencePath),
3329
2869
  entry,
3330
- metadata
2870
+ metadata,
2871
+ control_commit: controlCommit
3331
2872
  };
3332
2873
  }
3333
2874
  function syncControlPlane(root, args = {}) {
@@ -3346,9 +2887,7 @@ function syncControlPlane(root, args = {}) {
3346
2887
  }
3347
2888
  if (mode === "pre") {
3348
2889
  commands.push(runCommand("git", ["pull", "--rebase", remote, branch], { cwd: root }));
3349
- if (commandExists("bd", root)) commands.push(runCommand("bd", ["dolt", "pull"], { cwd: root }));
3350
2890
  } else if (mode === "post") {
3351
- if (commandExists("bd", root)) commands.push(runCommand("bd", ["dolt", "push"], { cwd: root }));
3352
2891
  commands.push(runCommand("git", ["push", remote, branch], { cwd: root }));
3353
2892
  } else {
3354
2893
  return { ok: false, error: `Invalid sync mode: ${mode}`, commands };
@@ -3356,43 +2895,267 @@ function syncControlPlane(root, args = {}) {
3356
2895
  return { ok: commands.every((cmd) => cmd.ok), mode, remote, branch, safety, commands };
3357
2896
  }
3358
2897
 
3359
- // src/core/application/runtime/packaged-assets.ts
3360
- var import_node_fs9 = __toESM(require("node:fs"));
3361
- var import_node_path18 = __toESM(require("node:path"));
3362
- var SEARCH_DEPTH = 8;
3363
- function embeddedAssets() {
3364
- return typeof __CADRE_EMBEDDED_ASSETS__ !== "undefined" ? __CADRE_EMBEDDED_ASSETS__ : null;
3365
- }
3366
- function normalizeRelativePath(value) {
3367
- return value.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+/g, "/");
2898
+ // src/core/application/runtime/text-utils.ts
2899
+ function compactLines(value, limit = 1200) {
2900
+ return String(value || "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean).join("\n").slice(0, limit);
3368
2901
  }
3369
- function unique2(values) {
3370
- return Array.from(new Set(values));
2902
+
2903
+ // src/core/application/runtime/spec-docs.ts
2904
+ function normalizedSpecHeading(heading) {
2905
+ return heading.toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, " ").trim();
3371
2906
  }
3372
- function isFile(file) {
3373
- try {
3374
- return import_node_fs9.default.statSync(file).isFile();
3375
- } catch {
3376
- return false;
2907
+ function specSectionKind(heading) {
2908
+ const normalized = normalizedSpecHeading(heading);
2909
+ if (["description", "summary", "overview", "goal", "goals", "objective", "objectives", "context", "problem"].includes(normalized)) {
2910
+ return "description";
3377
2911
  }
3378
- }
3379
- function walkingCandidates(factory) {
3380
- const candidates = [];
3381
- let dir = __dirname;
3382
- for (let depth = 0; depth < SEARCH_DEPTH; depth += 1) {
3383
- candidates.push(...factory(dir));
3384
- const parent = import_node_path18.default.dirname(dir);
3385
- if (parent === dir) break;
3386
- dir = parent;
2912
+ if ([
2913
+ "functional requirements",
2914
+ "functional requirement",
2915
+ "fr",
2916
+ "requirements",
2917
+ "requirement",
2918
+ "user facing behavior",
2919
+ "user facing behaviours",
2920
+ "user behavior",
2921
+ "user behaviour",
2922
+ "behavior",
2923
+ "behaviour"
2924
+ ].includes(normalized)) {
2925
+ return "functional_requirements";
3387
2926
  }
3388
- return unique2(candidates);
2927
+ if ([
2928
+ "non functional requirements",
2929
+ "non functional requirement",
2930
+ "nonfunctional requirements",
2931
+ "nonfunctional requirement",
2932
+ "nfr",
2933
+ "constraints",
2934
+ "constraint",
2935
+ "quality attributes",
2936
+ "quality attribute",
2937
+ "performance requirements",
2938
+ "security requirements"
2939
+ ].includes(normalized)) {
2940
+ return "non_functional_requirements";
2941
+ }
2942
+ if (["acceptance criteria", "acceptance criterion", "acceptance", "success criteria", "definition of done", "done"].includes(normalized)) {
2943
+ return "acceptance_criteria";
2944
+ }
2945
+ if (["out of scope", "out scope", "out of scopes", "non goals", "non goal", "nongoals", "exclusions", "exclusion"].includes(normalized)) {
2946
+ return "out_of_scope";
2947
+ }
2948
+ return null;
3389
2949
  }
3390
- function findFile(candidates) {
3391
- return candidates.find(isFile) || null;
2950
+ function cleanSpecItem(value) {
2951
+ const heading = compactLines(asOptionalString(value.heading || value.title || value.name) || "", 240);
2952
+ const body = normalizedText(asOptionalString(value.body || value.description || value.text) || "").trim();
2953
+ if (!heading && !body) return null;
2954
+ return { heading: heading || "Item", body };
3392
2955
  }
3393
- function walkTemplateFiles(dir, base = dir) {
2956
+ function parseSpecListItem(line) {
2957
+ const text = line.trim();
2958
+ const bold = text.match(/^\*\*(.+?)\*\*:?\s*(.*)$/);
2959
+ const keyed = !bold ? text.match(/^(.+?)\s*(?::|\s+-\s+|\s+--\s+|\s+—\s+)\s*(.+)$/) : null;
2960
+ if (bold?.[1]) return { heading: bold[1].trim(), body: (bold[2] || "").trim() };
2961
+ if (keyed?.[1]) return { heading: keyed[1].trim(), body: (keyed[2] || "").trim() };
2962
+ return { heading: text, body: "" };
2963
+ }
2964
+ function parseSpecListItems(body, fallbackHeading) {
2965
+ const lines = normalizedText(body).split("\n");
2966
+ const items = [];
2967
+ let current = null;
2968
+ const pushCurrent = () => {
2969
+ if (!current) return;
2970
+ const cleaned = cleanSpecItem(current);
2971
+ if (cleaned) items.push(cleaned);
2972
+ current = null;
2973
+ };
2974
+ for (const rawLine of lines) {
2975
+ const bullet = rawLine.match(/^\s*(?:[-*+]|\d+[.)])\s+(.+)$/);
2976
+ if (bullet?.[1]) {
2977
+ pushCurrent();
2978
+ current = parseSpecListItem(bullet[1]);
2979
+ continue;
2980
+ }
2981
+ const text = rawLine.trim();
2982
+ if (!text) continue;
2983
+ if (!current) {
2984
+ current = { heading: fallbackHeading, body: text };
2985
+ continue;
2986
+ }
2987
+ const existing = asOptionalString(current.body) || "";
2988
+ current.body = existing ? `${existing}
2989
+ ${text}` : text;
2990
+ }
2991
+ pushCurrent();
2992
+ if (items.length > 0) return items;
2993
+ const fallbackBody = normalizedText(body).trim();
2994
+ return fallbackBody ? [{ heading: fallbackHeading, body: fallbackBody }] : [];
2995
+ }
2996
+ function specItemsFromRaw(value) {
2997
+ return asArray(value).map((entry) => {
2998
+ if (typeof entry === "string") return cleanSpecItem({ heading: entry, body: "" });
2999
+ return cleanSpecItem(asJsonObject(entry));
3000
+ }).filter((entry) => Boolean(entry));
3001
+ }
3002
+ function specJsonFromText(trackId, text) {
3003
+ const parsed = splitMarkdownSections(text || `# Spec: ${trackId}
3004
+ `);
3005
+ const descriptionParts = [parsed.body].filter(Boolean);
3006
+ const functionalRequirements = [];
3007
+ const nonFunctionalRequirements = [];
3008
+ const acceptanceCriteria = [];
3009
+ const outOfScope = [];
3010
+ for (const rawSection of parsed.sections) {
3011
+ const section = asJsonObject(rawSection);
3012
+ const heading = asOptionalString(section.heading) || "";
3013
+ const body = asOptionalString(section.body) || "";
3014
+ const kind = specSectionKind(heading);
3015
+ if (kind === "description") descriptionParts.push(body);
3016
+ else if (kind === "functional_requirements") functionalRequirements.push(...parseSpecListItems(body, heading));
3017
+ else if (kind === "non_functional_requirements") nonFunctionalRequirements.push(...parseSpecListItems(body, heading));
3018
+ else if (kind === "acceptance_criteria") acceptanceCriteria.push(...parseSpecListItems(body, heading));
3019
+ else if (kind === "out_of_scope") outOfScope.push(...parseSpecListItems(body, heading));
3020
+ else if (body) descriptionParts.push(`### ${heading}
3021
+
3022
+ ${body}`);
3023
+ }
3024
+ return {
3025
+ version: 1,
3026
+ schema: "cadre.spec.v1",
3027
+ kind: "spec",
3028
+ track_id: trackId,
3029
+ title: parsed.title,
3030
+ description: descriptionParts.join("\n\n").trim(),
3031
+ functional_requirements: functionalRequirements,
3032
+ non_functional_requirements: nonFunctionalRequirements,
3033
+ acceptance_criteria: acceptanceCriteria,
3034
+ out_of_scope: outOfScope,
3035
+ updated_at: utcNow()
3036
+ };
3037
+ }
3038
+ function normalizedSpecFromRaw(raw) {
3039
+ if (asOptionalString(raw.description) || asArray(raw.functional_requirements).length > 0 || asArray(raw.non_functional_requirements).length > 0 || asArray(raw.acceptance_criteria).length > 0 || asArray(raw.out_of_scope).length > 0) {
3040
+ return {
3041
+ ...raw,
3042
+ description: asOptionalString(raw.description || raw.summary) || "",
3043
+ functional_requirements: specItemsFromRaw(raw.functional_requirements),
3044
+ non_functional_requirements: specItemsFromRaw(raw.non_functional_requirements),
3045
+ acceptance_criteria: specItemsFromRaw(raw.acceptance_criteria),
3046
+ out_of_scope: specItemsFromRaw(raw.out_of_scope)
3047
+ };
3048
+ }
3049
+ const title = asOptionalString(raw.title) || `Spec: ${asOptionalString(raw.track_id) || "track"}`;
3050
+ const parts = [`# ${title}`, ""];
3051
+ const summary = asOptionalString(raw.summary);
3052
+ if (summary) parts.push(summary, "");
3053
+ for (const rawSection of asArray(raw.sections)) {
3054
+ const section = asJsonObject(rawSection);
3055
+ const heading = asOptionalString(section.heading);
3056
+ const body = asOptionalString(section.body);
3057
+ if (heading && body) parts.push(`## ${heading}`, "", body, "");
3058
+ }
3059
+ return specJsonFromText(asOptionalString(raw.track_id) || "track", parts.join("\n"));
3060
+ }
3061
+ function appendSpecItemSection(parts, heading, items) {
3062
+ if (items.length === 0) return;
3063
+ parts.push(`## ${heading}`, "");
3064
+ for (const item of items) {
3065
+ const itemHeading = asOptionalString(item.heading) || "Item";
3066
+ const body = normalizedText(asOptionalString(item.body) || "").trim();
3067
+ if (!body) {
3068
+ parts.push(`- ${itemHeading}`);
3069
+ continue;
3070
+ }
3071
+ if (!body.includes("\n")) {
3072
+ parts.push(`- **${itemHeading}**: ${body}`);
3073
+ continue;
3074
+ }
3075
+ parts.push(`- **${itemHeading}**`);
3076
+ for (const line of body.split("\n")) {
3077
+ parts.push(line.trim() ? ` ${line}` : "");
3078
+ }
3079
+ }
3080
+ parts.push("");
3081
+ }
3082
+ function renderSpecMarkdown(raw) {
3083
+ const spec = normalizedSpecFromRaw(raw);
3084
+ const title = asOptionalString(spec.title) || `Spec: ${asOptionalString(spec.track_id) || "track"}`;
3085
+ const parts = [`# ${title}`, ""];
3086
+ const description = asOptionalString(spec.description);
3087
+ if (description) parts.push("## Description", "", description, "");
3088
+ appendSpecItemSection(parts, "Functional Requirements", specItemsFromRaw(spec.functional_requirements));
3089
+ appendSpecItemSection(parts, "Non-Functional Requirements", specItemsFromRaw(spec.non_functional_requirements));
3090
+ appendSpecItemSection(parts, "Acceptance Criteria", specItemsFromRaw(spec.acceptance_criteria));
3091
+ appendSpecItemSection(parts, "Out Of Scope", specItemsFromRaw(spec.out_of_scope));
3092
+ return normalizedText(parts.join("\n"));
3093
+ }
3094
+ function renderStyleGuideMarkdown(raw) {
3095
+ const id = asOptionalString(raw.id) || "styleguide";
3096
+ const title = asOptionalString(raw.title) || id;
3097
+ const parts = [`# ${title}`, ""];
3098
+ const summary = asOptionalString(raw.summary);
3099
+ if (summary) parts.push(summary, "");
3100
+ const rules = asArray(raw.rules);
3101
+ if (rules.length > 0) {
3102
+ parts.push("## Rules", "");
3103
+ for (const rawRule of rules) {
3104
+ const rule = asJsonObject(rawRule);
3105
+ const severity = asOptionalString(rule.severity);
3106
+ const suffix = severity ? ` (${severity})` : "";
3107
+ parts.push(`- ${asOptionalString(rule.summary) || asOptionalString(rule.id) || "Rule"}${suffix}`);
3108
+ const rationale = asOptionalString(rule.rationale);
3109
+ if (rationale) parts.push(` Rationale: ${rationale}`);
3110
+ }
3111
+ parts.push("");
3112
+ }
3113
+ for (const rawSection of asArray(raw.sections)) {
3114
+ const section = asJsonObject(rawSection);
3115
+ const heading = asOptionalString(section.heading);
3116
+ const body = asOptionalString(section.body);
3117
+ if (heading && body) parts.push(`## ${heading}`, "", body, "");
3118
+ }
3119
+ return normalizedText(parts.join("\n"));
3120
+ }
3121
+
3122
+ // src/core/application/runtime/packaged-assets.ts
3123
+ var import_node_fs10 = __toESM(require("node:fs"));
3124
+ var import_node_path18 = __toESM(require("node:path"));
3125
+ var SEARCH_DEPTH = 8;
3126
+ function embeddedAssets() {
3127
+ return typeof __CADRE_EMBEDDED_ASSETS__ !== "undefined" ? __CADRE_EMBEDDED_ASSETS__ : null;
3128
+ }
3129
+ function normalizeRelativePath(value) {
3130
+ return value.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+/g, "/");
3131
+ }
3132
+ function unique2(values) {
3133
+ return Array.from(new Set(values));
3134
+ }
3135
+ function isFile(file) {
3136
+ try {
3137
+ return import_node_fs10.default.statSync(file).isFile();
3138
+ } catch {
3139
+ return false;
3140
+ }
3141
+ }
3142
+ function walkingCandidates(factory) {
3143
+ const candidates = [];
3144
+ let dir = __dirname;
3145
+ for (let depth = 0; depth < SEARCH_DEPTH; depth += 1) {
3146
+ candidates.push(...factory(dir));
3147
+ const parent = import_node_path18.default.dirname(dir);
3148
+ if (parent === dir) break;
3149
+ dir = parent;
3150
+ }
3151
+ return unique2(candidates);
3152
+ }
3153
+ function findFile(candidates) {
3154
+ return candidates.find(isFile) || null;
3155
+ }
3156
+ function walkTemplateFiles(dir, base = dir) {
3394
3157
  const files = [];
3395
- for (const entry of import_node_fs9.default.readdirSync(dir, { withFileTypes: true })) {
3158
+ for (const entry of import_node_fs10.default.readdirSync(dir, { withFileTypes: true })) {
3396
3159
  const full = import_node_path18.default.join(dir, entry.name);
3397
3160
  if (entry.isDirectory()) {
3398
3161
  files.push(...walkTemplateFiles(full, base));
@@ -3415,7 +3178,7 @@ function packagedTemplateText(relativePath) {
3415
3178
  const embedded = embeddedAssets()?.templates?.[normalized];
3416
3179
  if (typeof embedded === "string") return embedded;
3417
3180
  const file = packagedTemplatePath(normalized);
3418
- return file ? import_node_fs9.default.readFileSync(file, "utf8") : null;
3181
+ return file ? import_node_fs10.default.readFileSync(file, "utf8") : null;
3419
3182
  }
3420
3183
  function packagedTemplateJson(relativePath) {
3421
3184
  const text = packagedTemplateText(relativePath);
@@ -3581,30 +3344,6 @@ function compactLspSetup(value) {
3581
3344
  recommended_count: Array.isArray(setup.recommended) ? setup.recommended.length : Number(setup.recommended_count || 0)
3582
3345
  };
3583
3346
  }
3584
- function compactBeadsPrefix(value) {
3585
- if (!isRecord(value)) return value;
3586
- const prefix = asJsonObject(value);
3587
- return {
3588
- selected: prefix.selected === true,
3589
- required: prefix.required === true,
3590
- epic_prefix: asOptionalString(prefix.epic_prefix) || "",
3591
- source: asOptionalString(prefix.source) || null,
3592
- example: asOptionalString(prefix.example) || null,
3593
- max_words: prefix.max_words,
3594
- missing_payload: asStringArray(prefix.missing_payload),
3595
- recommendations: Array.isArray(prefix.recommendations) ? prefix.recommendations.slice(0, 5).map((entry) => {
3596
- const recommendation2 = asJsonObject(entry);
3597
- return {
3598
- label: asOptionalString(recommendation2.label) || null,
3599
- epic_prefix: asOptionalString(recommendation2.epic_prefix) || null,
3600
- example: asOptionalString(recommendation2.example) || null,
3601
- recommended: recommendation2.recommended === true,
3602
- reason: asOptionalString(recommendation2.reason) || null
3603
- };
3604
- }) : [],
3605
- error: asOptionalString(prefix.error) || void 0
3606
- };
3607
- }
3608
3347
  function compactSetupResponse(result) {
3609
3348
  const styleGuides = compactStyleGuides(result.styleGuides);
3610
3349
  const reviewBundle = compactReviewBundle(result.review_bundle);
@@ -3656,14 +3395,6 @@ function compactSetupResponse(result) {
3656
3395
  provider: asJsonObject(result.integrations).provider || null,
3657
3396
  optional_mcps: Array.isArray(asJsonObject(result.integrations).optional_mcps) ? asJsonObject(result.integrations).optional_mcps : []
3658
3397
  } : null,
3659
- beads_init: isRecord(result.beads_init) ? {
3660
- ok: asJsonObject(result.beads_init).ok !== false,
3661
- available: asJsonObject(result.beads_init).available,
3662
- execute: asJsonObject(result.beads_init).execute === true,
3663
- dry_run: asJsonObject(result.beads_init).dry_run !== false,
3664
- reason: asOptionalString(asJsonObject(result.beads_init).reason) || null
3665
- } : result.beads_init,
3666
- beads_prefix: compactBeadsPrefix(result.beads_prefix),
3667
3398
  styleGuides,
3668
3399
  styleguide_ids: asStringArray(styleGuides.selected),
3669
3400
  templates: compactTemplateManifest(result.templates),
@@ -4490,7 +4221,7 @@ function planIntegrity(root, trackId = null) {
4490
4221
  }
4491
4222
 
4492
4223
  // src/core/application/runtime/review-bundles.ts
4493
- var import_node_fs10 = __toESM(require("node:fs"));
4224
+ var import_node_fs11 = __toESM(require("node:fs"));
4494
4225
  var import_node_path22 = __toESM(require("node:path"));
4495
4226
  var import_node_crypto2 = __toESM(require("node:crypto"));
4496
4227
  var import_node_os2 = __toESM(require("node:os"));
@@ -4782,12 +4513,12 @@ function workflowReviewBundle(root, workflow, args, reviewFiles, manifestExtras
4782
4513
  const unsafeExplicitDir = Boolean(explicitDir) && (directory === resolvedRoot || insideCadre);
4783
4514
  const warnings = unsafeExplicitDir ? [`Ignored unsafe reviewBundleDir ${explicitDir}; using a temp review bundle outside the project control plane.`] : [];
4784
4515
  if (unsafeExplicitDir) directory = defaultDirectory;
4785
- if (!explicitDir || unsafeExplicitDir) import_node_fs10.default.rmSync(directory, { recursive: true, force: true });
4786
- import_node_fs10.default.mkdirSync(directory, { recursive: true });
4516
+ if (!explicitDir || unsafeExplicitDir) import_node_fs11.default.rmSync(directory, { recursive: true, force: true });
4517
+ import_node_fs11.default.mkdirSync(directory, { recursive: true });
4787
4518
  const files = reviewFiles.map((file) => {
4788
4519
  const reviewPath = import_node_path22.default.join(directory, file.path);
4789
- import_node_fs10.default.mkdirSync(import_node_path22.default.dirname(reviewPath), { recursive: true });
4790
- import_node_fs10.default.writeFileSync(reviewPath, file.content);
4520
+ import_node_fs11.default.mkdirSync(import_node_path22.default.dirname(reviewPath), { recursive: true });
4521
+ import_node_fs11.default.writeFileSync(reviewPath, file.content);
4791
4522
  return {
4792
4523
  path: file.path,
4793
4524
  review_path: reviewPath,
@@ -4885,7 +4616,7 @@ function installedStyleGuideIds(root) {
4885
4616
  const dir = import_node_path22.default.join(root, "cadre", "styleguides");
4886
4617
  if (!fileExists(dir)) return [];
4887
4618
  try {
4888
- return import_node_fs10.default.readdirSync(dir).filter((file) => file.endsWith(".json") && file !== "index.json").map((file) => import_node_path22.default.basename(file, ".json")).sort();
4619
+ return import_node_fs11.default.readdirSync(dir).filter((file) => file.endsWith(".json") && file !== "index.json").map((file) => import_node_path22.default.basename(file, ".json")).sort();
4889
4620
  } catch {
4890
4621
  return [];
4891
4622
  }
@@ -5260,7 +4991,7 @@ function taskCounts(plan) {
5260
4991
  function listTrackDirs(root) {
5261
4992
  const tracksDir = import_node_path24.default.join(root, "cadre", "tracks");
5262
4993
  if (!fileExists(tracksDir)) return [];
5263
- return import_node_fs11.default.readdirSync(tracksDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => import_node_path24.default.join(tracksDir, entry.name)).sort();
4994
+ return import_node_fs12.default.readdirSync(tracksDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => import_node_path24.default.join(tracksDir, entry.name)).sort();
5264
4995
  }
5265
4996
  function listTracks(root) {
5266
4997
  const tracks = [];
@@ -5479,7 +5210,8 @@ function phaseSchedule(root, args = {}) {
5479
5210
  marker: task.marker,
5480
5211
  repo: task.repo || (topology.polyrepo ? topology.defaultRepo : "."),
5481
5212
  files: task.files || [],
5482
- depends: task.depends || []
5213
+ depends: task.depends || [],
5214
+ labels: task.labels || []
5483
5215
  }))
5484
5216
  };
5485
5217
  });
@@ -5652,16 +5384,6 @@ function teamStatus(root) {
5652
5384
  }))
5653
5385
  };
5654
5386
  }
5655
- function runBdJson(root, args) {
5656
- if (!commandExists("bd", root)) return { ok: false, available: false, args, json: null };
5657
- const result = runCommand("bd", args, { cwd: root, maxBuffer: 10 * 1024 * 1024 });
5658
- let json = null;
5659
- try {
5660
- json = JSON.parse(result.stdout || "null");
5661
- } catch {
5662
- }
5663
- return { ok: result.ok, available: true, args, json, stdout_tail: result.stdout.slice(-2e3), stderr_tail: result.stderr.slice(-2e3) };
5664
- }
5665
5387
  function asArray(value) {
5666
5388
  if (Array.isArray(value)) return value.filter(isRecord);
5667
5389
  if (isRecord(value) && Array.isArray(value.items)) return value.items.filter(isRecord).map(asJsonObject);
@@ -5687,7 +5409,7 @@ function metadataTrackSummary(track) {
5687
5409
  priority: track.metadata.priority || "medium",
5688
5410
  owner: track.metadata.owner || null,
5689
5411
  reviewer: track.metadata.reviewer || null,
5690
- beads_epic: track.metadata.beads_epic || null,
5412
+ tags: asStringArray(track.metadata.tags),
5691
5413
  review: track.metadata.review ? asJsonObject(track.metadata.review) : null
5692
5414
  };
5693
5415
  }
@@ -5750,12 +5472,11 @@ function teamBoard(root, args = {}) {
5750
5472
  const identity = gitIdentity(root);
5751
5473
  const scope = args.mine === true ? "mine" : "all";
5752
5474
  const byId = new Map(tracks.map((track) => [track.track_id, track]));
5753
- const byEpic = new Map(
5754
- tracks.flatMap((track) => track.metadata.beads_epic ? [[track.metadata.beads_epic, track]] : [])
5755
- );
5756
5475
  const wip = [];
5757
5476
  const reviewQueue = [];
5758
5477
  const blockers = [];
5478
+ const handoffs = [];
5479
+ const outgoingHandoffs = [];
5759
5480
  for (const track of tracks) {
5760
5481
  const summary = metadataTrackSummary(track);
5761
5482
  const hold = holdInfo(track);
@@ -5797,50 +5518,39 @@ function teamBoard(root, args = {}) {
5797
5518
  }
5798
5519
  }
5799
5520
  }
5800
- const beads = {
5801
- available: commandExists("bd", root),
5802
- wip: null,
5803
- handoffs: null,
5804
- review_labels: {},
5805
- blocked_edges: null
5806
- };
5807
- const handoffs = [];
5808
- if (beads.available) {
5809
- beads.wip = runBdJson(root, ["list", "--status", "in_progress", "--json"]);
5810
- beads.handoffs = runBdJson(root, ["list", "--label", "handoff:pending", "--json"]);
5811
- beads.blocked_edges = runBdJson(root, ["ready", "--json"]);
5812
- for (const label of ["review:changes", "review:ready", "review:requested"]) {
5813
- beads.review_labels[label] = runBdJson(root, ["list", "--label", label, "--json"]);
5814
- const reviewLabel = beads.review_labels[label];
5815
- for (const issue of asArray(reviewLabel?.json)) {
5816
- const id = asOptionalString(issue.id) || asOptionalString(issue.issue_id) || asOptionalString(issue.issueId) || asOptionalString(issue.parent) || asOptionalString(issue.epic) || null;
5817
- const track = id ? byEpic.get(id) : null;
5818
- if (track) {
5819
- reviewQueue.push({
5820
- ...metadataTrackSummary(track),
5821
- review_state: label.replace("review:", ""),
5822
- source: "beads_label",
5823
- bead_id: id
5824
- });
5825
- }
5826
- }
5827
- }
5828
- for (const issue of asArray(beads.handoffs?.json)) {
5829
- const id = asOptionalString(issue.id) || asOptionalString(issue.issue_id) || asOptionalString(issue.issueId) || null;
5830
- const track = id ? byEpic.get(id) : null;
5831
- const assignee = asOptionalString(issue.assignee) || asOptionalString(issue.assigned_to) || null;
5832
- if (scope === "mine" && assignee !== identity) continue;
5833
- handoffs.push({
5834
- track_id: track ? track.track_id : null,
5835
- bead_id: id,
5836
- assignee,
5837
- title: issue.title || issue.summary || null
5838
- });
5839
- }
5521
+ for (const message of readCadreMessages(root, "inbox", 200)) {
5522
+ if (asOptionalString(message.kind) !== "handoff") continue;
5523
+ const recipient = asOptionalString(message.to || message.recipient) || null;
5524
+ if (scope === "mine" && recipient && recipient !== identity) continue;
5525
+ handoffs.push({
5526
+ source: "message_inbox",
5527
+ message_id: asOptionalString(message.id) || null,
5528
+ track_id: asOptionalString(message.track_id) || null,
5529
+ from: asOptionalString(message.from) || null,
5530
+ to: recipient,
5531
+ subject: asOptionalString(message.subject) || null,
5532
+ status: asOptionalString(message.status) || "pending",
5533
+ recorded_at: asOptionalString(message.recorded_at) || null
5534
+ });
5535
+ }
5536
+ for (const message of readCadreMessages(root, "outbox", 200)) {
5537
+ if (asOptionalString(message.kind) !== "handoff") continue;
5538
+ const sender = asOptionalString(message.from) || null;
5539
+ if (scope === "mine" && sender && sender !== identity) continue;
5540
+ outgoingHandoffs.push({
5541
+ source: "message_outbox",
5542
+ message_id: asOptionalString(message.id) || null,
5543
+ track_id: asOptionalString(message.track_id) || null,
5544
+ from: sender,
5545
+ to: asOptionalString(message.to || message.recipient) || null,
5546
+ subject: asOptionalString(message.subject) || null,
5547
+ status: asOptionalString(message.status) || "pending",
5548
+ recorded_at: asOptionalString(message.recorded_at) || null
5549
+ });
5840
5550
  }
5841
5551
  const dedupReview = /* @__PURE__ */ new Map();
5842
5552
  for (const item of reviewQueue) {
5843
- const key = `${item.track_id}:${item.review_state}:${item.bead_id || ""}`;
5553
+ const key = `${item.track_id}:${item.review_state || ""}`;
5844
5554
  if (!dedupReview.has(key)) dedupReview.set(key, item);
5845
5555
  }
5846
5556
  return {
@@ -5852,9 +5562,10 @@ function teamBoard(root, args = {}) {
5852
5562
  summary: teamStatus(root),
5853
5563
  wip,
5854
5564
  incoming_handoffs: handoffs,
5565
+ outgoing_handoffs: outgoingHandoffs,
5855
5566
  review_queue: Array.from(dedupReview.values()),
5856
5567
  blockers,
5857
- beads,
5568
+ native_state: nativeStateSummary(root),
5858
5569
  lsp: lspRuntimeSummary(root)
5859
5570
  };
5860
5571
  }
@@ -5904,42 +5615,9 @@ function fleetStatus(root, args = {}) {
5904
5615
  repos,
5905
5616
  provider: providerMcpAvailability(root, args),
5906
5617
  lsp: lspRuntimeSummary(root),
5907
- beads_available: commandExists("bd", root),
5908
5618
  collisions: args.includeCollisions === false ? null : collisionScan(root)
5909
5619
  };
5910
5620
  }
5911
- function beadsSummary(root) {
5912
- const available = commandExists("bd", root);
5913
- if (!available) {
5914
- return {
5915
- ok: true,
5916
- available: false,
5917
- root,
5918
- reason: "Beads CLI (bd) is not installed or not on PATH",
5919
- ready: null,
5920
- in_progress: null,
5921
- blocked: null,
5922
- review: null
5923
- };
5924
- }
5925
- const ready = runBdJson(root, ["ready", "--json"]);
5926
- const inProgress = runBdJson(root, ["list", "--status", "in_progress", "--json"]);
5927
- const blocked = runBdJson(root, ["list", "--status", "blocked", "--json"]);
5928
- const review = {
5929
- requested: runBdJson(root, ["list", "--label", "review:requested", "--json"]),
5930
- ready: runBdJson(root, ["list", "--label", "review:ready", "--json"]),
5931
- changes: runBdJson(root, ["list", "--label", "review:changes", "--json"])
5932
- };
5933
- return {
5934
- ok: true,
5935
- available: true,
5936
- root,
5937
- ready,
5938
- in_progress: inProgress,
5939
- blocked,
5940
- review
5941
- };
5942
- }
5943
5621
  function availableWork(root) {
5944
5622
  const tracks = listTracks(root);
5945
5623
  const byId = new Map(tracks.map((track) => [track.track_id, track]));
@@ -6291,10 +5969,12 @@ function planJsonToParsedPlan(raw) {
6291
5969
  const taskKey = asOptionalString(task.task_key) || `phase${phaseIndex}_task${taskIndex}`;
6292
5970
  const files = asStringArray(task.files);
6293
5971
  const depends = asStringArray(task.depends_on || task.depends);
5972
+ const labels = asStringArray(task.labels);
6294
5973
  const taskAnnotations = {
6295
5974
  ...asJsonObject(task.annotations),
6296
5975
  ...files.length > 0 ? { files: files.join(", ") } : {},
6297
5976
  ...depends.length > 0 ? { depends: depends.join(",") } : {},
5977
+ ...labels.length > 0 ? { labels: labels.join(",") } : {},
6298
5978
  ...asOptionalString(task.repo) ? { repo: asOptionalString(task.repo) } : {}
6299
5979
  };
6300
5980
  return {
@@ -6305,6 +5985,7 @@ function planJsonToParsedPlan(raw) {
6305
5985
  annotations: taskAnnotations,
6306
5986
  files,
6307
5987
  depends,
5988
+ labels,
6308
5989
  repo: asOptionalString(task.repo) || null,
6309
5990
  line: Number(task.line || phaseIndex * 100 + taskIndex),
6310
5991
  phase_index: phaseIndex,
@@ -6342,6 +6023,7 @@ function renderPlanMarkdown(raw) {
6342
6023
  if (task.repo) parts.push(` <!-- repo: ${task.repo} -->`);
6343
6024
  if (task.files.length > 0) parts.push(` <!-- files: ${task.files.join(", ")} -->`);
6344
6025
  if (task.depends.length > 0) parts.push(` <!-- depends: ${task.depends.join(", ")} -->`);
6026
+ if (task.labels && task.labels.length > 0) parts.push(` <!-- labels: ${task.labels.join(", ")} -->`);
6345
6027
  if (task.commit_shas && task.commit_shas.length > 0) parts.push(` <!-- commits: ${task.commit_shas.join(", ")} -->`);
6346
6028
  if (task.task_type) parts.push(` <!-- task-type: ${task.task_type} -->`);
6347
6029
  if (task.manual_verification) {
@@ -6360,7 +6042,7 @@ function renderPlanMarkdown(raw) {
6360
6042
  // src/core/application/runtime/artifact-catalog.ts
6361
6043
  function safeReadDir(dir) {
6362
6044
  try {
6363
- return import_node_fs12.default.readdirSync(dir).sort();
6045
+ return import_node_fs13.default.readdirSync(dir).sort();
6364
6046
  } catch {
6365
6047
  return [];
6366
6048
  }
@@ -6420,7 +6102,6 @@ function artifactSchema(artifact) {
6420
6102
  owner: { type: "string" },
6421
6103
  reviewer: { type: "string" },
6422
6104
  review: { type: "object" },
6423
- beads_tasks: { type: "object" },
6424
6105
  worktree_path: { type: "string" }
6425
6106
  }),
6426
6107
  release: objectSchema(["version", "completed_tracks"], {
@@ -6474,7 +6155,6 @@ function artifactDefinitions(root, args = {}) {
6474
6155
  { id: "tracks-index", title: "Track index", canonical: "cadre/tracks.json", schema: TRACKS_INDEX_SCHEMA, scope: "project", sourceFormat: "json", projectionFormat: "none" },
6475
6156
  { id: "tech-stack", title: "Tech stack", canonical: "cadre/tech-stack.json", schema: "cadre.tech_stack.v1", scope: "project", sourceFormat: "json", projectionFormat: "none" },
6476
6157
  { id: "config", title: "Cadre config", canonical: "cadre/config.json", schema: "cadre.config.v1", scope: "project", sourceFormat: "json", projectionFormat: "none" },
6477
- { id: "beads-config", title: "Beads config", canonical: "cadre/beads.json", schema: "cadre.beads.v1", scope: "project", sourceFormat: "json", projectionFormat: "none" },
6478
6158
  { id: "setup-state", title: "Setup state", canonical: "cadre/setup_state.json", schema: "cadre.setup_state.v1", scope: "project", sourceFormat: "json", projectionFormat: "none" }
6479
6159
  ];
6480
6160
  if (fileExists(import_node_path27.default.join(root, "cadre", "repos.json")) || fileExists(import_node_path27.default.join(root, "cadre", "repos.md"))) {
@@ -6586,7 +6266,7 @@ ${JSON.stringify(value, null, 2)}
6586
6266
  }
6587
6267
  function readJsonl(file) {
6588
6268
  if (!fileExists(file)) return [];
6589
- return import_node_fs13.default.readFileSync(file, "utf8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
6269
+ return import_node_fs14.default.readFileSync(file, "utf8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
6590
6270
  try {
6591
6271
  return asJsonObject(JSON.parse(line));
6592
6272
  } catch {
@@ -6634,7 +6314,7 @@ function renderArtifact(root, def, args = {}) {
6634
6314
  }
6635
6315
  if (!body) return { ok: false, artifact_id: def.id, canonical_path: def.canonical, projection_path: def.projection, missing_canonical: missingCanonical };
6636
6316
  const content = withGeneratedMarker(def.canonical, def.schema, body);
6637
- const existing = projectionPath && fileExists(projectionPath) ? import_node_fs13.default.readFileSync(projectionPath, "utf8") : "";
6317
+ const existing = projectionPath && fileExists(projectionPath) ? import_node_fs14.default.readFileSync(projectionPath, "utf8") : "";
6638
6318
  return {
6639
6319
  ok: true,
6640
6320
  artifact_id: def.id,
@@ -6705,6 +6385,7 @@ function artifactSync(root, args = {}) {
6705
6385
  const skipped = [];
6706
6386
  const warnings = [];
6707
6387
  const errors = [];
6388
+ const traceBefore = execute && humanReviewConfirmed(args) ? beginTrace(root) : null;
6708
6389
  for (const def of defs) {
6709
6390
  const rendered = renderArtifact(root, def, args);
6710
6391
  artifacts.push({
@@ -6723,14 +6404,14 @@ function artifactSync(root, args = {}) {
6723
6404
  if (!execute) continue;
6724
6405
  if (!humanReviewConfirmed(args)) continue;
6725
6406
  const projectionFile = import_node_path28.default.join(root, def.projection);
6726
- const existing = fileExists(projectionFile) ? import_node_fs13.default.readFileSync(projectionFile, "utf8") : "";
6407
+ const existing = fileExists(projectionFile) ? import_node_fs14.default.readFileSync(projectionFile, "utf8") : "";
6727
6408
  if (existing && !hasGeneratedMarker(existing) && !force) {
6728
6409
  skipped.push(def.projection);
6729
6410
  warnings.push(`Skipped unmarked projection ${def.projection}; pass force:true or import first.`);
6730
6411
  continue;
6731
6412
  }
6732
6413
  ensureParent(projectionFile);
6733
- import_node_fs13.default.writeFileSync(projectionFile, rendered.content);
6414
+ import_node_fs14.default.writeFileSync(projectionFile, rendered.content);
6734
6415
  written.push(def.projection);
6735
6416
  }
6736
6417
  const reviewBundle = workflowReviewBundle(root, "artifacts", args, reviewFiles, {
@@ -6752,15 +6433,29 @@ function artifactSync(root, args = {}) {
6752
6433
  error: "Human confirmation is required before syncing artifacts"
6753
6434
  };
6754
6435
  }
6436
+ const controlCommit = execute ? commitTrace(root, args, {
6437
+ kind: "control",
6438
+ workflow: "artifacts",
6439
+ subject: "sync projections",
6440
+ before: traceBefore,
6441
+ files: written,
6442
+ note: {
6443
+ scope: args.scope || "all",
6444
+ artifact: args.artifact || null,
6445
+ written,
6446
+ skipped
6447
+ }
6448
+ }) : null;
6755
6449
  return {
6756
- ok: errors.length === 0,
6450
+ ok: errors.length === 0 && (!controlCommit || controlCommit.ok !== false),
6757
6451
  dry_run: !execute,
6758
- phase_state: execute ? "executed" : "dry_run",
6452
+ phase_state: execute ? controlCommit && controlCommit.ok === false ? "recovery_required" : "executed" : "dry_run",
6759
6453
  artifacts,
6760
6454
  review_bundle: reviewBundle,
6761
6455
  human_review: humanReview,
6762
6456
  written,
6763
6457
  skipped,
6458
+ control_commit: controlCommit,
6764
6459
  warnings,
6765
6460
  errors
6766
6461
  };
@@ -6787,64 +6482,19 @@ function artifactPacket(root, args = {}) {
6787
6482
  }
6788
6483
 
6789
6484
  // src/core/application/runtime/setup-infrastructure.ts
6790
- var import_node_fs14 = __toESM(require("node:fs"));
6485
+ var import_node_fs15 = __toESM(require("node:fs"));
6791
6486
  var import_node_path29 = __toESM(require("node:path"));
6792
6487
  function configuredCiProvider(root, args = {}) {
6793
6488
  const raw = asOptionalString(args.ciProvider || args.ci_provider) || asOptionalString(args.providerMode || args.provider_mode || args.provider) || asOptionalString(loadTopology(root).config.provider_mode);
6794
6489
  const provider = normalizeProviderMode(raw);
6795
6490
  return provider === "github" || provider === "gitlab" ? provider : null;
6796
6491
  }
6797
- function setupBeads(root, args = {}) {
6798
- const available = commandExists("bd", root);
6799
- const stateDir = import_node_path29.default.join(root, ".beads");
6800
- const initialized = fileExists(stateDir);
6801
- const command = ["bd", "init", "--non-interactive", "--role", "maintainer"];
6802
- if (args.execute !== true) {
6803
- return {
6804
- ok: true,
6805
- available,
6806
- initialized,
6807
- dry_run: true,
6808
- planned_command: command,
6809
- state_path: ".beads"
6810
- };
6811
- }
6812
- if (!available) {
6813
- return {
6814
- ok: false,
6815
- available: false,
6816
- initialized: false,
6817
- required: true,
6818
- error: "Beads CLI (bd) is required for cadre-setup execute and was not found on PATH"
6819
- };
6820
- }
6821
- if (initialized) {
6822
- return {
6823
- ok: true,
6824
- available: true,
6825
- initialized: true,
6826
- skipped: true,
6827
- reason: ".beads already exists",
6828
- state_path: ".beads"
6829
- };
6830
- }
6831
- const result = runCommand("bd", command.slice(1), { cwd: root, maxBuffer: 10 * 1024 * 1024 });
6832
- return {
6833
- ok: result.ok,
6834
- available: true,
6835
- initialized: result.ok || fileExists(stateDir),
6836
- command,
6837
- result,
6838
- state_path: ".beads"
6839
- };
6840
- }
6841
6492
  function setupGitattributes(root) {
6842
6493
  const file = import_node_path29.default.join(root, ".gitattributes");
6843
6494
  const required = [
6844
- ".beads/** merge=ours",
6845
6495
  "cadre/tracks/**/parallel_state.json merge=ours"
6846
6496
  ];
6847
- const existing = fileExists(file) ? import_node_fs14.default.readFileSync(file, "utf8") : "";
6497
+ const existing = fileExists(file) ? import_node_fs15.default.readFileSync(file, "utf8") : "";
6848
6498
  const lines = existing.split(/\r?\n/).filter(Boolean);
6849
6499
  let changed = false;
6850
6500
  for (const line of required) {
@@ -6854,7 +6504,7 @@ function setupGitattributes(root) {
6854
6504
  }
6855
6505
  }
6856
6506
  if (changed || !fileExists(file)) {
6857
- import_node_fs14.default.writeFileSync(file, `${lines.join("\n")}
6507
+ import_node_fs15.default.writeFileSync(file, `${lines.join("\n")}
6858
6508
  `);
6859
6509
  }
6860
6510
  const mergeDriver = runCommand("git", ["config", "merge.ours.driver", "true"], { cwd: root });
@@ -6880,8 +6530,8 @@ function setupCiTemplates(root, provider, args = {}) {
6880
6530
  if (fileExists(target) && args.force !== true) {
6881
6531
  return { ok: true, skipped: true, provider, source, path: import_node_path29.default.relative(root, target) };
6882
6532
  }
6883
- import_node_fs14.default.mkdirSync(import_node_path29.default.dirname(target), { recursive: true });
6884
- import_node_fs14.default.writeFileSync(target, sourceText);
6533
+ import_node_fs15.default.mkdirSync(import_node_path29.default.dirname(target), { recursive: true });
6534
+ import_node_fs15.default.writeFileSync(target, sourceText);
6885
6535
  return { ok: true, provider, source, path: import_node_path29.default.relative(root, target), written: true };
6886
6536
  }
6887
6537
  function setupSubmodulePlan(root, repos, args = {}) {
@@ -7110,7 +6760,6 @@ function doctor(root, options = {}) {
7110
6760
  "cadre/setup_state.json",
7111
6761
  "cadre/product.json",
7112
6762
  "cadre/config.json",
7113
- "cadre/beads.json",
7114
6763
  "cadre/lsp.json"
7115
6764
  ].filter((name) => fileExists(import_node_path30.default.join(candidateRoot, name)))
7116
6765
  },
@@ -7119,10 +6768,6 @@ function doctor(root, options = {}) {
7119
6768
  identity: gitIdentity(candidateRoot),
7120
6769
  merge_ours: mergeDriverStatus(candidateRoot)
7121
6770
  },
7122
- beads: {
7123
- available: commandExists("bd", candidateRoot),
7124
- config_present: fileExists(import_node_path30.default.join(candidateRoot, "cadre", "beads.json"))
7125
- },
7126
6771
  lsp: lspStatus,
7127
6772
  provider: providerMcpAvailability(candidateRoot, options),
7128
6773
  generated_bundles: {
@@ -7134,9 +6779,6 @@ function doctor(root, options = {}) {
7134
6779
  if (!checks.cadre_project.ok) {
7135
6780
  warnings.push("No Cadre project markers found. This is fine for the Cadre harness/source repo, but project-scoped Cadre workflows need setup first.");
7136
6781
  }
7137
- if (checks.cadre_project.ok && !checks.beads.available) {
7138
- warnings.push("Beads CLI (bd) is not available; Cadre project workflows require it.");
7139
- }
7140
6782
  if (checks.lsp.configured && lspMissing.length > 0) {
7141
6783
  warnings.push(`LSP config exists but missing server commands: ${lspMissing.join(", ")}`);
7142
6784
  }
@@ -7197,19 +6839,19 @@ function summarizeLspSetupResult(result) {
7197
6839
  function summarizeLspCoverage(root, args = {}) {
7198
6840
  const status = asJsonObject(lspConfigStatus(root));
7199
6841
  const setup = asJsonObject(lspSetup(root, { ...args, execute: false }));
7200
- const configured = Array.isArray(status.servers) ? status.servers.map((server) => asJsonObject(server).id || null).filter((id) => typeof id === "string" && id.length > 0) : [];
6842
+ const configured2 = Array.isArray(status.servers) ? status.servers.map((server) => asJsonObject(server).id || null).filter((id) => typeof id === "string" && id.length > 0) : [];
7201
6843
  const recommended = Array.isArray(setup.recommended) ? setup.recommended.map((entry) => asJsonObject(entry).id || null).filter((id) => typeof id === "string" && id.length > 0) : [];
7202
- const missing = recommended.filter((id) => !configured.includes(id));
7203
- const covered = recommended.filter((id) => configured.includes(id));
6844
+ const missing = recommended.filter((id) => !configured2.includes(id));
6845
+ const covered = recommended.filter((id) => configured2.includes(id));
7204
6846
  return {
7205
6847
  ok: status.configured !== false && setup.ok !== false,
7206
6848
  status_configured: status.configured !== false,
7207
- configured_count: configured.length,
6849
+ configured_count: configured2.length,
7208
6850
  recommended_count: recommended.length,
7209
6851
  covered_count: covered.length,
7210
6852
  missing_count: missing.length,
7211
6853
  coverage: recommended.length > 0 ? Math.round(covered.length / recommended.length * 100) : null,
7212
- configured: configured.slice(0, 10),
6854
+ configured: configured2.slice(0, 10),
7213
6855
  recommended: recommended.slice(0, 10),
7214
6856
  missing: missing.slice(0, 10)
7215
6857
  };
@@ -7234,10 +6876,10 @@ function normalizeIntegrationValue(value) {
7234
6876
  }
7235
6877
  if (isRecord(value)) {
7236
6878
  const entry = asJsonObject(value);
7237
- const configured = Object.keys(entry).length > 0;
6879
+ const configured2 = Object.keys(entry).length > 0;
7238
6880
  const available = typeof entry.available === "boolean" ? entry.available : typeof entry.enabled === "boolean" ? entry.enabled : typeof entry.configured === "boolean" ? entry.configured : entry.command || entry.server || entry.url ? true : null;
7239
6881
  return {
7240
- configured,
6882
+ configured: configured2,
7241
6883
  available,
7242
6884
  label: asOptionalString(entry.label) || asOptionalString(entry.name),
7243
6885
  command: asOptionalString(entry.command),
@@ -7370,16 +7012,543 @@ function integrationInventory(root, args = {}) {
7370
7012
  };
7371
7013
  }
7372
7014
 
7015
+ // src/core/application/runtime/formula-workflow.ts
7016
+ var import_node_fs17 = __toESM(require("node:fs"));
7017
+ var import_node_path32 = __toESM(require("node:path"));
7018
+
7019
+ // src/core/application/runtime/workflow-new-track.ts
7020
+ var import_node_fs16 = __toESM(require("node:fs"));
7021
+ var import_node_path31 = __toESM(require("node:path"));
7022
+ function newTrackReviewFiles(trackId, spec, plan, metadata) {
7023
+ const safeTrack = safeName(trackId);
7024
+ const specJson = normalizeSpecJson(trackId, spec);
7025
+ const planJson = normalizePlanJson(trackId, plan, specJson);
7026
+ const learningsEntry = {
7027
+ ...templateJson("learnings_seed.json", { id: "initial", kind: "learnings_seed" }),
7028
+ id: "initial",
7029
+ kind: "learnings_seed",
7030
+ track_id: trackId,
7031
+ recorded_at: utcNow(),
7032
+ text: trackLearningsText(trackId)
7033
+ };
7034
+ return [
7035
+ jsonReviewFile(
7036
+ `cadre/tracks/${safeTrack}/spec.json`,
7037
+ "Track spec canonical",
7038
+ "spec",
7039
+ specJson
7040
+ ),
7041
+ textReviewFile(
7042
+ `cadre/tracks/${safeTrack}/spec.md`,
7043
+ "Track spec",
7044
+ "spec.json",
7045
+ withGeneratedMarker(`cadre/tracks/${safeTrack}/spec.json`, "cadre.spec.v1", renderSpecMarkdown(specJson))
7046
+ ),
7047
+ jsonReviewFile(
7048
+ `cadre/tracks/${safeTrack}/plan.json`,
7049
+ "Track plan canonical",
7050
+ "plan",
7051
+ planJson
7052
+ ),
7053
+ textReviewFile(
7054
+ `cadre/tracks/${safeTrack}/plan.md`,
7055
+ "Track plan",
7056
+ "plan.json",
7057
+ withGeneratedMarker(`cadre/tracks/${safeTrack}/plan.json`, "cadre.plan.v1", renderPlanMarkdown(planJson))
7058
+ ),
7059
+ jsonReviewFile(
7060
+ `cadre/tracks/${safeTrack}/metadata.json`,
7061
+ "Track metadata",
7062
+ "metadata",
7063
+ metadata
7064
+ ),
7065
+ plainReviewFile(
7066
+ `cadre/tracks/${safeTrack}/learnings.jsonl`,
7067
+ "Track learnings canonical",
7068
+ "template:learnings_seed.json",
7069
+ `${JSON.stringify(learningsEntry)}
7070
+ `
7071
+ ),
7072
+ textReviewFile(
7073
+ `cadre/tracks/${safeTrack}/learnings.md`,
7074
+ "Track learnings",
7075
+ "learnings.jsonl",
7076
+ withGeneratedMarker(`cadre/tracks/${safeTrack}/learnings.jsonl`, "cadre.learnings.v1", trackLearningsText(trackId))
7077
+ )
7078
+ ];
7079
+ }
7080
+ function workflowNewTrack(root, args = {}) {
7081
+ const summary = workflowSummary(root, "newtrack", args);
7082
+ const markdownError = markdownPayloadError(args);
7083
+ if (markdownError) return { ...summary, ...markdownError };
7084
+ const trackId = args.trackId || args.track_id;
7085
+ if (!trackId) return { ...summary, ok: false, error: "trackId is required" };
7086
+ if (!isRecord(args.plan)) return { ...summary, ok: false, error: "plan is required" };
7087
+ const specJson = normalizeSpecJson(String(trackId), args.spec || { title: `Spec: ${trackId}`, description: asOptionalString(args.description) || String(trackId) });
7088
+ const planJson = normalizePlanJson(String(trackId), args.plan, specJson);
7089
+ const metadata = {
7090
+ track_id: trackId,
7091
+ type: "feature",
7092
+ status: "new",
7093
+ priority: "medium",
7094
+ depends_on: [],
7095
+ description: asOptionalString(args.description) || trackId,
7096
+ owner: gitIdentity(root) || null,
7097
+ reviewer: null,
7098
+ git_branch: `track/${trackId}`,
7099
+ worktree_path: `.worktrees/${trackId}`,
7100
+ ...args.metadata && typeof args.metadata === "object" ? args.metadata : {}
7101
+ };
7102
+ const reviewFiles = newTrackReviewFiles(String(trackId), specJson, planJson, metadata);
7103
+ const reviewArtifacts = reviewArtifactsFromFiles(reviewFiles);
7104
+ const reviewBundle = workflowReviewBundle(root, "newtrack", args, reviewFiles, { track_id: String(trackId) });
7105
+ const humanReview = humanReviewState("newtrack", args, reviewArtifacts, reviewBundle);
7106
+ const warnings = asStringArray(asJsonObject(reviewBundle).warnings);
7107
+ const dryRun = args.execute !== true;
7108
+ const assist = planAssist(root, { ...args, plan: planJson, trackId });
7109
+ if (dryRun) {
7110
+ return {
7111
+ ...summary,
7112
+ ok: assist.ok !== false,
7113
+ dry_run: true,
7114
+ track_id: trackId,
7115
+ metadata,
7116
+ plan_assist: assist,
7117
+ human_review: humanReview,
7118
+ review_artifacts: reviewArtifacts,
7119
+ review_bundle: reviewBundle,
7120
+ warnings
7121
+ };
7122
+ }
7123
+ if (findTrack(root, trackId)) {
7124
+ return { ...summary, ok: false, track_id: trackId, error: "Track already exists" };
7125
+ }
7126
+ if (!humanReviewConfirmed(args)) {
7127
+ return {
7128
+ ...summary,
7129
+ ok: false,
7130
+ dry_run: true,
7131
+ phase_state: "awaiting_human_review",
7132
+ stage: "human_review",
7133
+ track_id: trackId,
7134
+ metadata,
7135
+ plan_assist: assist,
7136
+ human_review: humanReview,
7137
+ review_artifacts: reviewArtifacts,
7138
+ review_bundle: reviewBundle,
7139
+ warnings,
7140
+ error: "Human confirmation is required before creating track artifacts"
7141
+ };
7142
+ }
7143
+ const traceBefore = beginTrace(root);
7144
+ const dir = import_node_path31.default.join(root, "cadre", "tracks", safeName(trackId));
7145
+ const learningsEntry = {
7146
+ ...templateJson("learnings_seed.json", { id: "initial", kind: "learnings_seed" }),
7147
+ id: "initial",
7148
+ kind: "learnings_seed",
7149
+ track_id: String(trackId),
7150
+ recorded_at: utcNow(),
7151
+ text: trackLearningsText(String(trackId))
7152
+ };
7153
+ import_node_fs16.default.mkdirSync(dir, { recursive: true });
7154
+ writeJson(import_node_path31.default.join(dir, "metadata.json"), metadata);
7155
+ writeJson(import_node_path31.default.join(dir, "spec.json"), specJson);
7156
+ writeJson(import_node_path31.default.join(dir, "plan.json"), planJson);
7157
+ import_node_fs16.default.writeFileSync(import_node_path31.default.join(dir, "spec.md"), withGeneratedMarker(`cadre/tracks/${safeName(trackId)}/spec.json`, "cadre.spec.v1", renderSpecMarkdown(specJson)));
7158
+ import_node_fs16.default.writeFileSync(import_node_path31.default.join(dir, "plan.md"), withGeneratedMarker(`cadre/tracks/${safeName(trackId)}/plan.json`, "cadre.plan.v1", renderPlanMarkdown(planJson)));
7159
+ import_node_fs16.default.writeFileSync(import_node_path31.default.join(dir, "learnings.jsonl"), `${JSON.stringify(learningsEntry)}
7160
+ `);
7161
+ import_node_fs16.default.writeFileSync(import_node_path31.default.join(dir, "learnings.md"), withGeneratedMarker(`cadre/tracks/${safeName(trackId)}/learnings.jsonl`, "cadre.learnings.v1", trackLearningsText(String(trackId))));
7162
+ const regen = regenIndex(root);
7163
+ const event = appendCadreEvent(root, {
7164
+ kind: "track_created",
7165
+ workflow: "newtrack",
7166
+ track_id: String(trackId),
7167
+ status: metadata.status,
7168
+ tags: metadata.tags || []
7169
+ });
7170
+ const controlCommit = commitTrace(root, args, {
7171
+ kind: "control",
7172
+ workflow: "newtrack",
7173
+ subject: `create ${trackId}`,
7174
+ before: traceBefore,
7175
+ trackId: String(trackId),
7176
+ note: {
7177
+ event_id: asOptionalString(asJsonObject(event.event).id) || null,
7178
+ formula_id: asOptionalString(args.formulaId || args.formula_id) || null,
7179
+ wisp_id: asOptionalString(args.wispId || args.wisp_id) || null
7180
+ }
7181
+ });
7182
+ return {
7183
+ ...summary,
7184
+ ok: regen.ok !== false && controlCommit.ok !== false,
7185
+ dry_run: false,
7186
+ track_id: trackId,
7187
+ metadata_path: import_node_path31.default.relative(root, import_node_path31.default.join(dir, "metadata.json")),
7188
+ regen,
7189
+ event,
7190
+ control_commit: controlCommit,
7191
+ phase_state: controlCommit.ok === false ? "recovery_required" : "executed",
7192
+ human_review: humanReview,
7193
+ worktree_plan: worktreePlan(root, { trackId })
7194
+ };
7195
+ }
7196
+
7197
+ // src/core/application/runtime/formula-workflow.ts
7198
+ var READ_ACTIONS = /* @__PURE__ */ new Set(["list", "show", "cook", "wisp_list", "pour"]);
7199
+ function formulaAction(args) {
7200
+ const rawArgs = args;
7201
+ const raw = asOptionalString(rawArgs.operation) || asOptionalString(rawArgs.mode) || asOptionalString(rawArgs.formulaAction || rawArgs.formula_action) || (asOptionalString(args.action) && asOptionalString(args.action) !== "formula" ? asOptionalString(args.action) : null) || "list";
7202
+ const normalized = raw.replace(/^formula_/, "").replace(/-/g, "_");
7203
+ if (normalized === "wisp_update") return "wisp_update_step";
7204
+ if (normalized === "squash") return "wisp_squash";
7205
+ if (normalized === "burn") return "wisp_burn";
7206
+ if (normalized === "create_wisp") return "wisp_create";
7207
+ if (normalized === "list_wisps") return "wisp_list";
7208
+ if (normalized === "update_step") return "wisp_update_step";
7209
+ return [
7210
+ "list",
7211
+ "show",
7212
+ "cook",
7213
+ "wisp_create",
7214
+ "wisp_list",
7215
+ "wisp_update_step",
7216
+ "wisp_squash",
7217
+ "wisp_burn",
7218
+ "pour"
7219
+ ].includes(normalized) ? normalized : "list";
7220
+ }
7221
+ function formulaDir(root) {
7222
+ return import_node_path32.default.join(root, "cadre", "formulas");
7223
+ }
7224
+ function wispDir(root) {
7225
+ return import_node_path32.default.join(root, "cadre", "local", "wisps");
7226
+ }
7227
+ function formulaId(args) {
7228
+ const rawArgs = args;
7229
+ return asOptionalString(args.id) || asOptionalString(rawArgs.formulaId || rawArgs.formula_id) || asOptionalString(args.name) || null;
7230
+ }
7231
+ function wispId(args) {
7232
+ const rawArgs = args;
7233
+ return asOptionalString(args.id) || asOptionalString(rawArgs.wispId || rawArgs.wisp_id) || null;
7234
+ }
7235
+ function formulaPath(root, id) {
7236
+ return import_node_path32.default.join(formulaDir(root), `${safeName(id).replace(/\.json$/i, "")}.json`);
7237
+ }
7238
+ function wispPath(root, id) {
7239
+ return import_node_path32.default.join(wispDir(root), `${safeName(id).replace(/\.json$/i, "")}.json`);
7240
+ }
7241
+ function loadFormula(root, id) {
7242
+ if (!id) return { ok: false, error: "formula id is required" };
7243
+ const file = formulaPath(root, id);
7244
+ const formula = readJson(file, null);
7245
+ if (!formula) return { ok: false, id, error: `Formula not found: ${id}`, path: import_node_path32.default.relative(root, file) };
7246
+ return { ok: true, id: asOptionalString(formula.id) || id, path: import_node_path32.default.relative(root, file), formula };
7247
+ }
7248
+ function variablesFromArgs(formula, args) {
7249
+ const rawArgs = args;
7250
+ return {
7251
+ ...asJsonObject(formula.defaults),
7252
+ ...asJsonObject(rawArgs.variables),
7253
+ ...asJsonObject(rawArgs.vars)
7254
+ };
7255
+ }
7256
+ function variableValue(variables, key) {
7257
+ const value = key.split(".").reduce((current, part) => isRecord(current) ? asJsonObject(current)[part] : void 0, variables);
7258
+ if (value == null) return "";
7259
+ return typeof value === "string" ? value : JSON.stringify(value);
7260
+ }
7261
+ function renderTemplateValue(value, variables) {
7262
+ if (typeof value === "string") {
7263
+ return value.replace(/\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}/g, (_match, key) => variableValue(variables, String(key)));
7264
+ }
7265
+ if (Array.isArray(value)) return value.map((item) => renderTemplateValue(item, variables));
7266
+ if (isRecord(value)) {
7267
+ return Object.fromEntries(Object.entries(asJsonObject(value)).map(([key, entry]) => [key, renderTemplateValue(entry, variables)]));
7268
+ }
7269
+ return value;
7270
+ }
7271
+ function stepsFromFormula(formula) {
7272
+ return Array.isArray(formula.steps) ? formula.steps.map(asJsonObject) : [];
7273
+ }
7274
+ function cookedPlan(trackId, formula, rendered) {
7275
+ if (isRecord(rendered.plan)) return asJsonObject(rendered.plan);
7276
+ const steps = stepsFromFormula(rendered);
7277
+ const phaseTitle = asOptionalString(rendered.phase_title) || asOptionalString(rendered.recommended_phase) || "Formula";
7278
+ return {
7279
+ version: 1,
7280
+ schema: "cadre.plan.v1",
7281
+ track_id: trackId,
7282
+ title: `Plan: ${trackId}`,
7283
+ phases: [{
7284
+ phase_index: 1,
7285
+ title: phaseTitle,
7286
+ execution_mode: asOptionalString(rendered.execution_mode) || "sequential",
7287
+ depends_on: asStringArray(rendered.dependencies),
7288
+ tasks: steps.map((step, index) => ({
7289
+ task_index: index + 1,
7290
+ task_key: asOptionalString(step.id || step.key) || `formula_step_${index + 1}`,
7291
+ title: asOptionalString(step.title) || asOptionalString(step.description) || `Formula step ${index + 1}`,
7292
+ status: asOptionalString(step.status) || "pending",
7293
+ labels: asStringArray(step.labels),
7294
+ depends_on: asStringArray(step.depends_on || step.depends),
7295
+ files: asStringArray(step.files),
7296
+ repo: asOptionalString(step.repo) || null,
7297
+ task_type: asOptionalString(step.task_type) || null,
7298
+ description: asOptionalString(step.description) || null
7299
+ }))
7300
+ }]
7301
+ };
7302
+ }
7303
+ function cookedSpec(trackId, formula, rendered) {
7304
+ if (isRecord(rendered.spec)) return asJsonObject(rendered.spec);
7305
+ return {
7306
+ version: 1,
7307
+ schema: "cadre.spec.v1",
7308
+ track_id: trackId,
7309
+ title: asOptionalString(rendered.title) || `Spec: ${trackId}`,
7310
+ description: asOptionalString(rendered.description) || asOptionalString(formula.description) || asOptionalString(formula.title) || trackId,
7311
+ acceptance: asStringArray(rendered.acceptance)
7312
+ };
7313
+ }
7314
+ function cookFormula(root, args) {
7315
+ const loaded = loadFormula(root, formulaId(args));
7316
+ if (loaded.ok === false) return loaded;
7317
+ const formula = asJsonObject(loaded.formula);
7318
+ const variables = variablesFromArgs(formula, args);
7319
+ const rendered = asJsonObject(renderTemplateValue(formula, variables));
7320
+ const trackId = asOptionalString(args.trackId || args.track_id) || asOptionalString(args.trackName || args.track_name) || `${asOptionalString(formula.id) || loaded.id}-draft`;
7321
+ return {
7322
+ ok: true,
7323
+ formula_id: loaded.id,
7324
+ title: asOptionalString(formula.title) || loaded.id,
7325
+ variables,
7326
+ recommended_phase: asOptionalString(formula.recommended_phase) || null,
7327
+ dependencies: asStringArray(formula.dependencies),
7328
+ spec: cookedSpec(trackId, formula, rendered),
7329
+ plan: cookedPlan(trackId, formula, rendered)
7330
+ };
7331
+ }
7332
+ function listFormulas(root) {
7333
+ ensureNativeState(root);
7334
+ const dir = formulaDir(root);
7335
+ const items = fileExists(dir) ? import_node_fs17.default.readdirSync(dir).filter((name) => name.endsWith(".json")).map((name) => {
7336
+ const file = import_node_path32.default.join(dir, name);
7337
+ const formula = readJson(file, {});
7338
+ return {
7339
+ id: asOptionalString(formula.id) || name.replace(/\.json$/i, ""),
7340
+ title: asOptionalString(formula.title) || asOptionalString(formula.id) || name,
7341
+ recommended_phase: asOptionalString(formula.recommended_phase) || null,
7342
+ path: import_node_path32.default.relative(root, file)
7343
+ };
7344
+ }) : [];
7345
+ return { ok: true, formulas: items, count: items.length };
7346
+ }
7347
+ function wispSteps(cooked) {
7348
+ const plan = asJsonObject(cooked.plan);
7349
+ const phases = Array.isArray(plan.phases) ? plan.phases.map(asJsonObject) : [];
7350
+ return phases.flatMap((phase) => {
7351
+ const phaseIndex = Number(phase.phase_index || phase.index || 1);
7352
+ return (Array.isArray(phase.tasks) ? phase.tasks.map(asJsonObject) : []).map((task, index) => ({
7353
+ step_id: asOptionalString(task.task_key || task.id || task.key) || `step_${phaseIndex}_${index + 1}`,
7354
+ phase_index: phaseIndex,
7355
+ task_index: Number(task.task_index || task.index || index + 1),
7356
+ title: asOptionalString(task.title) || `Step ${index + 1}`,
7357
+ status: "pending",
7358
+ evidence: null,
7359
+ updated_at: null
7360
+ }));
7361
+ });
7362
+ }
7363
+ function createWisp(root, args) {
7364
+ const cooked = cookFormula(root, args);
7365
+ if (cooked.ok === false) return cooked;
7366
+ const formula_id = asOptionalString(cooked.formula_id) || "formula";
7367
+ const now = utcNow();
7368
+ const id = asOptionalString(args.wispId || args.wisp_id) || `wisp_${safeName(formula_id)}_${textHash(`${now}:${JSON.stringify(cooked.variables || {})}`).slice(0, 10)}`;
7369
+ const wisp = {
7370
+ version: 1,
7371
+ schema: "cadre.wisp.v1",
7372
+ id,
7373
+ formula_id,
7374
+ status: "active",
7375
+ owner: asOptionalString(args.identity) || null,
7376
+ ttl: asOptionalString(args.ttl) || null,
7377
+ created_at: now,
7378
+ updated_at: now,
7379
+ variables: asJsonObject(cooked.variables),
7380
+ spec: asJsonObject(cooked.spec),
7381
+ plan: asJsonObject(cooked.plan),
7382
+ steps: wispSteps(asJsonObject(cooked)),
7383
+ evidence: []
7384
+ };
7385
+ const file = wispPath(root, id);
7386
+ writeJsonEnsured(file, wisp);
7387
+ const event = appendCadreEvent(root, { kind: "wisp_created", workflow: "formula", formula_id, wisp_id: id });
7388
+ return { ok: true, wisp_id: id, path: import_node_path32.default.relative(root, file), wisp, event };
7389
+ }
7390
+ function listWisps(root) {
7391
+ ensureNativeState(root);
7392
+ const dir = wispDir(root);
7393
+ const wisps = fileExists(dir) ? import_node_fs17.default.readdirSync(dir).filter((name) => name.endsWith(".json")).map((name) => {
7394
+ const file = import_node_path32.default.join(dir, name);
7395
+ const wisp = readJson(file, {});
7396
+ return {
7397
+ id: asOptionalString(wisp.id) || name.replace(/\.json$/i, ""),
7398
+ formula_id: asOptionalString(wisp.formula_id) || null,
7399
+ status: asOptionalString(wisp.status) || null,
7400
+ owner: asOptionalString(wisp.owner) || null,
7401
+ updated_at: asOptionalString(wisp.updated_at) || null,
7402
+ path: import_node_path32.default.relative(root, file)
7403
+ };
7404
+ }) : [];
7405
+ return { ok: true, wisps, count: wisps.length };
7406
+ }
7407
+ function updateWispStep(root, args) {
7408
+ const id = wispId(args);
7409
+ if (!id) return { ok: false, error: "wisp id is required" };
7410
+ const file = wispPath(root, id);
7411
+ const wisp = readJson(file, null);
7412
+ if (!wisp) return { ok: false, error: `Wisp not found: ${id}`, path: import_node_path32.default.relative(root, file) };
7413
+ const rawArgs = args;
7414
+ const stepId = asOptionalString(rawArgs.stepId || rawArgs.step_id || rawArgs.taskKey || rawArgs.task_key);
7415
+ const stepIndex = Number(rawArgs.stepIndex || rawArgs.step_index || args.taskIndex || 0);
7416
+ const steps = Array.isArray(wisp.steps) ? wisp.steps.map(asJsonObject) : [];
7417
+ const index = steps.findIndex(
7418
+ (step, offset) => stepId && asOptionalString(step.step_id) === stepId || stepIndex > 0 && offset + 1 === stepIndex
7419
+ );
7420
+ if (index < 0) return { ok: false, error: "Wisp step not found", wisp_id: id, step_id: stepId || null, step_index: stepIndex || null };
7421
+ const now = utcNow();
7422
+ const status = asOptionalString(args.status) || "completed";
7423
+ const currentStep = steps[index] || {};
7424
+ steps[index] = {
7425
+ ...currentStep,
7426
+ status,
7427
+ evidence: isRecord(args.evidence) ? asJsonObject(args.evidence) : asOptionalString(args.evidence) || asJsonObject(currentStep.evidence),
7428
+ summary: asOptionalString(args.summary) || asOptionalString(currentStep.summary) || null,
7429
+ updated_at: now
7430
+ };
7431
+ const next = { ...wisp, steps, status: asOptionalString(wisp.status) || "active", updated_at: now };
7432
+ writeJsonEnsured(file, next);
7433
+ const event = appendCadreEvent(root, { kind: "wisp_step_updated", workflow: "formula", wisp_id: id, step_id: asOptionalString(steps[index].step_id) || null, status });
7434
+ return { ok: true, wisp_id: id, path: import_node_path32.default.relative(root, file), step: steps[index], wisp: next, event };
7435
+ }
7436
+ function squashWisp(root, args) {
7437
+ const id = wispId(args);
7438
+ if (!id) return { ok: false, error: "wisp id is required" };
7439
+ const file = wispPath(root, id);
7440
+ const wisp = readJson(file, null);
7441
+ if (!wisp) return { ok: false, error: `Wisp not found: ${id}`, path: import_node_path32.default.relative(root, file) };
7442
+ const traceBefore = beginTrace(root);
7443
+ const digest = {
7444
+ version: 1,
7445
+ schema: "cadre.wisp_digest.v1",
7446
+ id: `digest_${safeName(id)}_${textHash(`${utcNow()}:${JSON.stringify(wisp)}`).slice(0, 10)}`,
7447
+ wisp_id: id,
7448
+ formula_id: asOptionalString(wisp.formula_id) || null,
7449
+ status: asOptionalString(args.status) || asOptionalString(wisp.status) || "squashed",
7450
+ summary: asOptionalString(args.summary) || null,
7451
+ recorded_at: utcNow(),
7452
+ steps: Array.isArray(wisp.steps) ? wisp.steps.map(asJsonObject) : [],
7453
+ evidence: Array.isArray(wisp.evidence) ? wisp.evidence.map(asJsonObject) : []
7454
+ };
7455
+ const digestPath = import_node_path32.default.join(root, "cadre", "operations", "wisp-digests.jsonl");
7456
+ appendJsonl(digestPath, digest);
7457
+ const event = appendCadreEvent(root, { kind: "wisp_squashed", workflow: "formula", wisp_id: id, digest_id: digest.id });
7458
+ const controlCommit = commitTrace(root, args, {
7459
+ kind: "control",
7460
+ workflow: "wisp",
7461
+ action: "wisp_squash",
7462
+ subject: `squash ${id}`,
7463
+ before: traceBefore,
7464
+ files: [
7465
+ import_node_path32.default.relative(root, digestPath)
7466
+ ],
7467
+ note: {
7468
+ event_id: asOptionalString(asJsonObject(event.event).id) || null,
7469
+ wisp_id: id,
7470
+ digest_id: digest.id,
7471
+ formula_id: digest.formula_id
7472
+ }
7473
+ });
7474
+ return { ok: controlCommit.ok !== false, wisp_id: id, digest, path: import_node_path32.default.relative(root, digestPath), event, control_commit: controlCommit };
7475
+ }
7476
+ function burnWisp(root, args) {
7477
+ const id = wispId(args);
7478
+ if (!id) return { ok: false, error: "wisp id is required" };
7479
+ const file = wispPath(root, id);
7480
+ const existed = fileExists(file);
7481
+ if (existed) import_node_fs17.default.rmSync(file, { force: true });
7482
+ const event = appendCadreEvent(root, { kind: "wisp_burned", workflow: "formula", wisp_id: id, existed });
7483
+ return { ok: true, wisp_id: id, existed, path: import_node_path32.default.relative(root, file), event };
7484
+ }
7485
+ function pourFormula(root, args) {
7486
+ const id = wispId(args);
7487
+ const wisp = id ? readJson(wispPath(root, id), null) : null;
7488
+ const cooked = wisp ? { ok: true, formula_id: asOptionalString(wisp.formula_id), spec: asJsonObject(wisp.spec), plan: asJsonObject(wisp.plan), variables: asJsonObject(wisp.variables) } : cookFormula(root, args);
7489
+ if (cooked.ok === false) return cooked;
7490
+ const formula_id = asOptionalString(cooked.formula_id) || formulaId(args) || "formula";
7491
+ const trackId = asOptionalString(args.trackId || args.track_id) || asOptionalString(args.outputTrackId || args.output_track_id) || `${safeName(formula_id)}-${textHash(JSON.stringify(cooked.variables || {})).slice(0, 8)}`;
7492
+ const tags = Array.from(/* @__PURE__ */ new Set([
7493
+ `formula:${formula_id}`,
7494
+ ...asStringArray(asJsonObject(args.metadata).tags)
7495
+ ]));
7496
+ const result = workflowNewTrack(root, {
7497
+ ...args,
7498
+ workflow: "newtrack",
7499
+ action: "newtrack",
7500
+ trackId,
7501
+ formulaId: formula_id,
7502
+ wispId: id || void 0,
7503
+ spec: asJsonObject(cooked.spec),
7504
+ plan: asJsonObject(cooked.plan),
7505
+ description: asOptionalString(args.description) || `Formula output: ${formula_id}`,
7506
+ metadata: {
7507
+ ...asJsonObject(args.metadata),
7508
+ tags
7509
+ }
7510
+ });
7511
+ const pourTraceBefore = result.ok === false ? null : beginTrace(root);
7512
+ const event = result.ok === false ? null : appendCadreEvent(root, { kind: "formula_poured", workflow: "formula", formula_id, wisp_id: id || null, track_id: trackId });
7513
+ const controlCommit = result.ok === false || !event ? null : { ok: true, skipped: true, reason: "formula pour is traced by the newtrack commit", trace_before: pourTraceBefore };
7514
+ return { ...result, ok: result.ok !== false && (!controlCommit || controlCommit.ok !== false), formula_id, wisp_id: id || null, pour_event: event, pour_commit: controlCommit };
7515
+ }
7516
+ function workflowFormula(root, args = {}) {
7517
+ const action = formulaAction(args);
7518
+ const summary = workflowSummary(root, "formula", args);
7519
+ ensureNativeState(root);
7520
+ if (action === "list") return { ...summary, action, ...listFormulas(root) };
7521
+ if (action === "show") return { ...summary, action, ...loadFormula(root, formulaId(args)) };
7522
+ if (action === "cook") return { ...summary, action, ...cookFormula(root, args) };
7523
+ if (action === "wisp_list") return { ...summary, action, ...listWisps(root) };
7524
+ if (args.execute !== true && !READ_ACTIONS.has(action)) {
7525
+ return {
7526
+ ...summary,
7527
+ ok: false,
7528
+ action,
7529
+ dry_run: true,
7530
+ phase_state: "awaiting_execute",
7531
+ error: `Formula action ${action} requires execute:true`
7532
+ };
7533
+ }
7534
+ if (action === "wisp_create") return { ...summary, action, ...createWisp(root, args) };
7535
+ if (action === "wisp_update_step") return { ...summary, action, ...updateWispStep(root, args) };
7536
+ if (action === "wisp_squash") return { ...summary, action, ...squashWisp(root, args) };
7537
+ if (action === "wisp_burn") return { ...summary, action, ...burnWisp(root, args) };
7538
+ if (action === "pour") return { ...summary, action, ...pourFormula(root, args) };
7539
+ return { ...summary, ok: false, action, error: `Unknown formula action: ${action}` };
7540
+ }
7541
+
7373
7542
  // src/core/application/runtime/parallel-state.ts
7374
- var import_node_path33 = __toESM(require("node:path"));
7543
+ var import_node_path35 = __toESM(require("node:path"));
7375
7544
 
7376
7545
  // src/core/application/runtime/task-completion.ts
7377
- var import_node_path32 = __toESM(require("node:path"));
7546
+ var import_node_path34 = __toESM(require("node:path"));
7378
7547
 
7379
7548
  // src/core/application/runtime/manual-verification.ts
7380
- var import_node_path31 = __toESM(require("node:path"));
7549
+ var import_node_path33 = __toESM(require("node:path"));
7381
7550
  function completionJournalPath(track) {
7382
- return import_node_path31.default.join(track.dir, "completion_journal.json");
7551
+ return import_node_path33.default.join(track.dir, "completion_journal.json");
7383
7552
  }
7384
7553
  function readCompletionJournal(track) {
7385
7554
  const value = readJson(completionJournalPath(track), { entries: {} });
@@ -7399,7 +7568,7 @@ function patchCompletionJournal(track, key, patcher) {
7399
7568
  journal.entries[key] = patcher({ ...before }, journal);
7400
7569
  journal.updated_at = utcNow();
7401
7570
  writeCompletionJournal(track, journal);
7402
- appendJsonl(import_node_path31.default.join(track.dir, "completion_journal.jsonl"), {
7571
+ appendJsonl(import_node_path33.default.join(track.dir, "completion_journal.jsonl"), {
7403
7572
  key,
7404
7573
  recorded_at: journal.updated_at,
7405
7574
  entry: journal.entries[key]
@@ -7616,50 +7785,30 @@ function completeTaskInner(root, args = {}) {
7616
7785
  reason: `Coverage ${coverage.coverage}% is below required ${threshold}%; task was not marked complete`
7617
7786
  };
7618
7787
  }
7619
- const metadataBefore = readJson(track.metadata_path, track.metadata) || track.metadata;
7620
- const mappedBeadsTaskId = metadataBefore.beads_tasks ? asOptionalString(metadataBefore.beads_tasks[task.task_key]) || null : null;
7621
- const explicitBeadsTaskId = args.beadsTaskId || args.taskId || null;
7622
- const beadsTaskId = explicitBeadsTaskId || mappedBeadsTaskId;
7623
- const beadsConfigured = Boolean(
7624
- explicitBeadsTaskId || metadataBefore.beads_epic || metadataBefore.beads_tasks && Object.keys(metadataBefore.beads_tasks).length > 0
7625
- );
7626
- const beadsAvailable = commandExists("bd", root);
7627
- const beads = {
7628
- attempted: false,
7629
- required: beadsConfigured,
7630
- available: beadsAvailable,
7631
- note: null,
7632
- close: null,
7633
- skipped_reason: null
7634
- };
7635
- if (beadsConfigured && !beadsTaskId) {
7636
- return {
7637
- ok: false,
7638
- stage: "beads_mapping",
7639
- blocked: true,
7640
- threshold,
7641
- working_root: workingRoot,
7642
- coverage,
7643
- beads,
7644
- reason: "Track has Beads metadata but this plan task has no mapped Beads task id; task was not marked complete"
7645
- };
7646
- }
7647
- if (beadsTaskId && !beadsAvailable) {
7648
- return {
7649
- ok: false,
7650
- stage: "beads_unavailable",
7651
- blocked: true,
7652
- threshold,
7653
- working_root: workingRoot,
7654
- coverage,
7655
- beads,
7656
- reason: "Beads CLI (bd) is required for this mapped task but is not installed or not on PATH; task was not marked complete"
7657
- };
7658
- }
7659
- if (!beadsConfigured) {
7660
- beads.skipped_reason = "Track has no Beads task mapping";
7661
- } else {
7662
- beads.attempted = true;
7788
+ let resolvedCommitSha = args.commitSha ? String(args.commitSha).trim() : "";
7789
+ let productCommit = null;
7790
+ if (!resolvedCommitSha && args.allowNoCommit !== true) {
7791
+ const productBefore = beginTrace(workingRoot.path);
7792
+ productCommit = commitTrace(root, args, {
7793
+ kind: "product",
7794
+ workflow: "complete_task",
7795
+ subject: task.title.replace(/^Task\s+\d+:\s*/i, ""),
7796
+ scope: asOptionalString(workingRoot.repo) && workingRoot.repo !== "." ? asOptionalString(workingRoot.repo) || "task" : "task",
7797
+ cwd: workingRoot.path,
7798
+ before: productBefore,
7799
+ files: asStringArray(args.filesChanged || args.files_changed || args.files).length > 0 ? asStringArray(args.filesChanged || args.files_changed || args.files) : task.files,
7800
+ allowDirty: true,
7801
+ trackId: track.track_id,
7802
+ repo: workingRoot.repo,
7803
+ note: {
7804
+ phase_index: phaseIndex,
7805
+ task_index: taskIndex,
7806
+ task_key: task.task_key,
7807
+ coverage: coverage.coverage ?? null
7808
+ }
7809
+ });
7810
+ if (productCommit.ok === false) return { ...productCommit, stage: "product_commit", working_root: workingRoot };
7811
+ resolvedCommitSha = asOptionalString(productCommit.commit_sha) || "";
7663
7812
  }
7664
7813
  const lastTestRun = manualVerificationTask ? null : {
7665
7814
  command: coverage.command,
@@ -7673,9 +7822,10 @@ function completeTaskInner(root, args = {}) {
7673
7822
  allow_missing_coverage: allowMissingCoverage,
7674
7823
  allow_low_coverage: allowLowCoverage
7675
7824
  };
7676
- const sha = args.commitSha ? String(args.commitSha).slice(0, 12) : "unknown";
7825
+ const sha = resolvedCommitSha ? resolvedCommitSha.slice(0, 12) : "unknown";
7677
7826
  const dedupKey = `key: ${track.track_id}:p${phaseIndex}:t${taskIndex}:${sha.slice(0, 7)}`;
7678
7827
  const journalKey = `${phaseIndex}:${taskIndex}:${sha}`;
7828
+ const controlBefore = beginTrace(root);
7679
7829
  const recordState = () => {
7680
7830
  const entry = patchCompletionJournal(track, journalKey, (current) => ({
7681
7831
  ...current,
@@ -7693,10 +7843,10 @@ function completeTaskInner(root, args = {}) {
7693
7843
  phaseIndex,
7694
7844
  taskIndex,
7695
7845
  status: args.status || "completed",
7696
- commitSha: args.commitSha,
7846
+ commitSha: resolvedCommitSha || args.commitSha,
7697
7847
  coverage: coverage.coverage,
7698
7848
  repo: workingRoot.repo,
7699
- workingRoot: import_node_path32.default.relative(root, workingRoot.path) || ".",
7849
+ workingRoot: import_node_path34.default.relative(root, workingRoot.path) || ".",
7700
7850
  ...lastTestRun ? { lastTestRun } : {},
7701
7851
  ...manualVerificationEvidence ? { manualVerificationEvidence } : {}
7702
7852
  });
@@ -7706,7 +7856,7 @@ function completeTaskInner(root, args = {}) {
7706
7856
  stage: "record_task_result_failed",
7707
7857
  error: taskResult.error || asOptionalString(taskResult.stage) || "record task result failed"
7708
7858
  }));
7709
- return { ok: false, stage: "record_task_result", threshold, working_root: workingRoot, coverage, task_result: taskResult, beads, journal: entry };
7859
+ return { ok: false, stage: "record_task_result", threshold, working_root: workingRoot, coverage, task_result: taskResult, journal: entry };
7710
7860
  }
7711
7861
  const taskResultJson = asJsonObject(taskResult);
7712
7862
  const recordedEntry = patchCompletionJournal(track, journalKey, (current) => ({
@@ -7722,75 +7872,62 @@ function completeTaskInner(root, args = {}) {
7722
7872
  return { ok: true, task_result: taskResult, journal: recordedEntry };
7723
7873
  };
7724
7874
  const stateResult = args.lock === false ? recordState() : withTrackLock(root, track.track_id, recordState);
7725
- if (!stateResult.ok) return { ...stateResult, threshold, working_root: workingRoot, coverage, beads };
7875
+ if (!stateResult.ok) return { ...stateResult, threshold, working_root: workingRoot, coverage };
7726
7876
  const stateTaskResult = asJsonObject(stateResult.task_result);
7727
- if (beadsTaskId) {
7728
- const latest = readCompletionJournal(track).entries[journalKey] || {};
7729
- if (!latest.beads_note_written) {
7730
- const note = [
7731
- dedupKey,
7732
- `COMPLETED: ${task.title}`,
7733
- `COMMIT: ${sha}`,
7734
- `COVERAGE: ${coverage.coverage == null ? "unmeasured" : `${coverage.coverage}%`}`,
7735
- args.summary ? `SUMMARY: ${args.summary}` : null
7736
- ].filter(Boolean).join("\n");
7737
- const noteResult = beadsTaskWrite(root, { operation: "note", id: beadsTaskId, note, dedupKey });
7738
- beads.note = noteResult;
7739
- if (!noteResult.ok) return { ok: false, stage: "beads_note", threshold, working_root: workingRoot, coverage, task_result: stateTaskResult, beads, journal: latest };
7740
- const writeNote = () => patchCompletionJournal(track, journalKey, (current) => ({
7741
- ...current,
7742
- stage: "beads_note_written",
7743
- beads_note_written: true,
7744
- beads_note_at: utcNow()
7745
- }));
7746
- if (args.lock === false) writeNote();
7747
- else {
7748
- const noteJournal = withTrackLock(root, track.track_id, writeNote);
7749
- if (!noteJournal.ok) return { ...noteJournal, stage: "journal_note", threshold, working_root: workingRoot, coverage, task_result: stateTaskResult, beads };
7750
- }
7751
- } else {
7752
- beads.note = { ok: true, skipped: true, reason: "completion journal already recorded Beads note" };
7753
- }
7754
- const afterNote = readCompletionJournal(track).entries[journalKey] || {};
7755
- if (!afterNote.beads_close_written) {
7756
- const closeResult = beadsTaskWrite(root, {
7757
- operation: "close",
7758
- id: beadsTaskId,
7759
- continue: true,
7760
- reason: args.reason || `commit: ${args.commitSha || "completed"}`
7761
- });
7762
- beads.close = closeResult;
7763
- if (!closeResult.ok) return { ok: false, stage: "beads_close", threshold, working_root: workingRoot, coverage, task_result: stateTaskResult, beads, journal: afterNote };
7764
- const writeClose = () => patchCompletionJournal(track, journalKey, (current) => ({
7765
- ...current,
7766
- stage: "beads_closed",
7767
- beads_close_written: true,
7768
- beads_close_at: utcNow()
7769
- }));
7770
- if (args.lock === false) writeClose();
7771
- else {
7772
- const closeJournal = withTrackLock(root, track.track_id, writeClose);
7773
- if (!closeJournal.ok) return { ...closeJournal, stage: "journal_close", threshold, working_root: workingRoot, coverage, task_result: stateTaskResult, beads };
7774
- }
7775
- } else {
7776
- beads.close = { ok: true, skipped: true, reason: "completion journal already recorded Beads close" };
7777
- }
7778
- }
7779
7877
  const markComplete = () => patchCompletionJournal(track, journalKey, (current) => ({
7780
7878
  ...current,
7781
7879
  stage: "completed",
7782
7880
  completed_at: current.completed_at || utcNow()
7783
7881
  }));
7784
7882
  const completedJournal = args.lock === false ? markComplete() : withTrackLock(root, track.track_id, markComplete);
7883
+ const event = appendCadreEvent(root, {
7884
+ kind: "task_completed",
7885
+ workflow: "complete_task",
7886
+ track_id: track.track_id,
7887
+ phase_index: phaseIndex,
7888
+ task_index: taskIndex,
7889
+ task_key: stateTaskResult.task_key,
7890
+ status: args.status || "completed",
7891
+ commit_sha: sha,
7892
+ coverage: coverage.coverage ?? null,
7893
+ summary: args.summary || null,
7894
+ journal_key: journalKey
7895
+ });
7896
+ const controlCommit = commitTrace(root, args, {
7897
+ kind: "control",
7898
+ workflow: "complete",
7899
+ subject: `record ${track.track_id} phase ${phaseIndex} task ${taskIndex}`,
7900
+ before: controlBefore,
7901
+ files: [
7902
+ import_node_path34.default.relative(root, track.metadata_path),
7903
+ import_node_path34.default.relative(root, track.plan_path),
7904
+ import_node_path34.default.relative(root, trackPlanJsonPath(track)),
7905
+ import_node_path34.default.relative(root, completionJournalPath(track)),
7906
+ import_node_path34.default.relative(root, `${completionJournalPath(track)}l`),
7907
+ "cadre/events.jsonl"
7908
+ ],
7909
+ trackId: track.track_id,
7910
+ repo: ".",
7911
+ note: {
7912
+ event_id: asOptionalString(asJsonObject(event.event).id) || null,
7913
+ phase_index: phaseIndex,
7914
+ task_index: taskIndex,
7915
+ task_key: stateTaskResult.task_key,
7916
+ product_commit_sha: asOptionalString(productCommit?.commit_sha) || resolvedCommitSha || null,
7917
+ coverage: coverage.coverage ?? null
7918
+ }
7919
+ });
7785
7920
  return {
7786
- ok: true,
7921
+ ok: controlCommit.ok !== false,
7787
7922
  track_id: track.track_id,
7788
7923
  task_key: stateTaskResult.task_key,
7789
7924
  working_root: workingRoot,
7790
7925
  threshold,
7791
7926
  coverage,
7927
+ product_commit: productCommit,
7928
+ control_commit: controlCommit,
7792
7929
  task_result: stateTaskResult,
7793
- beads,
7930
+ event,
7794
7931
  journal: completedJournal.ok === false ? completedJournal : completedJournal.value || completedJournal
7795
7932
  };
7796
7933
  }
@@ -7805,6 +7942,7 @@ function recordParallelWorkerInner(root, args = {}) {
7805
7942
  return withTrackLock(root, track.track_id, () => recordParallelWorkerUnlocked(root, track, args));
7806
7943
  }
7807
7944
  function recordParallelWorkerUnlocked(root, track, args = {}) {
7945
+ const traceBefore = beginTrace(root);
7808
7946
  const workerId = args.workerId || args.worker_id;
7809
7947
  if (!workerId) return { ok: false, error: "workerId is required" };
7810
7948
  const status = args.status || "awaiting_merge";
@@ -7813,7 +7951,7 @@ function recordParallelWorkerUnlocked(root, track, args = {}) {
7813
7951
  if (status === "awaiting_merge" && !args.commitSha && !args.commit && args.allowNoCommit !== true) {
7814
7952
  return { ok: false, error: "commitSha is required before a parallel worker can move to awaiting_merge" };
7815
7953
  }
7816
- const statePath = import_node_path33.default.join(track.dir, "parallel_state.json");
7954
+ const statePath = import_node_path35.default.join(track.dir, "parallel_state.json");
7817
7955
  const existing = readJson(statePath, {
7818
7956
  track_id: track.track_id,
7819
7957
  execution_mode: "parallel",
@@ -7838,7 +7976,6 @@ function recordParallelWorkerUnlocked(root, track, args = {}) {
7838
7976
  phase_index: args.phaseIndex ?? existingWorker?.phase_index ?? null,
7839
7977
  task_index: args.taskIndex ?? existingWorker?.task_index ?? null,
7840
7978
  task_key: args.phaseIndex && args.taskIndex ? `phase${args.phaseIndex}_task${args.taskIndex}` : existingWorker?.task_key ?? null,
7841
- beads_task_id: args.beadsTaskId || args.taskId || existingWorker?.beads_task_id || null,
7842
7979
  repo: args.repo || existingWorker?.repo || null,
7843
7980
  worktree: args.worktree || existingWorker?.worktree || null,
7844
7981
  branch: args.branch || existingWorker?.branch || null,
@@ -7874,7 +8011,6 @@ function recordParallelWorkerUnlocked(root, track, args = {}) {
7874
8011
  allowLowCoverage: args.allowLowCoverage,
7875
8012
  summary: args.summary || `parallel worker ${workerId}`,
7876
8013
  reason: args.reason || `merged ${workerId}`,
7877
- beadsTaskId: nextWorker.beads_task_id,
7878
8014
  repo: nextWorker.repo || args.repo,
7879
8015
  workingRoot: args.workingRoot || nextWorker.worktree || args.worktree,
7880
8016
  lock: false
@@ -7882,12 +8018,33 @@ function recordParallelWorkerUnlocked(root, track, args = {}) {
7882
8018
  if (!completion.ok) return { ok: false, stage: "complete_task", state_path: statePath, worker: nextWorker, completion };
7883
8019
  }
7884
8020
  writeJson(statePath, state);
8021
+ const shouldTrace = status !== "in_progress";
8022
+ const controlCommit = shouldTrace ? commitTrace(root, args, {
8023
+ kind: "control",
8024
+ workflow: "parallel",
8025
+ action: status,
8026
+ subject: `record ${workerId}`,
8027
+ before: traceBefore,
8028
+ files: [
8029
+ import_node_path35.default.relative(root, statePath)
8030
+ ],
8031
+ trackId: track.track_id,
8032
+ repo: nextWorker.repo || null,
8033
+ note: {
8034
+ worker_id: workerId,
8035
+ status,
8036
+ phase_index: nextWorker.phase_index ?? null,
8037
+ task_index: nextWorker.task_index ?? null,
8038
+ commit_sha: nextWorker.commit_sha || null
8039
+ }
8040
+ }) : { ok: true, skipped: true, reason: "parallel worker setup is transient" };
7885
8041
  return {
7886
- ok: true,
8042
+ ok: controlCommit.ok !== false,
7887
8043
  track_id: track.track_id,
7888
- state_path: import_node_path33.default.relative(root, statePath),
8044
+ state_path: import_node_path35.default.relative(root, statePath),
7889
8045
  worker: nextWorker,
7890
8046
  completion,
8047
+ control_commit: controlCommit,
7891
8048
  summary: {
7892
8049
  total_workers: state.workers.length,
7893
8050
  completed_workers: state.completed_workers,
@@ -7897,7 +8054,7 @@ function recordParallelWorkerUnlocked(root, track, args = {}) {
7897
8054
  };
7898
8055
  }
7899
8056
  function parallelStatePath(track) {
7900
- return import_node_path33.default.join(track.dir, "parallel_state.json");
8057
+ return import_node_path35.default.join(track.dir, "parallel_state.json");
7901
8058
  }
7902
8059
  function readParallelState(track) {
7903
8060
  const existing = readJson(parallelStatePath(track), {
@@ -7917,7 +8074,7 @@ function readParallelState(track) {
7917
8074
  }
7918
8075
 
7919
8076
  // src/core/application/runtime/parallel-workflow.ts
7920
- var import_node_path34 = __toESM(require("node:path"));
8077
+ var import_node_path36 = __toESM(require("node:path"));
7921
8078
  function positiveInt(value, fallback, max = 20) {
7922
8079
  const parsed = Number(value);
7923
8080
  if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
@@ -7930,7 +8087,7 @@ function changedFilesFromArgs(args) {
7930
8087
  return asStringArray(args.filesChanged || args.files_changed || args.files);
7931
8088
  }
7932
8089
  function isManifestChange(file) {
7933
- const base = import_node_path34.default.basename(file).toLowerCase();
8090
+ const base = import_node_path36.default.basename(file).toLowerCase();
7934
8091
  return [
7935
8092
  "package.json",
7936
8093
  "package-lock.json",
@@ -7951,7 +8108,7 @@ function isManifestChange(file) {
7951
8108
  ].includes(base);
7952
8109
  }
7953
8110
  function fileStem(file) {
7954
- return import_node_path34.default.basename(file).replace(/\.(test|spec|_test)\.[^.]+$/i, "").replace(/\.[^.]+$/, "");
8111
+ return import_node_path36.default.basename(file).replace(/\.(test|spec|_test)\.[^.]+$/i, "").replace(/\.[^.]+$/, "");
7955
8112
  }
7956
8113
  function isNarrowTestChange(file, ownedFiles) {
7957
8114
  const normalized = normalizeClaimPath(file);
@@ -8110,7 +8267,7 @@ function workerDispatchPayload(root, track, worker, worktree, sourceRoot, agentI
8110
8267
  `Source root: ${sourceRoot}`,
8111
8268
  `Worker worktree: ${worktree}`,
8112
8269
  ownedFiles.length > 0 ? `Owned files: ${ownedFiles.join(", ")}` : "Owned files: none declared; inspect the task plan before editing.",
8113
- "Use only Cadre packets for Cadre, Beads, provider, index, and worker-state mutations.",
8270
+ "Use only Cadre packets for Cadre, provider, index, and worker-state mutations.",
8114
8271
  "Change only the assigned product files unless the task requires a narrowly related test or manifest update.",
8115
8272
  "Run the smallest relevant tests first, then the configured project gate when practical.",
8116
8273
  "Commit the worker worktree changes and return the structured result JSON."
@@ -8180,7 +8337,7 @@ function parallelSetupWorkers(root, track, args = {}) {
8180
8337
  const worker = asJsonObject(rawWorker);
8181
8338
  const repo = asString(worker.repo, ".");
8182
8339
  const entry = entries.get(repo) || { root, base: args.base || "main" };
8183
- const worktree = import_node_path34.default.resolve(root, ".worktrees", track.track_id, safeName(repo), safeName(worker.task_key));
8340
+ const worktree = import_node_path36.default.resolve(root, ".worktrees", track.track_id, safeName(repo), safeName(worker.task_key));
8184
8341
  const sourceRoot = asString(entry.root || root);
8185
8342
  commands.push(plannedCommand(
8186
8343
  "git",
@@ -8349,8 +8506,8 @@ function parallelWorkflow(root, args = {}) {
8349
8506
  }
8350
8507
 
8351
8508
  // src/core/application/runtime/workflow-basic.ts
8352
- var import_node_fs15 = __toESM(require("node:fs"));
8353
- var import_node_path35 = __toESM(require("node:path"));
8509
+ var import_node_fs18 = __toESM(require("node:fs"));
8510
+ var import_node_path37 = __toESM(require("node:path"));
8354
8511
  function workflowImplement(root, args = {}) {
8355
8512
  const prep = implementationPrep(root, {
8356
8513
  ...args,
@@ -8371,7 +8528,6 @@ function workflowStatus(root, args = {}) {
8371
8528
  if (mode === "fleet" || mode === "repos") return { ...summary, ok: true, status: fleetStatus(root, args) };
8372
8529
  if (mode === "available") return { ...summary, ok: true, status: availableWork(root) };
8373
8530
  if (mode === "collisions") return { ...summary, ok: true, status: collisionScan(root) };
8374
- if (mode === "beads") return { ...summary, ok: true, status: beadsSummary(root) };
8375
8531
  if (mode === "doctor") return { ...summary, ok: true, status: doctor(root, { hasCadreProject: true }) };
8376
8532
  return { ...summary, ok: true, status: liveStatus(root) };
8377
8533
  }
@@ -8408,7 +8564,7 @@ function workflowValidate(root, args = {}) {
8408
8564
  integrity: planIntegrity(root, args.trackId || args.track_id || null),
8409
8565
  collisions: collisionScan(root),
8410
8566
  fleet: fleetStatus(root, { includeCollisions: false }),
8411
- beads: beadsSummary(root)
8567
+ native_state: nativeStateSummary(root)
8412
8568
  };
8413
8569
  }
8414
8570
  function workflowArchive(root, args = {}) {
@@ -8449,27 +8605,40 @@ function workflowArchive(root, args = {}) {
8449
8605
  }
8450
8606
  const syncPre = syncControlPlane(root, { mode: "pre" });
8451
8607
  if (syncPre.ok === false) return { ...summary, ok: false, phase_state: "blocked", stage: "sync_pre", sync_pre: syncPre };
8608
+ const traceBefore = beginTrace(root);
8452
8609
  const archived = [];
8453
- const archiveRoot = import_node_path35.default.join(root, "cadre", "archive");
8454
- import_node_fs15.default.mkdirSync(archiveRoot, { recursive: true });
8610
+ const archiveRoot = import_node_path37.default.join(root, "cadre", "archive");
8611
+ import_node_fs18.default.mkdirSync(archiveRoot, { recursive: true });
8455
8612
  for (const track of tracks) {
8456
- const target = import_node_path35.default.join(archiveRoot, track.track_id);
8613
+ const target = import_node_path37.default.join(archiveRoot, track.track_id);
8457
8614
  if (fileExists(target)) {
8458
8615
  archived.push({ track_id: track.track_id, ok: false, error: "Archive target already exists" });
8459
8616
  continue;
8460
8617
  }
8461
- import_node_fs15.default.renameSync(track.dir, target);
8462
- archived.push({ track_id: track.track_id, ok: true, path: import_node_path35.default.relative(root, target) });
8618
+ import_node_fs18.default.renameSync(track.dir, target);
8619
+ archived.push({ track_id: track.track_id, ok: true, path: import_node_path37.default.relative(root, target) });
8463
8620
  }
8464
8621
  const regen = regenIndex(root);
8622
+ const controlCommit = commitTrace(root, args, {
8623
+ kind: "control",
8624
+ workflow: "archive",
8625
+ subject: tracks.length === 1 ? `archive ${tracks[0]?.track_id || "track"}` : `archive ${tracks.length} tracks`,
8626
+ before: traceBefore,
8627
+ trackId: tracks.length === 1 ? tracks[0]?.track_id || null : null,
8628
+ note: {
8629
+ tracks: tracks.map((track) => track.track_id),
8630
+ archived: archived.map(asJsonObject)
8631
+ }
8632
+ });
8465
8633
  const syncPost = syncControlPlane(root, { mode: "post" });
8466
8634
  return {
8467
8635
  ...summary,
8468
- ok: archived.every((item) => item.ok !== false) && regen.ok !== false && syncPost.ok !== false,
8469
- phase_state: syncPost.ok === false ? "recovery_required" : "executed",
8636
+ ok: archived.every((item) => item.ok !== false) && regen.ok !== false && controlCommit.ok !== false && syncPost.ok !== false,
8637
+ phase_state: syncPost.ok === false || controlCommit.ok === false ? "recovery_required" : "executed",
8470
8638
  dry_run: false,
8471
8639
  archived,
8472
8640
  regen,
8641
+ control_commit: controlCommit,
8473
8642
  sync_pre: syncPre,
8474
8643
  sync_post: syncPost
8475
8644
  };
@@ -8489,16 +8658,16 @@ function workflowHandoff(root, args = {}) {
8489
8658
  "",
8490
8659
  "Resume from the packet context returned by Cadre MCP."
8491
8660
  ].join("\n");
8492
- const handoffPath = import_node_path35.default.join(track.dir, "HANDOFF.md");
8661
+ const handoffPath = import_node_path37.default.join(track.dir, "HANDOFF.md");
8493
8662
  const handoffJsonPath = trackHandoffJsonPath(track);
8494
8663
  const handoffJson = markdownDocJson("handoff", text, { track_id: trackId });
8495
8664
  const reviewFiles = [
8496
- jsonReviewFile(import_node_path35.default.relative(root, handoffJsonPath), "Track handoff canonical", "handoffText", handoffJson),
8665
+ jsonReviewFile(import_node_path37.default.relative(root, handoffJsonPath), "Track handoff canonical", "handoffText", handoffJson),
8497
8666
  textReviewFile(
8498
- import_node_path35.default.relative(root, handoffPath),
8667
+ import_node_path37.default.relative(root, handoffPath),
8499
8668
  "Track handoff",
8500
8669
  "handoff.json",
8501
- withGeneratedMarker(import_node_path35.default.relative(root, handoffJsonPath), "cadre.handoff.v1", renderMarkdownDoc(handoffJson, `Handoff: ${trackId}`))
8670
+ withGeneratedMarker(import_node_path37.default.relative(root, handoffJsonPath), "cadre.handoff.v1", renderMarkdownDoc(handoffJson, `Handoff: ${trackId}`))
8502
8671
  )
8503
8672
  ];
8504
8673
  const reviewArtifacts = reviewArtifactsFromFiles(reviewFiles);
@@ -8509,8 +8678,7 @@ function workflowHandoff(root, args = {}) {
8509
8678
  ...summary,
8510
8679
  track_id: trackId,
8511
8680
  track_context: context,
8512
- beads: beadsSummary(root),
8513
- handoff_path: import_node_path35.default.relative(root, handoffPath),
8681
+ handoff_path: import_node_path37.default.relative(root, handoffPath),
8514
8682
  human_review: humanReview,
8515
8683
  review_artifacts: reviewArtifacts,
8516
8684
  review_bundle: reviewBundle,
@@ -8534,206 +8702,57 @@ function workflowHandoff(root, args = {}) {
8534
8702
  error: "Human confirmation is required before writing handoff artifacts"
8535
8703
  };
8536
8704
  }
8705
+ const traceBefore = beginTrace(root);
8537
8706
  if (args.execute === true) {
8538
8707
  writeJsonEnsured(handoffJsonPath, handoffJson);
8539
- import_node_fs15.default.writeFileSync(handoffPath, withGeneratedMarker(import_node_path35.default.relative(root, handoffJsonPath), "cadre.handoff.v1", renderMarkdownDoc(handoffJson, `Handoff: ${trackId}`)));
8708
+ import_node_fs18.default.writeFileSync(handoffPath, withGeneratedMarker(import_node_path37.default.relative(root, handoffJsonPath), "cadre.handoff.v1", renderMarkdownDoc(handoffJson, `Handoff: ${trackId}`)));
8540
8709
  }
8541
- return {
8542
- ...base,
8543
- ok: true,
8544
- dry_run: args.execute !== true,
8545
- phase_state: "executed"
8546
- };
8547
- }
8548
-
8549
- // src/core/application/runtime/workflow-new-track.ts
8550
- var import_node_fs16 = __toESM(require("node:fs"));
8551
- var import_node_path36 = __toESM(require("node:path"));
8552
- function newTrackReviewFiles(trackId, spec, plan, metadata) {
8553
- const safeTrack = safeName(trackId);
8554
- const specJson = normalizeSpecJson(trackId, spec);
8555
- const planJson = normalizePlanJson(trackId, plan, specJson);
8556
- const learningsEntry = {
8557
- ...templateJson("learnings_seed.json", { id: "initial", kind: "learnings_seed" }),
8558
- id: "initial",
8559
- kind: "learnings_seed",
8710
+ const recipient = asOptionalString(args.to || args.assignee || track.metadata.reviewer) || null;
8711
+ const subject = asOptionalString(args.subject) || `Handoff: ${trackId}`;
8712
+ const message = appendCadreMessage(root, "outbox", {
8713
+ kind: "handoff",
8714
+ workflow: "handoff",
8560
8715
  track_id: trackId,
8561
- recorded_at: utcNow(),
8562
- text: trackLearningsText(trackId)
8563
- };
8564
- return [
8565
- jsonReviewFile(
8566
- `cadre/tracks/${safeTrack}/spec.json`,
8567
- "Track spec canonical",
8568
- "spec",
8569
- specJson
8570
- ),
8571
- textReviewFile(
8572
- `cadre/tracks/${safeTrack}/spec.md`,
8573
- "Track spec",
8574
- "spec.json",
8575
- withGeneratedMarker(`cadre/tracks/${safeTrack}/spec.json`, "cadre.spec.v1", renderSpecMarkdown(specJson))
8576
- ),
8577
- jsonReviewFile(
8578
- `cadre/tracks/${safeTrack}/plan.json`,
8579
- "Track plan canonical",
8580
- "plan",
8581
- planJson
8582
- ),
8583
- textReviewFile(
8584
- `cadre/tracks/${safeTrack}/plan.md`,
8585
- "Track plan",
8586
- "plan.json",
8587
- withGeneratedMarker(`cadre/tracks/${safeTrack}/plan.json`, "cadre.plan.v1", renderPlanMarkdown(planJson))
8588
- ),
8589
- jsonReviewFile(
8590
- `cadre/tracks/${safeTrack}/metadata.json`,
8591
- "Track metadata",
8592
- "metadata",
8593
- metadata
8594
- ),
8595
- plainReviewFile(
8596
- `cadre/tracks/${safeTrack}/learnings.jsonl`,
8597
- "Track learnings canonical",
8598
- "template:learnings_seed.json",
8599
- `${JSON.stringify(learningsEntry)}
8600
- `
8601
- ),
8602
- textReviewFile(
8603
- `cadre/tracks/${safeTrack}/learnings.md`,
8604
- "Track learnings",
8605
- "learnings.jsonl",
8606
- withGeneratedMarker(`cadre/tracks/${safeTrack}/learnings.jsonl`, "cadre.learnings.v1", trackLearningsText(trackId))
8607
- )
8608
- ];
8609
- }
8610
- function workflowNewTrack(root, args = {}) {
8611
- const summary = workflowSummary(root, "newtrack", args);
8612
- const markdownError = markdownPayloadError(args);
8613
- if (markdownError) return { ...summary, ...markdownError };
8614
- const trackId = args.trackId || args.track_id;
8615
- if (!trackId) return { ...summary, ok: false, error: "trackId is required" };
8616
- if (!isRecord(args.plan)) return { ...summary, ok: false, error: "plan is required" };
8617
- const specJson = normalizeSpecJson(String(trackId), args.spec || { title: `Spec: ${trackId}`, description: asOptionalString(args.description) || String(trackId) });
8618
- const planJson = normalizePlanJson(String(trackId), args.plan, specJson);
8619
- const metadata = {
8716
+ to: recipient,
8717
+ subject,
8718
+ body: asOptionalString(args.body) || text,
8719
+ handoff_path: import_node_path37.default.relative(root, handoffPath),
8720
+ handoff_json_path: import_node_path37.default.relative(root, handoffJsonPath)
8721
+ });
8722
+ const event = appendCadreEvent(root, {
8723
+ kind: "handoff_created",
8724
+ workflow: "handoff",
8620
8725
  track_id: trackId,
8621
- type: "feature",
8622
- status: "new",
8623
- priority: "medium",
8624
- depends_on: [],
8625
- description: asOptionalString(args.description) || trackId,
8626
- owner: gitIdentity(root) || null,
8627
- reviewer: null,
8628
- git_branch: `track/${trackId}`,
8629
- worktree_path: `.worktrees/${trackId}`,
8630
- ...args.metadata && typeof args.metadata === "object" ? args.metadata : {}
8631
- };
8632
- const reviewFiles = newTrackReviewFiles(String(trackId), specJson, planJson, metadata);
8633
- const reviewArtifacts = reviewArtifactsFromFiles(reviewFiles);
8634
- const reviewBundle = workflowReviewBundle(root, "newtrack", args, reviewFiles, { track_id: String(trackId) });
8635
- const humanReview = humanReviewState("newtrack", args, reviewArtifacts, reviewBundle);
8636
- const warnings = asStringArray(asJsonObject(reviewBundle).warnings);
8637
- const dryRun = args.execute !== true;
8638
- const assist = planAssist(root, { ...args, plan: planJson, trackId });
8639
- const beads = createBeadsTree(root, {
8640
- ...args,
8641
- dryRun: true,
8726
+ to: recipient,
8727
+ subject,
8728
+ handoff_path: import_node_path37.default.relative(root, handoffPath)
8729
+ });
8730
+ const controlCommit = commitTrace(root, args, {
8731
+ kind: "control",
8732
+ workflow: "handoff",
8733
+ subject: `record ${trackId} handoff`,
8734
+ before: traceBefore,
8642
8735
  trackId,
8643
- plan: planJson,
8644
- spec: specJson,
8645
- metadata
8736
+ note: {
8737
+ event_id: asOptionalString(asJsonObject(event.event).id) || null,
8738
+ message_id: asOptionalString(asJsonObject(message.message).id) || null,
8739
+ to: recipient
8740
+ }
8646
8741
  });
8647
- if (dryRun) {
8648
- return {
8649
- ...summary,
8650
- ok: assist.ok !== false && beads.ok !== false,
8651
- dry_run: true,
8652
- track_id: trackId,
8653
- metadata,
8654
- plan_assist: assist,
8655
- beads_tree: beads,
8656
- human_review: humanReview,
8657
- review_artifacts: reviewArtifacts,
8658
- review_bundle: reviewBundle,
8659
- warnings
8660
- };
8661
- }
8662
- if (findTrack(root, trackId)) {
8663
- return { ...summary, ok: false, track_id: trackId, error: "Track already exists" };
8664
- }
8665
- if (!humanReviewConfirmed(args)) {
8666
- return {
8667
- ...summary,
8668
- ok: false,
8669
- dry_run: true,
8670
- phase_state: "awaiting_human_review",
8671
- stage: "human_review",
8672
- track_id: trackId,
8673
- metadata,
8674
- plan_assist: assist,
8675
- beads_tree: beads,
8676
- human_review: humanReview,
8677
- review_artifacts: reviewArtifacts,
8678
- review_bundle: reviewBundle,
8679
- warnings,
8680
- error: "Human confirmation is required before creating track artifacts"
8681
- };
8682
- }
8683
- if (!commandExists("bd", root)) {
8684
- return {
8685
- ...summary,
8686
- ok: false,
8687
- track_id: trackId,
8688
- error: "Beads CLI (bd) is required for live track creation"
8689
- };
8690
- }
8691
- const dir = import_node_path36.default.join(root, "cadre", "tracks", safeName(trackId));
8692
- const learningsEntry = {
8693
- ...templateJson("learnings_seed.json", { id: "initial", kind: "learnings_seed" }),
8694
- id: "initial",
8695
- kind: "learnings_seed",
8696
- track_id: String(trackId),
8697
- recorded_at: utcNow(),
8698
- text: trackLearningsText(String(trackId))
8699
- };
8700
- import_node_fs16.default.mkdirSync(dir, { recursive: true });
8701
- writeJson(import_node_path36.default.join(dir, "metadata.json"), metadata);
8702
- writeJson(import_node_path36.default.join(dir, "spec.json"), specJson);
8703
- writeJson(import_node_path36.default.join(dir, "plan.json"), planJson);
8704
- import_node_fs16.default.writeFileSync(import_node_path36.default.join(dir, "spec.md"), withGeneratedMarker(`cadre/tracks/${safeName(trackId)}/spec.json`, "cadre.spec.v1", renderSpecMarkdown(specJson)));
8705
- import_node_fs16.default.writeFileSync(import_node_path36.default.join(dir, "plan.md"), withGeneratedMarker(`cadre/tracks/${safeName(trackId)}/plan.json`, "cadre.plan.v1", renderPlanMarkdown(planJson)));
8706
- import_node_fs16.default.writeFileSync(import_node_path36.default.join(dir, "learnings.jsonl"), `${JSON.stringify(learningsEntry)}
8707
- `);
8708
- import_node_fs16.default.writeFileSync(import_node_path36.default.join(dir, "learnings.md"), withGeneratedMarker(`cadre/tracks/${safeName(trackId)}/learnings.jsonl`, "cadre.learnings.v1", trackLearningsText(String(trackId))));
8709
- const liveBeads = createBeadsTree(root, { ...args, trackId, plan: planJson, spec: specJson, dryRun: false });
8710
- if (!liveBeads.ok) {
8711
- import_node_fs16.default.rmSync(dir, { recursive: true, force: true });
8712
- return {
8713
- ...summary,
8714
- ok: false,
8715
- track_id: trackId,
8716
- stage: "create_beads_tree",
8717
- beads_tree: liveBeads
8718
- };
8719
- }
8720
- const regen = regenIndex(root);
8721
8742
  return {
8722
- ...summary,
8723
- ok: regen.ok !== false,
8724
- dry_run: false,
8725
- track_id: trackId,
8726
- metadata_path: import_node_path36.default.relative(root, import_node_path36.default.join(dir, "metadata.json")),
8727
- beads_tree: liveBeads,
8728
- regen,
8729
- human_review: humanReview,
8730
- worktree_plan: worktreePlan(root, { trackId })
8743
+ ...base,
8744
+ ok: controlCommit.ok !== false,
8745
+ dry_run: args.execute !== true,
8746
+ phase_state: controlCommit.ok === false ? "recovery_required" : "executed",
8747
+ message,
8748
+ event,
8749
+ control_commit: controlCommit
8731
8750
  };
8732
8751
  }
8733
8752
 
8734
8753
  // src/core/application/runtime/workflow-refresh-revert.ts
8735
- var import_node_fs17 = __toESM(require("node:fs"));
8736
- var import_node_path37 = __toESM(require("node:path"));
8754
+ var import_node_fs19 = __toESM(require("node:fs"));
8755
+ var import_node_path38 = __toESM(require("node:path"));
8737
8756
  function refreshedPatternsText(text, now = utcNow()) {
8738
8757
  const stamp = `Last refreshed: ${now.slice(0, 10)}`;
8739
8758
  const next = /Last refreshed:\s*.*/.test(text) ? text.replace(/Last refreshed:\s*.*/, stamp) : `${text.replace(/\n*$/, "\n\n")}${stamp}
@@ -8741,7 +8760,7 @@ function refreshedPatternsText(text, now = utcNow()) {
8741
8760
  return { text: next, stamp };
8742
8761
  }
8743
8762
  function refreshedPatternsArtifacts(root) {
8744
- const jsonlPath = import_node_path37.default.join(root, "cadre", "patterns.jsonl");
8763
+ const jsonlPath = import_node_path38.default.join(root, "cadre", "patterns.jsonl");
8745
8764
  if (!fileExists(jsonlPath)) return null;
8746
8765
  const entries = readJsonl(jsonlPath);
8747
8766
  const seed = entries[0] || templateJson("patterns_seed.json", { id: "initial", kind: "patterns_seed", text: "# Codebase Patterns\n\nLast refreshed: YYYY-MM-DD\n" });
@@ -8750,11 +8769,11 @@ function refreshedPatternsArtifacts(root) {
8750
8769
  const nextEntries = [{ ...seed, text: next.text, refreshed_at: utcNow() }, ...entries.slice(1)];
8751
8770
  const jsonl = nextEntries.map((entry) => JSON.stringify(entry)).join("\n").replace(/\n*$/, "\n");
8752
8771
  const projection = withGeneratedMarker("cadre/patterns.jsonl", "cadre.patterns.v1", renderJsonlMarkdown("Project patterns", nextEntries));
8753
- const projectionPath = import_node_path37.default.join(root, "cadre", "patterns.md");
8772
+ const projectionPath = import_node_path38.default.join(root, "cadre", "patterns.md");
8754
8773
  return {
8755
8774
  files: [
8756
- plainReviewFile(import_node_path37.default.relative(root, jsonlPath), "Refreshed project patterns canonical", "refresh:patterns", jsonl),
8757
- textReviewFile(import_node_path37.default.relative(root, projectionPath), "Refreshed project patterns projection", "cadre/patterns.jsonl", projection)
8775
+ plainReviewFile(import_node_path38.default.relative(root, jsonlPath), "Refreshed project patterns canonical", "refresh:patterns", jsonl),
8776
+ textReviewFile(import_node_path38.default.relative(root, projectionPath), "Refreshed project patterns projection", "cadre/patterns.jsonl", projection)
8758
8777
  ],
8759
8778
  jsonlPath,
8760
8779
  projectionPath,
@@ -8827,6 +8846,7 @@ function workflowRevert(root, args = {}) {
8827
8846
  }
8828
8847
  const gitResults = args.execute === true ? runPlannedGitActions(gitActions) : [];
8829
8848
  const gitOk = actionResultsOk(gitResults);
8849
+ const traceBefore = args.execute === true && gitOk ? beginTrace(root) : null;
8830
8850
  const statusResult = args.execute === true && gitOk ? metadataPatch(root, {
8831
8851
  trackId,
8832
8852
  patch: {
@@ -8838,15 +8858,27 @@ function workflowRevert(root, args = {}) {
8838
8858
  }
8839
8859
  }
8840
8860
  }) : null;
8861
+ const controlCommit = args.execute === true && gitOk && statusResult && statusResult.ok !== false ? commitTrace(root, args, {
8862
+ kind: "control",
8863
+ workflow: "revert",
8864
+ subject: `record ${trackId} revert`,
8865
+ before: traceBefore,
8866
+ trackId,
8867
+ note: {
8868
+ git_results: gitResults.map(asJsonObject),
8869
+ reason: args.reason || null
8870
+ }
8871
+ }) : null;
8841
8872
  return {
8842
8873
  ...summary,
8843
- ok: args.execute === true ? gitOk && (!statusResult || statusResult.ok !== false) : true,
8844
- phase_state: args.execute !== true ? "dry_run" : gitOk ? "executed" : "recovery_required",
8874
+ ok: args.execute === true ? gitOk && (!statusResult || statusResult.ok !== false) && (!controlCommit || controlCommit.ok !== false) : true,
8875
+ phase_state: args.execute !== true ? "dry_run" : gitOk && (!controlCommit || controlCommit.ok !== false) ? "executed" : "recovery_required",
8845
8876
  dry_run: args.execute !== true,
8846
8877
  track_context: trackContext(root, trackId),
8847
8878
  git_actions: gitActions,
8848
8879
  git_results: gitResults,
8849
8880
  metadata_patch: statusResult,
8881
+ control_commit: controlCommit,
8850
8882
  human_review: humanReview,
8851
8883
  review_artifacts: reviewArtifacts
8852
8884
  };
@@ -8861,6 +8893,7 @@ function workflowRefresh(root, args = {}) {
8861
8893
  const warnings = asStringArray(asJsonObject(reviewBundle).warnings);
8862
8894
  const awaitingDocumentReview = args.execute === true && reviewFiles.length > 0 && !humanReviewConfirmed(args);
8863
8895
  const lspRequested = args.execute === true && !awaitingDocumentReview && setupLspWriteRequested(args);
8896
+ const traceBefore = args.execute === true && !awaitingDocumentReview ? beginTrace(root) : null;
8864
8897
  const lsp = lspRequested ? lspSetup(root, { ...args, execute: true }) : lspSetup(root, { ...args, execute: false });
8865
8898
  if (awaitingDocumentReview) {
8866
8899
  return {
@@ -8886,20 +8919,30 @@ function workflowRefresh(root, args = {}) {
8886
8919
  if (args.execute === true) {
8887
8920
  const refreshed = refreshedPatternsArtifacts(root);
8888
8921
  if (refreshed) {
8889
- import_node_fs17.default.writeFileSync(refreshed.jsonlPath, refreshed.jsonl);
8890
- import_node_fs17.default.writeFileSync(refreshed.projectionPath, refreshed.projection);
8922
+ import_node_fs19.default.writeFileSync(refreshed.jsonlPath, refreshed.jsonl);
8923
+ import_node_fs19.default.writeFileSync(refreshed.projectionPath, refreshed.projection);
8891
8924
  patterns = {
8892
8925
  ok: true,
8893
- path: import_node_path37.default.relative(root, refreshed.jsonlPath),
8894
- projection: import_node_path37.default.relative(root, refreshed.projectionPath),
8926
+ path: import_node_path38.default.relative(root, refreshed.jsonlPath),
8927
+ projection: import_node_path38.default.relative(root, refreshed.projectionPath),
8895
8928
  refreshed_at: refreshed.stamp
8896
8929
  };
8897
8930
  }
8898
8931
  }
8932
+ const controlCommit = args.execute === true ? commitTrace(root, args, {
8933
+ kind: "control",
8934
+ workflow: "refresh",
8935
+ subject: "refresh project context",
8936
+ before: traceBefore,
8937
+ note: {
8938
+ patterns: patterns ? asJsonObject(patterns) : null,
8939
+ lsp_setup: asJsonObject(lsp)
8940
+ }
8941
+ }) : null;
8899
8942
  return {
8900
8943
  ...summary,
8901
- ok: (!regen || regen.ok !== false) && lsp.ok !== false,
8902
- phase_state: args.execute === true ? "executed" : "dry_run",
8944
+ ok: (!regen || regen.ok !== false) && lsp.ok !== false && (!controlCommit || controlCommit.ok !== false),
8945
+ phase_state: args.execute === true ? controlCommit && controlCommit.ok === false ? "recovery_required" : "executed" : "dry_run",
8903
8946
  doctor: doctor(root, { hasCadreProject: true }),
8904
8947
  workspace: workspaceDiagnostics(root, { execute: false }),
8905
8948
  dependency_graph: dependencyGraph(root),
@@ -8907,6 +8950,7 @@ function workflowRefresh(root, args = {}) {
8907
8950
  lsp_setup: lsp,
8908
8951
  regen,
8909
8952
  patterns,
8953
+ control_commit: controlCommit,
8910
8954
  human_review: humanReview,
8911
8955
  review_artifacts: reviewArtifacts,
8912
8956
  review_bundle: reviewBundle,
@@ -8915,17 +8959,17 @@ function workflowRefresh(root, args = {}) {
8915
8959
  }
8916
8960
 
8917
8961
  // src/core/application/runtime/workflow-release-revise.ts
8918
- var import_node_fs18 = __toESM(require("node:fs"));
8919
- var import_node_path38 = __toESM(require("node:path"));
8962
+ var import_node_fs20 = __toESM(require("node:fs"));
8963
+ var import_node_path39 = __toESM(require("node:path"));
8920
8964
  function releaseArtifactPlan(root, args = {}) {
8921
8965
  const completed = listTracks(root).filter((track) => (track.metadata.status || "new") === "completed").map((track) => asJsonObject(metadataTrackSummary(track)));
8922
8966
  const rawArgs = args;
8923
8967
  const version = String(args.releaseVersion || args.release_version || args.bump || args.mode || `release-${utcNow().slice(0, 10)}`);
8924
8968
  const generatedAt = asOptionalString(rawArgs.generatedAt || rawArgs.generated_at) || utcNow();
8925
- const releaseDir = import_node_path38.default.join(root, "cadre", "releases");
8969
+ const releaseDir = import_node_path39.default.join(root, "cadre", "releases");
8926
8970
  const releaseSlug = safeName(version);
8927
- const releaseMd = import_node_path38.default.join(releaseDir, `${releaseSlug}.md`);
8928
- const releaseJson = import_node_path38.default.join(releaseDir, `${releaseSlug}.json`);
8971
+ const releaseMd = import_node_path39.default.join(releaseDir, `${releaseSlug}.md`);
8972
+ const releaseJson = import_node_path39.default.join(releaseDir, `${releaseSlug}.json`);
8929
8973
  const notes = asOptionalString(args.releaseNotes || args.release_notes) || [
8930
8974
  `# Release - ${version}`,
8931
8975
  "",
@@ -8946,7 +8990,7 @@ function releaseArtifactPlan(root, args = {}) {
8946
8990
  priority: track.priority,
8947
8991
  owner: track.owner,
8948
8992
  reviewer: track.reviewer,
8949
- beads_epic: track.beads_epic,
8993
+ tags: track.tags || [],
8950
8994
  review: track.review
8951
8995
  }))
8952
8996
  };
@@ -8956,14 +9000,14 @@ function releaseArtifactPlan(root, args = {}) {
8956
9000
  function releaseReviewFiles(root, plan) {
8957
9001
  return [
8958
9002
  textReviewFile(
8959
- import_node_path38.default.relative(root, plan.releaseMd),
9003
+ import_node_path39.default.relative(root, plan.releaseMd),
8960
9004
  "Release notes",
8961
9005
  "releaseNotes",
8962
9006
  plan.notes.endsWith("\n") ? plan.notes : `${plan.notes}
8963
9007
  `
8964
9008
  ),
8965
9009
  jsonReviewFile(
8966
- import_node_path38.default.relative(root, plan.releaseJson),
9010
+ import_node_path39.default.relative(root, plan.releaseJson),
8967
9011
  "Release metadata",
8968
9012
  "releaseMetadata",
8969
9013
  plan.metadata
@@ -8987,7 +9031,7 @@ function workflowRelease(root, args = {}) {
8987
9031
  ...summary,
8988
9032
  release_version: plan.version,
8989
9033
  completed_tracks: plan.completed,
8990
- release_artifacts: [import_node_path38.default.relative(root, plan.releaseMd), import_node_path38.default.relative(root, plan.releaseJson)],
9034
+ release_artifacts: [import_node_path39.default.relative(root, plan.releaseMd), import_node_path39.default.relative(root, plan.releaseJson)],
8991
9035
  git_actions: plan.gitActions,
8992
9036
  human_review: humanReview,
8993
9037
  review_artifacts: reviewArtifacts,
@@ -9012,30 +9056,42 @@ function workflowRelease(root, args = {}) {
9012
9056
  error: "Human confirmation is required before writing release artifacts"
9013
9057
  };
9014
9058
  }
9015
- import_node_fs18.default.mkdirSync(plan.releaseDir, { recursive: true });
9016
- import_node_fs18.default.writeFileSync(plan.releaseMd, plan.notes.endsWith("\n") ? plan.notes : `${plan.notes}
9059
+ const traceBefore = beginTrace(root);
9060
+ import_node_fs20.default.mkdirSync(plan.releaseDir, { recursive: true });
9061
+ import_node_fs20.default.writeFileSync(plan.releaseMd, plan.notes.endsWith("\n") ? plan.notes : `${plan.notes}
9017
9062
  `);
9018
9063
  writeJson(plan.releaseJson, plan.metadata);
9019
- const indexPatch = patchJsonFile(import_node_path38.default.join(root, "cadre", "setup_state.json"), (current) => {
9064
+ const indexPatch = patchJsonFile(import_node_path39.default.join(root, "cadre", "setup_state.json"), (current) => {
9020
9065
  current.last_release = {
9021
9066
  version: plan.version,
9022
- path: import_node_path38.default.relative(root, plan.releaseMd),
9023
- metadata: import_node_path38.default.relative(root, plan.releaseJson),
9067
+ path: import_node_path39.default.relative(root, plan.releaseMd),
9068
+ metadata: import_node_path39.default.relative(root, plan.releaseJson),
9024
9069
  completed_tracks: plan.completed.length,
9025
9070
  released_at: plan.generatedAt
9026
9071
  };
9027
9072
  current.updated_at = utcNow();
9028
9073
  return current;
9029
9074
  }, { lock: false });
9075
+ const controlCommit = commitTrace(root, args, {
9076
+ kind: "control",
9077
+ workflow: "release",
9078
+ subject: `prepare ${plan.version}`,
9079
+ before: traceBefore,
9080
+ note: {
9081
+ release_version: plan.version,
9082
+ completed_tracks: plan.completed.map((track) => asOptionalString(track.track_id)).filter((trackId) => Boolean(trackId))
9083
+ }
9084
+ });
9030
9085
  const gitResults = runPlannedGitActions(plan.gitActions);
9031
9086
  const gitOk = actionResultsOk(gitResults);
9032
9087
  return {
9033
9088
  ...base,
9034
- ok: indexPatch.ok !== false && gitOk,
9035
- phase_state: gitOk ? "executed" : "recovery_required",
9089
+ ok: indexPatch.ok !== false && controlCommit.ok !== false && gitOk,
9090
+ phase_state: gitOk && controlCommit.ok !== false ? "executed" : "recovery_required",
9036
9091
  dry_run: args.execute !== true,
9037
9092
  bump: args.bump || args.mode || "patch",
9038
9093
  setup_state: indexPatch,
9094
+ control_commit: controlCommit,
9039
9095
  git_results: gitResults
9040
9096
  };
9041
9097
  }
@@ -9063,21 +9119,21 @@ function workflowRevise(root, args = {}) {
9063
9119
  };
9064
9120
  }
9065
9121
  if (track && revisedSpec) {
9066
- reviewFiles.push(jsonReviewFile(import_node_path38.default.relative(root, trackSpecJsonPath(track)), "Revised track spec canonical", "spec", revisedSpec));
9122
+ reviewFiles.push(jsonReviewFile(import_node_path39.default.relative(root, trackSpecJsonPath(track)), "Revised track spec canonical", "spec", revisedSpec));
9067
9123
  reviewFiles.push(textReviewFile(
9068
- import_node_path38.default.relative(root, track.spec_path),
9124
+ import_node_path39.default.relative(root, track.spec_path),
9069
9125
  "Revised track spec",
9070
9126
  "spec.json",
9071
- withGeneratedMarker(import_node_path38.default.relative(root, trackSpecJsonPath(track)), "cadre.spec.v1", renderSpecMarkdown(revisedSpec))
9127
+ withGeneratedMarker(import_node_path39.default.relative(root, trackSpecJsonPath(track)), "cadre.spec.v1", renderSpecMarkdown(revisedSpec))
9072
9128
  ));
9073
9129
  }
9074
9130
  if (track && revisedPlan) {
9075
- reviewFiles.push(jsonReviewFile(import_node_path38.default.relative(root, trackPlanJsonPath(track)), "Revised track plan canonical", "plan", revisedPlan));
9131
+ reviewFiles.push(jsonReviewFile(import_node_path39.default.relative(root, trackPlanJsonPath(track)), "Revised track plan canonical", "plan", revisedPlan));
9076
9132
  reviewFiles.push(textReviewFile(
9077
- import_node_path38.default.relative(root, track.plan_path),
9133
+ import_node_path39.default.relative(root, track.plan_path),
9078
9134
  "Revised track plan",
9079
9135
  "plan.json",
9080
- withGeneratedMarker(import_node_path38.default.relative(root, trackPlanJsonPath(track)), "cadre.plan.v1", renderPlanMarkdown(revisedPlan))
9136
+ withGeneratedMarker(import_node_path39.default.relative(root, trackPlanJsonPath(track)), "cadre.plan.v1", renderPlanMarkdown(revisedPlan))
9081
9137
  ));
9082
9138
  }
9083
9139
  const reviewArtifacts = reviewArtifactsFromFiles(reviewFiles);
@@ -9129,36 +9185,49 @@ function workflowRevise(root, args = {}) {
9129
9185
  error: "Human confirmation is required before revising track artifacts"
9130
9186
  };
9131
9187
  }
9188
+ const traceBefore = beginTrace(root);
9132
9189
  const writeResult = withTrackLock(root, track.track_id, () => {
9133
9190
  const written = [];
9134
9191
  if (revisedSpec) {
9135
9192
  writeJsonEnsured(trackSpecJsonPath(track), revisedSpec);
9136
- import_node_fs18.default.writeFileSync(track.spec_path, withGeneratedMarker(import_node_path38.default.relative(root, trackSpecJsonPath(track)), "cadre.spec.v1", renderSpecMarkdown(revisedSpec)));
9137
- written.push(import_node_path38.default.relative(root, trackSpecJsonPath(track)));
9138
- written.push(import_node_path38.default.relative(root, track.spec_path));
9193
+ import_node_fs20.default.writeFileSync(track.spec_path, withGeneratedMarker(import_node_path39.default.relative(root, trackSpecJsonPath(track)), "cadre.spec.v1", renderSpecMarkdown(revisedSpec)));
9194
+ written.push(import_node_path39.default.relative(root, trackSpecJsonPath(track)));
9195
+ written.push(import_node_path39.default.relative(root, track.spec_path));
9139
9196
  }
9140
9197
  if (revisedPlan) {
9141
9198
  writeJsonEnsured(trackPlanJsonPath(track), revisedPlan);
9142
- import_node_fs18.default.writeFileSync(track.plan_path, withGeneratedMarker(import_node_path38.default.relative(root, trackPlanJsonPath(track)), "cadre.plan.v1", renderPlanMarkdown(revisedPlan)));
9143
- written.push(import_node_path38.default.relative(root, trackPlanJsonPath(track)));
9144
- written.push(import_node_path38.default.relative(root, track.plan_path));
9199
+ import_node_fs20.default.writeFileSync(track.plan_path, withGeneratedMarker(import_node_path39.default.relative(root, trackPlanJsonPath(track)), "cadre.plan.v1", renderPlanMarkdown(revisedPlan)));
9200
+ written.push(import_node_path39.default.relative(root, trackPlanJsonPath(track)));
9201
+ written.push(import_node_path39.default.relative(root, track.plan_path));
9145
9202
  }
9146
9203
  return { ok: true, written, revised_at: utcNow() };
9147
9204
  });
9148
9205
  const regen = writeResult.ok !== false ? regenIndex(root) : null;
9206
+ const controlCommit = writeResult.ok !== false && (!regen || regen.ok !== false) ? commitTrace(root, args, {
9207
+ kind: "control",
9208
+ workflow: "revise",
9209
+ subject: `update ${trackId}`,
9210
+ before: traceBefore,
9211
+ trackId,
9212
+ note: {
9213
+ revised_spec: Boolean(revisedSpec),
9214
+ revised_plan: Boolean(revisedPlan)
9215
+ }
9216
+ }) : null;
9149
9217
  return {
9150
9218
  ...base,
9151
- ok: writeResult.ok !== false && (!regen || regen.ok !== false),
9219
+ ok: writeResult.ok !== false && (!regen || regen.ok !== false) && (!controlCommit || controlCommit.ok !== false),
9152
9220
  dry_run: false,
9153
- phase_state: writeResult.ok === false || regen && regen.ok === false ? "recovery_required" : "executed",
9221
+ phase_state: writeResult.ok === false || regen && regen.ok === false || controlCommit && controlCommit.ok === false ? "recovery_required" : "executed",
9154
9222
  write: writeResult,
9155
- regen
9223
+ regen,
9224
+ control_commit: controlCommit
9156
9225
  };
9157
9226
  }
9158
9227
 
9159
9228
  // src/core/application/runtime/workflow-setup.ts
9160
- var import_node_fs19 = __toESM(require("node:fs"));
9161
- var import_node_path39 = __toESM(require("node:path"));
9229
+ var import_node_fs21 = __toESM(require("node:fs"));
9230
+ var import_node_path40 = __toESM(require("node:path"));
9162
9231
  function workflowSetup(root, args = {}) {
9163
9232
  const summary = workflowSummary(root, "setup", args);
9164
9233
  const markdownError = markdownPayloadError(args);
@@ -9174,8 +9243,6 @@ function workflowSetup(root, args = {}) {
9174
9243
  const lspWriteRequested = setupShouldWriteLsp(args, lspRecommendations);
9175
9244
  const detailMode = workflowResponseMode(args) === "detail";
9176
9245
  const workspaceHealthResult = workspaceHealth(root, { ...args, responseMode: detailMode ? "detail" : "compact" });
9177
- const beadsPlan = setupBeads(root, { ...args, execute: false });
9178
- const beadsPrefix = resolveBeadsEpicPrefix(root, args);
9179
9246
  const configOverrides = asJsonObject(rawArgs.config);
9180
9247
  const requestedSyncMode = asOptionalString(rawArgs.syncMode || rawArgs.sync_mode || configOverrides.sync_mode);
9181
9248
  const teamSize = Number(rawArgs.teamSize || rawArgs.team_size || 0);
@@ -9199,8 +9266,6 @@ function workflowSetup(root, args = {}) {
9199
9266
  lsp_setup: detailMode ? lspRecommendations : summarizeLspSetupResult(lspRecommendations),
9200
9267
  integrations: workspaceHealthResult.integrations,
9201
9268
  detail_resources: workspaceHealthResult.detail_resources,
9202
- beads_init: beadsPlan,
9203
- beads_prefix: beadsPrefix,
9204
9269
  provider,
9205
9270
  sync_mode: syncModeRecommendation,
9206
9271
  sync_recommendation: teamSize >= 2 && syncModeRecommendation !== "shared" ? "Team setup detected; use syncMode/shared sync for 10-20 person coordination." : null,
@@ -9211,9 +9276,8 @@ function workflowSetup(root, args = {}) {
9211
9276
  review_artifacts: reviewArtifacts,
9212
9277
  review_bundle: reviewBundle,
9213
9278
  warnings,
9214
- required_payload: args.execute === true ? ["product", "techStack"].concat(provider.requires_confirmation === true ? ["providerMode"] : []).concat(polyrepoRequested && !reposPayload ? ["repos"] : []).concat(beadsPrefix.selected ? [] : asStringArray(beadsPrefix.missing_payload)) : [],
9279
+ required_payload: args.execute === true ? ["product", "techStack"].concat(provider.requires_confirmation === true ? ["providerMode"] : []).concat(polyrepoRequested && !reposPayload ? ["repos"] : []) : [],
9215
9280
  next_actions: [
9216
- ...!beadsPrefix.selected ? ["Choose beadsEpicPrefix from the recommendations or provide another prefix using at most two words."] : [],
9217
9281
  ...provider.requires_confirmation === true ? ["Choose providerMode: local, github, or gitlab before setup writes cadre/config.json."] : [],
9218
9282
  "Review setup artifacts with the user; call setup_scaffold with execute:true and humanConfirmed:true only after explicit approval."
9219
9283
  ],
@@ -9225,14 +9289,13 @@ function workflowSetup(root, args = {}) {
9225
9289
  ]
9226
9290
  };
9227
9291
  if (args.execute !== true) return result;
9228
- const cadreDir = import_node_path39.default.join(root, "cadre");
9292
+ const cadreDir = import_node_path40.default.join(root, "cadre");
9229
9293
  const force = asBoolean(rawArgs.force, false);
9230
9294
  const missingPayload = [
9231
9295
  ...!isRecord(rawArgs.product) ? ["product"] : [],
9232
9296
  ...!techStackFromArgs(args) ? ["techStack"] : [],
9233
9297
  ...provider.requires_confirmation === true || !providerMode ? ["providerMode"] : [],
9234
- ...polyrepoRequested && !reposPayload ? ["repos"] : [],
9235
- ...beadsPrefix.selected ? [] : asStringArray(beadsPrefix.missing_payload)
9298
+ ...polyrepoRequested && !reposPayload ? ["repos"] : []
9236
9299
  ];
9237
9300
  if (missingPayload.length > 0) {
9238
9301
  return {
@@ -9251,55 +9314,48 @@ function workflowSetup(root, args = {}) {
9251
9314
  error: "Human confirmation is required before writing setup artifacts"
9252
9315
  };
9253
9316
  }
9254
- const beadsInit = setupBeads(root, args);
9255
- if (beadsInit.ok === false) {
9256
- return {
9257
- ...result,
9258
- ok: false,
9259
- phase_state: "blocked",
9260
- stage: "beads_init",
9261
- beads_init: beadsInit,
9262
- error: asOptionalString(beadsInit.error) || asOptionalString(beadsInit.reason) || "Beads initialization failed"
9263
- };
9264
- }
9317
+ const traceBefore = beginTrace(root);
9265
9318
  const written = [];
9266
9319
  const skipped = [];
9267
9320
  const writeText = (relativePath, text) => {
9268
- const file = import_node_path39.default.join(cadreDir, relativePath);
9321
+ const file = import_node_path40.default.join(cadreDir, relativePath);
9269
9322
  if (fileExists(file) && !force) {
9270
- skipped.push(import_node_path39.default.relative(root, file));
9323
+ skipped.push(import_node_path40.default.relative(root, file));
9271
9324
  return;
9272
9325
  }
9273
- import_node_fs19.default.mkdirSync(import_node_path39.default.dirname(file), { recursive: true });
9274
- import_node_fs19.default.writeFileSync(file, text);
9275
- written.push(import_node_path39.default.relative(root, file));
9326
+ import_node_fs21.default.mkdirSync(import_node_path40.default.dirname(file), { recursive: true });
9327
+ import_node_fs21.default.writeFileSync(file, text);
9328
+ written.push(import_node_path40.default.relative(root, file));
9276
9329
  };
9277
9330
  const writeSetupJson = (relativePath, value) => {
9278
- const file = import_node_path39.default.join(cadreDir, relativePath);
9331
+ const file = import_node_path40.default.join(cadreDir, relativePath);
9279
9332
  if (fileExists(file) && !force) {
9280
- skipped.push(import_node_path39.default.relative(root, file));
9333
+ skipped.push(import_node_path40.default.relative(root, file));
9281
9334
  return;
9282
9335
  }
9283
- import_node_fs19.default.mkdirSync(import_node_path39.default.dirname(file), { recursive: true });
9336
+ import_node_fs21.default.mkdirSync(import_node_path40.default.dirname(file), { recursive: true });
9284
9337
  writeJson(file, value);
9285
- written.push(import_node_path39.default.relative(root, file));
9338
+ written.push(import_node_path40.default.relative(root, file));
9286
9339
  };
9287
9340
  const writeSetupJsonlEntry = (relativePath, value) => {
9288
- const file = import_node_path39.default.join(cadreDir, relativePath);
9341
+ const file = import_node_path40.default.join(cadreDir, relativePath);
9289
9342
  if (fileExists(file) && !force) {
9290
- skipped.push(import_node_path39.default.relative(root, file));
9343
+ skipped.push(import_node_path40.default.relative(root, file));
9291
9344
  return;
9292
9345
  }
9293
9346
  appendJsonl(file, value);
9294
- written.push(import_node_path39.default.relative(root, file));
9347
+ written.push(import_node_path40.default.relative(root, file));
9295
9348
  };
9296
9349
  const writeProjectDoc = (relativePath, kind, value, title) => {
9297
9350
  const jsonPath = relativePath.replace(/\.md$/, ".json");
9298
9351
  writeSetupJson(jsonPath, value);
9299
9352
  writeText(relativePath, withGeneratedMarker(`cadre/${jsonPath}`, `cadre.${kind}.v1`, renderMarkdownDoc(value, title)));
9300
9353
  };
9301
- import_node_fs19.default.mkdirSync(import_node_path39.default.join(cadreDir, "tracks"), { recursive: true });
9302
- import_node_fs19.default.mkdirSync(import_node_path39.default.join(cadreDir, "archive"), { recursive: true });
9354
+ import_node_fs21.default.mkdirSync(import_node_path40.default.join(cadreDir, "tracks"), { recursive: true });
9355
+ import_node_fs21.default.mkdirSync(import_node_path40.default.join(cadreDir, "archive"), { recursive: true });
9356
+ const nativeState = ensureNativeState(root);
9357
+ const nativeIgnorePath = asOptionalString(nativeState.ignore_path);
9358
+ if (nativeIgnorePath) written.push(nativeIgnorePath);
9303
9359
  writeProjectDoc(
9304
9360
  "product.md",
9305
9361
  "product",
@@ -9382,17 +9438,6 @@ function workflowSetup(root, args = {}) {
9382
9438
  ...configOverrides
9383
9439
  };
9384
9440
  writeSetupJson("config.json", configPayload);
9385
- const beadsConfigOverrides = {
9386
- ...asJsonObject(rawArgs.beadsConfig),
9387
- ...asJsonObject(rawArgs.beads_config)
9388
- };
9389
- writeSetupJson("beads.json", {
9390
- ...templateJson("beads.json", { enabled: true, mode: "normal" }),
9391
- packet_only: true,
9392
- ...beadsConfigOverrides,
9393
- epicPrefix: beadsPrefix.epic_prefix,
9394
- epicPrefixMaxWords: 2
9395
- });
9396
9441
  let repos = null;
9397
9442
  if (reposPayload) {
9398
9443
  repos = reposPayload;
@@ -9411,11 +9456,33 @@ function workflowSetup(root, args = {}) {
9411
9456
  ci: ciSetup,
9412
9457
  submodules: setupSubmodulePlan(root, repos, args)
9413
9458
  } : null;
9459
+ const setupEvent = appendCadreEvent(root, {
9460
+ kind: "setup_completed",
9461
+ workflow: "setup",
9462
+ topology: polyrepoRequested ? "polyrepo" : "monorepo",
9463
+ sync_mode: syncModeRecommendation,
9464
+ provider_mode: providerMode || "local",
9465
+ written_count: written.length,
9466
+ skipped_count: skipped.length
9467
+ });
9468
+ const controlCommit = commitTrace(root, args, {
9469
+ kind: "control",
9470
+ workflow: "setup",
9471
+ subject: "initialize control plane",
9472
+ before: traceBefore,
9473
+ forceEnabled: true,
9474
+ note: {
9475
+ event_id: asOptionalString(asJsonObject(setupEvent.event).id) || null,
9476
+ topology: polyrepoRequested ? "polyrepo" : "monorepo",
9477
+ sync_mode: syncModeRecommendation,
9478
+ provider_mode: providerMode || "local"
9479
+ }
9480
+ });
9414
9481
  return {
9415
9482
  ...result,
9416
- ok: true,
9483
+ ok: controlCommit.ok !== false,
9417
9484
  scaffolded: true,
9418
- phase_state: "executed",
9485
+ phase_state: controlCommit.ok === false ? "recovery_required" : "executed",
9419
9486
  topology: polyrepoRequested ? "polyrepo" : "monorepo",
9420
9487
  written,
9421
9488
  skipped,
@@ -9425,7 +9492,9 @@ function workflowSetup(root, args = {}) {
9425
9492
  skipped: skipped.slice(beforeStyleSkipped)
9426
9493
  },
9427
9494
  lsp_setup: lspSetupResult,
9428
- beads_init: beadsInit,
9495
+ native_state: nativeState,
9496
+ event: setupEvent,
9497
+ control_commit: controlCommit,
9429
9498
  gitattributes,
9430
9499
  ci_setup: ciSetup,
9431
9500
  polyrepo_setup: polyrepoSetup,
@@ -9435,6 +9504,7 @@ function workflowSetup(root, args = {}) {
9435
9504
  }
9436
9505
 
9437
9506
  // src/core/application/runtime/workflow-ship-land.ts
9507
+ var import_node_path41 = __toESM(require("node:path"));
9438
9508
  function providerActionKind(workflow, provider) {
9439
9509
  if (provider === "gitlab") return workflow === "land" ? "open_merge_request_group" : "open_merge_request";
9440
9510
  return workflow === "land" ? "open_pull_request_group" : "open_pull_request";
@@ -9502,6 +9572,62 @@ function landGitActions(root, track, args = {}) {
9502
9572
  ));
9503
9573
  return actions;
9504
9574
  }
9575
+ function publicationLedger(root, workflow, track, args, data) {
9576
+ const before = beginTrace(root);
9577
+ const entry = {
9578
+ version: 1,
9579
+ schema: "cadre.publication.v1",
9580
+ workflow,
9581
+ track_id: track.track_id,
9582
+ recorded_at: utcNow(),
9583
+ continuation_token: asOptionalString(data.continuation_token) || null,
9584
+ ...data
9585
+ };
9586
+ const file = import_node_path41.default.join(root, "cadre", "operations", "publication.jsonl");
9587
+ appendJsonl(file, entry);
9588
+ const controlCommit = commitTrace(root, args, {
9589
+ kind: "control",
9590
+ workflow,
9591
+ subject: `publish ${track.track_id}`,
9592
+ before,
9593
+ files: [
9594
+ import_node_path41.default.relative(root, file)
9595
+ ],
9596
+ trackId: track.track_id,
9597
+ note: entry
9598
+ });
9599
+ return { ok: controlCommit.ok !== false, path: import_node_path41.default.relative(root, file), entry, control_commit: controlCommit };
9600
+ }
9601
+ function runPublicationGit(root, workflow, track, args, gitActions, providerActions) {
9602
+ const remote = asOptionalString(args.remote) || "origin";
9603
+ const pushKinds = /* @__PURE__ */ new Set(["push_branch", "push_control_branch"]);
9604
+ const beforePush = gitActions.filter((action) => !pushKinds.has(action.kind));
9605
+ const pushActions = gitActions.filter((action) => pushKinds.has(action.kind));
9606
+ const beforePushResults = runPlannedGitActions(beforePush);
9607
+ if (!actionResultsOk(beforePushResults)) {
9608
+ return { ok: false, stage: "git_before_push", git_results: beforePushResults };
9609
+ }
9610
+ const token = continuationToken(workflow, track.track_id, [...providerActions, ...gitActions]);
9611
+ const publication = publicationLedger(root, workflow, track, args, {
9612
+ git_actions: gitActions,
9613
+ provider_actions: providerActions,
9614
+ continuation_token: token
9615
+ });
9616
+ if (publication.ok === false) {
9617
+ return { ok: false, stage: "publication_ledger", git_results: beforePushResults, publication };
9618
+ }
9619
+ const noteActions = notesPushEnabled(root) ? Array.from(new Map([
9620
+ ...pushActions,
9621
+ ...repoEntriesForTrack(root, track, args).map((entry) => notesPushAction(root, asString(entry.repo, "."), asString(entry.root, root), remote))
9622
+ ].map((action) => [`${action.cwd}:${action.kind}:${action.repo}`, action])).values()) : pushActions;
9623
+ const pushResults = runPlannedGitActions(noteActions);
9624
+ return {
9625
+ ok: actionResultsOk(pushResults),
9626
+ git_results: [...beforePushResults, ...pushResults],
9627
+ publication,
9628
+ push_actions: noteActions
9629
+ };
9630
+ }
9505
9631
  function persistProviderEvidenceIfSupplied(root, track, args = {}) {
9506
9632
  const evidence = args.evidence || args.providerEvidence || args.provider_evidence;
9507
9633
  if (!evidence || args.execute !== true) return null;
@@ -9526,12 +9652,14 @@ function workflowShip(root, args = {}) {
9526
9652
  const blocked = gate.ok === false;
9527
9653
  const evidenceWrite = persistProviderEvidenceIfSupplied(root, track, args);
9528
9654
  const canExecuteGit = args.execute === true && !blocked && !evidenceSupplied && (!evidenceWrite || evidenceWrite.ok !== false);
9529
- const gitResults = canExecuteGit ? runPlannedGitActions(gitActions) : [];
9530
- const executionFailed = canExecuteGit && !actionResultsOk(gitResults);
9655
+ const execution = canExecuteGit ? runPublicationGit(root, "ship", track, args, gitActions, providerActions) : null;
9656
+ const gitResults = asArray(asJsonObject(execution).git_results);
9657
+ const publication = args.execute === true && evidenceWrite && evidenceWrite.ok !== false ? publicationLedger(root, "ship", track, args, { provider_evidence_write: asJsonObject(evidenceWrite), provider_actions: providerActions }) : asJsonObject(execution).publication || null;
9658
+ const executionFailed = canExecuteGit && (!execution || execution.ok === false);
9531
9659
  const phaseState = executionFailed ? "recovery_required" : workflowPhaseState(args, blocked || Boolean(evidenceWrite && evidenceWrite.ok === false), pendingProvider);
9532
9660
  return {
9533
9661
  ...summary,
9534
- ok: gate.ok !== false && (!evidenceWrite || evidenceWrite.ok !== false) && !executionFailed,
9662
+ ok: gate.ok !== false && (!evidenceWrite || evidenceWrite.ok !== false) && (!publication || asJsonObject(publication).ok !== false) && !executionFailed,
9535
9663
  phase_state: phaseState,
9536
9664
  gate,
9537
9665
  provider,
@@ -9539,6 +9667,7 @@ function workflowShip(root, args = {}) {
9539
9667
  provider_actions: providerActions,
9540
9668
  git_actions: gitActions,
9541
9669
  git_results: gitResults,
9670
+ publication,
9542
9671
  git_action_state: canExecuteGit ? "executed" : evidenceSupplied ? "skipped_provider_evidence_continuation" : "pending_execute",
9543
9672
  provider_evidence_write: evidenceWrite,
9544
9673
  continuation_token: continuationToken("ship", trackId, [...providerActions, ...gitActions]),
@@ -9565,12 +9694,14 @@ function workflowLand(root, args = {}) {
9565
9694
  const blocked = !topology.polyrepo || preflight.ok === false || gate.ok === false;
9566
9695
  const evidenceWrite = persistProviderEvidenceIfSupplied(root, track, args);
9567
9696
  const canExecuteGit = args.execute === true && !blocked && !evidenceSupplied && (!evidenceWrite || evidenceWrite.ok !== false);
9568
- const gitResults = canExecuteGit ? runPlannedGitActions(gitActions) : [];
9569
- const executionFailed = canExecuteGit && !actionResultsOk(gitResults);
9697
+ const execution = canExecuteGit ? runPublicationGit(root, "land", track, args, gitActions, providerActions) : null;
9698
+ const gitResults = asArray(asJsonObject(execution).git_results);
9699
+ const publication = args.execute === true && evidenceWrite && evidenceWrite.ok !== false ? publicationLedger(root, "land", track, args, { provider_evidence_write: asJsonObject(evidenceWrite), provider_actions: providerActions }) : asJsonObject(execution).publication || null;
9700
+ const executionFailed = canExecuteGit && (!execution || execution.ok === false);
9570
9701
  const phaseState = executionFailed ? "recovery_required" : workflowPhaseState(args, blocked || Boolean(evidenceWrite && evidenceWrite.ok === false), pendingProvider);
9571
9702
  return {
9572
9703
  ...summary,
9573
- ok: topology.polyrepo && preflight.ok !== false && gate.ok !== false && (!evidenceWrite || evidenceWrite.ok !== false) && !executionFailed,
9704
+ ok: topology.polyrepo && preflight.ok !== false && gate.ok !== false && (!evidenceWrite || evidenceWrite.ok !== false) && (!publication || asJsonObject(publication).ok !== false) && !executionFailed,
9574
9705
  phase_state: phaseState,
9575
9706
  topology: topology.polyrepo ? "polyrepo" : "monorepo",
9576
9707
  preflight,
@@ -9579,6 +9710,7 @@ function workflowLand(root, args = {}) {
9579
9710
  provider_actions: providerActions,
9580
9711
  git_actions: gitActions,
9581
9712
  git_results: gitResults,
9713
+ publication,
9582
9714
  git_action_state: canExecuteGit ? "executed" : evidenceSupplied ? "skipped_provider_evidence_continuation" : "pending_execute",
9583
9715
  provider_evidence_write: evidenceWrite,
9584
9716
  continuation_token: continuationToken("land", trackId, [...providerActions, ...gitActions]),
@@ -9604,6 +9736,7 @@ function workflowPacket(root, args = {}) {
9604
9736
  "refresh",
9605
9737
  "flag",
9606
9738
  "revert",
9739
+ "formula",
9607
9740
  "artifacts",
9608
9741
  "artifact_sync"
9609
9742
  ].includes(workflow);
@@ -9699,7 +9832,8 @@ function workflowPacket(root, args = {}) {
9699
9832
  error: "Human confirmation is required before flagging track status"
9700
9833
  };
9701
9834
  }
9702
- const statusResult = setTrackStatus(root, trackId, status);
9835
+ const traceBefore = beginTrace(root);
9836
+ const statusResult = setTrackStatus(root, trackId, status, { ...args, commitMode: "off" });
9703
9837
  if (statusResult.ok === false) return { ...summary, ok: false, track_context: context, status_result: statusResult };
9704
9838
  const patch = metadataPatch(root, {
9705
9839
  trackId,
@@ -9708,22 +9842,39 @@ function workflowPacket(root, args = {}) {
9708
9842
  last_status_at: utcNow()
9709
9843
  }
9710
9844
  });
9711
- const latestTrack = findTrack(root, trackId);
9712
- const epic = latestTrack?.metadata.beads_epic;
9713
- const beads = epic && reason ? beadsTaskWrite(root, {
9714
- operation: "note",
9715
- id: epic,
9716
- note: `Cadre ${status}: ${reason}`,
9717
- dedupKey: `cadre-flag-${trackId}-${status}-${textHash(reason).slice(0, 12)}`
9718
- }) : null;
9845
+ const event = appendCadreEvent(root, {
9846
+ kind: "status_changed",
9847
+ workflow: "flag",
9848
+ track_id: trackId,
9849
+ status,
9850
+ reason
9851
+ });
9852
+ const controlCommit = commitTrace(root, args, {
9853
+ kind: "control",
9854
+ workflow: "flag",
9855
+ subject: `mark ${trackId} ${status}`,
9856
+ before: traceBefore,
9857
+ files: [
9858
+ asOptionalString(asJsonObject(context.track).metadata_path) || `cadre/tracks/${trackId}/metadata.json`,
9859
+ "cadre/tracks.json",
9860
+ "cadre/events.jsonl"
9861
+ ],
9862
+ trackId,
9863
+ note: {
9864
+ event_id: asOptionalString(asJsonObject(event.event).id) || null,
9865
+ status,
9866
+ reason
9867
+ }
9868
+ });
9719
9869
  return {
9720
9870
  ...summary,
9721
- ok: patch.ok !== false && (!beads || beads.ok !== false),
9871
+ ok: patch.ok !== false && controlCommit.ok !== false,
9722
9872
  dry_run: false,
9723
9873
  track_context: context,
9724
9874
  status_result: statusResult,
9725
9875
  metadata_patch: patch,
9726
- beads,
9876
+ event,
9877
+ control_commit: controlCommit,
9727
9878
  human_review: humanReview,
9728
9879
  review_artifacts: reviewArtifacts
9729
9880
  };
@@ -9731,11 +9882,7 @@ function workflowPacket(root, args = {}) {
9731
9882
  case "revert":
9732
9883
  return workflowRevert(root, args);
9733
9884
  case "formula":
9734
- return {
9735
- ...workflowSummary(root, "formula", args),
9736
- ok: true,
9737
- formulas: commandExists("bd", root) ? beadsTaskWrite(root, { operation: "formula_list" }) : { ok: false, available: false }
9738
- };
9885
+ return workflowFormula(root, args);
9739
9886
  default:
9740
9887
  return {
9741
9888
  ...workflowSummary(root, workflow, args),
@@ -9748,20 +9895,20 @@ function workflowPacket(root, args = {}) {
9748
9895
  }
9749
9896
  // Annotate the CommonJS export names for ESM import in node:
9750
9897
  0 && (module.exports = {
9898
+ appendCadreEvent,
9899
+ appendCadreMessage,
9751
9900
  artifactCatalog,
9752
9901
  artifactPacket,
9753
9902
  artifactRender,
9754
9903
  artifactSchema,
9755
9904
  artifactSync,
9756
9905
  availableWork,
9757
- beadsSummary,
9758
- beadsTaskWrite,
9759
9906
  claimTrack,
9760
9907
  collisionScan,
9761
9908
  completeTask,
9762
- createBeadsTree,
9763
9909
  dependencyGraph,
9764
9910
  doctor,
9911
+ ensureNativeState,
9765
9912
  fleetStatus,
9766
9913
  heartbeatTrack,
9767
9914
  implementationPrep,
@@ -9775,6 +9922,7 @@ function workflowPacket(root, args = {}) {
9775
9922
  lspSetup,
9776
9923
  mcpReadiness,
9777
9924
  metadataPatch,
9925
+ nativeStateSummary,
9778
9926
  parallelWorkflow,
9779
9927
  parsePlanFile,
9780
9928
  parsePlanJson,
@@ -9784,6 +9932,8 @@ function workflowPacket(root, args = {}) {
9784
9932
  polyrepoPreflight,
9785
9933
  prCiStatus,
9786
9934
  providerEvidence,
9935
+ readCadreEvents,
9936
+ readCadreMessages,
9787
9937
  recordParallelWorker,
9788
9938
  recordReview,
9789
9939
  recordTaskResult,
@@ -9801,6 +9951,7 @@ function workflowPacket(root, args = {}) {
9801
9951
  testCoverage,
9802
9952
  testImpact,
9803
9953
  trackContext,
9954
+ workflowFormula,
9804
9955
  workflowPacket,
9805
9956
  workspaceDiagnostics,
9806
9957
  workspaceHealth,