cadre-ai 3.9.0 → 3.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +37 -0
- package/README.md +5 -5
- package/dist/cadre-cli.mjs +1 -1
- package/dist/cadre-mcp.mjs +376 -108
- package/package.json +1 -1
- package/skills/archive/SKILL.md +2 -0
- package/skills/implement/SKILL.md +4 -2
- package/skills/implement/references/governed-mode.md +1 -1
- package/skills/revert/SKILL.md +5 -1
- package/skills/review/SKILL.md +13 -11
- package/skills/revise/SKILL.md +1 -1
- package/skills/track/SKILL.md +1 -1
package/dist/cadre-mcp.mjs
CHANGED
|
@@ -21982,6 +21982,37 @@ function reconcileOperation(root, id3) {
|
|
|
21982
21982
|
}
|
|
21983
21983
|
return commit2;
|
|
21984
21984
|
}
|
|
21985
|
+
function committedOperationReceipt(root, id3, kind, baseCommit, expectedArtifacts = []) {
|
|
21986
|
+
const commit2 = reconcileOperation(root, id3);
|
|
21987
|
+
const body = readFileSync2(target(safeProjectRoot(root), receiptPath(id3)), "utf8");
|
|
21988
|
+
const receipt = receiptSchema.parse(JSON.parse(body));
|
|
21989
|
+
if (receipt.kind !== kind || baseCommit !== void 0 && receipt.baseCommit !== baseCommit) throw new Error("Completed operation does not match the requested identity");
|
|
21990
|
+
for (const file2 of expectedArtifacts) {
|
|
21991
|
+
const expected = file2.content === null ? null : receiptHash(file2.content);
|
|
21992
|
+
if (!receipt.artifacts.some((artifact2) => artifact2.path === file2.path && artifact2.sha256 === expected)) {
|
|
21993
|
+
throw new Error(`Completed operation evidence changed: ${file2.path}`);
|
|
21994
|
+
}
|
|
21995
|
+
}
|
|
21996
|
+
return { status: "committed", commit: commit2, operationId: id3, receiptHash: receiptHash(body), trailers: trailers(receipt) };
|
|
21997
|
+
}
|
|
21998
|
+
function committedReceiptForApproval(rootInput, id3, kind, approvalDigest, baseCommit) {
|
|
21999
|
+
const root = safeProjectRoot(rootInput), path = target(root, receiptPath(id3));
|
|
22000
|
+
if (!existsSync3(path)) return null;
|
|
22001
|
+
const receipt = receiptSchema.parse(JSON.parse(readFileSync2(path, "utf8")));
|
|
22002
|
+
if (receipt.approvalDigest !== approvalDigest) throw new Error("Completed operation approval digest differs from the requested approval");
|
|
22003
|
+
return committedOperationReceipt(root, id3, kind, baseCommit);
|
|
22004
|
+
}
|
|
22005
|
+
function committedReceiptForDigest(rootInput, kind, approvalDigest) {
|
|
22006
|
+
const root = safeProjectRoot(rootInput), directory = target(root, ".cadre/receipts");
|
|
22007
|
+
if (!existsSync3(directory)) return null;
|
|
22008
|
+
const matches = readdirSync2(directory).filter((file2) => file2.endsWith(".json")).map((file2) => {
|
|
22009
|
+
const receipt = receiptSchema.parse(JSON.parse(readFileSync2(target(root, `.cadre/receipts/${file2}`), "utf8")));
|
|
22010
|
+
if (file2 !== `${receipt.operationId}.json`) throw new Error("Immutable operation receipt filename does not match its identity");
|
|
22011
|
+
return receipt;
|
|
22012
|
+
}).filter((receipt) => receipt.kind === kind && receipt.approvalDigest === approvalDigest);
|
|
22013
|
+
if (matches.length > 1) throw new Error("Multiple operation receipts claim the same approved candidate");
|
|
22014
|
+
return matches[0] ? committedOperationReceipt(root, matches[0].operationId, kind) : null;
|
|
22015
|
+
}
|
|
21985
22016
|
function resumeOperation(root, id3, approvalDigest) {
|
|
21986
22017
|
const recovery = parseRecovery(readFileSync2(target(safeProjectRoot(root), recoveryPath(id3)), "utf8"));
|
|
21987
22018
|
const receipt = receiptSchema.parse(recovery.receipt);
|
|
@@ -23376,6 +23407,13 @@ function applyExecutionFinish(input, proposalDigest, preparedProposal) {
|
|
|
23376
23407
|
if (proposal.state.schemaVersion === 2) {
|
|
23377
23408
|
const operationId2 = `implement-${hash2([input.trackId, input.executionId, input.headCommit]).slice(0, 32)}`;
|
|
23378
23409
|
const prefix = `.cadre/tracks/${input.trackId}`;
|
|
23410
|
+
if (existsSync7(join6(safeProjectRoot(input.projectRoot), ".cadre/receipts", `${operationId2}.json`))) {
|
|
23411
|
+
return { ...proposal, receipt: committedOperationReceipt(input.projectRoot, operationId2, "implement", input.headCommit, [
|
|
23412
|
+
{ path: `${prefix}/executions/execution-${input.executionId}.json`, content: `${JSON.stringify(proposal.journal, null, 2)}
|
|
23413
|
+
` },
|
|
23414
|
+
{ path: `${prefix}/plan.md`, content: proposal.planContent }
|
|
23415
|
+
]) };
|
|
23416
|
+
}
|
|
23379
23417
|
const files = [
|
|
23380
23418
|
{ path: `${prefix}/executions/execution-${input.executionId}.json`, content: `${JSON.stringify(proposal.journal, null, 2)}
|
|
23381
23419
|
` },
|
|
@@ -23546,17 +23584,29 @@ function deriveNextStep(projectRoot, state, readiness = {}) {
|
|
|
23546
23584
|
if (!state || ["completed", "archived"].includes(state.status)) return null;
|
|
23547
23585
|
const active = state.operation?.action === "implement";
|
|
23548
23586
|
const reference = active ? state.operation : state.lastExecution;
|
|
23549
|
-
const step = (action, skill, reason,
|
|
23587
|
+
const step = (action, skill, reason, prerequisite2 = null) => ({
|
|
23550
23588
|
action,
|
|
23551
23589
|
plugin: "cadre",
|
|
23552
23590
|
skill,
|
|
23553
23591
|
projectRoot,
|
|
23554
23592
|
trackId: state.trackId,
|
|
23555
23593
|
executionId: reference?.executionId ?? null,
|
|
23556
|
-
prerequisite,
|
|
23594
|
+
prerequisite: prerequisite2,
|
|
23557
23595
|
reason
|
|
23558
23596
|
});
|
|
23559
23597
|
const blocked = (reason) => step("blocked", null, reason);
|
|
23598
|
+
const prerequisite = (kind, pending) => {
|
|
23599
|
+
const history = Array.isArray(state.history) ? state.history : [];
|
|
23600
|
+
const entry = history.filter((item) => Boolean(item) && typeof item === "object" && "action" in item && item.action === kind && "commit" in item && typeof item.commit === "string").at(-1);
|
|
23601
|
+
if (!entry?.commit.startsWith("op:")) return pending;
|
|
23602
|
+
try {
|
|
23603
|
+
resolveOperation(projectRoot, entry.commit);
|
|
23604
|
+
} catch (error51) {
|
|
23605
|
+
if (error51 instanceof CadreError && error51.code === "COMMIT_PENDING") return pending;
|
|
23606
|
+
throw error51;
|
|
23607
|
+
}
|
|
23608
|
+
return null;
|
|
23609
|
+
};
|
|
23560
23610
|
try {
|
|
23561
23611
|
const mode = resolveApprovalMode(reference, active ? void 0 : state.approvalModeMigration);
|
|
23562
23612
|
if (mode !== "autonomous" && !state.autonomousReview) return null;
|
|
@@ -23575,7 +23625,7 @@ function deriveNextStep(projectRoot, state, readiness = {}) {
|
|
|
23575
23625
|
}
|
|
23576
23626
|
if (!state.operation && state.status === "ready_for_review") {
|
|
23577
23627
|
if (loop.checkpoint === "reviewing") {
|
|
23578
|
-
return step("invoke_skill", "review", "Review the complete accumulated implementation in the same task.", "implementation_bookkeeping_commit");
|
|
23628
|
+
return step("invoke_skill", "review", "Review the complete accumulated implementation in the same task.", prerequisite("implement", "implementation_bookkeeping_commit"));
|
|
23579
23629
|
}
|
|
23580
23630
|
if (loop.checkpoint === "awaiting_approval") {
|
|
23581
23631
|
requireCleanAutonomousReview(loop, state.lastExecution ?? {}, []);
|
|
@@ -23583,7 +23633,7 @@ function deriveNextStep(projectRoot, state, readiness = {}) {
|
|
|
23583
23633
|
}
|
|
23584
23634
|
}
|
|
23585
23635
|
if (!state.operation && state.status === "in_progress" && loop.checkpoint === "remediating") {
|
|
23586
|
-
return step("invoke_skill", "implement", "Start a new execution for the approved remediation graph, preserving prior executions.", "review_bookkeeping_commit");
|
|
23636
|
+
return step("invoke_skill", "implement", "Start a new execution for the approved remediation graph, preserving prior executions.", prerequisite("review", "review_bookkeeping_commit"));
|
|
23587
23637
|
}
|
|
23588
23638
|
return blocked("Reconcile the Autonomous checkpoint, lifecycle, and operation before continuing.");
|
|
23589
23639
|
} catch (error51) {
|
|
@@ -23688,7 +23738,13 @@ function inspectDependencyContext(root, body, dependencies, specRevision, planRe
|
|
|
23688
23738
|
const context = dependencyContextSchema.parse(JSON.parse(body));
|
|
23689
23739
|
if (context.specRevision !== specRevision || context.planRevision !== planRevision || JSON.stringify(context.dependencies) !== JSON.stringify(dependencies)) throw new Error("Dependency context does not match the approved specification/plan/dependencies");
|
|
23690
23740
|
const expected = dependencySources(root, dependencies, read);
|
|
23691
|
-
if (context.graphHash !== expected.graphHash || JSON.stringify([...context.sources].sort((a, b) => a.path.localeCompare(b.path))) !== JSON.stringify(expected.sources))
|
|
23741
|
+
if (context.graphHash !== expected.graphHash || JSON.stringify([...context.sources].sort((a, b) => a.path.localeCompare(b.path))) !== JSON.stringify(expected.sources)) {
|
|
23742
|
+
throw new CadreError("DEPENDENCY_CONTEXT_STALE", "Dependency source coverage is missing or stale; reassess inherited constraints", {
|
|
23743
|
+
expectedGraphHash: expected.graphHash,
|
|
23744
|
+
expectedSources: expected.sources,
|
|
23745
|
+
instruction: "Read these exact sources completely, reassess source-linked constraints, and prepare the corrected candidate before approval."
|
|
23746
|
+
});
|
|
23747
|
+
}
|
|
23692
23748
|
if (new Set(context.constraints.map((item) => item.id)).size !== context.constraints.length) throw new Error("Dependency constraint IDs must be unique");
|
|
23693
23749
|
const paths = new Set(context.sources.map((source) => source.path));
|
|
23694
23750
|
for (const constraint of context.constraints) if (constraint.sources.some((path) => !paths.has(path))) throw new Error(`Unknown source for constraint ${constraint.id}`);
|
|
@@ -23702,7 +23758,7 @@ var contextInputSchema = external_exports.strictObject({
|
|
|
23702
23758
|
projectRoot: external_exports.string().min(1),
|
|
23703
23759
|
trackId: id2,
|
|
23704
23760
|
executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/).optional(),
|
|
23705
|
-
nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)
|
|
23761
|
+
nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/, "Use an exact graph node ID such as P1 or T1.1, not a track ID, phase slug, or commit-group name").describe("Exact node ID from the plan graph or scheduler (P1 or T1.1); omit for full track context").optional(),
|
|
23706
23762
|
maxBytes: external_exports.number().int().min(4096).max(65536).default(49152),
|
|
23707
23763
|
cursor: external_exports.string().max(1024).optional(),
|
|
23708
23764
|
retainedContextToken: external_exports.string().regex(/^cadre_ctx1_[A-Za-z0-9_-]{32}$/).optional(),
|
|
@@ -23949,7 +24005,7 @@ function readContext(raw) {
|
|
|
23949
24005
|
|
|
23950
24006
|
// src/domain/candidate-apply.ts
|
|
23951
24007
|
import { existsSync as existsSync15, readdirSync as readdirSync12 } from "node:fs";
|
|
23952
|
-
import { join as
|
|
24008
|
+
import { join as join15 } from "node:path";
|
|
23953
24009
|
|
|
23954
24010
|
// src/domain/staging.ts
|
|
23955
24011
|
import {
|
|
@@ -23972,7 +24028,11 @@ import { dirname as dirname3, extname, join as join9, relative as relative2, res
|
|
|
23972
24028
|
import { fileURLToPath } from "node:url";
|
|
23973
24029
|
|
|
23974
24030
|
// src/domain/version.ts
|
|
23975
|
-
var CADRE_RUNTIME_VERSION = "3.9.
|
|
24031
|
+
var CADRE_RUNTIME_VERSION = "3.9.1";
|
|
24032
|
+
var COMPATIBLE_RUNTIME_VERSIONS = ["3.9.0"];
|
|
24033
|
+
function isCompatibleRuntimeVersion(version2) {
|
|
24034
|
+
return typeof version2 === "string" && (version2 === CADRE_RUNTIME_VERSION || COMPATIBLE_RUNTIME_VERSIONS.includes(version2));
|
|
24035
|
+
}
|
|
23976
24036
|
var LEGACY_RUNTIME_VERSIONS = ["3.8.0", "3.7.1", "3.7.0", "3.6.0", "3.5.1", "3.5.0", "3.4.0", "3.3.0"];
|
|
23977
24037
|
var TEMPLATE_SET_VERSION = "v5";
|
|
23978
24038
|
var LEGACY_TEMPLATE_SET_VERSIONS = ["v1", "v2", "v3", "v4"];
|
|
@@ -24020,6 +24080,7 @@ var TEMPLATE_IDS = [
|
|
|
24020
24080
|
"track/state"
|
|
24021
24081
|
];
|
|
24022
24082
|
var TEMPLATE_ARTIFACT_PATHS = {
|
|
24083
|
+
"track/bug": "bugs/review-<cycle>.md",
|
|
24023
24084
|
"track/dependency-context": "dependency-context.json",
|
|
24024
24085
|
"track/revision": "revisions/revision-<id>.md",
|
|
24025
24086
|
"project/refresh": "refreshes/refresh-<id>.md",
|
|
@@ -24536,12 +24597,7 @@ function validateLearning(path, required2, errors) {
|
|
|
24536
24597
|
errors.push(`${path}: missing or invalid marked Pattern Seed section`);
|
|
24537
24598
|
}
|
|
24538
24599
|
}
|
|
24539
|
-
function
|
|
24540
|
-
if (!existsSync12(path)) {
|
|
24541
|
-
errors.push(`${path}: missing specification`);
|
|
24542
|
-
return;
|
|
24543
|
-
}
|
|
24544
|
-
const body = readInspectionText(path, "utf8");
|
|
24600
|
+
function validateSpecContent(body, path, errors) {
|
|
24545
24601
|
for (const heading of [
|
|
24546
24602
|
"## Functional Requirements",
|
|
24547
24603
|
"## Non-Functional Requirements",
|
|
@@ -24553,6 +24609,13 @@ function validateSpec(path, errors) {
|
|
|
24553
24609
|
if (!body.includes(heading)) errors.push(`${path}: missing ${heading}`);
|
|
24554
24610
|
}
|
|
24555
24611
|
}
|
|
24612
|
+
function validateSpec(path, errors) {
|
|
24613
|
+
if (!existsSync12(path)) {
|
|
24614
|
+
errors.push(`${path}: missing specification`);
|
|
24615
|
+
return;
|
|
24616
|
+
}
|
|
24617
|
+
validateSpecContent(readInspectionText(path, "utf8"), path, errors);
|
|
24618
|
+
}
|
|
24556
24619
|
function validateProjectOperations(root, byId, errors) {
|
|
24557
24620
|
const historicalHashes = [];
|
|
24558
24621
|
const operationsRoot = join11(root, "operations");
|
|
@@ -24713,7 +24776,7 @@ function validateProjectSnapshot(projectRoot) {
|
|
|
24713
24776
|
const planEvidence = [];
|
|
24714
24777
|
collectCommitReferences(project, "project.json", commitReferences);
|
|
24715
24778
|
if (![1, 2].includes(project.schemaVersion)) errors.push("project.json: unsupported schemaVersion");
|
|
24716
|
-
if (project.runtimeVersion
|
|
24779
|
+
if (!isCompatibleRuntimeVersion(project.runtimeVersion)) {
|
|
24717
24780
|
if (LEGACY_RUNTIME_VERSIONS.includes(project.runtimeVersion ?? "")) {
|
|
24718
24781
|
warnings.push(`PROJECT_REFRESH_REQUIRED: runtimeVersion ${project.runtimeVersion} must be refreshed to ${CADRE_RUNTIME_VERSION}`);
|
|
24719
24782
|
} else errors.push(`project.json: unsupported runtimeVersion ${String(project.runtimeVersion)}`);
|
|
@@ -24953,6 +25016,11 @@ function validateStagedState(root, candidateId, files, planValidations = []) {
|
|
|
24953
25016
|
const read = (path) => overlay.get(path) ?? readSafeArtifact(root, `.cadre/${path}`);
|
|
24954
25017
|
const parents = /* @__PURE__ */ new Set();
|
|
24955
25018
|
for (const file2 of files) {
|
|
25019
|
+
if (/^tracks\/[^/]+\/spec\.md$/.test(canonical(file2.path))) {
|
|
25020
|
+
const errors = [];
|
|
25021
|
+
validateSpecContent(file2.content, file2.path, errors);
|
|
25022
|
+
if (errors.length) throw new Error(errors.join("; "));
|
|
25023
|
+
}
|
|
24956
25024
|
const loopMatch = canonical(file2.path).match(/^tracks\/([^/]+)\/reviews\/loop-\d+\.json$/);
|
|
24957
25025
|
if (loopMatch && candidateId.startsWith("review-")) {
|
|
24958
25026
|
const state = JSON.parse(readSafeArtifact(root, `.cadre/tracks/${loopMatch[1]}/state.json`));
|
|
@@ -25118,6 +25186,83 @@ function inspectStagedMemory(projectRoot, candidateId, files) {
|
|
|
25118
25186
|
return { learning, policy: { templateSetVersion: project.templateSetVersion ?? null, historicalPaths }, inputs: [...inputs].sort(([a], [b]) => a.localeCompare(b)).map(([path, sha2562]) => ({ path, sha256: sha2562 })) };
|
|
25119
25187
|
}
|
|
25120
25188
|
|
|
25189
|
+
// src/domain/review-candidate.ts
|
|
25190
|
+
import { join as join14 } from "node:path";
|
|
25191
|
+
function deriveAutonomousReviewCandidate(root, previous, artifacts, reference) {
|
|
25192
|
+
const parent = `tracks/${previous.trackId}`;
|
|
25193
|
+
if (previous.status !== "ready_for_review") throw new Error("Review remediation requires canonical ready_for_review state");
|
|
25194
|
+
if (previous.operation) throw new Error("Reconcile the existing review operation before preparing v5 remediation");
|
|
25195
|
+
if (resolveApprovalMode(previous.lastExecution, previous.approvalModeMigration) !== "autonomous" || !previous.autonomousReview) {
|
|
25196
|
+
throw new Error("Automatic remediation requires persisted Autonomous authority");
|
|
25197
|
+
}
|
|
25198
|
+
if (previous.autonomousReview.specCommit !== previous.commits?.spec) throw new Error("Autonomous scope changed; obtain explicit authorization before remediation");
|
|
25199
|
+
if (artifacts.has(`${parent}/state.json`)) throw new Error("Autonomous review derives state.json from the loop snapshot; omit staged state.json");
|
|
25200
|
+
const cycle = (previous.reviewCycles?.length ?? 0) + 1;
|
|
25201
|
+
const snapshot = `${parent}/reviews/loop-${cycle}.json`;
|
|
25202
|
+
const snapshots = [...artifacts.keys()].filter((path) => path.startsWith(`${parent}/reviews/`));
|
|
25203
|
+
if (snapshots.length !== 1 || snapshots[0] !== snapshot) throw new Error(`Autonomous remediation requires exactly reviews/loop-${cycle}.json`);
|
|
25204
|
+
for (const file2 of ["plan.md", "learning.md", "dependency-context.json"]) {
|
|
25205
|
+
if (!artifacts.has(`${parent}/${file2}`)) throw new Error(`Review remediation requires reassessed ${file2}`);
|
|
25206
|
+
}
|
|
25207
|
+
const bugs = [...artifacts.keys()].filter((path) => path.startsWith(`${parent}/bugs/`));
|
|
25208
|
+
if (!bugs.length) throw new Error("Review remediation requires evidence-backed bug artifacts");
|
|
25209
|
+
const loop = validateAutonomousRemediation(
|
|
25210
|
+
autonomousReviewSchema.parse(previous.autonomousReview),
|
|
25211
|
+
JSON.parse(artifacts.get(snapshot)),
|
|
25212
|
+
previous.lastExecution ?? {}
|
|
25213
|
+
);
|
|
25214
|
+
const head = previous.lastExecution?.headCommit;
|
|
25215
|
+
const execution = previous.lastExecution;
|
|
25216
|
+
if (!head || !execution?.executionId || !execution.planRevision || !execution.graphDigest || !isGitAncestor(root, head)) throw new Error("Review requires completed execution evidence at an ancestor of canonical HEAD");
|
|
25217
|
+
requireReviewedProductUnchanged(root, head, previous.trackId);
|
|
25218
|
+
const errors = [];
|
|
25219
|
+
const original = parsePlanContent(readSafeArtifact(root, `.cadre/${parent}/plan.md`), `${parent}/plan.md`, errors);
|
|
25220
|
+
validatePlanGraph(`${parent}/plan.md`, original, previous.status, errors);
|
|
25221
|
+
validateExecutionJournal(join14(root, ".cadre", parent), previous, original, errors);
|
|
25222
|
+
const proposed = parsePlanContent(artifacts.get(`${parent}/plan.md`), `${parent}/plan.md`, errors);
|
|
25223
|
+
validatePlanGraph(`${parent}/plan.md`, proposed, "in_progress", errors);
|
|
25224
|
+
if (errors.length) throw new Error(errors.join("; "));
|
|
25225
|
+
if (proposed.specRevision !== original.specRevision || proposed.planRevision !== original.planRevision + 1 || proposed.phases.length <= original.phases.length) throw new Error("Review must append remediation to the next plan revision without changing specification scope");
|
|
25226
|
+
const evidence = (graph) => graph.phases.map(({ line: _line, tasks, ...phase }) => ({
|
|
25227
|
+
...phase,
|
|
25228
|
+
tasks: tasks.map(({ line: _taskLine, ...task }) => task)
|
|
25229
|
+
}));
|
|
25230
|
+
if (JSON.stringify(evidence(original)) !== JSON.stringify(evidence(proposed).slice(0, original.phases.length))) {
|
|
25231
|
+
throw new Error("Review remediation must preserve every completed phase, task and commit marker");
|
|
25232
|
+
}
|
|
25233
|
+
return {
|
|
25234
|
+
...previous,
|
|
25235
|
+
status: "in_progress",
|
|
25236
|
+
checkpoint: "ready",
|
|
25237
|
+
operation: null,
|
|
25238
|
+
autonomousReview: loop,
|
|
25239
|
+
reviewCycles: [...previous.reviewCycles ?? [], {
|
|
25240
|
+
cycle,
|
|
25241
|
+
outcome: "changes_requested",
|
|
25242
|
+
executionId: execution.executionId,
|
|
25243
|
+
planRevision: execution.planRevision,
|
|
25244
|
+
graphDigest: execution.graphDigest,
|
|
25245
|
+
reviewedHead: head,
|
|
25246
|
+
commitRange: `${loop.initialBaseCommit}..${head}`,
|
|
25247
|
+
bugs,
|
|
25248
|
+
attemptedFindingIds: loop.findings.filter((finding) => finding.status === "open").map((finding) => finding.id),
|
|
25249
|
+
authorization: { kind: "persisted-mode", originExecutionId: loop.originExecutionId, operation: reference }
|
|
25250
|
+
}]
|
|
25251
|
+
};
|
|
25252
|
+
}
|
|
25253
|
+
|
|
25254
|
+
// src/domain/candidate-state-changes.ts
|
|
25255
|
+
function candidateStateChanges(before, after) {
|
|
25256
|
+
return Object.entries(after).flatMap(([field, value]) => {
|
|
25257
|
+
const previous = before[field];
|
|
25258
|
+
if (JSON.stringify(previous) === JSON.stringify(value)) return [];
|
|
25259
|
+
if (Array.isArray(previous) && Array.isArray(value) && value.length >= previous.length && JSON.stringify(value.slice(0, previous.length)) === JSON.stringify(previous)) {
|
|
25260
|
+
return [{ field, action: "append", value: value.slice(previous.length) }];
|
|
25261
|
+
}
|
|
25262
|
+
return [{ field, action: "set", value }];
|
|
25263
|
+
});
|
|
25264
|
+
}
|
|
25265
|
+
|
|
25121
25266
|
// src/domain/candidate-apply.ts
|
|
25122
25267
|
var json3 = (value) => `${JSON.stringify(value, null, 2)}
|
|
25123
25268
|
`;
|
|
@@ -25141,7 +25286,10 @@ function previewCandidateApply(input) {
|
|
|
25141
25286
|
if (JSON.stringify(listCandidatePaths(root, input.candidateId)) !== JSON.stringify(staged.map((file2) => file2.path).sort())) throw new Error("Candidate stage must contain exactly the approved manifest");
|
|
25142
25287
|
const original = new Map(staged.map((file2) => [candidateArtifactPath(input.candidateId, file2.path), file2.content]));
|
|
25143
25288
|
if (original.size !== staged.length) throw new Error("Candidate aliases an artifact");
|
|
25144
|
-
for (const path of original.keys()) if (!allowed(input, path))
|
|
25289
|
+
for (const path of original.keys()) if (!allowed(input, path)) {
|
|
25290
|
+
const hint = input.workflow === "review" ? "; review bug artifacts must use bugs/review-<cycle>.md or bugs/bug-<number>.md with numeric suffixes" : input.workflow === "revert" ? "; revert artifact IDs use lowercase letters, digits and hyphens, e.g. reverts/revert-t1-1-execution-before.json for target T1.1" : input.workflow === "revise" ? "; revision artifact IDs use lowercase letters, digits and hyphens, e.g. revisions/revision-2.md" : "";
|
|
25291
|
+
throw new Error(`Candidate cannot promote ${path}${hint}`);
|
|
25292
|
+
}
|
|
25145
25293
|
const project = JSON.parse(readSafeArtifact(root, ".cadre/project.json"));
|
|
25146
25294
|
if (project.templateSetVersion !== "v5" && input.workflow !== "refresh") throw new Error("Refresh to v5 before using cohesive candidate promotion");
|
|
25147
25295
|
const operationId2 = `${input.workflow}-${contentHash(JSON.stringify([root, baseCommit, [...original].sort()])).slice(0, 32)}`;
|
|
@@ -25155,7 +25303,7 @@ function previewCandidateApply(input) {
|
|
|
25155
25303
|
const trackIds = new Set([...overlay.keys()].map((path) => /^tracks\/([^/]+)\//.exec(path)?.[1]).filter((id3) => Boolean(id3)));
|
|
25156
25304
|
if (input.workflow === "refresh") {
|
|
25157
25305
|
if (!overlay.has("project.json")) throw new Error("Refresh requires proposed project.json");
|
|
25158
|
-
for (const entry of readdirSync12(
|
|
25306
|
+
for (const entry of readdirSync12(join15(root, ".cadre/tracks"), { withFileTypes: true }).filter((entry2) => entry2.isDirectory())) {
|
|
25159
25307
|
const previous = JSON.parse(readSafeArtifact(root, `.cadre/tracks/${entry.name}/state.json`));
|
|
25160
25308
|
if (!["completed", "archived"].includes(previous.status)) trackIds.add(entry.name);
|
|
25161
25309
|
if (previous.operation && previous.operation.action !== "implement") throw new Error("Refresh requires reconciliation of the active operation");
|
|
@@ -25187,10 +25335,14 @@ function previewCandidateApply(input) {
|
|
|
25187
25335
|
}
|
|
25188
25336
|
for (const id3 of trackIds) {
|
|
25189
25337
|
const parent = `tracks/${id3}`, path = `${parent}/state.json`;
|
|
25190
|
-
|
|
25338
|
+
let state = JSON.parse(read(path));
|
|
25191
25339
|
if (state.trackId !== id3) throw new Error("Candidate state identity mismatch");
|
|
25192
25340
|
if (!state.title || typeof state.title !== "string" || !["feature", "bug"].includes(state.type) || !Number.isInteger(state.revision) || state.revision < 1 || !Array.isArray(state.artifactProgress) || !Array.isArray(state.dependencies) || state.dependencies.includes(id3) || new Set(state.dependencies).size !== state.dependencies.length) throw new Error("Candidate state requires a title, type, positive revision, artifact progress and unique non-self dependencies");
|
|
25193
|
-
const previous = existsSync15(
|
|
25341
|
+
const previous = existsSync15(join15(root, ".cadre", path)) ? JSON.parse(readSafeArtifact(root, `.cadre/${path}`)) : null;
|
|
25342
|
+
if (input.workflow === "review" && previous?.autonomousReview) {
|
|
25343
|
+
state = deriveAutonomousReviewCandidate(root, previous, original, reference);
|
|
25344
|
+
unchanged.set(path, contentHash(readSafeArtifact(root, `.cadre/${path}`)));
|
|
25345
|
+
}
|
|
25194
25346
|
if (previous && ["completed", "archived"].includes(previous.status)) throw new Error("Terminal tracks are immutable; create a successor");
|
|
25195
25347
|
if (previous && JSON.stringify(state.history ?? []) !== JSON.stringify(previous.history ?? [])) throw new Error("Preserve historical state evidence; promotion appends its receipt reference");
|
|
25196
25348
|
if (previous && input.workflow === "refresh") {
|
|
@@ -25210,20 +25362,23 @@ function previewCandidateApply(input) {
|
|
|
25210
25362
|
state.checkpoint = "ready";
|
|
25211
25363
|
state.operation = null;
|
|
25212
25364
|
}
|
|
25213
|
-
if (input.workflow === "review"
|
|
25365
|
+
if (input.workflow === "review") {
|
|
25366
|
+
if (previous?.status !== "ready_for_review") throw new Error("Review remediation requires canonical ready_for_review state; reconcile an interrupted promotion first");
|
|
25367
|
+
if (state.status !== "in_progress") throw new Error("Review remediation requires proposed in_progress state; Autonomous derives it from the next-cycle loop snapshot, other modes must stage state.json");
|
|
25368
|
+
}
|
|
25214
25369
|
const graph = parsePlanContent(read(`${parent}/plan.md`), `${parent}/plan.md`), errors = [];
|
|
25215
25370
|
validatePlanGraph(`${parent}/plan.md`, graph, state.status, errors);
|
|
25216
25371
|
if (errors.length) throw new Error(errors.join("; "));
|
|
25217
25372
|
inspectDependencyContext(root, read(`${parent}/dependency-context.json`), state.dependencies ?? [], graph.specRevision, graph.planRevision, (path2) => read(path2.replace(/^\.cadre\//, "")));
|
|
25218
25373
|
overlay.set(path, json3(state));
|
|
25219
25374
|
}
|
|
25220
|
-
const files = [...overlay].map(([path, content]) => ({ path, content, absolutePath:
|
|
25375
|
+
const files = [...overlay].map(([path, content]) => ({ path, content, absolutePath: join15(root, ".cadre", path) }));
|
|
25221
25376
|
validateStagedState(root, input.candidateId, files);
|
|
25222
25377
|
const memory = inspectStagedMemory(root, input.candidateId, files);
|
|
25223
25378
|
if (memory.learning.some((item) => !item.valid)) throw new Error("Candidate contains invalid or stale learning");
|
|
25224
25379
|
const tracks = [];
|
|
25225
25380
|
for (const location of ["tracks", "archive"]) {
|
|
25226
|
-
const ids = new Set(existsSync15(
|
|
25381
|
+
const ids = new Set(existsSync15(join15(root, ".cadre", location)) ? readdirSync12(join15(root, ".cadre", location), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name) : []);
|
|
25227
25382
|
if (location === "tracks") for (const id3 of trackIds) ids.add(id3);
|
|
25228
25383
|
for (const id3 of ids) {
|
|
25229
25384
|
const state = JSON.parse(read(`${location}/${id3}/state.json`));
|
|
@@ -25232,15 +25387,26 @@ function previewCandidateApply(input) {
|
|
|
25232
25387
|
}
|
|
25233
25388
|
overlay.set("tracks.md", buildTracks(tracks.sort((a, b) => a.id.localeCompare(b.id))));
|
|
25234
25389
|
const promoted = [...overlay].map(([path, content]) => ({ path: `.cadre/${path}`, content }));
|
|
25235
|
-
const before = promoted.map((file2) => ({ path: file2.path, sha256: existsSync15(
|
|
25390
|
+
const before = promoted.map((file2) => ({ path: file2.path, sha256: existsSync15(join15(root, file2.path)) ? contentHash(readSafeArtifact(root, file2.path)) : null }));
|
|
25236
25391
|
const manifest = promoted.map((file2) => ({ path: file2.path, sha256: contentHash(file2.content) }));
|
|
25237
25392
|
const digest3 = contentHash(JSON.stringify({ operationId: operationId2, baseCommit, manifest, before, memoryInputs: memory.inputs, unchanged: [...unchanged].sort() }));
|
|
25238
|
-
|
|
25393
|
+
const stateChanges = [...overlay].filter(([path]) => path === "project.json" || /^tracks\/[^/]+\/state\.json$/.test(path)).map(([path, content]) => ({
|
|
25394
|
+
path: `.cadre/${path}`,
|
|
25395
|
+
changes: candidateStateChanges(JSON.parse(original.get(path) ?? readSafeArtifact(root, `.cadre/${path}`)), JSON.parse(content))
|
|
25396
|
+
})).filter((item) => item.changes.length);
|
|
25397
|
+
return { operationId: operationId2, baseCommit, files: promoted, manifest, digest: digest3, memory, stateChanges, validation: { valid: true, errors: [] } };
|
|
25239
25398
|
}
|
|
25240
25399
|
function applyCandidate(input, digest3) {
|
|
25400
|
+
const committed = committedReceiptForDigest(input.projectRoot, input.workflow, digest3);
|
|
25401
|
+
if (committed) return { ...committed, changedPaths: [], changedCount: 0, validation: { valid: true, errors: [] } };
|
|
25241
25402
|
const preview = previewCandidateApply(input);
|
|
25242
25403
|
if (preview.digest !== digest3) throw new Error("Candidate or required context changed after approval; reassess and preview again");
|
|
25243
|
-
return {
|
|
25404
|
+
return {
|
|
25405
|
+
...promoteOperation(input.projectRoot, { operationId: preview.operationId, kind: input.workflow, approvalDigest: digest3, baseCommit: preview.baseCommit }, preview.files),
|
|
25406
|
+
changedPaths: preview.files.map((file2) => file2.path),
|
|
25407
|
+
changedCount: preview.files.length,
|
|
25408
|
+
validation: preview.validation
|
|
25409
|
+
};
|
|
25244
25410
|
}
|
|
25245
25411
|
|
|
25246
25412
|
// src/domain/status-views.ts
|
|
@@ -34900,9 +35066,9 @@ var StdioServerTransport = class {
|
|
|
34900
35066
|
};
|
|
34901
35067
|
|
|
34902
35068
|
// src/mcp/server.ts
|
|
34903
|
-
import { createHash as
|
|
35069
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
34904
35070
|
import { existsSync as existsSync20, readFileSync as readFileSync10, readdirSync as readdirSync17, realpathSync as realpathSync3 } from "node:fs";
|
|
34905
|
-
import { join as
|
|
35071
|
+
import { join as join21 } from "node:path";
|
|
34906
35072
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
34907
35073
|
|
|
34908
35074
|
// src/domain/init.ts
|
|
@@ -34918,7 +35084,7 @@ import {
|
|
|
34918
35084
|
writeFileSync as writeFileSync6
|
|
34919
35085
|
} from "node:fs";
|
|
34920
35086
|
import { dirname as dirname5 } from "node:path";
|
|
34921
|
-
import { isAbsolute as isAbsolute3, join as
|
|
35087
|
+
import { isAbsolute as isAbsolute3, join as join16, relative as relative5, resolve as resolve9 } from "node:path";
|
|
34922
35088
|
var REQUIRED_STAGED_FILES = /* @__PURE__ */ new Set(["product.md", "guidelines.md", "tech-stack.md"]);
|
|
34923
35089
|
var OPTIONAL_STAGED_FILE = /^(?:workflow\.md|styleguides\/[a-z0-9-]+\.md)$/;
|
|
34924
35090
|
function hash3(content) {
|
|
@@ -35067,14 +35233,14 @@ function previewProjectInitCandidate(input) {
|
|
|
35067
35233
|
}
|
|
35068
35234
|
function assertInitializationBootstrap(projectRootInput, proposal) {
|
|
35069
35235
|
const root = safeProjectRoot(projectRootInput);
|
|
35070
|
-
const cadreRoot2 =
|
|
35236
|
+
const cadreRoot2 = join16(root, ".cadre");
|
|
35071
35237
|
if (!existsSync16(cadreRoot2) || !lstatSync7(cadreRoot2).isDirectory() || lstatSync7(cadreRoot2).isSymbolicLink()) {
|
|
35072
35238
|
throw new Error(`${cadreRoot2} must be a prepared candidate-stage directory`);
|
|
35073
35239
|
}
|
|
35074
35240
|
const expected = new Map(proposal.files.map((file2) => [file2.path, file2.content]));
|
|
35075
35241
|
const visit = (directory) => {
|
|
35076
35242
|
for (const entry of readdirSync13(directory, { withFileTypes: true })) {
|
|
35077
|
-
const target2 =
|
|
35243
|
+
const target2 = join16(directory, entry.name);
|
|
35078
35244
|
const path = relative5(cadreRoot2, target2).replaceAll("\\", "/");
|
|
35079
35245
|
if (path === "stage" || path.startsWith("stage/")) continue;
|
|
35080
35246
|
if (entry.isSymbolicLink()) throw new Error(`Refusing symbolic link inside initialization state: ${target2}`);
|
|
@@ -35113,7 +35279,7 @@ function assertNoSymlinkPath(root, target2) {
|
|
|
35113
35279
|
}
|
|
35114
35280
|
function applyProjectInitAtRoot(input, proposal) {
|
|
35115
35281
|
const projectRoot = safeProjectRoot(input.projectRoot);
|
|
35116
|
-
const cadreRoot2 =
|
|
35282
|
+
const cadreRoot2 = join16(projectRoot, ".cadre");
|
|
35117
35283
|
for (const file2 of proposal.files) {
|
|
35118
35284
|
const target2 = targetWithin(cadreRoot2, file2.path);
|
|
35119
35285
|
assertNoSymlinkPath(cadreRoot2, target2);
|
|
@@ -35123,7 +35289,7 @@ function applyProjectInitAtRoot(input, proposal) {
|
|
|
35123
35289
|
if (current2 !== file2.content) throw new Error(`Interrupted initialization disagrees at ${file2.path}`);
|
|
35124
35290
|
continue;
|
|
35125
35291
|
}
|
|
35126
|
-
const temporaryPath =
|
|
35292
|
+
const temporaryPath = join16(dirname5(target2), `.cadre-init-${process.pid}-${randomUUID4()}.tmp`);
|
|
35127
35293
|
try {
|
|
35128
35294
|
writeFileSync6(temporaryPath, file2.content, { flag: "wx" });
|
|
35129
35295
|
renameSync4(temporaryPath, target2);
|
|
@@ -35150,7 +35316,7 @@ function applyProjectInitCandidate(input, proposalDigest) {
|
|
|
35150
35316
|
function recordSetupCommit(projectRootInput, commit2) {
|
|
35151
35317
|
if (!/^[0-9a-f]{7,40}$/.test(commit2)) throw new Error("commit must be a hexadecimal Git commit SHA");
|
|
35152
35318
|
const root = safeProjectRoot(projectRootInput);
|
|
35153
|
-
const path =
|
|
35319
|
+
const path = join16(root, ".cadre", "project.json");
|
|
35154
35320
|
const project = JSON.parse(readFileSync7(path, "utf8"));
|
|
35155
35321
|
if (project.schemaVersion === 2 && typeof project.setup?.commit === "string" && project.setup.commit.startsWith("op:")) {
|
|
35156
35322
|
const actual = reconcileOperation(root, project.setup.commit.slice(3));
|
|
@@ -35164,7 +35330,7 @@ function recordSetupCommit(projectRootInput, commit2) {
|
|
|
35164
35330
|
throw new Error(`Project setup checkpoint is ${String(project.setup.checkpoint)}, not commit-pending`);
|
|
35165
35331
|
}
|
|
35166
35332
|
for (const artifact2 of project.setup.operation.approvedArtifactHashes ?? []) {
|
|
35167
|
-
const artifactPath = targetWithin(
|
|
35333
|
+
const artifactPath = targetWithin(join16(root, ".cadre"), normalizeCadrePath(artifact2.path));
|
|
35168
35334
|
if (!existsSync16(artifactPath) || lstatSync7(artifactPath).isSymbolicLink()) {
|
|
35169
35335
|
throw new Error(`Approved setup artifact is unavailable: ${artifact2.path}`);
|
|
35170
35336
|
}
|
|
@@ -35186,7 +35352,7 @@ function recordSetupCommit(projectRootInput, commit2) {
|
|
|
35186
35352
|
}
|
|
35187
35353
|
function recordGitInitialized(projectRootInput) {
|
|
35188
35354
|
const root = safeProjectRoot(projectRootInput);
|
|
35189
|
-
const path =
|
|
35355
|
+
const path = join16(root, ".cadre", "project.json");
|
|
35190
35356
|
const project = JSON.parse(readFileSync7(path, "utf8"));
|
|
35191
35357
|
if (project.schemaVersion === 2 && project.setup?.status === "completed") return path;
|
|
35192
35358
|
if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
|
|
@@ -35207,7 +35373,7 @@ function recordGitInitialized(projectRootInput) {
|
|
|
35207
35373
|
// src/domain/worktrees.ts
|
|
35208
35374
|
import { createHash as createHash8 } from "node:crypto";
|
|
35209
35375
|
import { existsSync as existsSync17, lstatSync as lstatSync8, readdirSync as readdirSync14, realpathSync as realpathSync2, rmdirSync as rmdirSync3 } from "node:fs";
|
|
35210
|
-
import { dirname as dirname6, join as
|
|
35376
|
+
import { dirname as dirname6, join as join17, relative as relative6, resolve as resolve10 } from "node:path";
|
|
35211
35377
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
35212
35378
|
var SHA2 = /^[0-9a-f]{7,40}$/;
|
|
35213
35379
|
var TRACK_ID2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
@@ -35253,7 +35419,7 @@ function worktreeIdentity(root, trackId, executionId2, nodeId, phaseId) {
|
|
|
35253
35419
|
const resolvedPhaseId = phaseForNode(nodeId);
|
|
35254
35420
|
const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId2}/tasks/${resolvedPhaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId2}/phases/${nodeId}`;
|
|
35255
35421
|
const branch = `cadre/${trackId}/${executionId2}/${task ? "task" : "phase"}-${nodeSlug(nodeId)}`;
|
|
35256
|
-
return { path:
|
|
35422
|
+
return { path: join17(root, relativePath), relativePath, branch };
|
|
35257
35423
|
}
|
|
35258
35424
|
function branchHead(root, branch) {
|
|
35259
35425
|
const result = git2(root, ["rev-parse", "--verify", `refs/heads/${branch}`], true);
|
|
@@ -35341,9 +35507,16 @@ function ownedExecutionState(root, input) {
|
|
|
35341
35507
|
const errors = [];
|
|
35342
35508
|
const graph = parsePlanContent(readSafeArtifact(root, `${parent}/plan.md`), `${parent}/plan.md`, errors);
|
|
35343
35509
|
validatePlanGraph(`${parent}/plan.md`, graph, state.status, errors);
|
|
35344
|
-
validateExecutionJournal(
|
|
35510
|
+
validateExecutionJournal(join17(root, parent), state, graph, errors);
|
|
35345
35511
|
if (errors.length) throw new CadreError("INTEGRATION_STATE_INVALID", `Active execution state failed validation: ${errors.slice(0, 3).join("; ")}`, { errors });
|
|
35346
|
-
|
|
35512
|
+
const owned = { [statePath]: contentHash(body), [journalPath]: contentHash(readSafeArtifact(root, journalPath)) };
|
|
35513
|
+
if (existsSync17(join17(root, ".cadre/tracks.md"))) {
|
|
35514
|
+
const index = readSafeArtifact(root, ".cadre/tracks.md");
|
|
35515
|
+
if (index === renderTracksWithState(root, join17(root, statePath), state).tracksContent) {
|
|
35516
|
+
owned[".cadre/tracks.md"] = contentHash(index);
|
|
35517
|
+
}
|
|
35518
|
+
}
|
|
35519
|
+
return owned;
|
|
35347
35520
|
}
|
|
35348
35521
|
function targetIdentity(root, input) {
|
|
35349
35522
|
if (TASK_ID.test(input.nodeId)) {
|
|
@@ -35487,7 +35660,7 @@ function applyWorktreeCleanup(input, proposalDigest, preparedProposal) {
|
|
|
35487
35660
|
const root = assertRepository(input.projectRoot);
|
|
35488
35661
|
if (!proposal.alreadyRemoved) git2(root, ["worktree", "remove", proposal.path]);
|
|
35489
35662
|
if (branchHead(root, proposal.branch)) git2(proposal.targetPath, ["branch", "-d", proposal.branch]);
|
|
35490
|
-
const managedRoot =
|
|
35663
|
+
const managedRoot = join17(root, ".cadre", ".worktrees");
|
|
35491
35664
|
let directory = dirname6(proposal.path);
|
|
35492
35665
|
while (directory.startsWith(`${managedRoot}/`)) {
|
|
35493
35666
|
if (!existsSync17(directory) || readdirSync14(directory).length) break;
|
|
@@ -35501,7 +35674,7 @@ function integrationRequiresApproval(input) {
|
|
|
35501
35674
|
}
|
|
35502
35675
|
function managedWorktreeStatus(projectRoot) {
|
|
35503
35676
|
const root = assertRepository(projectRoot);
|
|
35504
|
-
const managedRoot =
|
|
35677
|
+
const managedRoot = join17(root, ".cadre", ".worktrees");
|
|
35505
35678
|
const worktrees = registeredWorktrees(root).map((entry) => ({
|
|
35506
35679
|
...entry,
|
|
35507
35680
|
managed: relative6(managedRoot, entry.path) !== "" && !relative6(managedRoot, entry.path).startsWith("..")
|
|
@@ -35516,15 +35689,59 @@ function managedWorktreeStatus(projectRoot) {
|
|
|
35516
35689
|
orphanedDirectories.push(directory);
|
|
35517
35690
|
return;
|
|
35518
35691
|
}
|
|
35519
|
-
for (const entry of entries) if (entry.isDirectory()) walk2(
|
|
35692
|
+
for (const entry of entries) if (entry.isDirectory()) walk2(join17(directory, entry.name));
|
|
35520
35693
|
if (!entries.length && resolve10(directory) !== resolve10(managedRoot)) orphanedDirectories.push(directory);
|
|
35521
35694
|
}
|
|
35522
35695
|
walk2(managedRoot);
|
|
35523
35696
|
return { worktrees, orphanedDirectories };
|
|
35524
35697
|
}
|
|
35525
35698
|
|
|
35699
|
+
// src/domain/archive-promotion.ts
|
|
35700
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
35701
|
+
var archiveOperationId = (batchId) => `archive-${createHash9("sha256").update(JSON.stringify(batchId)).digest("hex").slice(0, 32)}`;
|
|
35702
|
+
function deriveArchivePromotion(project, batchId, selectedTracks, moves) {
|
|
35703
|
+
const operationId2 = archiveOperationId(batchId), reference = operationRef(operationId2);
|
|
35704
|
+
return {
|
|
35705
|
+
operationId: operationId2,
|
|
35706
|
+
project: { ...project, history: [...project.history ?? [], { action: "archive", selectedTracks, commit: reference }] },
|
|
35707
|
+
states: new Map(moves.map((move) => [move.trackId, {
|
|
35708
|
+
...move.state,
|
|
35709
|
+
checkpoint: "archived",
|
|
35710
|
+
history: [...Array.isArray(move.state.history) ? move.state.history : [], { action: "archive", commit: reference }]
|
|
35711
|
+
}]))
|
|
35712
|
+
};
|
|
35713
|
+
}
|
|
35714
|
+
function explainArchiveState(sourcePath, path, before, after) {
|
|
35715
|
+
return { sourcePath, path, sha256: createHash9("sha256").update(`${JSON.stringify(after, null, 2)}
|
|
35716
|
+
`).digest("hex"), changes: candidateStateChanges(before, after) };
|
|
35717
|
+
}
|
|
35718
|
+
|
|
35719
|
+
// src/domain/archive-replay.ts
|
|
35720
|
+
import { join as join18 } from "node:path";
|
|
35721
|
+
function archiveReceiptPath(input) {
|
|
35722
|
+
const id3 = archiveOperationId(input.batchId);
|
|
35723
|
+
return join18(safeProjectRoot(input.projectRoot), ".cadre/receipts", `${id3}.json`);
|
|
35724
|
+
}
|
|
35725
|
+
function replayCommittedArchive(input, approvalDigest) {
|
|
35726
|
+
const root = safeProjectRoot(input.projectRoot);
|
|
35727
|
+
const id3 = archiveOperationId(input.batchId);
|
|
35728
|
+
const receipt = committedReceiptForApproval(root, id3, "archive", approvalDigest, input.baseCommit);
|
|
35729
|
+
if (!receipt) return null;
|
|
35730
|
+
const validation = validateProject(root);
|
|
35731
|
+
return {
|
|
35732
|
+
operationPath: archiveReceiptPath(input),
|
|
35733
|
+
operation: { checkpoint: "completed" },
|
|
35734
|
+
receipt,
|
|
35735
|
+
moves: input.selectedTracks.map((trackId) => ({ trackId, targetPath: join18(root, ".cadre/archive", trackId) })),
|
|
35736
|
+
writes: [],
|
|
35737
|
+
tracksPath: join18(root, ".cadre/tracks.md"),
|
|
35738
|
+
valid: validation.errors.length === 0,
|
|
35739
|
+
derivedStateCurrent: !validation.warnings.some((warning) => warning.startsWith("TRACKS_INDEX_STALE:"))
|
|
35740
|
+
};
|
|
35741
|
+
}
|
|
35742
|
+
|
|
35526
35743
|
// src/domain/governance.ts
|
|
35527
|
-
import { createHash as
|
|
35744
|
+
import { createHash as createHash10, randomUUID as randomUUID5 } from "node:crypto";
|
|
35528
35745
|
import {
|
|
35529
35746
|
existsSync as existsSync18,
|
|
35530
35747
|
lstatSync as lstatSync9,
|
|
@@ -35535,15 +35752,15 @@ import {
|
|
|
35535
35752
|
unlinkSync as unlinkSync5,
|
|
35536
35753
|
writeFileSync as writeFileSync7
|
|
35537
35754
|
} from "node:fs";
|
|
35538
|
-
import { dirname as dirname7, join as
|
|
35755
|
+
import { dirname as dirname7, join as join19, relative as relative7 } from "node:path";
|
|
35539
35756
|
var SHA3 = /^[0-9a-f]{7,40}$/;
|
|
35540
35757
|
var TRACK_ID3 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
35541
35758
|
var BATCH_ID = /^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
|
|
35542
35759
|
function hash5(value) {
|
|
35543
|
-
return
|
|
35760
|
+
return createHash10("sha256").update(JSON.stringify(value)).digest("hex");
|
|
35544
35761
|
}
|
|
35545
35762
|
function contentHash2(content) {
|
|
35546
|
-
return
|
|
35763
|
+
return createHash10("sha256").update(content).digest("hex");
|
|
35547
35764
|
}
|
|
35548
35765
|
function json4(value) {
|
|
35549
35766
|
return `${JSON.stringify(value, null, 2)}
|
|
@@ -35558,7 +35775,7 @@ function writeApprovedFile(path, content) {
|
|
|
35558
35775
|
assertWritableFile(path);
|
|
35559
35776
|
mkdirSync6(dirname7(path), { recursive: true });
|
|
35560
35777
|
if (existsSync18(path) && readFileSync8(path, "utf8") === content) return;
|
|
35561
|
-
const temporaryPath =
|
|
35778
|
+
const temporaryPath = join19(dirname7(path), `.${randomUUID5()}.cadre.tmp`);
|
|
35562
35779
|
try {
|
|
35563
35780
|
writeFileSync7(temporaryPath, content, { flag: "wx" });
|
|
35564
35781
|
renameSync5(temporaryPath, path);
|
|
@@ -35630,8 +35847,8 @@ function previewReviewComplete(input) {
|
|
|
35630
35847
|
if (!isGitAncestor(root, range[1], input.reviewedHead)) throw new Error("Autonomous review baseline is not an ancestor of reviewed HEAD");
|
|
35631
35848
|
requireReviewedProductUnchanged(root, input.reviewedHead, input.trackId);
|
|
35632
35849
|
}
|
|
35633
|
-
const statePath =
|
|
35634
|
-
const tracksPath =
|
|
35850
|
+
const statePath = join19(cadreRoot(root), track.location, "state.json");
|
|
35851
|
+
const tracksPath = join19(cadreRoot(root), "tracks.md");
|
|
35635
35852
|
const stateBody = readFileSync8(statePath, "utf8");
|
|
35636
35853
|
const tracksBody = readFileSync8(tracksPath, "utf8");
|
|
35637
35854
|
const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
|
|
@@ -35687,6 +35904,9 @@ function applyReviewComplete(input, proposalDigest) {
|
|
|
35687
35904
|
}
|
|
35688
35905
|
if (proposal.state.schemaVersion === 2) {
|
|
35689
35906
|
const operationId2 = `review-${hash5([input.trackId, input.reviewedHead, proposal.state.reviewCycles?.at(-1)?.cycle]).slice(0, 32)}`;
|
|
35907
|
+
if (proposal.resuming) return { ...proposal, receipt: committedOperationReceipt(input.projectRoot, operationId2, "review", void 0, [
|
|
35908
|
+
{ path: `.cadre/tracks/${input.trackId}/state.json`, content: json4(proposal.state) }
|
|
35909
|
+
]), valid: true, derivedStateCurrent: true };
|
|
35690
35910
|
const receipt = promoteOperation(input.projectRoot, { operationId: operationId2, kind: "review", approvalDigest: proposalDigest, baseCommit: resolveGitCommit(input.projectRoot) }, [
|
|
35691
35911
|
{ path: `.cadre/tracks/${input.trackId}/state.json`, content: json4(proposal.state) },
|
|
35692
35912
|
{ path: ".cadre/tracks.md", content: proposal.tracksContent }
|
|
@@ -35724,9 +35944,9 @@ function dependencyOrder(tracks) {
|
|
|
35724
35944
|
function deriveMaterializedArchiveBatch(input) {
|
|
35725
35945
|
const root = safeProjectRoot(input.projectRoot);
|
|
35726
35946
|
const validation = requireCurrentProject(root);
|
|
35727
|
-
const operationsPath =
|
|
35947
|
+
const operationsPath = join19(cadreRoot(root), "operations");
|
|
35728
35948
|
const activeOperation = existsSync18(operationsPath) ? readdirSync15(operationsPath).filter((file2) => file2.endsWith(".json")).map(
|
|
35729
|
-
(file2) => JSON.parse(readFileSync8(
|
|
35949
|
+
(file2) => JSON.parse(readFileSync8(join19(operationsPath, file2), "utf8"))
|
|
35730
35950
|
).find((operation) => operation.action === "archive" && operation.status === "in_progress") : void 0;
|
|
35731
35951
|
const selectedTracks = input.selectedTracks?.length ? [...new Set(input.selectedTracks)] : activeOperation?.selectedTracks ?? dependencyOrder(
|
|
35732
35952
|
validation.tracks.filter((track) => track.status === "completed" && track.location === `tracks/${track.id}`)
|
|
@@ -35808,7 +36028,10 @@ function previewArchiveBatchCandidate(input) {
|
|
|
35808
36028
|
return previewMaterializedArchiveBatch(loadArchiveBatchCandidate(input));
|
|
35809
36029
|
}
|
|
35810
36030
|
function applyArchiveBatchCandidate(input, proposalDigest) {
|
|
35811
|
-
|
|
36031
|
+
const replay = replayCommittedArchive(input, proposalDigest);
|
|
36032
|
+
if (replay) return replay;
|
|
36033
|
+
const applied = applyMaterializedArchiveBatch(loadArchiveBatchCandidate(input), proposalDigest);
|
|
36034
|
+
return "receipt" in applied ? { ...applied, operationPath: archiveReceiptPath(input) } : applied;
|
|
35812
36035
|
}
|
|
35813
36036
|
function assertArchiveUpdate(path, selected) {
|
|
35814
36037
|
if (path === "patterns/index.md" || /^patterns\/[a-z0-9]+(?:-[a-z0-9]+)*\.md$/.test(path)) return;
|
|
@@ -35820,7 +36043,7 @@ function directorySnapshot(path) {
|
|
|
35820
36043
|
const files = [];
|
|
35821
36044
|
function visit(directory) {
|
|
35822
36045
|
for (const entry of readdirSync15(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
35823
|
-
const target2 =
|
|
36046
|
+
const target2 = join19(directory, entry.name);
|
|
35824
36047
|
if (entry.isSymbolicLink()) throw new Error(`refusing archive source symbolic link ${target2}`);
|
|
35825
36048
|
if (entry.isDirectory()) visit(target2);
|
|
35826
36049
|
else if (entry.isFile()) files.push({ path: relative7(path, target2), content: readFileSync8(target2, "utf8") });
|
|
@@ -35839,7 +36062,7 @@ function previewMaterializedArchiveBatch(input) {
|
|
|
35839
36062
|
}
|
|
35840
36063
|
if (input.selectedTracks.some((trackId) => !TRACK_ID3.test(trackId))) throw new Error("invalid selected track ID");
|
|
35841
36064
|
const root = safeProjectRoot(input.projectRoot);
|
|
35842
|
-
const operationPath =
|
|
36065
|
+
const operationPath = join19(cadreRoot(root), "operations", `${input.batchId}.json`);
|
|
35843
36066
|
const existingOperation = existsSync18(operationPath) ? JSON.parse(readFileSync8(operationPath, "utf8")) : null;
|
|
35844
36067
|
if (existingOperation && (existingOperation.action !== "archive" || existingOperation.status !== "in_progress" || existingOperation.baseCommit !== input.baseCommit || JSON.stringify(existingOperation.selectedTracks) !== JSON.stringify(input.selectedTracks))) {
|
|
35845
36068
|
throw new Error(`archive batch ${input.batchId} does not match the approved input`);
|
|
@@ -35857,10 +36080,10 @@ function previewMaterializedArchiveBatch(input) {
|
|
|
35857
36080
|
for (const update of updates) assertArchiveUpdate(update.path, selected);
|
|
35858
36081
|
if (validation.project.schemaVersion === 2) {
|
|
35859
36082
|
const relocate = (path) => path.replace(/^\.cadre\/tracks\/([^/]+)\//, (prefix, id3) => selected.has(id3) ? `.cadre/archive/${id3}/` : prefix);
|
|
35860
|
-
const read = (path) => updates.find((item) => `.cadre/${item.path}` === path)?.content ?? readFileSync8(
|
|
36083
|
+
const read = (path) => updates.find((item) => `.cadre/${item.path}` === path)?.content ?? readFileSync8(join19(root, path), "utf8");
|
|
35861
36084
|
for (const track of validation.tracks.filter((item) => item.location === `tracks/${item.id}` && !selected.has(item.id) && !["completed", "archived"].includes(item.status))) {
|
|
35862
36085
|
const path = `tracks/${track.id}/dependency-context.json`;
|
|
35863
|
-
if (!existsSync18(
|
|
36086
|
+
if (!existsSync18(join19(root, ".cadre", path))) throw new Error(`${track.id}: reassess missing dependency context before archive`);
|
|
35864
36087
|
const state = validation.states.get(track.id);
|
|
35865
36088
|
const graph = parsePlanContent(read(`.cadre/tracks/${track.id}/plan.md`), "plan.md");
|
|
35866
36089
|
const body = read(`.cadre/${path}`);
|
|
@@ -35875,7 +36098,7 @@ function previewMaterializedArchiveBatch(input) {
|
|
|
35875
36098
|
}
|
|
35876
36099
|
}
|
|
35877
36100
|
}
|
|
35878
|
-
const memory = inspectStagedMemory(root, "archive-validation", updates.map((update) => ({ ...update, absolutePath:
|
|
36101
|
+
const memory = inspectStagedMemory(root, "archive-validation", updates.map((update) => ({ ...update, absolutePath: join19(root, ".cadre", update.path) })));
|
|
35879
36102
|
const invalidMemory = memory.learning.filter((entry) => !entry.valid);
|
|
35880
36103
|
if (invalidMemory.length) throw new Error(`Archive seed reassessment required: ${JSON.stringify(invalidMemory)}`);
|
|
35881
36104
|
const approvalDigest = hash5({
|
|
@@ -35889,9 +36112,9 @@ function previewMaterializedArchiveBatch(input) {
|
|
|
35889
36112
|
if (existingOperation && existingOperation.approvalDigest !== approvalDigest) {
|
|
35890
36113
|
throw new Error(`archive batch ${input.batchId} content differs from its approved journal`);
|
|
35891
36114
|
}
|
|
35892
|
-
const activeOperations =
|
|
36115
|
+
const activeOperations = join19(cadreRoot(root), "operations");
|
|
35893
36116
|
const unfinished = existsSync18(activeOperations) ? readdirSync15(activeOperations).filter((file2) => file2.endsWith(".json")).find((file2) => {
|
|
35894
|
-
const operation2 = JSON.parse(readFileSync8(
|
|
36117
|
+
const operation2 = JSON.parse(readFileSync8(join19(activeOperations, file2), "utf8"));
|
|
35895
36118
|
return operation2.status === "in_progress";
|
|
35896
36119
|
}) : void 0;
|
|
35897
36120
|
if (unfinished && unfinished !== `${input.batchId}.json`) {
|
|
@@ -35906,8 +36129,8 @@ function previewMaterializedArchiveBatch(input) {
|
|
|
35906
36129
|
if (!pending && !partiallyPromoted || state.operation != null) {
|
|
35907
36130
|
throw new Error(`${trackId} is not an eligible completed track`);
|
|
35908
36131
|
}
|
|
35909
|
-
const sourcePath =
|
|
35910
|
-
const targetPath =
|
|
36132
|
+
const sourcePath = join19(cadreRoot(root), pending ? "tracks" : "archive", trackId);
|
|
36133
|
+
const targetPath = join19(cadreRoot(root), "archive", trackId);
|
|
35911
36134
|
if (pending && existsSync18(targetPath)) throw new Error(`archive target already exists for ${trackId}`);
|
|
35912
36135
|
return { trackId, sourcePath, targetPath, state: { ...state, status: "archived" }, needsMove: pending };
|
|
35913
36136
|
});
|
|
@@ -35941,23 +36164,36 @@ function previewMaterializedArchiveBatch(input) {
|
|
|
35941
36164
|
artifactProgress: [...moveArtifacts, ...updateArtifacts, "tracks.md"]
|
|
35942
36165
|
};
|
|
35943
36166
|
const current2 = {
|
|
35944
|
-
project: readFileSync8(
|
|
35945
|
-
tracks: readFileSync8(
|
|
36167
|
+
project: readFileSync8(join19(cadreRoot(root), "project.json"), "utf8"),
|
|
36168
|
+
tracks: readFileSync8(join19(cadreRoot(root), "tracks.md"), "utf8"),
|
|
35946
36169
|
sources: moves.map((move) => ({ trackId: move.trackId, files: directorySnapshot(move.sourcePath) })),
|
|
35947
36170
|
updates: updates.map((update) => ({
|
|
35948
36171
|
path: update.path,
|
|
35949
|
-
content: existsSync18(
|
|
36172
|
+
content: existsSync18(join19(cadreRoot(root), update.path)) ? readFileSync8(join19(cadreRoot(root), update.path), "utf8") : null
|
|
35950
36173
|
}))
|
|
35951
36174
|
};
|
|
36175
|
+
const project = JSON.parse(current2.project);
|
|
36176
|
+
const promotion = project.schemaVersion === 2 ? deriveArchivePromotion(project, input.batchId, input.selectedTracks, moves) : null;
|
|
36177
|
+
const stateChanges = promotion ? [
|
|
36178
|
+
explainArchiveState(join19(cadreRoot(root), "project.json"), join19(cadreRoot(root), "project.json"), project, promotion.project),
|
|
36179
|
+
...moves.map((move) => explainArchiveState(
|
|
36180
|
+
join19(move.sourcePath, "state.json"),
|
|
36181
|
+
join19(move.targetPath, "state.json"),
|
|
36182
|
+
JSON.parse(current2.sources.find((source) => source.trackId === move.trackId).files.find((file2) => file2.path === "state.json").content),
|
|
36183
|
+
promotion.states.get(move.trackId)
|
|
36184
|
+
))
|
|
36185
|
+
] : [];
|
|
35952
36186
|
return {
|
|
35953
36187
|
operationPath,
|
|
35954
36188
|
initialOperation,
|
|
35955
36189
|
operation,
|
|
35956
36190
|
moves,
|
|
35957
36191
|
writes: updates,
|
|
35958
|
-
tracksPath:
|
|
36192
|
+
tracksPath: join19(cadreRoot(root), "tracks.md"),
|
|
35959
36193
|
tracksContent,
|
|
35960
36194
|
resuming: existingOperation != null,
|
|
36195
|
+
stateChanges,
|
|
36196
|
+
promotion,
|
|
35961
36197
|
digest: hash5({ current: current2, input, initialOperation, operation, moves: moves.map(({ trackId, state, needsMove }) => ({ trackId, state, needsMove })), updates, tracksContent })
|
|
35962
36198
|
};
|
|
35963
36199
|
}
|
|
@@ -35969,31 +36205,30 @@ function applyMaterializedArchiveBatch(input, proposalDigest) {
|
|
|
35969
36205
|
throw new Error("archive batch proposal is stale; preview it again");
|
|
35970
36206
|
}
|
|
35971
36207
|
}
|
|
35972
|
-
const projectPath =
|
|
36208
|
+
const projectPath = join19(cadreRoot(input.projectRoot), "project.json");
|
|
35973
36209
|
const project = JSON.parse(readFileSync8(projectPath, "utf8"));
|
|
35974
36210
|
if (project.schemaVersion === 2) {
|
|
35975
|
-
const
|
|
36211
|
+
const { operationId: operationId2, states, project: archivedProject } = proposal.promotion;
|
|
35976
36212
|
const files = [];
|
|
35977
36213
|
for (const move of proposal.moves) {
|
|
35978
36214
|
for (const file2 of directorySnapshot(move.sourcePath)) {
|
|
35979
|
-
files.push({ path: `.cadre/archive/${move.trackId}/${file2.path}`, content: file2.path === "state.json" ? json4(
|
|
36215
|
+
files.push({ path: `.cadre/archive/${move.trackId}/${file2.path}`, content: file2.path === "state.json" ? json4(states.get(move.trackId)) : file2.content });
|
|
35980
36216
|
files.push({ path: `.cadre/tracks/${move.trackId}/${file2.path}`, content: null });
|
|
35981
36217
|
}
|
|
35982
36218
|
}
|
|
35983
36219
|
for (const update of proposal.writes) files.push({ path: `.cadre/${update.path}`, content: update.content });
|
|
35984
|
-
|
|
35985
|
-
files.push({ path: ".cadre/project.json", content: json4(project) }, { path: ".cadre/tracks.md", content: proposal.tracksContent });
|
|
36220
|
+
files.push({ path: ".cadre/project.json", content: json4(archivedProject) }, { path: ".cadre/tracks.md", content: proposal.tracksContent });
|
|
35986
36221
|
const receipt = promoteOperation(input.projectRoot, { operationId: operationId2, kind: "archive", approvalDigest: proposalDigest, baseCommit: input.baseCommit }, files);
|
|
35987
36222
|
return { ...proposal, receipt, valid: true, derivedStateCurrent: true };
|
|
35988
36223
|
}
|
|
35989
36224
|
const currentOperation = existsSync18(proposal.operationPath) ? JSON.parse(readFileSync8(proposal.operationPath, "utf8")) : proposal.initialOperation;
|
|
35990
36225
|
if (!existsSync18(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json4(currentOperation));
|
|
35991
|
-
mkdirSync6(
|
|
36226
|
+
mkdirSync6(join19(cadreRoot(input.projectRoot), "archive"), { recursive: true });
|
|
35992
36227
|
const completedTracks = new Set(currentOperation.completedTracks);
|
|
35993
36228
|
const artifactProgress = new Set(currentOperation.artifactProgress);
|
|
35994
36229
|
for (const move of proposal.moves) {
|
|
35995
36230
|
if (move.needsMove) renameSync5(move.sourcePath, move.targetPath);
|
|
35996
|
-
writeApprovedFile(
|
|
36231
|
+
writeApprovedFile(join19(move.targetPath, "state.json"), json4(move.state));
|
|
35997
36232
|
completedTracks.add(move.trackId);
|
|
35998
36233
|
artifactProgress.add(`archive/${move.trackId}`);
|
|
35999
36234
|
writeApprovedFile(proposal.operationPath, json4({
|
|
@@ -36003,7 +36238,7 @@ function applyMaterializedArchiveBatch(input, proposalDigest) {
|
|
|
36003
36238
|
}));
|
|
36004
36239
|
}
|
|
36005
36240
|
for (const update of proposal.writes) {
|
|
36006
|
-
writeApprovedFile(
|
|
36241
|
+
writeApprovedFile(join19(cadreRoot(input.projectRoot), update.path), update.content);
|
|
36007
36242
|
artifactProgress.add(update.path);
|
|
36008
36243
|
writeApprovedFile(proposal.operationPath, json4({
|
|
36009
36244
|
...currentOperation,
|
|
@@ -36026,17 +36261,17 @@ function previewArchiveBatchRecord(input) {
|
|
|
36026
36261
|
if (!BATCH_ID.test(input.batchId)) throw new Error("invalid archive batchId");
|
|
36027
36262
|
if (!SHA3.test(input.archiveCommit)) throw new Error("archiveCommit must be a Git commit SHA");
|
|
36028
36263
|
const root = safeProjectRoot(input.projectRoot);
|
|
36029
|
-
const operationPath =
|
|
36264
|
+
const operationPath = join19(cadreRoot(root), "operations", `${input.batchId}.json`);
|
|
36030
36265
|
const operationBody = readFileSync8(operationPath, "utf8");
|
|
36031
36266
|
const currentOperation = JSON.parse(operationBody);
|
|
36032
36267
|
if (currentOperation.action !== "archive" || !["in_progress", "completed"].includes(currentOperation.status) || currentOperation.status === "completed" && currentOperation.archiveCommit !== input.archiveCommit) {
|
|
36033
36268
|
throw new Error(`${input.batchId} is not a matching archive batch`);
|
|
36034
36269
|
}
|
|
36035
|
-
const projectPath =
|
|
36270
|
+
const projectPath = join19(cadreRoot(root), "project.json");
|
|
36036
36271
|
const projectBody = readFileSync8(projectPath, "utf8");
|
|
36037
36272
|
const currentProject = JSON.parse(projectBody);
|
|
36038
36273
|
const states = currentOperation.selectedTracks.map((trackId) => {
|
|
36039
|
-
const path =
|
|
36274
|
+
const path = join19(cadreRoot(root), "archive", trackId, "state.json");
|
|
36040
36275
|
const body = readFileSync8(path, "utf8");
|
|
36041
36276
|
const current2 = JSON.parse(body);
|
|
36042
36277
|
if (current2.status !== "archived") throw new Error(`${trackId} is not archived`);
|
|
@@ -36283,7 +36518,7 @@ import {
|
|
|
36283
36518
|
} from "node:fs";
|
|
36284
36519
|
import { homedir as homedir2 } from "node:os";
|
|
36285
36520
|
import { constants } from "node:fs";
|
|
36286
|
-
import { join as
|
|
36521
|
+
import { join as join20, resolve as resolve12 } from "node:path";
|
|
36287
36522
|
var TOKEN_PREFIX = "cadre_pt1_";
|
|
36288
36523
|
var TOKEN_PATTERN = /^cadre_pt1_[A-Za-z0-9_-]{32}$/;
|
|
36289
36524
|
var RECORD_PATTERN = /^cadre_pt1_[A-Za-z0-9_-]{32}\.json$/;
|
|
@@ -36300,8 +36535,8 @@ var envelopeSchema = external_exports.object({
|
|
|
36300
36535
|
});
|
|
36301
36536
|
var proposalTokenSchema = external_exports.string().regex(TOKEN_PATTERN, "invalid proposal token format");
|
|
36302
36537
|
function defaultProposalRoot() {
|
|
36303
|
-
const cadreHome = process.env.CADRE_HOME ? resolve12(process.env.CADRE_HOME) :
|
|
36304
|
-
return
|
|
36538
|
+
const cadreHome = process.env.CADRE_HOME ? resolve12(process.env.CADRE_HOME) : join20(homedir2(), ".cadre");
|
|
36539
|
+
return join20(cadreHome, "runtime", "proposals");
|
|
36305
36540
|
}
|
|
36306
36541
|
var ProposalTokenStore = class {
|
|
36307
36542
|
root;
|
|
@@ -36408,13 +36643,13 @@ var ProposalTokenStore = class {
|
|
|
36408
36643
|
if ((stat.mode & 63) !== 0) chmodSync(this.root, 448);
|
|
36409
36644
|
}
|
|
36410
36645
|
pathFor(token) {
|
|
36411
|
-
return
|
|
36646
|
+
return join20(this.root, `${token}.json`);
|
|
36412
36647
|
}
|
|
36413
36648
|
records() {
|
|
36414
36649
|
const records = [];
|
|
36415
36650
|
for (const entry of readdirSync16(this.root)) {
|
|
36416
36651
|
if (!RECORD_PATTERN.test(entry)) continue;
|
|
36417
|
-
const path =
|
|
36652
|
+
const path = join20(this.root, entry);
|
|
36418
36653
|
let stat;
|
|
36419
36654
|
try {
|
|
36420
36655
|
stat = lstatSync10(path);
|
|
@@ -36521,7 +36756,16 @@ var digestSchema = external_exports.string().regex(/^[0-9a-f]{64}$/);
|
|
|
36521
36756
|
var commitSchema = external_exports.string().regex(/^[0-9a-f]{7,40}$/);
|
|
36522
36757
|
var proposalTokenSchema2 = external_exports.string().regex(/^cadre_pt1_[A-Za-z0-9_-]{32}$/);
|
|
36523
36758
|
var commandStatusSchema = external_exports.enum(["approval_required", "applied"]);
|
|
36524
|
-
var receiptResultSchema = external_exports.strictObject({
|
|
36759
|
+
var receiptResultSchema = external_exports.strictObject({
|
|
36760
|
+
status: external_exports.enum(["commit_pending", "committed"]),
|
|
36761
|
+
operationId: external_exports.string(),
|
|
36762
|
+
commit: external_exports.string().nullable(),
|
|
36763
|
+
receiptHash: external_exports.string().optional(),
|
|
36764
|
+
trailers: external_exports.array(external_exports.string()).optional(),
|
|
36765
|
+
changedPaths: external_exports.array(external_exports.string()).optional(),
|
|
36766
|
+
changedCount: external_exports.number().int().nonnegative().optional(),
|
|
36767
|
+
validation: external_exports.strictObject({ valid: external_exports.boolean(), errors: external_exports.array(external_exports.string()) }).optional()
|
|
36768
|
+
});
|
|
36525
36769
|
var jsonObjectSchema = external_exports.record(external_exports.string(), external_exports.unknown());
|
|
36526
36770
|
function sharedDetail(schema) {
|
|
36527
36771
|
return jsonObjectSchema.superRefine((value, context) => {
|
|
@@ -36858,6 +37102,12 @@ var archivePrepareSchema = external_exports.strictObject({
|
|
|
36858
37102
|
checkpoint: external_exports.string(),
|
|
36859
37103
|
resuming: external_exports.boolean(),
|
|
36860
37104
|
moves: external_exports.array(archiveMovePrepareSchema),
|
|
37105
|
+
stateChanges: external_exports.array(external_exports.strictObject({
|
|
37106
|
+
sourcePath: pathSchema,
|
|
37107
|
+
path: pathSchema,
|
|
37108
|
+
sha256: digestSchema,
|
|
37109
|
+
changes: external_exports.array(external_exports.strictObject({ field: external_exports.string(), action: external_exports.enum(["set", "append"]), value: external_exports.unknown() }))
|
|
37110
|
+
})),
|
|
36861
37111
|
writes: external_exports.array(artifactSchema),
|
|
36862
37112
|
tracks: artifactSchema
|
|
36863
37113
|
});
|
|
@@ -36987,7 +37237,15 @@ var workflowOutcomeSchema = external_exports.strictObject({
|
|
|
36987
37237
|
});
|
|
36988
37238
|
var CADRE_MCP_OUTPUT_SCHEMAS = {
|
|
36989
37239
|
[CADRE_MCP_TOOLS.contextRead]: compatibleOutputSchema(contextPageSchema),
|
|
36990
|
-
[CADRE_MCP_TOOLS.candidateApply]: compatibleOutputSchema(receiptResultSchema, external_exports.strictObject({
|
|
37240
|
+
[CADRE_MCP_TOOLS.candidateApply]: compatibleOutputSchema(receiptResultSchema, external_exports.strictObject({
|
|
37241
|
+
commandStatus: external_exports.literal("approval_required"),
|
|
37242
|
+
proposalToken: proposalTokenSchema2,
|
|
37243
|
+
operationId: external_exports.string(),
|
|
37244
|
+
files: external_exports.array(artifactSchema),
|
|
37245
|
+
stateChanges: external_exports.array(external_exports.strictObject({ path: pathSchema, changes: external_exports.array(external_exports.strictObject({ field: external_exports.string(), action: external_exports.enum(["set", "append"]), value: external_exports.unknown() })) })),
|
|
37246
|
+
digest: digestSchema,
|
|
37247
|
+
validation: external_exports.strictObject({ valid: external_exports.boolean(), errors: stringArray })
|
|
37248
|
+
})),
|
|
36991
37249
|
[CADRE_MCP_TOOLS.diagnosticRead]: compatibleOutputSchema(external_exports.strictObject({ diagnosticId: external_exports.string(), content: external_exports.string(), offset: external_exports.number().int(), nextOffset: external_exports.number().int().nullable(), totalBytes: external_exports.number().int() })),
|
|
36992
37250
|
[CADRE_MCP_TOOLS.workflowElicit]: compatibleOutputSchema(workflowOutcomeSchema),
|
|
36993
37251
|
[CADRE_MCP_TOOLS.templateGetMany]: compatibleOutputSchema(templateSetSchema),
|
|
@@ -37062,7 +37320,7 @@ function createResultFormatter(format) {
|
|
|
37062
37320
|
|
|
37063
37321
|
// src/mcp/server.ts
|
|
37064
37322
|
function sha256(content) {
|
|
37065
|
-
return
|
|
37323
|
+
return createHash11("sha256").update(content).digest("hex");
|
|
37066
37324
|
}
|
|
37067
37325
|
function artifact(path, content) {
|
|
37068
37326
|
return { path, sha256: sha256(content) };
|
|
@@ -37077,10 +37335,10 @@ function jsonArtifact(path, value) {
|
|
|
37077
37335
|
function requireCurrentProject2(projectRoot, continuingExecution = false) {
|
|
37078
37336
|
requireCommittedOperations(projectRoot);
|
|
37079
37337
|
const root = safeProjectRoot(projectRoot);
|
|
37080
|
-
const path =
|
|
37338
|
+
const path = join21(root, ".cadre", "project.json");
|
|
37081
37339
|
const project = JSON.parse(readFileSync10(path, "utf8"));
|
|
37082
|
-
if (continuingExecution &&
|
|
37083
|
-
if (project.runtimeVersion
|
|
37340
|
+
if (continuingExecution && (isCompatibleRuntimeVersion(project.runtimeVersion) || project.runtimeVersion === "3.8.0") && project.templateSetVersion === "v4") return root;
|
|
37341
|
+
if (!isCompatibleRuntimeVersion(project.runtimeVersion) || project.templateSetVersion !== TEMPLATE_SET_VERSION) {
|
|
37084
37342
|
throw new CadreError(
|
|
37085
37343
|
"PROJECT_REFRESH_REQUIRED",
|
|
37086
37344
|
`Cadre project refresh required before mutation: current ${project.runtimeVersion ?? "unknown"}/${project.templateSetVersion ?? "unknown"}, target ${CADRE_RUNTIME_VERSION}/${TEMPLATE_SET_VERSION}.`,
|
|
@@ -37169,7 +37427,7 @@ function projectStatusView(validation) {
|
|
|
37169
37427
|
} : null,
|
|
37170
37428
|
lastRefresh: validation.project.lastRefresh ?? null
|
|
37171
37429
|
} : null,
|
|
37172
|
-
upgradeRequired: validation.project ? validation.project.runtimeVersion
|
|
37430
|
+
upgradeRequired: validation.project ? !isCompatibleRuntimeVersion(validation.project.runtimeVersion) || validation.project.templateSetVersion !== TEMPLATE_SET_VERSION : false,
|
|
37173
37431
|
targetRuntimeVersion: CADRE_RUNTIME_VERSION,
|
|
37174
37432
|
targetTemplateSetVersion: TEMPLATE_SET_VERSION,
|
|
37175
37433
|
counts,
|
|
@@ -37181,20 +37439,20 @@ function projectStatusView(validation) {
|
|
|
37181
37439
|
function focusedValidationErrors(validation, root, trackIds) {
|
|
37182
37440
|
const markers = trackIds.flatMap((id3) => [
|
|
37183
37441
|
`${id3}:`,
|
|
37184
|
-
|
|
37185
|
-
|
|
37442
|
+
join21(root, ".cadre", "tracks", id3),
|
|
37443
|
+
join21(root, ".cadre", "archive", id3),
|
|
37186
37444
|
`/${id3}/`
|
|
37187
37445
|
]);
|
|
37188
37446
|
return validation.errors.filter((error51) => markers.some((marker) => error51.includes(marker)));
|
|
37189
37447
|
}
|
|
37190
37448
|
function stagedTrackCandidates(root, validation) {
|
|
37191
|
-
const stageRoot =
|
|
37449
|
+
const stageRoot = join21(root, ".cadre", "stage");
|
|
37192
37450
|
if (!existsSync20(stageRoot)) return [];
|
|
37193
37451
|
return readdirSync17(stageRoot, { withFileTypes: true }).filter((entry) => entry.name.startsWith("track-") && entry.name.length > "track-".length).map((entry) => {
|
|
37194
37452
|
const candidateId = entry.name;
|
|
37195
37453
|
const trackId = candidateId.slice("track-".length);
|
|
37196
37454
|
const canonical = validation.tracks.find((track) => track.id === trackId);
|
|
37197
|
-
const canonicalState = canonical?.location.startsWith("archive/") ? "archived" : canonical ? "active" : [
|
|
37455
|
+
const canonicalState = canonical?.location.startsWith("archive/") ? "archived" : canonical ? "active" : [join21(root, ".cadre", "tracks", trackId), join21(root, ".cadre", "archive", trackId)].some((path) => existsSync20(path)) ? "invalid" : "absent";
|
|
37198
37456
|
try {
|
|
37199
37457
|
const paths = listCandidatePaths(root, candidateId);
|
|
37200
37458
|
const files = candidateManifest(readCandidateFiles(root, candidateId, paths));
|
|
@@ -37437,8 +37695,8 @@ function createCadreServer() {
|
|
|
37437
37695
|
const stagedCandidate = stagedTrackCandidates(root, validation).find((candidate) => candidate.trackId === trackId);
|
|
37438
37696
|
if (!track) {
|
|
37439
37697
|
const canonicalPaths = [
|
|
37440
|
-
|
|
37441
|
-
|
|
37698
|
+
join21(root, ".cadre", "tracks", trackId),
|
|
37699
|
+
join21(root, ".cadre", "archive", trackId)
|
|
37442
37700
|
];
|
|
37443
37701
|
if (canonicalPaths.some((path) => existsSync20(path))) {
|
|
37444
37702
|
throw new CadreError(
|
|
@@ -37463,7 +37721,7 @@ function createCadreServer() {
|
|
|
37463
37721
|
kind: "staged_track_candidate",
|
|
37464
37722
|
valid: validation.errors.length === 0 && stagedCandidate.valid,
|
|
37465
37723
|
derivedStateCurrent: validation.warnings.length === 0,
|
|
37466
|
-
upgradeRequired: validation.project?.runtimeVersion
|
|
37724
|
+
upgradeRequired: !isCompatibleRuntimeVersion(validation.project?.runtimeVersion) || validation.project?.templateSetVersion !== TEMPLATE_SET_VERSION,
|
|
37467
37725
|
targetRuntimeVersion: CADRE_RUNTIME_VERSION,
|
|
37468
37726
|
targetTemplateSetVersion: TEMPLATE_SET_VERSION,
|
|
37469
37727
|
trackId,
|
|
@@ -37479,7 +37737,7 @@ function createCadreServer() {
|
|
|
37479
37737
|
kind: "canonical_track",
|
|
37480
37738
|
valid: validation.errors.length === 0,
|
|
37481
37739
|
derivedStateCurrent: validation.warnings.length === 0,
|
|
37482
|
-
upgradeRequired: validation.project?.runtimeVersion
|
|
37740
|
+
upgradeRequired: !isCompatibleRuntimeVersion(validation.project?.runtimeVersion) || validation.project?.templateSetVersion !== TEMPLATE_SET_VERSION,
|
|
37483
37741
|
targetRuntimeVersion: CADRE_RUNTIME_VERSION,
|
|
37484
37742
|
targetTemplateSetVersion: TEMPLATE_SET_VERSION,
|
|
37485
37743
|
track: trackSummary(track),
|
|
@@ -37501,7 +37759,7 @@ function createCadreServer() {
|
|
|
37501
37759
|
if (view === "track") {
|
|
37502
37760
|
return result({ ...focused, nextStep }, `${trackId}: ${track.status}; checkpoint=${track.checkpoint ?? "none"}.`);
|
|
37503
37761
|
}
|
|
37504
|
-
const planPath =
|
|
37762
|
+
const planPath = join21(root, ".cadre", track.location, "plan.md");
|
|
37505
37763
|
const graphErrors = [];
|
|
37506
37764
|
const graph = validation.plans.get(trackId) ?? parsePlan(planPath, graphErrors);
|
|
37507
37765
|
validatePlanGraph(planPath, graph, track.status, graphErrors);
|
|
@@ -37509,7 +37767,7 @@ function createCadreServer() {
|
|
|
37509
37767
|
const executionJournal = activeExecutionId ? executionStatus(root, trackId, activeExecutionId).journal : null;
|
|
37510
37768
|
const execution = executionJournal ? compactExecutionStatus(executionJournal) : null;
|
|
37511
37769
|
const worktreeStatus = managedWorktreeStatus(root);
|
|
37512
|
-
const trackWorktreeSegment = `${
|
|
37770
|
+
const trackWorktreeSegment = `${join21(".cadre", ".worktrees", trackId)}/`;
|
|
37513
37771
|
return result({
|
|
37514
37772
|
...focused,
|
|
37515
37773
|
nextStep: graphErrors.length ? deriveNextStep(root, validation.states.get(trackId), { errors: graphErrors }) : nextStep,
|
|
@@ -37657,7 +37915,13 @@ function createCadreServer() {
|
|
|
37657
37915
|
}
|
|
37658
37916
|
const { mode: _mode, ...input } = request;
|
|
37659
37917
|
const preview = previewCandidateApply(input);
|
|
37660
|
-
return proposalResult("candidate_apply", input, {
|
|
37918
|
+
return proposalResult("candidate_apply", input, {
|
|
37919
|
+
operationId: preview.operationId,
|
|
37920
|
+
files: preview.manifest,
|
|
37921
|
+
stateChanges: preview.stateChanges,
|
|
37922
|
+
digest: preview.digest,
|
|
37923
|
+
validation: preview.validation
|
|
37924
|
+
});
|
|
37661
37925
|
} catch (error51) {
|
|
37662
37926
|
return failure(error51);
|
|
37663
37927
|
}
|
|
@@ -37671,8 +37935,8 @@ function createCadreServer() {
|
|
|
37671
37935
|
}, async ({ projectRoot, trackId }) => {
|
|
37672
37936
|
try {
|
|
37673
37937
|
const root = safeProjectRoot(projectRoot);
|
|
37674
|
-
const statePath =
|
|
37675
|
-
const planPath =
|
|
37938
|
+
const statePath = join21(root, ".cadre", "tracks", trackId, "state.json");
|
|
37939
|
+
const planPath = join21(root, ".cadre", "tracks", trackId, "plan.md");
|
|
37676
37940
|
const state = JSON.parse(readFileSync10(statePath, "utf8"));
|
|
37677
37941
|
const errors = [];
|
|
37678
37942
|
const graph = parsePlan(planPath, errors);
|
|
@@ -37705,14 +37969,15 @@ function createCadreServer() {
|
|
|
37705
37969
|
const proposal = proposalTokens.resolve("review_complete", adaptive.proposalToken);
|
|
37706
37970
|
requireCurrentProject2(proposal.input.projectRoot);
|
|
37707
37971
|
const applied = applyReviewComplete(proposal.input, proposal.digest);
|
|
37972
|
+
const committed = "receipt" in applied && applied.receipt.status === "committed";
|
|
37708
37973
|
return result({
|
|
37709
37974
|
commandStatus: "applied",
|
|
37710
37975
|
trackId: proposal.input.trackId,
|
|
37711
37976
|
status: applied.state.status,
|
|
37712
37977
|
checkpoint: applied.state.checkpoint,
|
|
37713
37978
|
digest: proposal.digest,
|
|
37714
|
-
changedPaths: [applied.statePath, applied.tracksPath],
|
|
37715
|
-
changedCount: 2,
|
|
37979
|
+
changedPaths: committed ? [] : [applied.statePath, applied.tracksPath],
|
|
37980
|
+
changedCount: committed ? 0 : 2,
|
|
37716
37981
|
valid: applied.valid,
|
|
37717
37982
|
derivedStateCurrent: applied.derivedStateCurrent,
|
|
37718
37983
|
..."receipt" in applied ? { receipt: applied.receipt } : {}
|
|
@@ -37770,6 +38035,7 @@ function createCadreServer() {
|
|
|
37770
38035
|
);
|
|
37771
38036
|
requireCurrentProject2(proposal.input.projectRoot);
|
|
37772
38037
|
const applied = applyArchiveBatchCandidate(proposal.input, proposal.digest);
|
|
38038
|
+
const committed = "receipt" in applied && applied.receipt.status === "committed";
|
|
37773
38039
|
return result({
|
|
37774
38040
|
commandStatus: "applied",
|
|
37775
38041
|
batchId: proposal.input.batchId,
|
|
@@ -37779,8 +38045,8 @@ function createCadreServer() {
|
|
|
37779
38045
|
checkpoint: applied.operation.checkpoint,
|
|
37780
38046
|
digest: proposal.digest,
|
|
37781
38047
|
moves: applied.moves.map(({ trackId, targetPath }) => ({ trackId, targetPath })),
|
|
37782
|
-
changedPaths: [...applied.writes.map((write2) => write2.path), applied.tracksPath],
|
|
37783
|
-
changedCount: applied.writes.length + 1,
|
|
38048
|
+
changedPaths: committed ? [] : [...applied.writes.map((write2) => write2.path), applied.tracksPath],
|
|
38049
|
+
changedCount: committed ? 0 : applied.writes.length + 1,
|
|
37784
38050
|
valid: applied.valid,
|
|
37785
38051
|
derivedStateCurrent: applied.derivedStateCurrent
|
|
37786
38052
|
});
|
|
@@ -37795,6 +38061,7 @@ function createCadreServer() {
|
|
|
37795
38061
|
operationPath: preview.operationPath,
|
|
37796
38062
|
checkpoint: preview.operation.checkpoint,
|
|
37797
38063
|
resuming: preview.resuming,
|
|
38064
|
+
stateChanges: preview.stateChanges,
|
|
37798
38065
|
moves: preview.moves.map(({ trackId, sourcePath, targetPath, needsMove }) => ({
|
|
37799
38066
|
trackId,
|
|
37800
38067
|
sourcePath,
|
|
@@ -37999,6 +38266,7 @@ function createCadreServer() {
|
|
|
37999
38266
|
const preview = previewExecutionFinish(derived);
|
|
38000
38267
|
const applied = applyExecutionFinish(derived, preview.digest, preview);
|
|
38001
38268
|
const validation = validateProject(input.projectRoot);
|
|
38269
|
+
const committed = applied.receipt?.status === "committed";
|
|
38002
38270
|
return result({
|
|
38003
38271
|
commandStatus: "applied",
|
|
38004
38272
|
executionId: derived.executionId,
|
|
@@ -38007,10 +38275,10 @@ function createCadreServer() {
|
|
|
38007
38275
|
headCommit: applied.journal.headCommit,
|
|
38008
38276
|
...applied.receipt ? { receipt: applied.receipt } : {},
|
|
38009
38277
|
digest: preview.digest,
|
|
38010
|
-
changedPaths: [applied.journalPath, applied.statePath, applied.planPath, applied.tracksPath],
|
|
38011
|
-
changedCount: 4,
|
|
38278
|
+
changedPaths: committed ? [] : [applied.journalPath, applied.statePath, applied.planPath, applied.tracksPath],
|
|
38279
|
+
changedCount: committed ? 0 : 4,
|
|
38012
38280
|
nextStep: deriveNextStep(safeProjectRoot(input.projectRoot), validation.states.get(input.trackId), {
|
|
38013
|
-
errors: validation.errors,
|
|
38281
|
+
errors: validation.errors.filter((error51) => !(applied.receipt?.status === "commit_pending" && error51.endsWith(`commit_pending: no reachable commit contains operation ${applied.receipt.operationId}`))),
|
|
38014
38282
|
staleMemory: validation.staleMemory.some((finding) => [
|
|
38015
38283
|
input.trackId,
|
|
38016
38284
|
...validation.states.get(input.trackId)?.dependencies ?? []
|