@mstar-harness/cli 3.9.4 → 3.10.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.
Files changed (2) hide show
  1. package/dist/mstar-harness.js +1675 -208
  2. package/package.json +1 -1
@@ -2435,14 +2435,14 @@ import { randomUUID } from "node:crypto";
2435
2435
  import { basename, dirname, join, resolve } from "node:path";
2436
2436
  import { readFileSync as readFileSync2, statSync } from "node:fs";
2437
2437
  import { dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2 } from "node:path";
2438
- import { existsSync as existsSync8, mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as readFileSync8, realpathSync as realpathSync3, statSync as statSync3, writeFileSync as writeFileSync3 } from "node:fs";
2438
+ import { existsSync as existsSync8, mkdirSync as mkdirSync5, readdirSync as readdirSync6, readFileSync as readFileSync8, realpathSync as realpathSync3, statSync as statSync3, writeFileSync as writeFileSync3 } from "node:fs";
2439
2439
  import { execFileSync } from "node:child_process";
2440
- import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute6, join as join10, relative as relative2, resolve as resolve8 } from "node:path";
2441
- import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync7, readdirSync as readdirSync4 } from "node:fs";
2442
- import { basename as basename4, join as join9, resolve as resolve7 } from "node:path";
2443
- import { existsSync as existsSync6, readdirSync as readdirSync3, readFileSync as readFileSync6 } from "node:fs";
2444
- import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync2, realpathSync as realpathSync2 } from "node:fs";
2445
- import { dirname as dirname5, join as join7, resolve as resolve6, sep as sep2 } from "node:path";
2440
+ import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute6, join as join10, relative as relative2, resolve as resolve9 } from "node:path";
2441
+ import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync7, readdirSync as readdirSync5 } from "node:fs";
2442
+ import { basename as basename4, join as join9, resolve as resolve8 } from "node:path";
2443
+ import { existsSync as existsSync6, readdirSync as readdirSync4, readFileSync as readFileSync6 } from "node:fs";
2444
+ import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync3, realpathSync as realpathSync2 } from "node:fs";
2445
+ import { dirname as dirname5, join as join7, resolve as resolve7, sep as sep2 } from "node:path";
2446
2446
  import { mkdirSync as mkdirSync2, rmdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
2447
2447
  import { dirname as dirname3, isAbsolute as isAbsolute2, join as join3, resolve as resolve3 } from "node:path";
2448
2448
  import { setTimeout as sleep } from "node:timers/promises";
@@ -2453,28 +2453,28 @@ import { existsSync as existsSync2, readFileSync as readFileSync3, realpathSync
2453
2453
  import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join4, resolve as resolve4 } from "node:path";
2454
2454
  import { existsSync as existsSync3, readdirSync, unlinkSync as unlinkSync3 } from "node:fs";
2455
2455
  import { basename as basename3, isAbsolute as isAbsolute4, join as join5, resolve as resolve5, sep } from "node:path";
2456
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4 } from "node:fs";
2457
- import { isAbsolute as isAbsolute5, join as join6 } from "node:path";
2456
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4, readdirSync as readdirSync2, rmdirSync as rmdirSync2 } from "node:fs";
2457
+ import { isAbsolute as isAbsolute5, join as join6, resolve as resolve6 } from "node:path";
2458
2458
  import { execFileSync as execFileSync2 } from "node:child_process";
2459
2459
  import { existsSync as existsSync9, realpathSync as realpathSync4 } from "node:fs";
2460
- import { isAbsolute as isAbsolute7, join as join11, resolve as resolve9 } from "node:path";
2460
+ import { isAbsolute as isAbsolute7, join as join11, resolve as resolve10 } from "node:path";
2461
2461
  import { existsSync as existsSync10 } from "node:fs";
2462
2462
  import { join as join12, dirname as dirname8 } from "node:path";
2463
2463
  import { execFileSync as execFileSync3, spawn } from "node:child_process";
2464
- import { mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as readFileSync9, realpathSync as realpathSync5, statSync as statSync4, writeFileSync as writeFileSync4 } from "node:fs";
2464
+ import { mkdirSync as mkdirSync6, readdirSync as readdirSync7, readFileSync as readFileSync9, realpathSync as realpathSync5, statSync as statSync4, writeFileSync as writeFileSync4 } from "node:fs";
2465
2465
  import { constants as osConstants } from "node:os";
2466
- import { basename as basename7, dirname as dirname9, isAbsolute as isAbsolute8, join as join13, relative as relative3, resolve as resolve10 } from "node:path";
2466
+ import { basename as basename7, dirname as dirname9, isAbsolute as isAbsolute8, join as join13, relative as relative3, resolve as resolve11 } from "node:path";
2467
2467
  import { execFileSync as execFileSync4 } from "node:child_process";
2468
- import { existsSync as existsSync12, mkdirSync as mkdirSync8, readdirSync as readdirSync8, readFileSync as readFileSync11, rmdirSync as rmdirSync2, writeFileSync as writeFileSync6 } from "node:fs";
2469
- import { basename as basename10, join as join16, resolve as resolve13, sep as sep4 } from "node:path";
2470
- import { existsSync as existsSync13, readdirSync as readdirSync9, readFileSync as readFileSync12 } from "node:fs";
2471
- import { basename as basename11, isAbsolute as isAbsolute10, join as join17, relative as relative6, resolve as resolve14, sep as sep5 } from "node:path";
2468
+ import { existsSync as existsSync12, mkdirSync as mkdirSync8, readdirSync as readdirSync9, readFileSync as readFileSync11, rmdirSync as rmdirSync3, writeFileSync as writeFileSync6 } from "node:fs";
2469
+ import { basename as basename10, join as join16, resolve as resolve14, sep as sep4 } from "node:path";
2470
+ import { existsSync as existsSync13, readdirSync as readdirSync10, readFileSync as readFileSync12 } from "node:fs";
2471
+ import { basename as basename11, isAbsolute as isAbsolute10, join as join17, relative as relative6, resolve as resolve15, sep as sep5 } from "node:path";
2472
2472
  import { existsSync as existsSync14 } from "node:fs";
2473
2473
  import { join as join18 } from "node:path";
2474
- import { readdirSync as readdirSync10 } from "node:fs";
2474
+ import { readdirSync as readdirSync11 } from "node:fs";
2475
2475
  import { isAbsolute as isAbsolute11, join as join19 } from "node:path";
2476
2476
  import { existsSync as existsSync15, mkdirSync as mkdirSync9, readFileSync as readFileSync13, statSync as statSync6, unlinkSync as unlinkSync4, writeFileSync as writeFileSync7 } from "node:fs";
2477
- import { basename as basename12, dirname as dirname12, isAbsolute as isAbsolute12, join as join20, resolve as resolve15, sep as sep6 } from "node:path";
2477
+ import { basename as basename12, dirname as dirname12, isAbsolute as isAbsolute12, join as join20, resolve as resolve16, sep as sep6 } from "node:path";
2478
2478
  var SEVERITY_ORDER = ["critical", "high", "medium", "low", "nit"];
2479
2479
  function readJson(filePath) {
2480
2480
  if (!existsSync(filePath))
@@ -3295,6 +3295,7 @@ var REQUIRED_FIELDS = [
3295
3295
  var REVIEW_SEAT_ROLES = ["qc-specialist", "qc-specialist-2", "qc-specialist-3", "code-reviewer", "qa-engineer"];
3296
3296
  var BUDGET_LABELS = ["Budget (review / QC seats)", "Budget"];
3297
3297
  var RETURN_SHAPE_LABELS = ["Return shape (review / QC seats)", "Return shape"];
3298
+ var TASK_BUDGET_LABELS = ["Task budget (implement / ops rounds)", "Task budget"];
3298
3299
  function violation2(severity, code, message, fix) {
3299
3300
  return { ok: false, severity, code, message, fix };
3300
3301
  }
@@ -3322,6 +3323,8 @@ function parseAssignmentFields(assignmentText) {
3322
3323
  fields.budget = value;
3323
3324
  else if (RETURN_SHAPE_LABELS.includes(label))
3324
3325
  fields.returnShape = value;
3326
+ else if (TASK_BUDGET_LABELS.includes(label))
3327
+ fields.taskBudget = value;
3325
3328
  }
3326
3329
  return fields;
3327
3330
  }
@@ -3416,6 +3419,12 @@ function validateAssignmentFields(assignmentText, opts = {}) {
3416
3419
  violations.push(violation2("high", field.code, `${subject} must declare a round ${field.label} \u2014 ${missing}`, field.fix));
3417
3420
  }
3418
3421
  }
3422
+ if (!reviewSeat && !auditRound) {
3423
+ const missing = describeAbsence(fields.taskBudget);
3424
+ if (missing !== undefined) {
3425
+ violations.push(violation2("high", "assignment.field.task-budget-missing", `implement/ops round "${role}" must declare a Task budget \u2014 ${missing}`, `add "**Task budget (implement / ops rounds)**: <one implementer round closing the task's declared Files list and verification gates> \u2014 capacity contract spec \u00a7 A1/A2"`));
3426
+ }
3427
+ }
3419
3428
  if (writable) {
3420
3429
  const workingPresent = fields.workingBranch !== undefined && fields.workingBranch !== "";
3421
3430
  const policyPresent = fields.branchPolicy !== undefined && fields.branchPolicy !== "";
@@ -3492,6 +3501,8 @@ var WORKFLOW_SNAPSHOT_FILE = "snapshot.json";
3492
3501
  var WORKFLOW_LIFECYCLE_STATUSES = ["running", "paused", "completed", "failed", "stopped"];
3493
3502
  var WORKFLOW_TERMINAL_STATUSES = ["completed", "failed", "stopped"];
3494
3503
  var WORKFLOW_LIFECYCLE_TYPES = ["plan", "iteration"];
3504
+ var WORKFLOW_DELIVERY_KINDS = ["development", "verification/report-only"];
3505
+ var WORKFLOW_COMPOUND_OUTCOMES = ["created", "updated", "skipped"];
3495
3506
  function stableJson(value) {
3496
3507
  if (Array.isArray(value))
3497
3508
  return `[${value.map(stableJson).join(",")}]`;
@@ -3516,6 +3527,61 @@ function validateWorktreePathValue(violations, value, field) {
3516
3527
  violations.push(violation3("high", "workflow.snapshot.invalid-integration-worktree-path", `${field} must be a non-empty absolute path \u2014 got ${JSON.stringify(value)}`, "record the absolute integration checkout path (integration_worktree_path)"));
3517
3528
  }
3518
3529
  }
3530
+ function deliveryEvidenceViolations(value, what) {
3531
+ const violations = [];
3532
+ const invalid2 = (message) => {
3533
+ violations.push(violation3("medium", "workflow.snapshot.invalid-delivery-evidence", `${what}: ${message}`));
3534
+ };
3535
+ if (!isPlainObject2(value)) {
3536
+ invalid2("must be an object");
3537
+ return violations;
3538
+ }
3539
+ const members = ["compound", "pr", "merge", "completion"];
3540
+ const unknownMembers = Object.keys(value).filter((key) => !members.includes(key));
3541
+ if (unknownMembers.length > 0)
3542
+ invalid2(`unknown member(s) ${unknownMembers.join(", ")} \u2014 expected ${members.join(" | ")}`);
3543
+ const compound = value.compound;
3544
+ if (compound !== undefined) {
3545
+ if (!isPlainObject2(compound))
3546
+ invalid2("compound must be an object");
3547
+ else {
3548
+ const unknown = Object.keys(compound).filter((key) => key !== "outcome" && key !== "reason");
3549
+ if (unknown.length > 0)
3550
+ invalid2(`compound has unknown key(s) ${unknown.join(", ")}`);
3551
+ if (typeof compound.outcome !== "string" || !WORKFLOW_COMPOUND_OUTCOMES.includes(compound.outcome)) {
3552
+ invalid2(`compound.outcome must be one of ${WORKFLOW_COMPOUND_OUTCOMES.join(" | ")} \u2014 got ${JSON.stringify(compound.outcome)}`);
3553
+ } else if (compound.outcome === "skipped" && (typeof compound.reason !== "string" || compound.reason.trim() === "")) {
3554
+ invalid2("compound reason is required when the disposition outcome is 'skipped' (contract \u00a74c)");
3555
+ } else if (compound.reason !== undefined && (typeof compound.reason !== "string" || compound.reason.trim() === "")) {
3556
+ invalid2("compound.reason must be a non-empty string when given");
3557
+ }
3558
+ }
3559
+ }
3560
+ const stringMembers = {
3561
+ pr: ["repo", "head", "target"],
3562
+ merge: ["provider", "evidence"],
3563
+ completion: ["policy", "evidence"]
3564
+ };
3565
+ for (const member of ["pr", "merge", "completion"]) {
3566
+ const block = value[member];
3567
+ if (block === undefined)
3568
+ continue;
3569
+ if (!isPlainObject2(block)) {
3570
+ invalid2(`${member} must be an object`);
3571
+ continue;
3572
+ }
3573
+ const fields = stringMembers[member];
3574
+ const unknown = Object.keys(block).filter((key) => !fields.includes(key));
3575
+ if (unknown.length > 0)
3576
+ invalid2(`${member} has unknown key(s) ${unknown.join(", ")}`);
3577
+ for (const field of fields) {
3578
+ if (typeof block[field] !== "string" || block[field].trim() === "") {
3579
+ invalid2(`${member}.${field} must be a non-empty string`);
3580
+ }
3581
+ }
3582
+ }
3583
+ return violations;
3584
+ }
3519
3585
  function validateWorkflowSnapshot(doc) {
3520
3586
  const violations = [];
3521
3587
  if (!isPlainObject2(doc)) {
@@ -3581,7 +3647,7 @@ function validateWorkflowSnapshot(doc) {
3581
3647
  if (!isPlainObject2(doc.branch)) {
3582
3648
  violations.push(violation3("medium", "workflow.snapshot.invalid-branch", "branch must be an object"));
3583
3649
  } else {
3584
- for (const key of ["base", "integration", "target"]) {
3650
+ for (const key of ["base", "source", "integration", "target"]) {
3585
3651
  if (doc.branch[key] !== undefined && (typeof doc.branch[key] !== "string" || doc.branch[key].trim() === "")) {
3586
3652
  violations.push(violation3("medium", "workflow.snapshot.invalid-branch", `branch.${key} must be a non-empty string`));
3587
3653
  }
@@ -3607,6 +3673,20 @@ function validateWorkflowSnapshot(doc) {
3607
3673
  if (doc.compass_ref !== undefined) {
3608
3674
  validateNonEmptyString2(violations, doc.compass_ref, "compass_ref", "workflow.snapshot.missing-compass-ref", "workflow.snapshot.invalid-compass-ref");
3609
3675
  }
3676
+ if (doc.delivery_kind !== undefined) {
3677
+ if (typeof doc.delivery_kind !== "string" || !WORKFLOW_DELIVERY_KINDS.includes(doc.delivery_kind)) {
3678
+ violations.push(violation3("medium", "workflow.snapshot.invalid-delivery-kind", `delivery_kind must be one of ${WORKFLOW_DELIVERY_KINDS.join(" | ")} \u2014 got ${JSON.stringify(doc.delivery_kind)}`));
3679
+ }
3680
+ }
3681
+ if (doc.project !== undefined) {
3682
+ validateNonEmptyString2(violations, doc.project, "project", "workflow.snapshot.missing-project", "workflow.snapshot.invalid-project");
3683
+ }
3684
+ if (doc.completion_policy !== undefined) {
3685
+ validateNonEmptyString2(violations, doc.completion_policy, "completion_policy", "workflow.snapshot.missing-completion-policy", "workflow.snapshot.invalid-completion-policy");
3686
+ }
3687
+ if (doc.delivery !== undefined) {
3688
+ violations.push(...deliveryEvidenceViolations(doc.delivery, "delivery"));
3689
+ }
3610
3690
  const terminal = typeof doc.status === "string" && WORKFLOW_TERMINAL_STATUSES.includes(doc.status);
3611
3691
  if (terminal) {
3612
3692
  if (doc.ended_at === undefined) {
@@ -3737,6 +3817,74 @@ async function validateAndPutWorkflowSnapshot(store, snapshot, snapshotPath) {
3737
3817
  function isTerminalSnapshot(doc) {
3738
3818
  return WORKFLOW_TERMINAL_STATUSES.includes(doc.status);
3739
3819
  }
3820
+ function nonEmptyString(value) {
3821
+ return typeof value === "string" && value.trim() !== "";
3822
+ }
3823
+ function assertDeliveryRegistrationCoherence(kind, evidence, what) {
3824
+ if (kind === "development" && (!nonEmptyString(evidence.branchSource) || !nonEmptyString(evidence.branchTarget))) {
3825
+ throw new Error(`${what}: a development workflow requires its delivery source and target branches (--branch-source/--branch-target) \u2014 missing branch fields are incomplete registration, not an exempt workflow (contract \u00a71/\u00a74a)`);
3826
+ }
3827
+ if (kind === "verification/report-only" && !nonEmptyString(evidence.completionPolicy)) {
3828
+ throw new Error(`${what}: a verification/report-only workflow requires the completion policy (--completion-policy) naming the evidence that completes it (contract \u00a71)`);
3829
+ }
3830
+ for (const [field, value] of Object.entries({ branchSource: evidence.branchSource, branchTarget: evidence.branchTarget, completionPolicy: evidence.completionPolicy })) {
3831
+ if (value !== undefined && !nonEmptyString(value)) {
3832
+ throw new Error(`${what}: ${field} must be a non-empty string when given`);
3833
+ }
3834
+ }
3835
+ }
3836
+ function consultDeliveryEvidence(snapshot) {
3837
+ if (snapshot.type !== "plan")
3838
+ return [];
3839
+ const workflowId = nonEmptyString(snapshot.id) ? snapshot.id : "<unknown>";
3840
+ const kind = snapshot.delivery_kind;
3841
+ if (typeof kind !== "string" || !WORKFLOW_DELIVERY_KINDS.includes(kind)) {
3842
+ return [
3843
+ violation3("high", "PHASE6_DELIVERY_KIND_UNREGISTERED", `Workflow '${workflowId}' is type 'plan' but carries no registered delivery_kind \u2014 a plan workflow declares its delivery kind at registration (mstar-artifacts/references/plan-workflow-lifecycle-contract.md \u00a71), so this snapshot's delivery evidence cannot be consulted`, "Delivery evidence is declared at registration, before execution. A still-ACTIVE kind-less workflow is repaired by the authorized one-time declaration 'mstar workflow evidence --workflow <id> --declare-kind <development|verification/report-only> [--branch-source <b> --branch-target <b> | --completion-policy <text>] [--session <envelope>]' (declared once, never re-declared); a TERMINAL legacy snapshot cannot be backfilled \u2014 'mstar workflow register' is create-only and its registration identity can never match a terminal snapshot \u2014 so repair requires an explicit owner snapshot amendment recording the declared kind (the known affected population \u2014 audit-promotion's grandfathered type: plan snapshots \u2014 is disclosed as a residual by plan QC), then re-run the close / 'mstar iteration gate --phase 6 --workflow <id>'")
3844
+ ];
3845
+ }
3846
+ const branch = isPlainObject2(snapshot.branch) ? snapshot.branch : undefined;
3847
+ const delivery = isPlainObject2(snapshot.delivery) ? snapshot.delivery : undefined;
3848
+ const missing = [];
3849
+ if (kind === "development") {
3850
+ if (!nonEmptyString(branch?.source))
3851
+ missing.push("branch.source");
3852
+ if (!nonEmptyString(branch?.target))
3853
+ missing.push("branch.target");
3854
+ if (!isPlainObject2(delivery?.compound))
3855
+ missing.push("delivery.compound (compound disposition, \u00a74c)");
3856
+ const pr = isPlainObject2(delivery?.pr) ? delivery.pr : undefined;
3857
+ if (pr === undefined) {
3858
+ missing.push("delivery.pr (PR repo/head/target identity, \u00a74d)");
3859
+ } else {
3860
+ if (nonEmptyString(branch?.source) && pr.head !== branch.source) {
3861
+ missing.push(`delivery.pr.head (recorded ${JSON.stringify(pr.head)}, registered branch.source ${JSON.stringify(branch.source)} \u2014 \u00a74d: the recorded PR identity must be the registered delivery)`);
3862
+ }
3863
+ if (nonEmptyString(branch?.target) && pr.target !== branch.target) {
3864
+ missing.push(`delivery.pr.target (recorded ${JSON.stringify(pr.target)}, registered branch.target ${JSON.stringify(branch.target)} \u2014 \u00a74d: the recorded PR identity must be the registered delivery)`);
3865
+ }
3866
+ }
3867
+ if (!isPlainObject2(delivery?.merge))
3868
+ missing.push("delivery.merge (PM-recorded verified-merge evidence, \u00a74f)");
3869
+ } else {
3870
+ const policy = snapshot.completion_policy;
3871
+ if (!nonEmptyString(policy))
3872
+ missing.push("completion_policy (the recorded alternative completion policy, \u00a71)");
3873
+ const completion = isPlainObject2(delivery?.completion) ? delivery.completion : undefined;
3874
+ if (completion === undefined) {
3875
+ missing.push("delivery.completion (the fulfilment record of the registered policy, \u00a71)");
3876
+ } else if (nonEmptyString(policy) && completion.policy !== policy) {
3877
+ missing.push(`delivery.completion.policy (\u00a71 \u2014 recorded ${JSON.stringify(completion.policy)}, registered completion_policy ${JSON.stringify(policy)})`);
3878
+ }
3879
+ }
3880
+ if (missing.length === 0)
3881
+ return [];
3882
+ const incomplete = (fix) => violation3("high", "PHASE6_DELIVERY_EVIDENCE_INCOMPLETE", `Workflow '${workflowId}' declares delivery_kind '${kind}' but its delivery evidence is incomplete \u2014 missing: ${missing.join(", ")} (mstar-artifacts/references/plan-workflow-lifecycle-contract.md \u00a73 lifecycle stages + \u00a74c/\u00a74d/\u00a74f)`, fix);
3883
+ const record = `Record the missing evidence with 'mstar workflow evidence --workflow ${workflowId} --file <payload.json>' (add --session <coordinator envelope> for a coordinated workflow)`;
3884
+ return [
3885
+ kind === "development" ? incomplete(`${record}: the compound disposition (\u00a74c, before the PR head is finalized), the PR identity (\u00a74d, at submission) and the verified-merge record (\u00a74f, the PM's own check \u2014 the engine never verifies the remote merge). Done rows alone are not delivery evidence`) : incomplete(`${record}: the fulfilment record must name the registered completion policy and its evidence (\u00a71)`)
3886
+ ];
3887
+ }
3740
3888
  function isCloseTimestamp(value) {
3741
3889
  if (typeof value !== "string")
3742
3890
  return false;
@@ -3769,11 +3917,275 @@ async function closeWorkflow(workflowId, dir, opts) {
3769
3917
  if (snapshot.plans.some((row) => row.status !== "Done")) {
3770
3918
  throw new Error("refusing to close workflow: every plan row must be Done");
3771
3919
  }
3920
+ const deliveryViolations = consultDeliveryEvidence(snapshot);
3921
+ if (deliveryViolations.length > 0) {
3922
+ const detail = deliveryViolations.map((v) => `${v.code}: ${v.message}${v.fix !== undefined ? ` (fix: ${v.fix})` : ""}`).join("; ");
3923
+ throw new Error(`refusing to close workflow: ${detail}`);
3924
+ }
3772
3925
  const completed = { ...snapshot, status: "completed", ended_at: opts.endedAt, updated_at: opts.endedAt };
3773
3926
  await validateAndPutWorkflowSnapshot(store, completed, snapshotPath);
3774
3927
  return completed;
3775
3928
  });
3776
3929
  }
3930
+ async function recordWorkflowDelivery(workflowId, dir, opts) {
3931
+ const evidence = opts.evidence;
3932
+ if (!isPlainObject2(evidence)) {
3933
+ throw new Error("recordWorkflowDelivery: options.evidence must be an object naming at least one delivery-evidence member");
3934
+ }
3935
+ const members = Object.keys(evidence);
3936
+ if (members.length === 0) {
3937
+ throw new Error("recordWorkflowDelivery: options.evidence must name at least one of compound | pr | merge | completion");
3938
+ }
3939
+ const nonObject = members.filter((member) => !isPlainObject2(evidence[member]));
3940
+ if (nonObject.length > 0) {
3941
+ throw new Error(`refusing to record delivery evidence: member(s) ${nonObject.join(", ")} must be objects \u2014 omit a member to leave it untouched`);
3942
+ }
3943
+ const shapeViolations = deliveryEvidenceViolations(evidence, "evidence");
3944
+ if (shapeViolations.length > 0) {
3945
+ throw new Error(`refusing to record invalid delivery evidence: ${shapeViolations.map((v) => v.message).join("; ")}`);
3946
+ }
3947
+ const at = opts.at ?? new Date().toISOString();
3948
+ if (!isCloseTimestamp(at)) {
3949
+ throw new Error("recordWorkflowDelivery: options.at must be a valid YYYY-MM-DD date or RFC3339 timestamp");
3950
+ }
3951
+ const snapshotPath = join6(dir, WORKFLOW_SNAPSHOT_FILE);
3952
+ const store = getArtifactStore();
3953
+ const ref = { kind: "snapshot", key: workflowId };
3954
+ assertFsStorePath(store, ref, snapshotPath);
3955
+ mkdirSync3(dir, { recursive: true });
3956
+ return withStatusWriteLock(snapshotPath, async () => {
3957
+ const doc = await store.get(ref);
3958
+ if (doc === undefined)
3959
+ throw new Error(`workflow snapshot not found: ${snapshotPath}`);
3960
+ const { snapshot } = normalizeWorkflowSnapshot(doc, snapshotPath);
3961
+ if (snapshot.id !== workflowId) {
3962
+ throw new Error(`workflow snapshot identity mismatch: expected ${workflowId}, got ${snapshot.id}`);
3963
+ }
3964
+ if (isTerminalSnapshot(snapshot)) {
3965
+ throw new Error(`refusing to record delivery evidence for workflow ${JSON.stringify(workflowId)}: the lifecycle is terminal (${snapshot.status}) \u2014 delivery evidence is recorded before the close and a closed lifecycle is never amended`);
3966
+ }
3967
+ assertCoordinatedSnapshotWriter(doc, snapshotPath, opts.sessionPath, "delivery-evidence write");
3968
+ const kind = snapshot.delivery_kind;
3969
+ if (snapshot.type !== "plan" || kind !== "development" && kind !== "verification/report-only") {
3970
+ throw new Error(`refusing to record delivery evidence for workflow ${JSON.stringify(workflowId)}: only a type: plan lifecycle with a registered delivery_kind carries delivery evidence (got type ${JSON.stringify(snapshot.type)} / delivery_kind ${JSON.stringify(kind)}) \u2014 the kind is declared at registration and never inferred (\u00a71)`);
3971
+ }
3972
+ const allowed = kind === "development" ? ["compound", "pr", "merge"] : ["completion"];
3973
+ const unused = members.filter((member) => !allowed.includes(member));
3974
+ if (unused.length > 0) {
3975
+ throw new Error(`refusing to record delivery evidence for workflow ${JSON.stringify(workflowId)}: member(s) ${unused.join(", ")} do not belong to the declared delivery_kind '${kind}' (expected ${allowed.join(" | ")})`);
3976
+ }
3977
+ const stored = isPlainObject2(snapshot.delivery) ? snapshot.delivery : {};
3978
+ const recordedPr = isPlainObject2(stored.pr) ? stored.pr : undefined;
3979
+ const incomingPr = isPlainObject2(evidence.pr) ? evidence.pr : undefined;
3980
+ if (recordedPr !== undefined && incomingPr !== undefined && stableJson(recordedPr) !== stableJson(incomingPr)) {
3981
+ throw new Error(`refusing to rewrite the recorded PR identity of workflow ${JSON.stringify(workflowId)}: \u00a74d records it once at submission \u2014 recorded ${JSON.stringify(recordedPr)}, refused ${JSON.stringify(incomingPr)} (a different PR is a different delivery, not an evidence update)`);
3982
+ }
3983
+ const merged = { ...stored, ...evidence };
3984
+ if (stableJson(snapshot.delivery ?? null) === stableJson(merged)) {
3985
+ return { snapshot, written: false };
3986
+ }
3987
+ const next = { ...snapshot, delivery: merged, updated_at: at };
3988
+ await validateAndPutWorkflowSnapshot(store, next, snapshotPath);
3989
+ return { snapshot: next, written: true };
3990
+ });
3991
+ }
3992
+ async function declareWorkflowDeliveryKind(workflowId, dir, opts) {
3993
+ const kind = opts.deliveryKind;
3994
+ if (typeof kind !== "string" || !WORKFLOW_DELIVERY_KINDS.includes(kind)) {
3995
+ throw new Error(`declareWorkflowDeliveryKind: deliveryKind must be one of ${WORKFLOW_DELIVERY_KINDS.join(" | ")} \u2014 got ${JSON.stringify(kind)}`);
3996
+ }
3997
+ assertDeliveryRegistrationCoherence(kind, opts, "declareWorkflowDeliveryKind");
3998
+ const at = opts.at ?? new Date().toISOString();
3999
+ if (!isCloseTimestamp(at)) {
4000
+ throw new Error("declareWorkflowDeliveryKind: options.at must be a valid YYYY-MM-DD date or RFC3339 timestamp");
4001
+ }
4002
+ const snapshotPath = join6(dir, WORKFLOW_SNAPSHOT_FILE);
4003
+ const store = getArtifactStore();
4004
+ const ref = { kind: "snapshot", key: workflowId };
4005
+ assertFsStorePath(store, ref, snapshotPath);
4006
+ mkdirSync3(dir, { recursive: true });
4007
+ return withStatusWriteLock(snapshotPath, async () => {
4008
+ const doc = await store.get(ref);
4009
+ if (doc === undefined)
4010
+ throw new Error(`workflow snapshot not found: ${snapshotPath}`);
4011
+ const { snapshot } = normalizeWorkflowSnapshot(doc, snapshotPath);
4012
+ if (snapshot.id !== workflowId) {
4013
+ throw new Error(`workflow snapshot identity mismatch: expected ${workflowId}, got ${snapshot.id}`);
4014
+ }
4015
+ if (isTerminalSnapshot(snapshot)) {
4016
+ throw new Error(`refusing to declare a delivery kind for workflow ${JSON.stringify(workflowId)}: the lifecycle is terminal (${snapshot.status}) \u2014 a closed lifecycle is never amended (\u00a75); a terminal snapshot without a registered kind stays on the documented owner-amendment path`);
4017
+ }
4018
+ assertCoordinatedSnapshotWriter(doc, snapshotPath, opts.sessionPath, "delivery-kind declaration");
4019
+ if (snapshot.type !== "plan") {
4020
+ throw new Error(`refusing to declare a delivery kind for workflow ${JSON.stringify(workflowId)}: only a type: plan lifecycle declares one (got type ${JSON.stringify(snapshot.type)})`);
4021
+ }
4022
+ if (snapshot.delivery_kind !== undefined) {
4023
+ throw new Error(`refusing to declare a delivery kind for workflow ${JSON.stringify(workflowId)}: it already declares ${JSON.stringify(snapshot.delivery_kind)} \u2014 the kind is registration evidence, declared once and never re-inferred (\u00a71)`);
4024
+ }
4025
+ const branch = isPlainObject2(snapshot.branch) ? { ...snapshot.branch } : {};
4026
+ for (const [anchor, supplied] of [
4027
+ ["source", opts.branchSource],
4028
+ ["target", opts.branchTarget]
4029
+ ]) {
4030
+ if (supplied === undefined)
4031
+ continue;
4032
+ const registered = branch[anchor];
4033
+ if (registered !== undefined && registered !== supplied) {
4034
+ throw new Error(`refusing to declare a delivery kind for workflow ${JSON.stringify(workflowId)}: branch.${anchor} is already ${JSON.stringify(registered)} \u2014 the supplied ${JSON.stringify(supplied)} conflicts with the anchor the snapshot ` + `registers, and the registered delivery anchor is never overwritten (\u00a71)`);
4035
+ }
4036
+ branch[anchor] = supplied;
4037
+ }
4038
+ const next = { ...snapshot, delivery_kind: kind, updated_at: at };
4039
+ if (Object.keys(branch).length > 0)
4040
+ next.branch = branch;
4041
+ if (opts.completionPolicy !== undefined)
4042
+ next.completion_policy = opts.completionPolicy;
4043
+ await validateAndPutWorkflowSnapshot(store, next, snapshotPath);
4044
+ return next;
4045
+ });
4046
+ }
4047
+ function planWorkflowRegistrationIdentity(snapshot) {
4048
+ const coordinator = snapshot.coordination?.coordinator;
4049
+ return stableJson({
4050
+ type: snapshot.type,
4051
+ status: snapshot.status,
4052
+ delivery_kind: snapshot.delivery_kind ?? null,
4053
+ project: snapshot.project ?? null,
4054
+ completion_policy: snapshot.completion_policy ?? null,
4055
+ branch: snapshot.branch ?? null,
4056
+ plans: snapshot.plans,
4057
+ coordinator: coordinator ? { session_id: coordinator.session_id, session_file: coordinator.session_file } : null
4058
+ });
4059
+ }
4060
+ async function registerPlanWorkflow(workflowId, options) {
4061
+ if (typeof options.harnessDir !== "string" || options.harnessDir.trim() === "") {
4062
+ throw new Error("registerPlanWorkflow: options.harnessDir is required (must contain status.json + workflows/)");
4063
+ }
4064
+ assertSafePathComponent(workflowId, "workflow id");
4065
+ const { plan, deliveryKind } = options;
4066
+ if (!isPlainObject2(plan)) {
4067
+ throw new Error("registerPlanWorkflow: options.plan is required (the owned plan: id, title, file)");
4068
+ }
4069
+ for (const field of ["id", "title", "file"]) {
4070
+ if (typeof plan[field] !== "string" || plan[field].trim() === "") {
4071
+ throw new Error(`registerPlanWorkflow: options.plan.${field} must be a non-empty string`);
4072
+ }
4073
+ }
4074
+ if (typeof deliveryKind !== "string" || !WORKFLOW_DELIVERY_KINDS.includes(deliveryKind)) {
4075
+ throw new Error(`registerPlanWorkflow: options.deliveryKind must be one of ${WORKFLOW_DELIVERY_KINDS.join(" | ")} \u2014 got ${JSON.stringify(deliveryKind)}`);
4076
+ }
4077
+ assertDeliveryRegistrationCoherence(deliveryKind, options, "registerPlanWorkflow");
4078
+ for (const field of ["project", "branchSource", "branchTarget"]) {
4079
+ const value = options[field];
4080
+ if (value !== undefined && (typeof value !== "string" || value.trim() === "")) {
4081
+ throw new Error(`registerPlanWorkflow: options.${field} must be a non-empty string when given`);
4082
+ }
4083
+ }
4084
+ if (options.coordinator !== undefined) {
4085
+ const { coordinator } = options;
4086
+ if (typeof coordinator.session_id !== "string" || coordinator.session_id.trim() === "") {
4087
+ throw new Error("registerPlanWorkflow: options.coordinator.session_id must be a non-empty string");
4088
+ }
4089
+ if (typeof coordinator.session_file !== "string" || !isAbsolute5(coordinator.session_file)) {
4090
+ throw new Error("registerPlanWorkflow: options.coordinator.session_file must be an absolute path");
4091
+ }
4092
+ }
4093
+ const startedAt = options.startedAt ?? new Date().toISOString();
4094
+ if (!isCloseTimestamp(startedAt)) {
4095
+ throw new Error("registerPlanWorkflow: options.startedAt must be a valid YYYY-MM-DD date or RFC3339 timestamp");
4096
+ }
4097
+ const harnessDir = resolve6(options.harnessDir);
4098
+ const statusPath = join6(harnessDir, "status.json");
4099
+ const workflowDir = join6(harnessDir, "workflows", workflowId);
4100
+ const snapshotPath = join6(workflowDir, WORKFLOW_SNAPSHOT_FILE);
4101
+ const store = getArtifactStore();
4102
+ const planRow = { id: plan.id, title: plan.title, file: plan.file, status: "Todo" };
4103
+ const snapshot = {
4104
+ schema_version: 1,
4105
+ id: workflowId,
4106
+ type: "plan",
4107
+ status: "running",
4108
+ started_at: startedAt,
4109
+ updated_at: startedAt.slice(0, 10),
4110
+ plans: [planRow],
4111
+ delivery_kind: deliveryKind
4112
+ };
4113
+ if (options.project !== undefined)
4114
+ snapshot.project = options.project;
4115
+ if (options.completionPolicy !== undefined)
4116
+ snapshot.completion_policy = options.completionPolicy;
4117
+ if (options.branchSource !== undefined || options.branchTarget !== undefined) {
4118
+ snapshot.branch = {
4119
+ ...options.branchSource !== undefined ? { source: options.branchSource } : {},
4120
+ ...options.branchTarget !== undefined ? { target: options.branchTarget } : {}
4121
+ };
4122
+ }
4123
+ if (options.coordinator !== undefined) {
4124
+ snapshot.coordination = {
4125
+ coordinator: { session_id: options.coordinator.session_id, session_file: options.coordinator.session_file, bound_at: startedAt }
4126
+ };
4127
+ }
4128
+ const entry = {
4129
+ id: workflowId,
4130
+ type: "plan",
4131
+ started_at: snapshot.started_at,
4132
+ dir: `workflows/${workflowId}`
4133
+ };
4134
+ const entryGate = validateWorkflowEntry(entry);
4135
+ if (!entryGate.ok) {
4136
+ throw new Error(`refusing to register invalid workflow entry: ${entryGate.violations.map((v) => v.message).join("; ")}`);
4137
+ }
4138
+ return withStatusWriteLock(statusPath, async () => {
4139
+ if (existsSync4(snapshotPath)) {
4140
+ const rootDoc = readJson(statusPath);
4141
+ const workflows = Array.isArray(rootDoc.workflows) ? rootDoc.workflows : [];
4142
+ if (workflows.some((candidate) => isPlainObject2(candidate) && candidate.id === workflowId)) {
4143
+ throw new Error(`refusing to register workflow ${JSON.stringify(workflowId)}: it is already registered (snapshot at ${snapshotPath}, root entry in ${statusPath}) \u2014 registration is create-only; ` + `remove that workflow before registering again`);
4144
+ }
4145
+ const existing = readWorkflowSnapshot(workflowDir);
4146
+ if (planWorkflowRegistrationIdentity(existing.snapshot) !== planWorkflowRegistrationIdentity(snapshot)) {
4147
+ throw new Error(`refusing to register workflow ${JSON.stringify(workflowId)}: snapshot ${snapshotPath} already exists ` + `with a different registration identity \u2014 remove that workflow or register under a different id`);
4148
+ }
4149
+ const recoveryEntry = {
4150
+ id: workflowId,
4151
+ type: "plan",
4152
+ started_at: existing.snapshot.started_at,
4153
+ dir: `workflows/${workflowId}`
4154
+ };
4155
+ const recoveryGate = validateWorkflowEntry(recoveryEntry);
4156
+ if (!recoveryGate.ok) {
4157
+ throw new Error(`refusing to register invalid workflow entry: ${recoveryGate.violations.map((v) => v.message).join("; ")}`);
4158
+ }
4159
+ await registerWorkflowEntryLocked(statusPath, recoveryEntry);
4160
+ return { workflowId, snapshotPath, recovered: true };
4161
+ }
4162
+ let createdVersion;
4163
+ try {
4164
+ await writeWorkflowSnapshot(snapshot, workflowDir, { createOnly: true });
4165
+ createdVersion = readArtifactBytes(snapshotPath)?.version;
4166
+ await registerWorkflowEntryLocked(statusPath, entry);
4167
+ } catch (error) {
4168
+ if (createdVersion !== undefined) {
4169
+ await withStatusWriteLock(snapshotPath, async () => {
4170
+ const current = readArtifactBytes(snapshotPath);
4171
+ if (current === undefined || current.version !== createdVersion)
4172
+ return;
4173
+ const remove = store.delete?.bind(store);
4174
+ if (remove !== undefined) {
4175
+ await withProtectedWrite(snapshotPath, "delete", () => remove({ kind: "snapshot", key: workflowId }));
4176
+ }
4177
+ });
4178
+ }
4179
+ try {
4180
+ if (readdirSync2(workflowDir).length === 0) {
4181
+ rmdirSync2(workflowDir);
4182
+ }
4183
+ } catch {}
4184
+ throw error;
4185
+ }
4186
+ return { workflowId, snapshotPath, recovered: false };
4187
+ });
4188
+ }
3777
4189
  var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
3778
4190
  function rowPlanIds(row) {
3779
4191
  if (!isPlainObject2(row))
@@ -3943,7 +4355,7 @@ function validateStatusV2(docOrPath, opts = {}) {
3943
4355
  if (typeof docOrPath === "string") {
3944
4356
  try {
3945
4357
  doc = readJson(docOrPath);
3946
- harnessDir = dirname5(resolve6(docOrPath));
4358
+ harnessDir = dirname5(resolve7(docOrPath));
3947
4359
  } catch (error) {
3948
4360
  return {
3949
4361
  ok: false,
@@ -4104,7 +4516,7 @@ async function unregisterWorkflow(root, id) {
4104
4516
  if (typeof id !== "string" || id.trim() === "") {
4105
4517
  throw new Error("refusing to unregister workflow: id must be a non-empty string");
4106
4518
  }
4107
- const statusPath = resolve6(root);
4519
+ const statusPath = resolve7(root);
4108
4520
  const store = getArtifactStore();
4109
4521
  assertFsStorePath(store, { kind: "status", key: "root" }, statusPath);
4110
4522
  const harnessDir = dirname5(statusPath);
@@ -4373,6 +4785,16 @@ function evaluatePostMergeClose(snapshotDoc, rootDoc) {
4373
4785
  violations.push(violation5("high", "PHASE6_DANGLING_LEASE", "Terminal snapshot still carries a lease (plans[].execution_lease or integration_merge_lease) \u2014 close never releases leases", "Release the lease(s) with the owner action, then re-run 'mstar iteration gate --phase 6 --workflow <id>'"));
4374
4786
  }
4375
4787
  const workflowId = isPlainObject3(snapshotDoc) && typeof snapshotDoc.id === "string" ? snapshotDoc.id : null;
4788
+ if (shapeOk && terminal && isPlainObject3(snapshotDoc) && snapshotDoc.type === "plan" && snapshotDoc.status === "completed") {
4789
+ violations.push(...consultDeliveryEvidence(snapshotDoc));
4790
+ if (Array.isArray(snapshotDoc.plans)) {
4791
+ for (const row of snapshotDoc.plans) {
4792
+ if (isPlainObject3(row) && row.status !== PLAN_STATUS_DONE) {
4793
+ violations.push(violation5("high", "PHASE6_PLAN_ROW_NOT_DONE", `Workflow '${String(workflowId)}' is completed but owned plan row '${String(row.id)}' is ${JSON.stringify(row.status)} \u2014 a completed close requires every plan row Done (mstar-artifacts/references/plan-workflow-lifecycle-contract.md \u00a73 terminal stage)`, "Bring the owned plan row to Done (or close the lifecycle as failed/stopped with a recorded reason), then re-run 'mstar iteration gate --phase 6 --workflow <id>'"));
4794
+ }
4795
+ }
4796
+ }
4797
+ }
4376
4798
  const rootGate = validateStatusV2(rootDoc);
4377
4799
  if (!rootGate.ok) {
4378
4800
  violations.push(violation5("high", "PHASE6_INVALID_ROOT", "Root status.json is not a readable v2 workflow registry (workflows[] missing or not an array) \u2014 an invalid/unreadable root is not proof that the entry is gone", "Repair or migrate {HARNESS_DIR}/status.json to the v2 shape, then re-run the gate"));
@@ -4557,8 +4979,8 @@ async function appendProjectRegisterEntries(opts) {
4557
4979
  if (opts.entries.length === 0) {
4558
4980
  throw new Error("refusing to append residual entries: entries must not be empty");
4559
4981
  }
4560
- const registerPath = resolve7(join9(opts.projectDir, PROJECT_REGISTER_FILE));
4561
- const projectKey = basename4(resolve7(opts.projectDir));
4982
+ const registerPath = resolve8(join9(opts.projectDir, PROJECT_REGISTER_FILE));
4983
+ const projectKey = basename4(resolve8(opts.projectDir));
4562
4984
  const store = getArtifactStore();
4563
4985
  assertFsStorePath(store, { kind: "residuals", key: projectKey }, registerPath);
4564
4986
  mkdirSync4(opts.projectDir, { recursive: true });
@@ -4602,8 +5024,8 @@ async function appendProjectRegisterEntries(opts) {
4602
5024
  });
4603
5025
  }
4604
5026
  async function closeProjectRegisterEntry(opts) {
4605
- const registerPath = resolve7(join9(opts.projectDir, PROJECT_REGISTER_FILE));
4606
- const projectKey = basename4(resolve7(opts.projectDir));
5027
+ const registerPath = resolve8(join9(opts.projectDir, PROJECT_REGISTER_FILE));
5028
+ const projectKey = basename4(resolve8(opts.projectDir));
4607
5029
  const store = getArtifactStore();
4608
5030
  assertFsStorePath(store, { kind: "residuals", key: projectKey }, registerPath);
4609
5031
  mkdirSync4(opts.projectDir, { recursive: true });
@@ -4682,7 +5104,7 @@ function techDebtRollup(projectDir) {
4682
5104
  const items = [];
4683
5105
  let entries;
4684
5106
  try {
4685
- entries = readdirSync4(projectDir, { withFileTypes: true });
5107
+ entries = readdirSync5(projectDir, { withFileTypes: true });
4686
5108
  } catch {
4687
5109
  entries = [];
4688
5110
  }
@@ -4726,14 +5148,14 @@ function techDebtRollup(projectDir) {
4726
5148
  return { computed, stored, checks, overall };
4727
5149
  }
4728
5150
  function resolveHarnessDir(startDir = process.cwd(), opts = {}) {
4729
- const start = resolve8(startDir);
5151
+ const start = resolve9(startDir);
4730
5152
  const explicit = opts.harnessDir ?? process.env.MSTAR_HARNESS_DIR;
4731
5153
  if (explicit)
4732
- return resolve8(start, explicit);
4733
- const boundary = resolve8(start, opts.workspaceRoot ?? defaultWorkspaceRoot(start));
5154
+ return resolve9(start, explicit);
5155
+ const boundary = resolve9(start, opts.workspaceRoot ?? defaultWorkspaceRoot(start));
4734
5156
  const rc = loadMstarc(start, boundary);
4735
5157
  if (rc !== null && rc.config.harnessDir)
4736
- return resolve8(rc.dir, rc.config.harnessDir);
5158
+ return resolve9(rc.dir, rc.config.harnessDir);
4737
5159
  let dir = start;
4738
5160
  for (;; ) {
4739
5161
  if (!isAtOrBelow2(dir, boundary))
@@ -4764,7 +5186,7 @@ function defaultWorkspaceRoot(startDir) {
4764
5186
  if (segment && segment !== ".")
4765
5187
  boundary = dirname6(boundary);
4766
5188
  }
4767
- return resolve8(boundary);
5189
+ return resolve9(boundary);
4768
5190
  } catch {}
4769
5191
  return startDir;
4770
5192
  }
@@ -4773,10 +5195,10 @@ function isAtOrBelow2(dir, root) {
4773
5195
  return rel === "" || !rel.startsWith("..") && !isAbsolute6(rel);
4774
5196
  }
4775
5197
  function mstarcDirOverride(harnessDir, key) {
4776
- const dir = resolve8(harnessDir);
5198
+ const dir = resolve9(harnessDir);
4777
5199
  const rc = loadMstarc(dir, dirname6(dir));
4778
5200
  const declared = rc?.config[key];
4779
- return declared ? resolve8(rc.dir, declared) : null;
5201
+ return declared ? resolve9(rc.dir, declared) : null;
4780
5202
  }
4781
5203
  function resolveSpecsDir(harnessDir, opts = {}) {
4782
5204
  const declared = mstarcDirOverride(harnessDir, "specsDir");
@@ -4785,7 +5207,7 @@ function resolveSpecsDir(harnessDir, opts = {}) {
4785
5207
  mkdirSync5(declared, { recursive: true });
4786
5208
  return declared;
4787
5209
  }
4788
- const harness = resolve8(harnessDir);
5210
+ const harness = resolve9(harnessDir);
4789
5211
  const repoRoot = dirname6(harness);
4790
5212
  const candidates = [
4791
5213
  join10(harness, "specs"),
@@ -4807,7 +5229,7 @@ function resolvePlanDir(harnessDir) {
4807
5229
  const declared = mstarcDirOverride(harnessDir, "planDir");
4808
5230
  if (declared !== null)
4809
5231
  return declared;
4810
- const dir = resolve8(harnessDir);
5232
+ const dir = resolve9(harnessDir);
4811
5233
  const name = basename5(dir);
4812
5234
  if (name === ".plans" || name === "plans")
4813
5235
  return dir;
@@ -4819,7 +5241,7 @@ function assertSafePathComponent(value, what) {
4819
5241
  }
4820
5242
  }
4821
5243
  function canonicalizeNearestExisting(path) {
4822
- const abs = resolve8(path);
5244
+ const abs = resolve9(path);
4823
5245
  let dir = abs;
4824
5246
  const tail = [];
4825
5247
  for (;; ) {
@@ -4839,7 +5261,7 @@ function canonicalizeNearestExisting(path) {
4839
5261
  }
4840
5262
  function resolveSddDir(harnessDir, planId) {
4841
5263
  assertSafePathComponent(planId, "planId");
4842
- const base = resolve8(harnessDir);
5264
+ const base = resolve9(harnessDir);
4843
5265
  const declared = mstarcDirOverride(base, "sddDir");
4844
5266
  const sddBase = declared !== null ? declared : join10(base, "sdd");
4845
5267
  return join10(sddBase, planId);
@@ -4847,10 +5269,10 @@ function resolveSddDir(harnessDir, planId) {
4847
5269
  function resolveHarnessSubdir(startDir, opts, key, fallback) {
4848
5270
  const harness = resolveHarnessDir(startDir, opts);
4849
5271
  if (harness === null) {
4850
- throw new Error(`harness dir not found from ${resolve8(startDir)} \u2014 cannot resolve the ${fallback} dir (run \`mstar harness scaffold\`, pass opts.harnessDir, or set MSTAR_HARNESS_DIR)`);
5272
+ throw new Error(`harness dir not found from ${resolve9(startDir)} \u2014 cannot resolve the ${fallback} dir (run \`mstar harness scaffold\`, pass opts.harnessDir, or set MSTAR_HARNESS_DIR)`);
4851
5273
  }
4852
5274
  const declared = mstarcDirOverride(harness, key);
4853
- return declared !== null ? declared : join10(resolve8(harness), fallback);
5275
+ return declared !== null ? declared : join10(resolve9(harness), fallback);
4854
5276
  }
4855
5277
  function resolveWorkflowDir(startDir = process.cwd(), opts = {}) {
4856
5278
  return resolveHarnessSubdir(startDir, opts, "workflowDir", "workflows");
@@ -4865,11 +5287,11 @@ var EMPTY_STATUS_TEMPLATE = {
4865
5287
  };
4866
5288
  var SCAFFOLD_DIRS = ["plans", "iterations", "knowledge", "specs", "sdd"];
4867
5289
  function resolveScaffoldDirs(root) {
4868
- const start = resolve8(root);
4869
- const boundary = resolve8(start, defaultWorkspaceRoot(start));
5290
+ const start = resolve9(root);
5291
+ const boundary = resolve9(start, defaultWorkspaceRoot(start));
4870
5292
  const rc = loadMstarc(start, boundary);
4871
5293
  const explicit = process.env.MSTAR_HARNESS_DIR;
4872
- const harnessDir = explicit ? resolve8(start, explicit) : rc !== null && rc.config.harnessDir ? resolve8(rc.dir, rc.config.harnessDir) : join10(start, ".mstar");
5294
+ const harnessDir = explicit ? resolve9(start, explicit) : rc !== null && rc.config.harnessDir ? resolve9(rc.dir, rc.config.harnessDir) : join10(start, ".mstar");
4873
5295
  const declaredProjectDir = mstarcDirOverride(harnessDir, "projectDir");
4874
5296
  const projectDir = declaredProjectDir !== null ? declaredProjectDir : join10(harnessDir, "projects");
4875
5297
  return { harnessDir, projectDir };
@@ -4961,7 +5383,7 @@ function emitGitignoreSnippet(kind) {
4961
5383
  function detectHarnessKind(harnessDir) {
4962
5384
  if (!harnessDir)
4963
5385
  return null;
4964
- const name = basename5(resolve8(harnessDir));
5386
+ const name = basename5(resolve9(harnessDir));
4965
5387
  if (name === ".mstar")
4966
5388
  return "mstar";
4967
5389
  if (name === ".agents")
@@ -4969,7 +5391,7 @@ function detectHarnessKind(harnessDir) {
4969
5391
  return null;
4970
5392
  }
4971
5393
  function assertPlanWritingPath(planPath, harnessDir) {
4972
- const planAbs = resolve8(planPath);
5394
+ const planAbs = resolve9(planPath);
4973
5395
  if (!harnessDir) {
4974
5396
  return {
4975
5397
  ok: false,
@@ -4994,7 +5416,7 @@ function assertPlanWritingPath(planPath, harnessDir) {
4994
5416
  if (existsSync8(planAbs)) {
4995
5417
  try {
4996
5418
  const canonicalPlan = realpathSync3(planAbs);
4997
- const canonicalPlanDir = existsSync8(planDir) ? realpathSync3(planDir) : resolve8(planDir);
5419
+ const canonicalPlanDir = existsSync8(planDir) ? realpathSync3(planDir) : resolve9(planDir);
4998
5420
  const canonicalRel = relative2(canonicalPlanDir, canonicalPlan);
4999
5421
  const canonicalInside = canonicalRel === "" || !canonicalRel.startsWith("..") && !isAbsolute6(canonicalRel);
5000
5422
  if (!canonicalInside) {
@@ -5024,7 +5446,7 @@ function isDirectory(dir) {
5024
5446
  }
5025
5447
  function hasFiles(dir) {
5026
5448
  try {
5027
- for (const entry of readdirSync5(dir, { withFileTypes: true })) {
5449
+ for (const entry of readdirSync6(dir, { withFileTypes: true })) {
5028
5450
  if (entry.isDirectory()) {
5029
5451
  if (hasFiles(join10(dir, entry.name)))
5030
5452
  return true;
@@ -5344,7 +5766,7 @@ function l1PreDispatchCheck(input, opts = {}) {
5344
5766
  const violations = [];
5345
5767
  const checkoutCache = new Map;
5346
5768
  const checkout = (path) => {
5347
- const key = resolve9(path);
5769
+ const key = resolve10(path);
5348
5770
  if (!checkoutCache.has(key))
5349
5771
  checkoutCache.set(key, probeCheckout(path, opts));
5350
5772
  return checkoutCache.get(key);
@@ -5395,7 +5817,7 @@ function l1PreDispatchCheck(input, opts = {}) {
5395
5817
  }
5396
5818
  }
5397
5819
  const identityViolation = (aPath, bPath, code, describe, fix) => {
5398
- if (resolve9(aPath) === resolve9(bPath)) {
5820
+ if (resolve10(aPath) === resolve10(bPath)) {
5399
5821
  return violation8("critical", code, `${describe} \u2014 the same checkout (normalized path equality) is not isolation`, fix);
5400
5822
  }
5401
5823
  if (!existsSync9(aPath) || !existsSync9(bPath))
@@ -5456,7 +5878,7 @@ function l2PreDispatchCheck(input, opts = {}) {
5456
5878
  violations.push(violation8("high", "worktree.l2.track-path-relative", `track ${index + 1} worktreePath "${track.worktreePath}" is not an absolute path \u2014 L2 tracks MUST use absolute worktree checkout paths (consistent with the lease validator's absolute worktree_path enforcement)`, `use an absolute path for track ${index + 1} (e.g. /Users/<you>/worktrees/<branch>)`));
5457
5879
  return;
5458
5880
  }
5459
- const normalized = resolve9(track.worktreePath);
5881
+ const normalized = resolve10(track.worktreePath);
5460
5882
  if (seenPaths.has(normalized)) {
5461
5883
  violations.push(violation8("high", "worktree.l2.track-path-collision", `duplicate worktreePath "${track.worktreePath}" across parallel tracks \u2014 L2 parallel-writable isolation requires a distinct absolute Worktree path per track (N parallel invokes \u2260 isolation)`, "give every parallel track its own git worktree checkout"));
5462
5884
  return;
@@ -5654,7 +6076,7 @@ function hasWorkflowSnapshot(harnessDir) {
5654
6076
  if (!isDirectory2(workflowsDir))
5655
6077
  return false;
5656
6078
  try {
5657
- for (const entry of readdirSync6(workflowsDir, { withFileTypes: true })) {
6079
+ for (const entry of readdirSync7(workflowsDir, { withFileTypes: true })) {
5658
6080
  if (entry.isDirectory() && isFile2(join13(workflowsDir, entry.name, "snapshot.json")))
5659
6081
  return true;
5660
6082
  }
@@ -5664,9 +6086,9 @@ function hasWorkflowSnapshot(harnessDir) {
5664
6086
  return false;
5665
6087
  }
5666
6088
  function checkoutRootNearestExisting(dir, boundary) {
5667
- const stop = resolve10(boundary);
5668
- const startInside = isInside(resolve10(dir), stop);
5669
- let current = resolve10(dir);
6089
+ const stop = resolve11(boundary);
6090
+ const startInside = isInside(resolve11(dir), stop);
6091
+ let current = resolve11(dir);
5670
6092
  for (;; ) {
5671
6093
  const probed = probeCheckoutRoot(current);
5672
6094
  if (probed !== null)
@@ -5720,12 +6142,12 @@ function sddWorkspace(planId, opts = {}) {
5720
6142
  const harnessOverride = opts.harnessDir ?? (process.env.MSTAR_HARNESS_DIR || undefined);
5721
6143
  let harnessDir;
5722
6144
  if (harnessOverride) {
5723
- harnessDir = resolve10(root, harnessOverride);
6145
+ harnessDir = resolve11(root, harnessOverride);
5724
6146
  } else {
5725
6147
  const rc = findMstarc(root, root);
5726
6148
  const rcHarnessDir = rc !== null ? parseMstarc(readFileSync9(rc, "utf8")).harnessDir : undefined;
5727
6149
  if (rcHarnessDir) {
5728
- harnessDir = resolve10(rc !== null ? dirname9(rc) : root, rcHarnessDir);
6150
+ harnessDir = resolve11(rc !== null ? dirname9(rc) : root, rcHarnessDir);
5729
6151
  } else {
5730
6152
  const probed = probeHarnessWithStatus(root);
5731
6153
  if (probed) {
@@ -5757,7 +6179,7 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
5757
6179
  const bound = opts.context;
5758
6180
  const observedCwd = opts.cwd ?? process.cwd();
5759
6181
  if (bound) {
5760
- const inputPlan = canonicalizeNearestExisting(resolve10(observedCwd, planFile));
6182
+ const inputPlan = canonicalizeNearestExisting(resolve11(observedCwd, planFile));
5761
6183
  if (inputPlan !== canonicalizeNearestExisting(bound.planFile)) {
5762
6184
  throwGateFail([
5763
6185
  contextViolation("high", "sdd.context.plan-file-mismatch", `plan file "${planFile}" does not match the bound context plan file "${bound.planFile}" \u2014 ` + "bound mode extracts only the resolved context's plan; refused before any read or write")
@@ -5773,7 +6195,7 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
5773
6195
  let out;
5774
6196
  let mkdirAfterGate = null;
5775
6197
  if (outFile) {
5776
- out = bound ? resolve10(observedCwd, outFile) : outFile;
6198
+ out = bound ? resolve11(observedCwd, outFile) : outFile;
5777
6199
  } else if (bound) {
5778
6200
  out = join13(bound.sddDir, `task-${taskN}-brief.md`);
5779
6201
  mkdirAfterGate = bound.sddDir;
@@ -5816,7 +6238,7 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
5816
6238
  if (printed.length === 0) {
5817
6239
  throw new SddScriptError(`task ${taskN} not found in ${planFile} (no heading matching Task ${taskN})`, 3);
5818
6240
  }
5819
- return bound ? resolve10(observedCwd, out) : out;
6241
+ return bound ? resolve11(observedCwd, out) : out;
5820
6242
  }
5821
6243
  function reviewPackage(base, head, outFile, opts = {}) {
5822
6244
  if (!base || !head) {
@@ -5837,7 +6259,7 @@ function reviewPackage(base, head, outFile, opts = {}) {
5837
6259
  let out;
5838
6260
  let mkdirAfterGate = null;
5839
6261
  if (outFile) {
5840
- out = bound ? resolve10(observedCwd, outFile) : outFile;
6262
+ out = bound ? resolve11(observedCwd, outFile) : outFile;
5841
6263
  } else if (bound) {
5842
6264
  const shortBase = gitOut(cwd, ["rev-parse", "--short", base]) ?? base;
5843
6265
  const shortHead = gitOut(cwd, ["rev-parse", "--short", head]) ?? head;
@@ -5881,7 +6303,7 @@ function reviewPackage(base, head, outFile, opts = {}) {
5881
6303
  run(["diff", "-U10", `${base}..${head}`])
5882
6304
  ];
5883
6305
  writeFileSync4(out, Buffer.concat(parts));
5884
- return bound ? resolve10(observedCwd, out) : out;
6306
+ return bound ? resolve11(observedCwd, out) : out;
5885
6307
  }
5886
6308
  function isPlainObject7(value) {
5887
6309
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -5928,24 +6350,28 @@ function normalizeSnapshotWorktreePath(doc) {
5928
6350
  const { control_worktree_path: _dropped, ...rest } = doc;
5929
6351
  return { ...rest, integration_worktree_path: legacy };
5930
6352
  }
5931
- function readActiveWorkflowIds(controlHarnessRoot) {
6353
+ function classifyWorkflowRegisterState(controlHarnessRoot) {
5932
6354
  const statusPath = join13(controlHarnessRoot, "status.json");
5933
6355
  if (!isFile2(statusPath))
5934
- return null;
6356
+ return { state: "absent" };
5935
6357
  let doc;
5936
6358
  try {
5937
6359
  doc = readJson(statusPath);
5938
6360
  } catch {
5939
- return null;
6361
+ return { state: "unreadable" };
5940
6362
  }
5941
6363
  if (!isPlainObject7(doc) || doc.version !== 2 || !Array.isArray(doc.workflows))
5942
- return null;
5943
- const ids = new Set;
6364
+ return { state: "unreadable" };
6365
+ const activeIds = new Set;
5944
6366
  for (const entry of doc.workflows) {
5945
6367
  if (isPlainObject7(entry) && typeof entry.id === "string")
5946
- ids.add(entry.id);
6368
+ activeIds.add(entry.id);
5947
6369
  }
5948
- return ids;
6370
+ return { state: "readable", activeIds };
6371
+ }
6372
+ function readActiveWorkflowIds(controlHarnessRoot) {
6373
+ const register = classifyWorkflowRegisterState(controlHarnessRoot);
6374
+ return register.state === "readable" ? register.activeIds : null;
5949
6375
  }
5950
6376
  function findWorkflowPlanRow(controlHarnessRoot, planId) {
5951
6377
  let workflowsDir;
@@ -5958,7 +6384,7 @@ function findWorkflowPlanRow(controlHarnessRoot, planId) {
5958
6384
  return { kind: "none" };
5959
6385
  let workflowIds;
5960
6386
  try {
5961
- workflowIds = readdirSync6(workflowsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
6387
+ workflowIds = readdirSync7(workflowsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
5962
6388
  } catch {
5963
6389
  return { kind: "none" };
5964
6390
  }
@@ -6094,6 +6520,12 @@ function resolveSddExecutionContext(input) {
6094
6520
  contextViolation("critical", "sdd.context.feature-in-control", `featureCwd "${canonicalFeatureCwd}" is inside the control checkout "${controlCheckout}" and is not a distinct Git checkout \u2014 a plain subdirectory or symlink alias of the control checkout is not isolation; product edits never land in the control checkout (execution_lease.worktree_path MUST be a distinct checkout)`, "use a distinct feature worktree for the plan (git worktree add <path> <branch>)")
6095
6521
  ]);
6096
6522
  }
6523
+ const registerState = classifyWorkflowRegisterState(canonicalControlHarnessRoot);
6524
+ if (registerState.state === "unreadable") {
6525
+ throwGateFail([
6526
+ contextViolation("critical", "sdd.context.register-unreadable", `control harness root "${canonicalControlHarnessRoot}" has a status.json that is present but not a readable v2 workflow register (malformed JSON, non-v2 version, or missing workflows[]) \u2014 ` + 'a damaged register is never treated as "no register": registered active lifecycles cannot be resolved over it, so execution is refused (plan-workflow-lifecycle contract \u00a76 S2) instead of silently continuing on branch alignment alone', "repair or migrate the control root's status.json to the v2 shape ('mstar migrate' / register repair), then retry the execution")
6527
+ ]);
6528
+ }
6097
6529
  const match = findWorkflowPlanRow(canonicalControlHarnessRoot, planId);
6098
6530
  if (match.kind === "ambiguous") {
6099
6531
  throwGateFail([
@@ -6136,6 +6568,11 @@ function resolveSddExecutionContext(input) {
6136
6568
  } else if (match.kind === "row" && match.row.status === "InProgress") {
6137
6569
  throwGateFail(verifyPlanExecutionLease(match.row, planId).violations);
6138
6570
  } else {
6571
+ if (match.kind === "none" && registerState.state === "readable") {
6572
+ throwGateFail([
6573
+ contextViolation("high", "sdd.context.plan-not-registered", `plan "${planId}" has no active registered workflow row in the control harness's workflow register \u2014 ` + "on the normal plan route, SDD execution requires a registered running workflow row (plan-workflow-lifecycle contract \u00a76 S2; a retained terminal snapshot's row is history, never registration evidence): " + `register it with \`mstar workflow register --workflow <id> --plan-id <id> --plan-title <title> --plan-file <path> --delivery-kind <${WORKFLOW_DELIVERY_KINDS.join("|")}> ...` + "` (`registerPlanWorkflow`), then retry \u2014 registration is create-only and preserves prior state; " + "re-running the same register command completes an interrupted registration without duplicating identity", "register the plan workflow, then retry the execution")
6574
+ ]);
6575
+ }
6139
6576
  const branchGate = assertBranchAlignment(canonicalFeatureCwd, workingBranch);
6140
6577
  if (!branchGate.ok)
6141
6578
  throwGateFail(branchGate.violations);
@@ -6165,11 +6602,11 @@ function checkSddAction(context, action) {
6165
6602
  const featureReal = canonicalDir(context.featureCwd);
6166
6603
  const canonicalSddDir = canonicalizeNearestExisting(context.sddDir);
6167
6604
  const canonicalPlanFile = canonicalizeNearestExisting(context.planFile);
6168
- const cwdResolved = resolve10(action.cwd);
6605
+ const cwdResolved = resolve11(action.cwd);
6169
6606
  const checkTarget = (baseDir, target, kind) => {
6170
6607
  if (featureReal === null)
6171
6608
  return;
6172
- const targetAbs = resolve10(baseDir, target);
6609
+ const targetAbs = resolve11(baseDir, target);
6173
6610
  const canonical = canonicalizeNearestExisting(targetAbs);
6174
6611
  if (!isInside(canonical, featureReal)) {
6175
6612
  const declaredPrefix = targetAbs === featureReal || targetAbs.startsWith(`${featureReal}/`);
@@ -6197,10 +6634,10 @@ function checkSddAction(context, action) {
6197
6634
  add("sdd.context.target-missing", "artifact checks require the destination target");
6198
6635
  return { ok: false, violations };
6199
6636
  }
6200
- const targetAbs = resolve10(cwdResolved, action.target);
6637
+ const targetAbs = resolve11(cwdResolved, action.target);
6201
6638
  const canonical = canonicalizeNearestExisting(targetAbs);
6202
6639
  if (!isInside(canonical, canonicalSddDir) && canonical !== canonicalPlanFile) {
6203
- const rawSddDir = resolve10(context.sddDir);
6640
+ const rawSddDir = resolve11(context.sddDir);
6204
6641
  const declaredPrefix = targetAbs === rawSddDir || targetAbs.startsWith(`${rawSddDir}/`) || targetAbs === canonicalSddDir || targetAbs.startsWith(`${canonicalSddDir}/`) || targetAbs === canonicalPlanFile;
6205
6642
  if (declaredPrefix) {
6206
6643
  add("sdd.context.artifact-symlink-escape", `artifact target "${targetAbs}" canonicalizes to "${canonical}", outside the plan's control sddDir \u2014 symlink escape refused before write`);
@@ -7004,7 +7441,7 @@ var LOCKFILE_NAMES = [
7004
7441
  function rootLockfiles(root) {
7005
7442
  let entries;
7006
7443
  try {
7007
- entries = readdirSync8(root, { withFileTypes: true });
7444
+ entries = readdirSync9(root, { withFileTypes: true });
7008
7445
  } catch {
7009
7446
  return [];
7010
7447
  }
@@ -7037,7 +7474,7 @@ function supplyChainChecks(repoRoot) {
7037
7474
  const workflowsDir = join16(repoRoot, ".github", "workflows");
7038
7475
  let wfEntries = [];
7039
7476
  try {
7040
- wfEntries = readdirSync8(workflowsDir, { withFileTypes: true });
7477
+ wfEntries = readdirSync9(workflowsDir, { withFileTypes: true });
7041
7478
  } catch {
7042
7479
  wfEntries = [];
7043
7480
  }
@@ -7203,7 +7640,7 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7203
7640
  mkdirSync8(outDir, { recursive: true });
7204
7641
  const existingReadme = join16(outDir, "README.md");
7205
7642
  const carried = existsSync12(existingReadme) ? extractSecurityDispositionSections(readFileSync11(existingReadme, "utf8")) : { needsVerification: [], hardeningChecked: [] };
7206
- const existing = readdirSync8(outDir).filter((f) => /^\d{3}-.*\.md$/.test(f));
7643
+ const existing = readdirSync9(outDir).filter((f) => /^\d{3}-.*\.md$/.test(f));
7207
7644
  let next = existing.reduce((max, f) => Math.max(max, Number(f.slice(0, 3))), 0) + 1;
7208
7645
  const redactedFindings = findings.map(redactFinding);
7209
7646
  const written = [];
@@ -7268,7 +7705,7 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7268
7705
  needsVerification: needsVerificationLines,
7269
7706
  hardeningChecked: hardeningCheckedLines
7270
7707
  }));
7271
- return { outDir: resolve13(outDir), date, files: written, nextNumber: next };
7708
+ return { outDir: resolve14(outDir), date, files: written, nextNumber: next };
7272
7709
  }
7273
7710
  async function promoteAuditPlans(outDir, selected, options) {
7274
7711
  if (selected.length === 0) {
@@ -7277,9 +7714,13 @@ async function promoteAuditPlans(outDir, selected, options) {
7277
7714
  if (typeof options.harnessDir !== "string" || options.harnessDir.trim() === "") {
7278
7715
  throw new Error("promoteAuditPlans: options.harnessDir is required (must contain status.json + workflows/)");
7279
7716
  }
7280
- const workflowId = options.workflowId ?? basename10(resolve13(outDir));
7717
+ if (typeof options.deliveryKind !== "string" || !WORKFLOW_DELIVERY_KINDS.includes(options.deliveryKind)) {
7718
+ throw new Error(`promoteAuditPlans: options.deliveryKind must be one of ${WORKFLOW_DELIVERY_KINDS.join(" | ")} \u2014 got ${JSON.stringify(options.deliveryKind)} (a promoted plan workflow declares its delivery kind at registration; it is never inferred and never defaulted)`);
7719
+ }
7720
+ assertDeliveryRegistrationCoherence(options.deliveryKind, options, "promoteAuditPlans");
7721
+ const workflowId = options.workflowId ?? basename10(resolve14(outDir));
7281
7722
  assertSafePathComponent(workflowId, "workflow id");
7282
- const harnessDir = resolve13(options.harnessDir);
7723
+ const harnessDir = resolve14(options.harnessDir);
7283
7724
  const statusPath = join16(harnessDir, "status.json");
7284
7725
  const workflowDir = join16(harnessDir, "workflows", workflowId);
7285
7726
  const snapshotPath = join16(workflowDir, WORKFLOW_SNAPSHOT_FILE);
@@ -7306,8 +7747,17 @@ async function promoteAuditPlans(outDir, selected, options) {
7306
7747
  status: "running",
7307
7748
  started_at: now.toISOString(),
7308
7749
  updated_at: now.toISOString().slice(0, 10),
7309
- plans
7750
+ plans,
7751
+ delivery_kind: options.deliveryKind
7310
7752
  };
7753
+ if (options.branchSource !== undefined || options.branchTarget !== undefined) {
7754
+ snapshot.branch = {
7755
+ ...options.branchSource !== undefined ? { source: options.branchSource } : {},
7756
+ ...options.branchTarget !== undefined ? { target: options.branchTarget } : {}
7757
+ };
7758
+ }
7759
+ if (options.completionPolicy !== undefined)
7760
+ snapshot.completion_policy = options.completionPolicy;
7311
7761
  const entry = {
7312
7762
  id: workflowId,
7313
7763
  type: "plan",
@@ -7340,8 +7790,8 @@ async function promoteAuditPlans(outDir, selected, options) {
7340
7790
  });
7341
7791
  }
7342
7792
  try {
7343
- if (readdirSync8(workflowDir).length === 0) {
7344
- rmdirSync2(workflowDir);
7793
+ if (readdirSync9(workflowDir).length === 0) {
7794
+ rmdirSync3(workflowDir);
7345
7795
  }
7346
7796
  } catch {}
7347
7797
  throw error;
@@ -7351,7 +7801,7 @@ async function promoteAuditPlans(outDir, selected, options) {
7351
7801
  return { workflowId, snapshotPath };
7352
7802
  }
7353
7803
  function resolveSelectedPlanFiles(outDir, selected) {
7354
- const files = readdirSync8(outDir).filter((f) => /^\d{3}-.*\.md$/.test(f)).sort();
7804
+ const files = readdirSync9(outDir).filter((f) => /^\d{3}-.*\.md$/.test(f)).sort();
7355
7805
  const byNum = new Map;
7356
7806
  const byStem = new Map;
7357
7807
  for (const file of files) {
@@ -7366,7 +7816,7 @@ function resolveSelectedPlanFiles(outDir, selected) {
7366
7816
  for (const id of selected) {
7367
7817
  const file = byNum.get(id) ?? byStem.get(id) ?? byStem.get(id.replace(/\.md$/, ""));
7368
7818
  if (file === undefined) {
7369
- throw new Error(`promoteAuditPlans: selected plan ${JSON.stringify(id)} does not match any NNN-*.md file in ${resolve13(outDir)}`);
7819
+ throw new Error(`promoteAuditPlans: selected plan ${JSON.stringify(id)} does not match any NNN-*.md file in ${resolve14(outDir)}`);
7370
7820
  }
7371
7821
  if (!seen.has(file)) {
7372
7822
  seen.add(file);
@@ -7405,7 +7855,7 @@ function readExecutionOrderIndex(outDir) {
7405
7855
  return rows;
7406
7856
  }
7407
7857
  function planFileRel(outDir, planFile) {
7408
- const resolved = resolve13(outDir);
7858
+ const resolved = resolve14(outDir);
7409
7859
  const parts = resolved.split(sep4);
7410
7860
  const plansIdx = parts.lastIndexOf("plans");
7411
7861
  if (plansIdx >= 0) {
@@ -7657,7 +8107,7 @@ function collectKnowledgeDocs(dir) {
7657
8107
  const current = stack.pop();
7658
8108
  let entries;
7659
8109
  try {
7660
- entries = readdirSync9(current, { withFileTypes: true });
8110
+ entries = readdirSync10(current, { withFileTypes: true });
7661
8111
  } catch {
7662
8112
  continue;
7663
8113
  }
@@ -7712,9 +8162,9 @@ function isFileLikeRoot(root) {
7712
8162
  return /^[^.]*\.[A-Za-z0-9]{1,10}$/.test(basename11(root));
7713
8163
  }
7714
8164
  function scopeGuard(path, allowedRoots) {
7715
- const resolved = resolve14(path);
8165
+ const resolved = resolve15(path);
7716
8166
  for (const root of allowedRoots) {
7717
- const r = resolve14(root);
8167
+ const r = resolve15(root);
7718
8168
  if (isFileLikeRoot(r)) {
7719
8169
  if (resolved === r)
7720
8170
  return { ok: true, violations: [] };
@@ -8536,7 +8986,7 @@ function prReviewReportPath(opts) {
8536
8986
  const sameStem = new RegExp(`^${escaped}(?:-r([0-9]+))?\\.md$`);
8537
8987
  let dirents;
8538
8988
  try {
8539
- dirents = readdirSync10(opts.reportsDir, { withFileTypes: true });
8989
+ dirents = readdirSync11(opts.reportsDir, { withFileTypes: true });
8540
8990
  } catch (error) {
8541
8991
  if (error.code === "ENOENT")
8542
8992
  dirents = [];
@@ -9279,7 +9729,7 @@ function localStore(harnessRoot) {
9279
9729
  try {
9280
9730
  store = getArtifactStore();
9281
9731
  } catch (error) {
9282
- throw new CoordinationError("coordination.local-store-required", `no artifact store is resolvable from ${resolve15(process.cwd())} \u2014 scoped coordination requires createFsStore(<control harness root>): ${errorMessage(error)}`, { harness_root: harnessRoot });
9732
+ throw new CoordinationError("coordination.local-store-required", `no artifact store is resolvable from ${resolve16(process.cwd())} \u2014 scoped coordination requires createFsStore(<control harness root>): ${errorMessage(error)}`, { harness_root: harnessRoot });
9283
9733
  }
9284
9734
  const root = "root" in store ? store.root : undefined;
9285
9735
  if (typeof root !== "string") {
@@ -9295,8 +9745,8 @@ function localStore(harnessRoot) {
9295
9745
  }
9296
9746
  function resolveProcessHarnessDir(cwd = process.cwd(), harnessDir) {
9297
9747
  if (isNonEmptyString(harnessDir))
9298
- return resolve15(cwd, harnessDir);
9299
- const start = resolve15(cwd);
9748
+ return resolve16(cwd, harnessDir);
9749
+ const start = resolve16(cwd);
9300
9750
  const main = readMainWorktree(start);
9301
9751
  if (main !== null)
9302
9752
  return resolveHarnessDir(main.root);
@@ -9336,7 +9786,7 @@ function readSessionEnvelope(sessionPath) {
9336
9786
  if (!isNonEmptyString(sessionPath) || !isAbsolute12(sessionPath)) {
9337
9787
  throw invalidInput("sessionPath must be an absolute path");
9338
9788
  }
9339
- const abs = resolve15(sessionPath);
9789
+ const abs = resolve16(sessionPath);
9340
9790
  if (!existsSync15(abs)) {
9341
9791
  throw new CoordinationError("coordination.session-not-found", `session envelope not found: ${abs}`, { path: abs });
9342
9792
  }
@@ -10978,13 +11428,13 @@ class ScreenManager {
10978
11428
  // ../../node_modules/.bun/@inquirer+core@12.0.3+72cd8510778f549e/node_modules/@inquirer/core/dist/lib/promise-polyfill.js
10979
11429
  class PromisePolyfill extends Promise {
10980
11430
  static withResolver() {
10981
- let resolve11;
11431
+ let resolve12;
10982
11432
  let reject;
10983
11433
  const promise = new Promise((res, rej) => {
10984
- resolve11 = res;
11434
+ resolve12 = res;
10985
11435
  reject = rej;
10986
11436
  });
10987
- return { promise, resolve: resolve11, reject };
11437
+ return { promise, resolve: resolve12, reject };
10988
11438
  }
10989
11439
  }
10990
11440
 
@@ -11029,7 +11479,7 @@ function createPrompt(view) {
11029
11479
  });
11030
11480
  output.mute();
11031
11481
  const screen = new ScreenManager(rl);
11032
- const { promise, resolve: resolve11, reject } = PromisePolyfill.withResolver();
11482
+ const { promise, resolve: resolve12, reject } = PromisePolyfill.withResolver();
11033
11483
  return withHooks(rl, (cycle) => {
11034
11484
  const clearEffects = AsyncResource3.bind(() => effectScheduler.clearAll());
11035
11485
  const settlePrompt = (settle) => {
@@ -11040,7 +11490,7 @@ function createPrompt(view) {
11040
11490
  reject(error);
11041
11491
  }
11042
11492
  };
11043
- const resolvePrompt = (value) => settlePrompt(() => resolve11(value));
11493
+ const resolvePrompt = (value) => settlePrompt(() => resolve12(value));
11044
11494
  const rejectPrompt = (error) => settlePrompt(() => reject(error));
11045
11495
  const promptPromise = Object.assign(promise.finally(() => {
11046
11496
  cleanups.forEach((cleanup) => cleanup());
@@ -11313,16 +11763,16 @@ var {
11313
11763
  // ../engine/dist/engine.js
11314
11764
  import { existsSync as existsSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync10, renameSync as renameSync2, unlinkSync as unlinkSync5, writeFileSync as writeFileSync5 } from "node:fs";
11315
11765
  import { randomUUID as randomUUID2 } from "node:crypto";
11316
- import { basename as basename6, dirname as dirname7, join as join8, resolve as resolve11 } from "node:path";
11766
+ import { basename as basename6, dirname as dirname7, join as join8, resolve as resolve12 } from "node:path";
11317
11767
  import { fileURLToPath } from "node:url";
11318
11768
  import { readFileSync as readFileSync22, statSync as statSync5 } from "node:fs";
11319
11769
  import { dirname as dirname22, isAbsolute as isAbsolute9, join as join22, relative as relative4, resolve as resolve22 } from "node:path";
11320
- import { existsSync as existsSync82, mkdirSync as mkdirSync52, readdirSync as readdirSync52, readFileSync as readFileSync82, realpathSync as realpathSync32, statSync as statSync32, writeFileSync as writeFileSync32 } from "node:fs";
11770
+ import { existsSync as existsSync82, mkdirSync as mkdirSync52, readdirSync as readdirSync62, readFileSync as readFileSync82, realpathSync as realpathSync32, statSync as statSync32, writeFileSync as writeFileSync32 } from "node:fs";
11321
11771
  import { execFileSync as execFileSync5 } from "node:child_process";
11322
- import { basename as basename52, dirname as dirname62, isAbsolute as isAbsolute62, join as join102, relative as relative22, resolve as resolve82 } from "node:path";
11323
- import { existsSync as existsSync52, readFileSync as readFileSync52, readdirSync as readdirSync22, realpathSync as realpathSync22 } from "node:fs";
11324
- import { dirname as dirname52, join as join72, resolve as resolve62, sep as sep22 } from "node:path";
11325
- import { mkdirSync as mkdirSync22, rmdirSync as rmdirSync3, statSync as statSync22, unlinkSync as unlinkSync22, writeFileSync as writeFileSync22 } from "node:fs";
11772
+ import { basename as basename52, dirname as dirname62, isAbsolute as isAbsolute62, join as join102, relative as relative22, resolve as resolve92 } from "node:path";
11773
+ import { existsSync as existsSync52, readFileSync as readFileSync52, readdirSync as readdirSync32, realpathSync as realpathSync22 } from "node:fs";
11774
+ import { dirname as dirname52, join as join72, resolve as resolve72, sep as sep22 } from "node:path";
11775
+ import { mkdirSync as mkdirSync22, rmdirSync as rmdirSync4, statSync as statSync22, unlinkSync as unlinkSync22, writeFileSync as writeFileSync22 } from "node:fs";
11326
11776
  import { dirname as dirname32, isAbsolute as isAbsolute22, join as join32, resolve as resolve32 } from "node:path";
11327
11777
  import { setTimeout as sleep2 } from "node:timers/promises";
11328
11778
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
@@ -11330,23 +11780,23 @@ import { AsyncLocalStorage as AsyncLocalStorage22 } from "node:async_hooks";
11330
11780
  import { createHash as createHash2 } from "node:crypto";
11331
11781
  import { existsSync as existsSync22, readFileSync as readFileSync32, realpathSync as realpathSync6 } from "node:fs";
11332
11782
  import { basename as basename22, dirname as dirname42, isAbsolute as isAbsolute32, join as join42, resolve as resolve42 } from "node:path";
11333
- import { existsSync as existsSync32, readdirSync as readdirSync7, unlinkSync as unlinkSync32 } from "node:fs";
11783
+ import { existsSync as existsSync32, readdirSync as readdirSync8, unlinkSync as unlinkSync32 } from "node:fs";
11334
11784
  import { basename as basename32, isAbsolute as isAbsolute42, join as join52, resolve as resolve52, sep as sep3 } from "node:path";
11335
- import { existsSync as existsSync42, mkdirSync as mkdirSync32, readFileSync as readFileSync42 } from "node:fs";
11336
- import { isAbsolute as isAbsolute52, join as join62 } from "node:path";
11785
+ import { existsSync as existsSync42, mkdirSync as mkdirSync32, readFileSync as readFileSync42, readdirSync as readdirSync22, rmdirSync as rmdirSync22 } from "node:fs";
11786
+ import { isAbsolute as isAbsolute52, join as join62, resolve as resolve62 } from "node:path";
11337
11787
  import { createHash as createHash22 } from "node:crypto";
11338
11788
  import { basename as basename62, dirname as dirname72 } from "node:path";
11339
11789
  import { execFileSync as execFileSync22 } from "node:child_process";
11340
11790
  import { existsSync as existsSync92, realpathSync as realpathSync42 } from "node:fs";
11341
- import { isAbsolute as isAbsolute72, join as join112, resolve as resolve92 } from "node:path";
11342
- import { mkdirSync as mkdirSync62, readdirSync as readdirSync62, readFileSync as readFileSync92, realpathSync as realpathSync52, statSync as statSync42, writeFileSync as writeFileSync42 } from "node:fs";
11343
- import { basename as basename72, dirname as dirname92, isAbsolute as isAbsolute82, join as join132, relative as relative32, resolve as resolve102 } from "node:path";
11344
- import { copyFileSync, mkdirSync as mkdirSync72, readFileSync as readFileSync102, readdirSync as readdirSync72, writeFileSync as writeFileSync52 } from "node:fs";
11345
- import { basename as basename9, dirname as dirname11, isAbsolute as isAbsolute92, join as join15, relative as relative5, resolve as resolve12, sep as sep32 } from "node:path";
11791
+ import { isAbsolute as isAbsolute72, join as join112, resolve as resolve102 } from "node:path";
11792
+ import { mkdirSync as mkdirSync62, readdirSync as readdirSync72, readFileSync as readFileSync92, realpathSync as realpathSync52, statSync as statSync42, writeFileSync as writeFileSync42 } from "node:fs";
11793
+ import { basename as basename72, dirname as dirname92, isAbsolute as isAbsolute82, join as join132, relative as relative32, resolve as resolve112 } from "node:path";
11794
+ import { mkdirSync as mkdirSync72, readFileSync as readFileSync102, readdirSync as readdirSync82, writeFileSync as writeFileSync52 } from "node:fs";
11795
+ import { basename as basename9, dirname as dirname11, isAbsolute as isAbsolute92, join as join15, relative as relative5, resolve as resolve13, sep as sep32 } from "node:path";
11346
11796
  import { execFileSync as execFileSync52 } from "node:child_process";
11347
11797
  import { randomUUID as randomUUID22 } from "node:crypto";
11348
11798
  import { existsSync as existsSync152, mkdirSync as mkdirSync92, readFileSync as readFileSync132, statSync as statSync62, unlinkSync as unlinkSync42, writeFileSync as writeFileSync72 } from "node:fs";
11349
- import { basename as basename122, dirname as dirname122, isAbsolute as isAbsolute122, join as join202, resolve as resolve152, sep as sep62 } from "node:path";
11799
+ import { basename as basename122, dirname as dirname122, isAbsolute as isAbsolute122, join as join202, resolve as resolve162, sep as sep62 } from "node:path";
11350
11800
  var SEVERITY_ORDER2 = ["critical", "high", "medium", "low", "nit"];
11351
11801
  function readJson2(filePath) {
11352
11802
  if (!existsSync11(filePath))
@@ -11376,7 +11826,7 @@ function writeJson2(filePath, value) {
11376
11826
  }
11377
11827
  }
11378
11828
  function resolveProjectRoot(startDir = process.cwd()) {
11379
- const start = resolve11(startDir);
11829
+ const start = resolve12(startDir);
11380
11830
  let dir = start;
11381
11831
  for (;; ) {
11382
11832
  if (existsSync11(join8(dir, "package.json")) || existsSync11(join8(dir, "bun.lock")))
@@ -11390,7 +11840,7 @@ function resolveProjectRoot(startDir = process.cwd()) {
11390
11840
  function findRootPackageJson(startDir) {
11391
11841
  let dir = startDir;
11392
11842
  for (;; ) {
11393
- const candidate = resolve11(dir, "package.json");
11843
+ const candidate = resolve12(dir, "package.json");
11394
11844
  try {
11395
11845
  const pkg = JSON.parse(readFileSync10(candidate, "utf8"));
11396
11846
  if (pkg.name === "morning-star")
@@ -11741,7 +12191,7 @@ async function withStatusWriteLock2(statusPath, fn, opts = {}) {
11741
12191
  try {
11742
12192
  unlinkSync22(join32(lockDir, LOCKDIR_HOLDER_PID2));
11743
12193
  } catch {}
11744
- rmdirSync3(lockDir);
12194
+ rmdirSync4(lockDir);
11745
12195
  }
11746
12196
  } catch {}
11747
12197
  }
@@ -12161,7 +12611,7 @@ function listJsonKeys2(dir) {
12161
12611
  }
12162
12612
  function readDirEntries2(dir) {
12163
12613
  try {
12164
- return readdirSync7(dir, { withFileTypes: true });
12614
+ return readdirSync8(dir, { withFileTypes: true });
12165
12615
  } catch (error) {
12166
12616
  const code = error.code;
12167
12617
  if (code === "ENOENT" || code === "ENOTDIR")
@@ -12285,6 +12735,8 @@ var WORKFLOW_SNAPSHOT_FILE2 = "snapshot.json";
12285
12735
  var WORKFLOW_LIFECYCLE_STATUSES2 = ["running", "paused", "completed", "failed", "stopped"];
12286
12736
  var WORKFLOW_TERMINAL_STATUSES2 = ["completed", "failed", "stopped"];
12287
12737
  var WORKFLOW_LIFECYCLE_TYPES2 = ["plan", "iteration"];
12738
+ var WORKFLOW_DELIVERY_KINDS2 = ["development", "verification/report-only"];
12739
+ var WORKFLOW_COMPOUND_OUTCOMES2 = ["created", "updated", "skipped"];
12288
12740
  function stableJson2(value) {
12289
12741
  if (Array.isArray(value))
12290
12742
  return `[${value.map(stableJson2).join(",")}]`;
@@ -12309,6 +12761,61 @@ function validateWorktreePathValue2(violations, value, field) {
12309
12761
  violations.push(violation32("high", "workflow.snapshot.invalid-integration-worktree-path", `${field} must be a non-empty absolute path \u2014 got ${JSON.stringify(value)}`, "record the absolute integration checkout path (integration_worktree_path)"));
12310
12762
  }
12311
12763
  }
12764
+ function deliveryEvidenceViolations2(value, what) {
12765
+ const violations = [];
12766
+ const invalid22 = (message) => {
12767
+ violations.push(violation32("medium", "workflow.snapshot.invalid-delivery-evidence", `${what}: ${message}`));
12768
+ };
12769
+ if (!isPlainObject22(value)) {
12770
+ invalid22("must be an object");
12771
+ return violations;
12772
+ }
12773
+ const members = ["compound", "pr", "merge", "completion"];
12774
+ const unknownMembers = Object.keys(value).filter((key) => !members.includes(key));
12775
+ if (unknownMembers.length > 0)
12776
+ invalid22(`unknown member(s) ${unknownMembers.join(", ")} \u2014 expected ${members.join(" | ")}`);
12777
+ const compound = value.compound;
12778
+ if (compound !== undefined) {
12779
+ if (!isPlainObject22(compound))
12780
+ invalid22("compound must be an object");
12781
+ else {
12782
+ const unknown = Object.keys(compound).filter((key) => key !== "outcome" && key !== "reason");
12783
+ if (unknown.length > 0)
12784
+ invalid22(`compound has unknown key(s) ${unknown.join(", ")}`);
12785
+ if (typeof compound.outcome !== "string" || !WORKFLOW_COMPOUND_OUTCOMES2.includes(compound.outcome)) {
12786
+ invalid22(`compound.outcome must be one of ${WORKFLOW_COMPOUND_OUTCOMES2.join(" | ")} \u2014 got ${JSON.stringify(compound.outcome)}`);
12787
+ } else if (compound.outcome === "skipped" && (typeof compound.reason !== "string" || compound.reason.trim() === "")) {
12788
+ invalid22("compound reason is required when the disposition outcome is 'skipped' (contract \u00a74c)");
12789
+ } else if (compound.reason !== undefined && (typeof compound.reason !== "string" || compound.reason.trim() === "")) {
12790
+ invalid22("compound.reason must be a non-empty string when given");
12791
+ }
12792
+ }
12793
+ }
12794
+ const stringMembers = {
12795
+ pr: ["repo", "head", "target"],
12796
+ merge: ["provider", "evidence"],
12797
+ completion: ["policy", "evidence"]
12798
+ };
12799
+ for (const member of ["pr", "merge", "completion"]) {
12800
+ const block = value[member];
12801
+ if (block === undefined)
12802
+ continue;
12803
+ if (!isPlainObject22(block)) {
12804
+ invalid22(`${member} must be an object`);
12805
+ continue;
12806
+ }
12807
+ const fields = stringMembers[member];
12808
+ const unknown = Object.keys(block).filter((key) => !fields.includes(key));
12809
+ if (unknown.length > 0)
12810
+ invalid22(`${member} has unknown key(s) ${unknown.join(", ")}`);
12811
+ for (const field of fields) {
12812
+ if (typeof block[field] !== "string" || block[field].trim() === "") {
12813
+ invalid22(`${member}.${field} must be a non-empty string`);
12814
+ }
12815
+ }
12816
+ }
12817
+ return violations;
12818
+ }
12312
12819
  function validateWorkflowSnapshot2(doc) {
12313
12820
  const violations = [];
12314
12821
  if (!isPlainObject22(doc)) {
@@ -12374,7 +12881,7 @@ function validateWorkflowSnapshot2(doc) {
12374
12881
  if (!isPlainObject22(doc.branch)) {
12375
12882
  violations.push(violation32("medium", "workflow.snapshot.invalid-branch", "branch must be an object"));
12376
12883
  } else {
12377
- for (const key of ["base", "integration", "target"]) {
12884
+ for (const key of ["base", "source", "integration", "target"]) {
12378
12885
  if (doc.branch[key] !== undefined && (typeof doc.branch[key] !== "string" || doc.branch[key].trim() === "")) {
12379
12886
  violations.push(violation32("medium", "workflow.snapshot.invalid-branch", `branch.${key} must be a non-empty string`));
12380
12887
  }
@@ -12400,6 +12907,20 @@ function validateWorkflowSnapshot2(doc) {
12400
12907
  if (doc.compass_ref !== undefined) {
12401
12908
  validateNonEmptyString22(violations, doc.compass_ref, "compass_ref", "workflow.snapshot.missing-compass-ref", "workflow.snapshot.invalid-compass-ref");
12402
12909
  }
12910
+ if (doc.delivery_kind !== undefined) {
12911
+ if (typeof doc.delivery_kind !== "string" || !WORKFLOW_DELIVERY_KINDS2.includes(doc.delivery_kind)) {
12912
+ violations.push(violation32("medium", "workflow.snapshot.invalid-delivery-kind", `delivery_kind must be one of ${WORKFLOW_DELIVERY_KINDS2.join(" | ")} \u2014 got ${JSON.stringify(doc.delivery_kind)}`));
12913
+ }
12914
+ }
12915
+ if (doc.project !== undefined) {
12916
+ validateNonEmptyString22(violations, doc.project, "project", "workflow.snapshot.missing-project", "workflow.snapshot.invalid-project");
12917
+ }
12918
+ if (doc.completion_policy !== undefined) {
12919
+ validateNonEmptyString22(violations, doc.completion_policy, "completion_policy", "workflow.snapshot.missing-completion-policy", "workflow.snapshot.invalid-completion-policy");
12920
+ }
12921
+ if (doc.delivery !== undefined) {
12922
+ violations.push(...deliveryEvidenceViolations2(doc.delivery, "delivery"));
12923
+ }
12403
12924
  const terminal = typeof doc.status === "string" && WORKFLOW_TERMINAL_STATUSES2.includes(doc.status);
12404
12925
  if (terminal) {
12405
12926
  if (doc.ended_at === undefined) {
@@ -12519,6 +13040,22 @@ function mergePhaseProjection2(stored, incoming) {
12519
13040
  }
12520
13041
  return next;
12521
13042
  }
13043
+ function nonEmptyString2(value) {
13044
+ return typeof value === "string" && value.trim() !== "";
13045
+ }
13046
+ function assertDeliveryRegistrationCoherence2(kind, evidence, what) {
13047
+ if (kind === "development" && (!nonEmptyString2(evidence.branchSource) || !nonEmptyString2(evidence.branchTarget))) {
13048
+ throw new Error(`${what}: a development workflow requires its delivery source and target branches (--branch-source/--branch-target) \u2014 missing branch fields are incomplete registration, not an exempt workflow (contract \u00a71/\u00a74a)`);
13049
+ }
13050
+ if (kind === "verification/report-only" && !nonEmptyString2(evidence.completionPolicy)) {
13051
+ throw new Error(`${what}: a verification/report-only workflow requires the completion policy (--completion-policy) naming the evidence that completes it (contract \u00a71)`);
13052
+ }
13053
+ for (const [field, value] of Object.entries({ branchSource: evidence.branchSource, branchTarget: evidence.branchTarget, completionPolicy: evidence.completionPolicy })) {
13054
+ if (value !== undefined && !nonEmptyString2(value)) {
13055
+ throw new Error(`${what}: ${field} must be a non-empty string when given`);
13056
+ }
13057
+ }
13058
+ }
12522
13059
  var DATE_RE4 = /^\d{4}-\d{2}-\d{2}$/;
12523
13060
  function rowPlanIds2(row) {
12524
13061
  if (!isPlainObject22(row))
@@ -12682,7 +13219,7 @@ function validateStatusV22(docOrPath, opts = {}) {
12682
13219
  if (typeof docOrPath === "string") {
12683
13220
  try {
12684
13221
  doc = readJson2(docOrPath);
12685
- harnessDir = dirname52(resolve62(docOrPath));
13222
+ harnessDir = dirname52(resolve72(docOrPath));
12686
13223
  } catch (error) {
12687
13224
  return {
12688
13225
  ok: false,
@@ -12940,14 +13477,14 @@ function findingsCleanupGate2(register, planId, opts) {
12940
13477
  return { ok: violations.length === 0, violations };
12941
13478
  }
12942
13479
  function resolveHarnessDir2(startDir = process.cwd(), opts = {}) {
12943
- const start = resolve82(startDir);
13480
+ const start = resolve92(startDir);
12944
13481
  const explicit = opts.harnessDir ?? process.env.MSTAR_HARNESS_DIR;
12945
13482
  if (explicit)
12946
- return resolve82(start, explicit);
12947
- const boundary = resolve82(start, opts.workspaceRoot ?? defaultWorkspaceRoot2(start));
13483
+ return resolve92(start, explicit);
13484
+ const boundary = resolve92(start, opts.workspaceRoot ?? defaultWorkspaceRoot2(start));
12948
13485
  const rc = loadMstarc2(start, boundary);
12949
13486
  if (rc !== null && rc.config.harnessDir)
12950
- return resolve82(rc.dir, rc.config.harnessDir);
13487
+ return resolve92(rc.dir, rc.config.harnessDir);
12951
13488
  let dir = start;
12952
13489
  for (;; ) {
12953
13490
  if (!isAtOrBelow22(dir, boundary))
@@ -12978,7 +13515,7 @@ function defaultWorkspaceRoot2(startDir) {
12978
13515
  if (segment && segment !== ".")
12979
13516
  boundary = dirname62(boundary);
12980
13517
  }
12981
- return resolve82(boundary);
13518
+ return resolve92(boundary);
12982
13519
  } catch {}
12983
13520
  return startDir;
12984
13521
  }
@@ -12987,16 +13524,16 @@ function isAtOrBelow22(dir, root) {
12987
13524
  return rel === "" || !rel.startsWith("..") && !isAbsolute62(rel);
12988
13525
  }
12989
13526
  function mstarcDirOverride2(harnessDir, key) {
12990
- const dir = resolve82(harnessDir);
13527
+ const dir = resolve92(harnessDir);
12991
13528
  const rc = loadMstarc2(dir, dirname62(dir));
12992
13529
  const declared = rc?.config[key];
12993
- return declared ? resolve82(rc.dir, declared) : null;
13530
+ return declared ? resolve92(rc.dir, declared) : null;
12994
13531
  }
12995
13532
  function resolvePlanDir2(harnessDir) {
12996
13533
  const declared = mstarcDirOverride2(harnessDir, "planDir");
12997
13534
  if (declared !== null)
12998
13535
  return declared;
12999
- const dir = resolve82(harnessDir);
13536
+ const dir = resolve92(harnessDir);
13000
13537
  const name = basename52(dir);
13001
13538
  if (name === ".plans" || name === "plans")
13002
13539
  return dir;
@@ -13008,7 +13545,7 @@ function assertSafePathComponent2(value, what) {
13008
13545
  }
13009
13546
  }
13010
13547
  function canonicalizeNearestExisting2(path2) {
13011
- const abs = resolve82(path2);
13548
+ const abs = resolve92(path2);
13012
13549
  let dir = abs;
13013
13550
  const tail = [];
13014
13551
  for (;; ) {
@@ -13028,7 +13565,7 @@ function canonicalizeNearestExisting2(path2) {
13028
13565
  }
13029
13566
  function resolveSddDir2(harnessDir, planId) {
13030
13567
  assertSafePathComponent2(planId, "planId");
13031
- const base = resolve82(harnessDir);
13568
+ const base = resolve92(harnessDir);
13032
13569
  const declared = mstarcDirOverride2(base, "sddDir");
13033
13570
  const sddBase = declared !== null ? declared : join102(base, "sdd");
13034
13571
  return join102(sddBase, planId);
@@ -13036,10 +13573,10 @@ function resolveSddDir2(harnessDir, planId) {
13036
13573
  function resolveHarnessSubdir2(startDir, opts, key, fallback) {
13037
13574
  const harness = resolveHarnessDir2(startDir, opts);
13038
13575
  if (harness === null) {
13039
- throw new Error(`harness dir not found from ${resolve82(startDir)} \u2014 cannot resolve the ${fallback} dir (run \`mstar harness scaffold\`, pass opts.harnessDir, or set MSTAR_HARNESS_DIR)`);
13576
+ throw new Error(`harness dir not found from ${resolve92(startDir)} \u2014 cannot resolve the ${fallback} dir (run \`mstar harness scaffold\`, pass opts.harnessDir, or set MSTAR_HARNESS_DIR)`);
13040
13577
  }
13041
13578
  const declared = mstarcDirOverride2(harness, key);
13042
- return declared !== null ? declared : join102(resolve82(harness), fallback);
13579
+ return declared !== null ? declared : join102(resolve92(harness), fallback);
13043
13580
  }
13044
13581
  function resolveWorkflowDir2(startDir = process.cwd(), opts = {}) {
13045
13582
  return resolveHarnessSubdir2(startDir, opts, "workflowDir", "workflows");
@@ -13073,7 +13610,7 @@ var GITIGNORE_PROCESS_ENTRIES2 = GITIGNORE_SNIPPET2.split(`
13073
13610
  var GITIGNORE_PROCESS_ENTRIES_AGENTS2 = GITIGNORE_SNIPPET_AGENTS2.split(`
13074
13611
  `).filter((line) => line.startsWith(".agents/") || line.startsWith("!.agents/")).map((line) => line.trim());
13075
13612
  function assertPlanWritingPath2(planPath, harnessDir) {
13076
- const planAbs = resolve82(planPath);
13613
+ const planAbs = resolve92(planPath);
13077
13614
  if (!harnessDir) {
13078
13615
  return {
13079
13616
  ok: false,
@@ -13098,7 +13635,7 @@ function assertPlanWritingPath2(planPath, harnessDir) {
13098
13635
  if (existsSync82(planAbs)) {
13099
13636
  try {
13100
13637
  const canonicalPlan = realpathSync32(planAbs);
13101
- const canonicalPlanDir = existsSync82(planDir) ? realpathSync32(planDir) : resolve82(planDir);
13638
+ const canonicalPlanDir = existsSync82(planDir) ? realpathSync32(planDir) : resolve92(planDir);
13102
13639
  const canonicalRel = relative22(canonicalPlanDir, canonicalPlan);
13103
13640
  const canonicalInside = canonicalRel === "" || !canonicalRel.startsWith("..") && !isAbsolute62(canonicalRel);
13104
13641
  if (!canonicalInside) {
@@ -14259,7 +14796,7 @@ function l1PreDispatchCheck2(input, opts = {}) {
14259
14796
  const violations = [];
14260
14797
  const checkoutCache = new Map;
14261
14798
  const checkout = (path2) => {
14262
- const key = resolve92(path2);
14799
+ const key = resolve102(path2);
14263
14800
  if (!checkoutCache.has(key))
14264
14801
  checkoutCache.set(key, probeCheckout2(path2, opts));
14265
14802
  return checkoutCache.get(key);
@@ -14310,7 +14847,7 @@ function l1PreDispatchCheck2(input, opts = {}) {
14310
14847
  }
14311
14848
  }
14312
14849
  const identityViolation = (aPath, bPath, code, describe, fix) => {
14313
- if (resolve92(aPath) === resolve92(bPath)) {
14850
+ if (resolve102(aPath) === resolve102(bPath)) {
14314
14851
  return violation82("critical", code, `${describe} \u2014 the same checkout (normalized path equality) is not isolation`, fix);
14315
14852
  }
14316
14853
  if (!existsSync92(aPath) || !existsSync92(bPath))
@@ -14468,24 +15005,28 @@ function normalizeSnapshotWorktreePath2(doc) {
14468
15005
  const { control_worktree_path: _dropped, ...rest } = doc;
14469
15006
  return { ...rest, integration_worktree_path: legacy };
14470
15007
  }
14471
- function readActiveWorkflowIds2(controlHarnessRoot) {
15008
+ function classifyWorkflowRegisterState2(controlHarnessRoot) {
14472
15009
  const statusPath = join132(controlHarnessRoot, "status.json");
14473
15010
  if (!isFile22(statusPath))
14474
- return null;
15011
+ return { state: "absent" };
14475
15012
  let doc;
14476
15013
  try {
14477
15014
  doc = readJson2(statusPath);
14478
15015
  } catch {
14479
- return null;
15016
+ return { state: "unreadable" };
14480
15017
  }
14481
15018
  if (!isPlainObject72(doc) || doc.version !== 2 || !Array.isArray(doc.workflows))
14482
- return null;
14483
- const ids = new Set;
15019
+ return { state: "unreadable" };
15020
+ const activeIds = new Set;
14484
15021
  for (const entry of doc.workflows) {
14485
15022
  if (isPlainObject72(entry) && typeof entry.id === "string")
14486
- ids.add(entry.id);
15023
+ activeIds.add(entry.id);
14487
15024
  }
14488
- return ids;
15025
+ return { state: "readable", activeIds };
15026
+ }
15027
+ function readActiveWorkflowIds2(controlHarnessRoot) {
15028
+ const register = classifyWorkflowRegisterState2(controlHarnessRoot);
15029
+ return register.state === "readable" ? register.activeIds : null;
14489
15030
  }
14490
15031
  function findWorkflowPlanRow2(controlHarnessRoot, planId) {
14491
15032
  let workflowsDir;
@@ -14498,7 +15039,7 @@ function findWorkflowPlanRow2(controlHarnessRoot, planId) {
14498
15039
  return { kind: "none" };
14499
15040
  let workflowIds;
14500
15041
  try {
14501
- workflowIds = readdirSync62(workflowsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
15042
+ workflowIds = readdirSync72(workflowsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
14502
15043
  } catch {
14503
15044
  return { kind: "none" };
14504
15045
  }
@@ -14634,6 +15175,12 @@ function resolveSddExecutionContext2(input) {
14634
15175
  contextViolation2("critical", "sdd.context.feature-in-control", `featureCwd "${canonicalFeatureCwd}" is inside the control checkout "${controlCheckout}" and is not a distinct Git checkout \u2014 a plain subdirectory or symlink alias of the control checkout is not isolation; product edits never land in the control checkout (execution_lease.worktree_path MUST be a distinct checkout)`, "use a distinct feature worktree for the plan (git worktree add <path> <branch>)")
14635
15176
  ]);
14636
15177
  }
15178
+ const registerState = classifyWorkflowRegisterState2(canonicalControlHarnessRoot);
15179
+ if (registerState.state === "unreadable") {
15180
+ throwGateFail2([
15181
+ contextViolation2("critical", "sdd.context.register-unreadable", `control harness root "${canonicalControlHarnessRoot}" has a status.json that is present but not a readable v2 workflow register (malformed JSON, non-v2 version, or missing workflows[]) \u2014 ` + 'a damaged register is never treated as "no register": registered active lifecycles cannot be resolved over it, so execution is refused (plan-workflow-lifecycle contract \u00a76 S2) instead of silently continuing on branch alignment alone', "repair or migrate the control root's status.json to the v2 shape ('mstar migrate' / register repair), then retry the execution")
15182
+ ]);
15183
+ }
14637
15184
  const match = findWorkflowPlanRow2(canonicalControlHarnessRoot, planId);
14638
15185
  if (match.kind === "ambiguous") {
14639
15186
  throwGateFail2([
@@ -14676,6 +15223,11 @@ function resolveSddExecutionContext2(input) {
14676
15223
  } else if (match.kind === "row" && match.row.status === "InProgress") {
14677
15224
  throwGateFail2(verifyPlanExecutionLease2(match.row, planId).violations);
14678
15225
  } else {
15226
+ if (match.kind === "none" && registerState.state === "readable") {
15227
+ throwGateFail2([
15228
+ contextViolation2("high", "sdd.context.plan-not-registered", `plan "${planId}" has no active registered workflow row in the control harness's workflow register \u2014 ` + "on the normal plan route, SDD execution requires a registered running workflow row (plan-workflow-lifecycle contract \u00a76 S2; a retained terminal snapshot's row is history, never registration evidence): " + `register it with \`mstar workflow register --workflow <id> --plan-id <id> --plan-title <title> --plan-file <path> --delivery-kind <${WORKFLOW_DELIVERY_KINDS2.join("|")}> ...` + "` (`registerPlanWorkflow`), then retry \u2014 registration is create-only and preserves prior state; " + "re-running the same register command completes an interrupted registration without duplicating identity", "register the plan workflow, then retry the execution")
15229
+ ]);
15230
+ }
14679
15231
  const branchGate = assertBranchAlignment2(canonicalFeatureCwd, workingBranch);
14680
15232
  if (!branchGate.ok)
14681
15233
  throwGateFail2(branchGate.violations);
@@ -14705,11 +15257,11 @@ function checkSddAction2(context, action) {
14705
15257
  const featureReal = canonicalDir2(context.featureCwd);
14706
15258
  const canonicalSddDir = canonicalizeNearestExisting2(context.sddDir);
14707
15259
  const canonicalPlanFile = canonicalizeNearestExisting2(context.planFile);
14708
- const cwdResolved = resolve102(action.cwd);
15260
+ const cwdResolved = resolve112(action.cwd);
14709
15261
  const checkTarget = (baseDir, target, kind) => {
14710
15262
  if (featureReal === null)
14711
15263
  return;
14712
- const targetAbs = resolve102(baseDir, target);
15264
+ const targetAbs = resolve112(baseDir, target);
14713
15265
  const canonical = canonicalizeNearestExisting2(targetAbs);
14714
15266
  if (!isInside2(canonical, featureReal)) {
14715
15267
  const declaredPrefix = targetAbs === featureReal || targetAbs.startsWith(`${featureReal}/`);
@@ -14737,10 +15289,10 @@ function checkSddAction2(context, action) {
14737
15289
  add("sdd.context.target-missing", "artifact checks require the destination target");
14738
15290
  return { ok: false, violations };
14739
15291
  }
14740
- const targetAbs = resolve102(cwdResolved, action.target);
15292
+ const targetAbs = resolve112(cwdResolved, action.target);
14741
15293
  const canonical = canonicalizeNearestExisting2(targetAbs);
14742
15294
  if (!isInside2(canonical, canonicalSddDir) && canonical !== canonicalPlanFile) {
14743
- const rawSddDir = resolve102(context.sddDir);
15295
+ const rawSddDir = resolve112(context.sddDir);
14744
15296
  const declaredPrefix = targetAbs === rawSddDir || targetAbs.startsWith(`${rawSddDir}/`) || targetAbs === canonicalSddDir || targetAbs.startsWith(`${canonicalSddDir}/`) || targetAbs === canonicalPlanFile;
14745
15297
  if (declaredPrefix) {
14746
15298
  add("sdd.context.artifact-symlink-escape", `artifact target "${targetAbs}" canonicalizes to "${canonical}", outside the plan's control sddDir \u2014 symlink escape refused before write`);
@@ -14803,7 +15355,7 @@ function scanCompasses(harnessDir) {
14803
15355
  const out = [];
14804
15356
  let entries;
14805
15357
  try {
14806
- entries = readdirSync72(iterationsDir, { withFileTypes: true });
15358
+ entries = readdirSync82(iterationsDir, { withFileTypes: true });
14807
15359
  } catch {
14808
15360
  return out;
14809
15361
  }
@@ -14895,7 +15447,7 @@ function buildIterationSnapshot(compass, rowById, rootUpdatedAt) {
14895
15447
  data: snapshot
14896
15448
  };
14897
15449
  }
14898
- function buildStandaloneSnapshot(row, rootUpdatedAt, migrationNotes) {
15450
+ function buildStandaloneSnapshot(row, rootUpdatedAt, migrationNotes, declaration = {}) {
14899
15451
  const id = rowIdOf(row) ?? "<unnamed>";
14900
15452
  const statusValue = row.status;
14901
15453
  let status;
@@ -14922,6 +15474,17 @@ function buildStandaloneSnapshot(row, rootUpdatedAt, migrationNotes) {
14922
15474
  updated_at: status === "completed" ? endedAt : updatedAt,
14923
15475
  plans: [row]
14924
15476
  };
15477
+ if (status !== "completed" && declaration.deliveryKind !== undefined) {
15478
+ snapshot.delivery_kind = declaration.deliveryKind;
15479
+ if (declaration.branchSource !== undefined || declaration.branchTarget !== undefined) {
15480
+ snapshot.branch = {
15481
+ ...declaration.branchSource !== undefined ? { source: declaration.branchSource } : {},
15482
+ ...declaration.branchTarget !== undefined ? { target: declaration.branchTarget } : {}
15483
+ };
15484
+ }
15485
+ if (declaration.completionPolicy !== undefined)
15486
+ snapshot.completion_policy = declaration.completionPolicy;
15487
+ }
14925
15488
  return {
14926
15489
  id,
14927
15490
  type: "plan",
@@ -15073,10 +15636,22 @@ function collectNotesFiles(snapshots) {
15073
15636
  return out;
15074
15637
  }
15075
15638
  function migrateHarnessTree(root, opts = {}) {
15076
- const harnessDir = resolve12(root);
15639
+ const harnessDir = resolve13(root);
15077
15640
  const workflowDir = resolveWorkflowDir2(harnessDir, { harnessDir });
15078
15641
  const projectDir = resolveProjectDir2(harnessDir, { harnessDir });
15079
15642
  const projectId = opts.projectId ?? _DEFAULT_PROJECT2;
15643
+ if (opts.deliveryKind !== undefined && !WORKFLOW_DELIVERY_KINDS2.includes(opts.deliveryKind)) {
15644
+ throw new Error(`refusing to migrate: options.deliveryKind must be one of ${WORKFLOW_DELIVERY_KINDS2.join(" | ")} \u2014 got ${JSON.stringify(opts.deliveryKind)}`);
15645
+ }
15646
+ if (opts.deliveryKind !== undefined) {
15647
+ assertDeliveryRegistrationCoherence2(opts.deliveryKind, opts, "migrate");
15648
+ }
15649
+ const declaration = {
15650
+ deliveryKind: opts.deliveryKind,
15651
+ branchSource: opts.branchSource,
15652
+ branchTarget: opts.branchTarget,
15653
+ completionPolicy: opts.completionPolicy
15654
+ };
15080
15655
  const statusPath = join15(harnessDir, MIGRATE_STATUS_FILE);
15081
15656
  const source = readArtifactBytes2(statusPath);
15082
15657
  const sourceVersion = source?.version ?? "absent";
@@ -15092,6 +15667,8 @@ function migrateHarnessTree(root, opts = {}) {
15092
15667
  alreadyMigrated: true,
15093
15668
  message: `no-op: ${statusPath} is already at schema version 2 (migrated) \u2014 nothing to do`,
15094
15669
  snapshots: [],
15670
+ deliveryKindRequired: [],
15671
+ deliveryKindAmbiguous: [],
15095
15672
  notesFiles: [],
15096
15673
  register: null,
15097
15674
  roadmap: null,
@@ -15142,8 +15719,11 @@ function migrateHarnessTree(root, opts = {}) {
15142
15719
  for (const row of rows) {
15143
15720
  const id = rowIdOf(row);
15144
15721
  if (id !== null && !byPlan.has(id))
15145
- snapshots.push(buildStandaloneSnapshot(row, rootUpdatedAt, migrationNotes));
15722
+ snapshots.push(buildStandaloneSnapshot(row, rootUpdatedAt, migrationNotes, declaration));
15146
15723
  }
15724
+ const deliveryKindRequired = snapshots.filter((snapshot) => snapshot.type === "plan" && snapshot.status !== "completed" && snapshot.data.delivery_kind === undefined).map((snapshot) => snapshot.id);
15725
+ const declaredKindTargets = declaration.deliveryKind === undefined ? [] : snapshots.filter((snapshot) => snapshot.type === "plan" && snapshot.status !== "completed" && snapshot.data.delivery_kind !== undefined).map((snapshot) => snapshot.id).sort(compareIds);
15726
+ const deliveryKindAmbiguous = declaredKindTargets.length > 1 ? declaredKindTargets : [];
15147
15727
  const lifecycleSources = new Map;
15148
15728
  for (const snapshot of snapshots) {
15149
15729
  const sources = lifecycleSources.get(snapshot.id) ?? [];
@@ -15213,6 +15793,8 @@ function migrateHarnessTree(root, opts = {}) {
15213
15793
  alreadyMigrated: false,
15214
15794
  message: `planned migration of ${snapshots.length} lifecycles (${steps.length} steps)`,
15215
15795
  snapshots,
15796
+ deliveryKindRequired,
15797
+ deliveryKindAmbiguous,
15216
15798
  notesFiles,
15217
15799
  register,
15218
15800
  roadmap,
@@ -15226,14 +15808,20 @@ async function applyMigratePlan(plan) {
15226
15808
  if (plan.dryRun) {
15227
15809
  return { applied: false, message: `dry-run: ${plan.steps.length} steps planned (source \u2192 destination), zero writes` };
15228
15810
  }
15811
+ if (plan.deliveryKindAmbiguous.length > 0) {
15812
+ throw new Error(`refusing to apply migration: one delivery declaration cannot describe ${plan.deliveryKindAmbiguous.length} active standalone plan lifts (${plan.deliveryKindAmbiguous.join(", ")}) \u2014 ` + `migrate them in batches of one declared lifecycle (CLI: run migrate once per plan, each with its own --delivery-kind)`);
15813
+ }
15814
+ if (plan.deliveryKindRequired.length > 0) {
15815
+ throw new Error(`refusing to apply migration: ${plan.deliveryKindRequired.length} active standalone plan snapshot(s) (${plan.deliveryKindRequired.join(", ")}) would be lifted without a declared delivery kind \u2014 ` + `re-plan with an explicit deliveryKind (CLI: --delivery-kind <${WORKFLOW_DELIVERY_KINDS2.join("|")}>)`);
15816
+ }
15229
15817
  const statusPath = join15(plan.root, MIGRATE_STATUS_FILE);
15230
15818
  const current = readJson2(statusPath);
15231
15819
  if (current.version === 2) {
15232
15820
  return { applied: false, message: "no-op: status.json already at schema version 2 (migrated) \u2014 nothing to do" };
15233
15821
  }
15234
- const harnessRoot = resolve12(plan.root);
15235
- const workflowRoot = resolve12(plan.workflowDir);
15236
- const projectRoot = resolve12(plan.projectDir);
15822
+ const harnessRoot = resolve13(plan.root);
15823
+ const workflowRoot = resolve13(plan.workflowDir);
15824
+ const projectRoot = resolve13(plan.projectDir);
15237
15825
  if (!isAbsolute92(plan.workflowDir) || !isAbsolute92(plan.projectDir)) {
15238
15826
  throw new Error(`refusing to apply migration: plan workflowDir/projectDir must be absolute (got ${JSON.stringify(plan.workflowDir)} / ${JSON.stringify(plan.projectDir)})`);
15239
15827
  }
@@ -15245,7 +15833,7 @@ async function applyMigratePlan(plan) {
15245
15833
  ...plan.roadmap !== null ? [plan.roadmap.file] : []
15246
15834
  ];
15247
15835
  for (const destination of allDestinations) {
15248
- const resolvedDest = resolve12(join15(plan.root, destination));
15836
+ const resolvedDest = resolve13(join15(plan.root, destination));
15249
15837
  const inside = (dir) => resolvedDest === dir || resolvedDest.startsWith(`${dir}${sep32}`);
15250
15838
  if (!inside(harnessRoot) && !inside(workflowRoot) && !inside(projectRoot)) {
15251
15839
  throw new Error(`refusing to apply migration: destination escapes the harness dir (${JSON.stringify(destination)}) \u2014 every write must stay under ${JSON.stringify(plan.root)}, the workflow dir (${JSON.stringify(plan.workflowDir)}) or the project dir (${JSON.stringify(plan.projectDir)})`);
@@ -15254,6 +15842,32 @@ async function applyMigratePlan(plan) {
15254
15842
  const store = getArtifactStore2();
15255
15843
  return withStatusWriteLock2(statusPath, () => applyMigratePlanLocked(plan, statusPath, store, workflowRoot, projectRoot));
15256
15844
  }
15845
+ function rawTargetStoreError(filePath, error) {
15846
+ return new CoordinationError2("coordination.store", `cannot write migration target ${filePath}: ${error instanceof Error ? error.message : String(error)}`, { path: filePath });
15847
+ }
15848
+ function writeRawMigrateTarget(filePath, expected) {
15849
+ try {
15850
+ mkdirSync72(dirname11(filePath), { recursive: true });
15851
+ } catch (error) {
15852
+ throw rawTargetStoreError(filePath, error);
15853
+ }
15854
+ try {
15855
+ writeFileSync52(filePath, expected, { flag: "wx" });
15856
+ return;
15857
+ } catch (error) {
15858
+ if (error.code !== "EEXIST")
15859
+ throw rawTargetStoreError(filePath, error);
15860
+ }
15861
+ let existing;
15862
+ try {
15863
+ existing = readFileSync102(filePath);
15864
+ } catch (error) {
15865
+ throw rawTargetStoreError(filePath, error);
15866
+ }
15867
+ if (Buffer.compare(existing, expected) !== 0) {
15868
+ throw new CoordinationError2("coordination.version-conflict", `refusing to apply migration: ${filePath} already exists with different content \u2014 migration is additive-only`, { path: filePath });
15869
+ }
15870
+ }
15257
15871
  async function applyMigratePlanLocked(plan, statusPath, store, workflowRoot, projectRoot) {
15258
15872
  const workflowTargetOf = (canonicalFile) => join15(workflowRoot, relative5("workflows", canonicalFile));
15259
15873
  const projectTargetOf = (canonicalFile) => join15(projectRoot, relative5("projects", canonicalFile));
@@ -15266,8 +15880,7 @@ async function applyMigratePlanLocked(plan, statusPath, store, workflowRoot, pro
15266
15880
  if (sourceVersion !== plan.sourceVersion) {
15267
15881
  throw new CoordinationError2("coordination.version-conflict", `refusing to apply migration: ${statusPath} changed since the plan was built (planned ${plan.sourceVersion}, found ${sourceVersion}) \u2014 re-run the plan against the current root`, { path: statusPath, expected: plan.sourceVersion, actual: sourceVersion });
15268
15882
  }
15269
- mkdirSync72(join15(plan.root, dirname11(plan.archive.file)), { recursive: true });
15270
- copyFileSync(statusPath, join15(plan.root, plan.archive.file));
15883
+ writeRawMigrateTarget(join15(plan.root, plan.archive.file), readFileSync102(statusPath));
15271
15884
  for (const snapshot of plan.snapshots) {
15272
15885
  const snapshotDir = dirname11(workflowTargetOf(snapshot.file));
15273
15886
  const snapshotPath = join15(snapshotDir, WORKFLOW_SNAPSHOT_FILE2);
@@ -15281,12 +15894,10 @@ async function applyMigratePlanLocked(plan, statusPath, store, workflowRoot, pro
15281
15894
  }
15282
15895
  }
15283
15896
  for (const notes of plan.notesFiles) {
15284
- const filePath = workflowTargetOf(notes.file);
15285
- mkdirSync72(dirname11(filePath), { recursive: true });
15286
15897
  const content = notes.lines.length > 0 ? `${notes.lines.join(`
15287
15898
  `)}
15288
15899
  ` : "";
15289
- writeFileSync52(filePath, content, "utf8");
15900
+ writeRawMigrateTarget(workflowTargetOf(notes.file), Buffer.from(content, "utf8"));
15290
15901
  }
15291
15902
  if (plan.register !== null) {
15292
15903
  const registerData = plan.register.data;
@@ -15312,9 +15923,7 @@ async function applyMigratePlanLocked(plan, statusPath, store, workflowRoot, pro
15312
15923
  }
15313
15924
  }
15314
15925
  if (plan.roadmap !== null) {
15315
- const filePath = projectTargetOf(plan.roadmap.file);
15316
- mkdirSync72(dirname11(filePath), { recursive: true });
15317
- writeFileSync52(filePath, plan.roadmap.content, "utf8");
15926
+ writeRawMigrateTarget(projectTargetOf(plan.roadmap.file), Buffer.from(plan.roadmap.content, "utf8"));
15318
15927
  }
15319
15928
  const rootGate = validateStatusV22(plan.rootV2.data, { harnessDir: plan.root });
15320
15929
  if (!rootGate.ok) {
@@ -15439,7 +16048,7 @@ function localStore2(harnessRoot) {
15439
16048
  try {
15440
16049
  store = getArtifactStore2();
15441
16050
  } catch (error) {
15442
- throw new CoordinationError2("coordination.local-store-required", `no artifact store is resolvable from ${resolve152(process.cwd())} \u2014 scoped coordination requires createFsStore(<control harness root>): ${errorMessage2(error)}`, { harness_root: harnessRoot });
16051
+ throw new CoordinationError2("coordination.local-store-required", `no artifact store is resolvable from ${resolve162(process.cwd())} \u2014 scoped coordination requires createFsStore(<control harness root>): ${errorMessage2(error)}`, { harness_root: harnessRoot });
15443
16052
  }
15444
16053
  const root = "root" in store ? store.root : undefined;
15445
16054
  if (typeof root !== "string") {
@@ -15458,8 +16067,8 @@ function isWithin(parent, child) {
15458
16067
  }
15459
16068
  function resolveProcessHarnessDir2(cwd = process.cwd(), harnessDir) {
15460
16069
  if (isNonEmptyString2(harnessDir))
15461
- return resolve152(cwd, harnessDir);
15462
- const start = resolve152(cwd);
16070
+ return resolve162(cwd, harnessDir);
16071
+ const start = resolve162(cwd);
15463
16072
  const main = readMainWorktree2(start);
15464
16073
  if (main !== null)
15465
16074
  return resolveHarnessDir2(main.root);
@@ -15499,7 +16108,7 @@ var ASSIGNMENT_FIELDS = [
15499
16108
  ];
15500
16109
  var ABSOLUTE_PATH_HEADERS = ["control harness root", "plan path", "worktree path", "sdd dir"];
15501
16110
  function parseAssignmentFile(assignmentPath) {
15502
- const abs = resolve152(assignmentPath);
16111
+ const abs = resolve162(assignmentPath);
15503
16112
  if (!existsSync152(abs)) {
15504
16113
  throw new CoordinationError2("coordination.assignment-invalid", `Assignment not found: ${abs}`, { path: abs });
15505
16114
  }
@@ -15631,7 +16240,7 @@ function registerPathOf(harnessRoot, projectId) {
15631
16240
  }
15632
16241
  function scopeFromAssignment(assignment, cwd, options) {
15633
16242
  const harnessRoot = assignment.controlHarnessRoot;
15634
- const processRoot = resolveProcessHarnessDir2(cwd);
16243
+ const processRoot = options.chosenRoot === undefined ? resolveProcessHarnessDir2(cwd) : null;
15635
16244
  if (processRoot !== null && canonicalTarget2(processRoot) !== harnessRoot) {
15636
16245
  throw new CoordinationError2("coordination.scope-mismatch", `Assignment "Control harness root" ${harnessRoot} does not match the process harness root ${canonicalTarget2(processRoot)}`, { expected: harnessRoot, actual: canonicalTarget2(processRoot) });
15637
16246
  }
@@ -15698,7 +16307,7 @@ async function resolvePlanScope(input, cwd = process.cwd()) {
15698
16307
  }
15699
16308
  const harnessRoot = resolveProcessHarnessDir2(cwd, harnessDir);
15700
16309
  if (harnessRoot === null) {
15701
- throw new CoordinationError2("coordination.harness-not-found", `no harness root is resolvable from ${resolve152(cwd)} \u2014 pass the control harness root explicitly`, { cwd: resolve152(cwd) });
16310
+ throw new CoordinationError2("coordination.harness-not-found", `no harness root is resolvable from ${resolve162(cwd)} \u2014 pass the control harness root explicitly`, { cwd: resolve162(cwd) });
15702
16311
  }
15703
16312
  const snapshot = readSnapshot2(dirname122(snapshotPathOf(harnessRoot, workflowId)));
15704
16313
  const { row } = findPlanRow2(snapshot, planId);
@@ -15713,7 +16322,7 @@ function readSessionEnvelope2(sessionPath) {
15713
16322
  if (!isNonEmptyString2(sessionPath) || !isAbsolute122(sessionPath)) {
15714
16323
  throw invalidInput2("sessionPath must be an absolute path");
15715
16324
  }
15716
- const abs = resolve152(sessionPath);
16325
+ const abs = resolve162(sessionPath);
15717
16326
  if (!existsSync152(abs)) {
15718
16327
  throw new CoordinationError2("coordination.session-not-found", `session envelope not found: ${abs}`, { path: abs });
15719
16328
  }
@@ -16060,11 +16669,12 @@ function assertRootRegisterEntry(harnessRoot, workflowId) {
16060
16669
  if (entry === undefined) {
16061
16670
  throw new CoordinationError2("coordination.workflow-not-found", `workflow ${workflowId} is not an active entry of ${path2} (kind ${store.root})`, { path: path2, workflow_id: workflowId });
16062
16671
  }
16672
+ return entry;
16063
16673
  }
16064
16674
  function assertCoordinatorResidency(cwd, snapshot) {
16065
16675
  const main = readMainWorktree2(cwd);
16066
16676
  if (main === null) {
16067
- throw new CoordinationError2("coordination.not-in-git", `coordinator binding requires a Git process root \u2014 ${resolve152(cwd)} has no readable main worktree`, { cwd: resolve152(cwd) });
16677
+ throw new CoordinationError2("coordination.not-in-git", `coordinator binding requires a Git process root \u2014 ${resolve162(cwd)} has no readable main worktree`, { cwd: resolve162(cwd) });
16068
16678
  }
16069
16679
  const here = canonicalizeNearestExisting2(cwd);
16070
16680
  const allowed = [canonicalTarget2(main.root)];
@@ -16121,7 +16731,7 @@ async function bindCoordinatorSession(cwd, workflowId, harnessDir) {
16121
16731
  function requireProcessRoot(cwd, harnessDir) {
16122
16732
  const root = resolveProcessHarnessDir2(cwd, harnessDir);
16123
16733
  if (root === null) {
16124
- throw new CoordinationError2("coordination.harness-not-found", `no harness root is resolvable from ${resolve152(cwd)} \u2014 pass the control harness root explicitly`, { cwd: resolve152(cwd) });
16734
+ throw new CoordinationError2("coordination.harness-not-found", `no harness root is resolvable from ${resolve162(cwd)} \u2014 pass the control harness root explicitly`, { cwd: resolve162(cwd) });
16125
16735
  }
16126
16736
  return root;
16127
16737
  }
@@ -16636,7 +17246,10 @@ async function mutatePlanCoordination(request) {
16636
17246
  throw invalidInput2("prepare requires an absolute assignmentPath");
16637
17247
  }
16638
17248
  const assignment = parseAssignmentFile(operation.assignmentPath);
16639
- const scope = scopeFromAssignment(assignment, session.harness_root, { requirePrepared: false });
17249
+ const scope = scopeFromAssignment(assignment, session.harness_root, {
17250
+ requirePrepared: false,
17251
+ chosenRoot: session.harness_root
17252
+ });
16640
17253
  if (request.planId !== undefined && request.planId !== scope.planId) {
16641
17254
  throw new CoordinationError2("coordination.scope-mismatch", `request planId ${request.planId} is not the Assignment's plan ${scope.planId}`, { expected: scope.planId, actual: request.planId });
16642
17255
  }
@@ -16812,7 +17425,7 @@ function gitCheckout(path2) {
16812
17425
  let operation;
16813
17426
  for (const [marker, label] of UNFINISHED_GIT_OPERATIONS) {
16814
17427
  const markerPath = gitRead(path2, ["rev-parse", "--git-path", marker]);
16815
- if (markerPath !== undefined && markerPath.length > 0 && existsSync152(resolve152(path2, markerPath))) {
17428
+ if (markerPath !== undefined && markerPath.length > 0 && existsSync152(resolve162(path2, markerPath))) {
16816
17429
  operation = label;
16817
17430
  break;
16818
17431
  }
@@ -17523,21 +18136,639 @@ async function mutateReconcile(scope, session, sessionPath, request) {
17523
18136
  view: buildView(scope.harnessRoot, scope.workflowId, scope.projectId, scope, result.snapshot, result.row, session, sessionPath)
17524
18137
  };
17525
18138
  }
17526
- // src/sdd-evidence.ts
17527
- var import_picocolors = __toESM(require_picocolors2(), 1);
17528
- import { execFileSync as execFileSync7, spawn as spawn2 } from "node:child_process";
17529
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
17530
- import fs from "node:fs";
17531
- import fsp from "node:fs/promises";
17532
- import os from "node:os";
17533
- import { basename as basename8, delimiter, dirname as dirname10, isAbsolute as isAbsolute13, join as join14, relative as relative7, resolve as resolvePath } from "node:path";
17534
- import { performance } from "node:perf_hooks";
17535
- var EVIDENCE_SCHEMA2 = "mstar.sdd-evidence/v1";
17536
- var TIMEOUT_DEFAULT_MS2 = 600000;
17537
- var TIMEOUT_MIN_MS2 = 1;
17538
- var TIMEOUT_MAX_MS2 = 3600000;
17539
- var LOG_STREAM_CAP2 = 8388608;
17540
- var INPUT_BYTES_CAP2 = 536870912;
18139
+ var PREPARE_PHASE = "phase-1-prepare";
18140
+ var PREPARE_PATCH_KEYS = [
18141
+ "mainWorktreeBranch",
18142
+ "appendPlans",
18143
+ "integrationWorktreePath",
18144
+ "planParallelism"
18145
+ ];
18146
+ var PREPARE_APPEND_KEYS = ["id", "title", "file", "metadata"];
18147
+ var PREPARE_APPEND_METADATA_KEYS = [
18148
+ "primary_spec",
18149
+ "spec_refs",
18150
+ "iteration_compass",
18151
+ "iteration_refs",
18152
+ "working_branch",
18153
+ "spec_integration_branch",
18154
+ "merge_target"
18155
+ ];
18156
+ var PLAN_PARALLELISM_VALUES = ["serial", "parallel"];
18157
+ function prepareAmendmentRefusal(reason, message, details = {}) {
18158
+ const code = `coordination.prepare-amendment.${reason}`;
18159
+ return new CoordinationError2(code, message, details);
18160
+ }
18161
+ function prepareWorkflowScope(sessionPath, cwd) {
18162
+ const session = readSessionEnvelope2(sessionPath);
18163
+ if (session.role !== "coordinator") {
18164
+ throw new CoordinationError2("coordination.session-role", `workflow Prepare verbs require a coordinator session, not ${session.role}`, { actual: session.role });
18165
+ }
18166
+ const harnessRoot = canonicalizeNearestExisting2(session.harness_root);
18167
+ localStore2(harnessRoot);
18168
+ const processRoot = resolveProcessHarnessDir2(cwd);
18169
+ if (processRoot !== null && canonicalTarget2(processRoot) !== harnessRoot) {
18170
+ throw new CoordinationError2("coordination.scope-mismatch", `session ${session.session_id} belongs to harness root ${harnessRoot}, but this process resolves ${canonicalTarget2(processRoot)}`, { expected: harnessRoot, actual: canonicalTarget2(processRoot) });
18171
+ }
18172
+ const workflowId = safePlanId(session.workflow_id, "workflow_id");
18173
+ const snapshotPath = assertSnapshotPath2(harnessRoot, workflowId, snapshotPathOf(harnessRoot, workflowId));
18174
+ return { session, sessionPath: canonicalTarget2(sessionPath), harnessRoot, workflowId, snapshotPath };
18175
+ }
18176
+ function readPrepareSnapshot(snapshotPath) {
18177
+ const bytes = readArtifactBytes2(snapshotPath);
18178
+ if (bytes === undefined) {
18179
+ throw new CoordinationError2("coordination.workflow-not-found", `workflow snapshot not found: ${snapshotPath}`, {
18180
+ path: snapshotPath
18181
+ });
18182
+ }
18183
+ return { snapshot: readSnapshot2(dirname122(snapshotPath)), version: bytes.version };
18184
+ }
18185
+ function prepareCompassDeclaration(frontmatter, key, workflowId, path2) {
18186
+ const value = frontmatter[key];
18187
+ if (value === undefined)
18188
+ return;
18189
+ if (!isNonEmptyString2(value)) {
18190
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${workflowId} compass ${path2} declares a malformed ${key} \u2014 every declaration must be a non-empty string`, { workflow_id: workflowId, path: path2, field: key, actual: value });
18191
+ }
18192
+ return value;
18193
+ }
18194
+ function readPrepareCompass(harnessRoot, snapshot) {
18195
+ const ref = snapshot.compass_ref;
18196
+ if (!isNonEmptyString2(ref) || isAbsolute122(ref)) {
18197
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${snapshot.id} declares no usable compass_ref \u2014 the amendment requires the reviewed iteration compass`, { workflow_id: snapshot.id, actual: ref ?? null });
18198
+ }
18199
+ const root = canonicalizeNearestExisting2(harnessRoot);
18200
+ const path2 = canonicalTarget2(join202(harnessRoot, ref));
18201
+ if (!isWithin(root, path2)) {
18202
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${snapshot.id} compass_ref ${JSON.stringify(ref)} resolves outside the harness root ${root}`, { workflow_id: snapshot.id, path: path2, expected: ref });
18203
+ }
18204
+ let bytes;
18205
+ try {
18206
+ bytes = readFileSync132(path2);
18207
+ } catch (error) {
18208
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${snapshot.id} compass ${path2} is unreadable: ${errorMessage2(error)}`, { workflow_id: snapshot.id, path: path2 });
18209
+ }
18210
+ let frontmatter;
18211
+ try {
18212
+ frontmatter = parseCompassFrontmatterText2(bytes.toString("utf8"), path2);
18213
+ } catch (error) {
18214
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${snapshot.id} compass ${path2} has no parsable frontmatter: ${errorMessage2(error)}`, { workflow_id: snapshot.id, path: path2 });
18215
+ }
18216
+ const iterationId = frontmatter.iteration_id;
18217
+ if (!isNonEmptyString2(iterationId)) {
18218
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${snapshot.id} compass ${path2} declares no iteration_id \u2014 a lifecycle amends only its own compass`, { workflow_id: snapshot.id, path: path2, actual: iterationId ?? null });
18219
+ }
18220
+ if (iterationId !== snapshot.id) {
18221
+ throw prepareAmendmentRefusal("compass-mismatch", `compass ${path2} declares iteration_id ${iterationId}, not workflow ${snapshot.id} \u2014 a lifecycle amends only its own compass`, { workflow_id: snapshot.id, expected: snapshot.id, actual: iterationId });
18222
+ }
18223
+ const declaredPlans = frontmatter.plans;
18224
+ if (!Array.isArray(declaredPlans) || declaredPlans.length === 0) {
18225
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${snapshot.id} compass ${path2} declares no plan ids in its frontmatter \u2014 the amendment cannot verify the approved plan set`, { workflow_id: snapshot.id, path: path2, actual: declaredPlans ?? null });
18226
+ }
18227
+ const malformed = declaredPlans.filter((entry) => !isNonEmptyString2(entry));
18228
+ if (malformed.length > 0) {
18229
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${snapshot.id} compass ${path2} declares ${malformed.length} malformed plan id(s) \u2014 every plans entry must be a non-empty string`, { workflow_id: snapshot.id, path: path2, plans: declaredPlans });
18230
+ }
18231
+ const planIds = declaredPlans;
18232
+ if (new Set(planIds).size !== planIds.length) {
18233
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${snapshot.id} compass ${path2} declares the same plan id more than once \u2014 the reviewed plan set is not a multiset`, { workflow_id: snapshot.id, path: path2, plans: planIds });
18234
+ }
18235
+ const specIntegrationBranch = prepareCompassDeclaration(frontmatter, "spec_integration_branch", snapshot.id, path2);
18236
+ const integrationWorktreePath = prepareCompassDeclaration(frontmatter, "integration_worktree_path", snapshot.id, path2);
18237
+ return {
18238
+ path: path2,
18239
+ version: `sha256:${sha256Bytes(bytes)}`,
18240
+ planIds,
18241
+ ...specIntegrationBranch !== undefined ? { specIntegrationBranch } : {},
18242
+ ...integrationWorktreePath !== undefined ? { integrationWorktreePath } : {}
18243
+ };
18244
+ }
18245
+ function prepareAdmission(harnessRoot, workflowId, snapshot) {
18246
+ const entry = assertRootRegisterEntry(harnessRoot, workflowId);
18247
+ if (isNonEmptyString2(entry.status) && entry.status !== "running") {
18248
+ return {
18249
+ ok: false,
18250
+ reason: "not-prepare",
18251
+ message: `root register entry ${workflowId} is ${entry.status} \u2014 the amendment is available only while the lifecycle runs`,
18252
+ details: { workflow_id: workflowId, status: entry.status }
18253
+ };
18254
+ }
18255
+ if (snapshot.status !== "running") {
18256
+ return {
18257
+ ok: false,
18258
+ reason: "not-prepare",
18259
+ message: `workflow ${workflowId} is ${snapshot.status} \u2014 the amendment is available only in Prepare`,
18260
+ details: { workflow_id: workflowId, status: snapshot.status }
18261
+ };
18262
+ }
18263
+ if (snapshot.phase !== PREPARE_PHASE) {
18264
+ return {
18265
+ ok: false,
18266
+ reason: "not-prepare",
18267
+ message: `workflow ${workflowId} is in ${snapshot.phase ?? "no declared phase"}, not ${PREPARE_PHASE}`,
18268
+ details: { workflow_id: workflowId, expected: PREPARE_PHASE, actual: snapshot.phase ?? null }
18269
+ };
18270
+ }
18271
+ if (snapshot.integration_merge_lease !== undefined) {
18272
+ return {
18273
+ ok: false,
18274
+ reason: "execution-started",
18275
+ message: `workflow ${workflowId} carries an integration merge lease \u2014 execution ownership already exists`,
18276
+ details: { workflow_id: workflowId }
18277
+ };
18278
+ }
18279
+ for (const row of snapshot.plans) {
18280
+ const planId = rowPlanIds2(row)[0] ?? "";
18281
+ const status = rowStatusOf(row);
18282
+ if (status !== "Todo") {
18283
+ return {
18284
+ ok: false,
18285
+ reason: "execution-started",
18286
+ message: `plan ${planId} is ${status} \u2014 the amendment is available only while every row is Todo`,
18287
+ details: { workflow_id: workflowId, plan_id: planId, actual: status }
18288
+ };
18289
+ }
18290
+ if (row.progress !== undefined && row.progress !== 0) {
18291
+ return {
18292
+ ok: false,
18293
+ reason: "execution-started",
18294
+ message: `plan ${planId} reports progress ${JSON.stringify(row.progress)} \u2014 the amendment must not rewrite executed work`,
18295
+ details: { workflow_id: workflowId, plan_id: planId, actual: row.progress }
18296
+ };
18297
+ }
18298
+ if (row.execution_lease !== undefined) {
18299
+ return {
18300
+ ok: false,
18301
+ reason: "execution-started",
18302
+ message: `plan ${planId} carries an execution lease \u2014 the plan has an owner and is no longer in Prepare`,
18303
+ details: { workflow_id: workflowId, plan_id: planId, holder: isPlainObject22(row.execution_lease) ? row.execution_lease.holder : null }
18304
+ };
18305
+ }
18306
+ if (row.coordination !== undefined) {
18307
+ return {
18308
+ ok: false,
18309
+ reason: "execution-started",
18310
+ message: `plan ${planId} carries a coordination block \u2014 preparation or execution evidence already exists for this row`,
18311
+ details: { workflow_id: workflowId, plan_id: planId, revision: rowCoordinationOf(row)?.revision ?? null }
18312
+ };
18313
+ }
18314
+ }
18315
+ return { ok: true };
18316
+ }
18317
+ var PLAN_CONSULTED_HEADERS = {
18318
+ plan_id: true,
18319
+ "main worktree branch": true,
18320
+ "working branch": true
18321
+ };
18322
+ function planHeadersOf(planPath, planId) {
18323
+ const headers = new Map;
18324
+ let marker;
18325
+ let markerLength = 0;
18326
+ for (const raw of readFileSync132(planPath, "utf8").split(/\r?\n/)) {
18327
+ const line = raw.trim();
18328
+ const fence = /^(`{3,}|~{3,})/.exec(line);
18329
+ if (fence !== null) {
18330
+ const run = fence[1];
18331
+ if (marker === undefined) {
18332
+ marker = run.charAt(0);
18333
+ markerLength = run.length;
18334
+ } else if (run.charAt(0) === marker && run.length >= markerLength) {
18335
+ marker = undefined;
18336
+ }
18337
+ continue;
18338
+ }
18339
+ if (marker !== undefined)
18340
+ continue;
18341
+ const match = /^\*{0,2}([^:*]+?)\*{0,2}:\*{0,2}\s*(\S.*)$/.exec(line);
18342
+ if (match === null)
18343
+ continue;
18344
+ const label = match[1].trim();
18345
+ const key = label.toLowerCase();
18346
+ if (PLAN_CONSULTED_HEADERS[key] !== true)
18347
+ continue;
18348
+ const value = match[2].trim();
18349
+ const prior = headers.get(key);
18350
+ if (prior !== undefined && prior !== value) {
18351
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${planId} markdown declares conflicting "${label}" headers (${prior} vs ${value})`, { plan_id: planId, header: label });
18352
+ }
18353
+ headers.set(key, value);
18354
+ }
18355
+ return headers;
18356
+ }
18357
+ function prepareReferencePath(harnessRoot, value, field, planId) {
18358
+ if (!isNonEmptyString2(value) || !isAbsolute122(value)) {
18359
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${planId} ${field} must be an absolute path \u2014 got ${JSON.stringify(value ?? null)}`, { plan_id: planId, field, actual: value ?? null });
18360
+ }
18361
+ const canonical = canonicalTarget2(value);
18362
+ if (!isWithin(canonicalizeNearestExisting2(harnessRoot), canonical)) {
18363
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${planId} ${field} ${canonical} escapes the harness root ${harnessRoot}`, { plan_id: planId, field, path: canonical, expected: harnessRoot });
18364
+ }
18365
+ if (!existsSync152(canonical) || !statSync62(canonical).isFile()) {
18366
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${planId} ${field} does not exist: ${canonical}`, {
18367
+ plan_id: planId,
18368
+ field,
18369
+ path: canonical
18370
+ });
18371
+ }
18372
+ return canonical;
18373
+ }
18374
+ function prepareReferenceList(harnessRoot, value, field, planId) {
18375
+ if (!Array.isArray(value)) {
18376
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${planId} ${field} must be an array of absolute paths \u2014 got ${JSON.stringify(value ?? null)}`, { plan_id: planId, field, actual: value ?? null });
18377
+ }
18378
+ return value.map((entry, index) => prepareReferencePath(harnessRoot, entry, `${field}[${index}]`, planId));
18379
+ }
18380
+ function prepareMetadataString(metadata, key, planId) {
18381
+ const value = metadata[key];
18382
+ if (!isNonEmptyString2(value)) {
18383
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${planId} metadata.${key} must be a non-empty string \u2014 got ${JSON.stringify(value ?? null)}`, { plan_id: planId, field: `metadata.${key}`, actual: value ?? null });
18384
+ }
18385
+ return value;
18386
+ }
18387
+ function readPlanAppend(value, context) {
18388
+ if (!isPlainObject22(value)) {
18389
+ throw prepareAmendmentRefusal("invalid-plan", "every appendPlans entry must be an object", { actual: value ?? null });
18390
+ }
18391
+ const unexpected = Object.keys(value).filter((key) => !PREPARE_APPEND_KEYS.includes(key));
18392
+ if (unexpected.length > 0) {
18393
+ throw prepareAmendmentRefusal("invalid-plan", `a plan append accepts only ${PREPARE_APPEND_KEYS.join(", ")} \u2014 unexpected key(s): ${unexpected.join(", ")}`, { allowed: [...PREPARE_APPEND_KEYS], unexpected });
18394
+ }
18395
+ const id = value.id;
18396
+ if (!isNonEmptyString2(id)) {
18397
+ throw prepareAmendmentRefusal("invalid-plan", `a plan append requires a non-empty id \u2014 got ${JSON.stringify(id ?? null)}`, {
18398
+ actual: id ?? null
18399
+ });
18400
+ }
18401
+ try {
18402
+ assertSafePathComponent2(id, "plan id");
18403
+ } catch (error) {
18404
+ throw prepareAmendmentRefusal("invalid-plan", `plan id ${JSON.stringify(id)} is not a safe path component: ${errorMessage2(error)}`, {
18405
+ plan_id: id
18406
+ });
18407
+ }
18408
+ const title = value.title;
18409
+ if (!isNonEmptyString2(title)) {
18410
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} requires a non-empty title`, { plan_id: id, actual: title ?? null });
18411
+ }
18412
+ const declaredFile = value.file;
18413
+ if (!isNonEmptyString2(declaredFile) || !isAbsolute122(declaredFile)) {
18414
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} file must be the absolute plan path \u2014 got ${JSON.stringify(declaredFile ?? null)}`, { plan_id: id, actual: declaredFile ?? null });
18415
+ }
18416
+ const planPath = canonicalTarget2(declaredFile);
18417
+ const planDir = canonicalizeNearestExisting2(resolvePlanDir2(context.harnessRoot));
18418
+ if (dirname122(planPath) !== planDir || basename122(planPath) !== `${id}.md`) {
18419
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} file ${planPath} is not ${join202(planDir, `${id}.md`)}`, { plan_id: id, expected: join202(planDir, `${id}.md`), actual: planPath });
18420
+ }
18421
+ if (!existsSync152(planPath) || !statSync62(planPath).isFile()) {
18422
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} markdown not found: ${planPath}`, { plan_id: id, path: planPath });
18423
+ }
18424
+ const headers = planHeadersOf(planPath, id);
18425
+ const declaredPlanId = headers.get("plan_id");
18426
+ if (declaredPlanId === undefined) {
18427
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} markdown ${planPath} declares no plan_id header \u2014 the row cannot be traced to its reviewed plan`, { plan_id: id, path: planPath });
18428
+ }
18429
+ if (declaredPlanId !== id) {
18430
+ throw prepareAmendmentRefusal("invalid-plan", `plan append id ${id} does not match the plan markdown header plan_id ${declaredPlanId} (${planPath})`, { plan_id: id, expected: id, actual: declaredPlanId, path: planPath });
18431
+ }
18432
+ const metadata = value.metadata;
18433
+ if (!isPlainObject22(metadata)) {
18434
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} metadata must be an object`, { plan_id: id, actual: metadata ?? null });
18435
+ }
18436
+ const unexpectedMetadata = Object.keys(metadata).filter((key) => !PREPARE_APPEND_METADATA_KEYS.includes(key));
18437
+ if (unexpectedMetadata.length > 0) {
18438
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} metadata accepts only ${PREPARE_APPEND_METADATA_KEYS.join(", ")} \u2014 unexpected key(s): ${unexpectedMetadata.join(", ")}`, { plan_id: id, allowed: [...PREPARE_APPEND_METADATA_KEYS], unexpected: unexpectedMetadata });
18439
+ }
18440
+ const primarySpec = prepareReferencePath(context.harnessRoot, metadata.primary_spec, "metadata.primary_spec", id);
18441
+ const specRefs = prepareReferenceList(context.harnessRoot, metadata.spec_refs, "metadata.spec_refs", id);
18442
+ const iterationCompass = prepareReferencePath(context.harnessRoot, metadata.iteration_compass, "metadata.iteration_compass", id);
18443
+ if (iterationCompass !== context.compass.path) {
18444
+ throw prepareAmendmentRefusal("compass-mismatch", `plan ${id} metadata.iteration_compass ${iterationCompass} is not this workflow's reviewed compass ${context.compass.path}`, { plan_id: id, expected: context.compass.path, actual: iterationCompass });
18445
+ }
18446
+ const iterationRefs = prepareReferenceList(context.harnessRoot, metadata.iteration_refs, "metadata.iteration_refs", id);
18447
+ const workingBranch = prepareMetadataString(metadata, "working_branch", id);
18448
+ const specIntegrationBranch = prepareMetadataString(metadata, "spec_integration_branch", id);
18449
+ const mergeTarget = prepareMetadataString(metadata, "merge_target", id);
18450
+ const anchors = context.snapshot.branch ?? {};
18451
+ for (const [label, branch] of [
18452
+ ["branch.base", anchors.base],
18453
+ ["branch.integration", anchors.integration],
18454
+ ["branch.target", anchors.target]
18455
+ ]) {
18456
+ if (isNonEmptyString2(branch) && branch === workingBranch) {
18457
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} metadata.working_branch ${workingBranch} is the workflow's ${label} \u2014 a plan row owns its own feature branch`, { plan_id: id, field: "metadata.working_branch", actual: workingBranch });
18458
+ }
18459
+ }
18460
+ const declaredWorking = headers.get("working branch");
18461
+ if (declaredWorking === undefined) {
18462
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} markdown ${planPath} declares no Working branch header \u2014 the appended row's branch metadata cannot be verified against the reviewed plan`, { plan_id: id, field: "metadata.working_branch", path: planPath });
18463
+ }
18464
+ if (declaredWorking !== workingBranch) {
18465
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} metadata.working_branch ${workingBranch} does not match the Working branch declared by ${planPath} (${declaredWorking})`, { plan_id: id, expected: declaredWorking, actual: workingBranch, path: planPath });
18466
+ }
18467
+ const declaredMain = headers.get("main worktree branch");
18468
+ if (declaredMain === undefined) {
18469
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} markdown ${planPath} declares no Main worktree branch header \u2014 the amendment cannot verify the branch the reviewed plan was written against`, { plan_id: id, field: "mainWorktreeBranch", path: planPath });
18470
+ }
18471
+ if (declaredMain !== context.mainWorktreeBranch) {
18472
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} metadata records main worktree branch ${context.mainWorktreeBranch}, but ${planPath} declares ${declaredMain}`, { plan_id: id, expected: declaredMain, actual: context.mainWorktreeBranch, path: planPath });
18473
+ }
18474
+ if (isNonEmptyString2(anchors.integration)) {
18475
+ for (const [field, recorded] of [
18476
+ ["metadata.spec_integration_branch", specIntegrationBranch],
18477
+ ["metadata.merge_target", mergeTarget]
18478
+ ]) {
18479
+ if (recorded !== anchors.integration) {
18480
+ throw prepareAmendmentRefusal("invalid-plan", `plan ${id} ${field} ${recorded} is not the workflow's integration branch ${anchors.integration}`, { plan_id: id, expected: anchors.integration, actual: recorded });
18481
+ }
18482
+ }
18483
+ }
18484
+ if (context.compass.specIntegrationBranch !== undefined && specIntegrationBranch !== context.compass.specIntegrationBranch) {
18485
+ throw prepareAmendmentRefusal("compass-mismatch", `plan ${id} metadata.spec_integration_branch ${specIntegrationBranch} is not the reviewed compass integration branch ${context.compass.specIntegrationBranch}`, { plan_id: id, expected: context.compass.specIntegrationBranch, actual: specIntegrationBranch });
18486
+ }
18487
+ const row = {
18488
+ id,
18489
+ title,
18490
+ file: planPath,
18491
+ status: "Todo",
18492
+ owner: "project-manager",
18493
+ progress: 0,
18494
+ created_at: nowIso(),
18495
+ metadata: {
18496
+ primary_spec: primarySpec,
18497
+ spec_refs: specRefs,
18498
+ iteration_compass: iterationCompass,
18499
+ iteration_refs: iterationRefs,
18500
+ working_branch: workingBranch,
18501
+ spec_integration_branch: specIntegrationBranch,
18502
+ merge_target: mergeTarget
18503
+ }
18504
+ };
18505
+ const gate22 = validatePlanRow2(row);
18506
+ if (!gate22.ok) {
18507
+ throw prepareAmendmentRefusal("invalid-plan", `constructed row ${id} fails plan-row validation \u2014 ${summarize2(gate22.violations)}`, {
18508
+ plan_id: id,
18509
+ violations: gate22.violations.map((entry) => entry.code)
18510
+ });
18511
+ }
18512
+ return row;
18513
+ }
18514
+ function readIntegrationWorktreePath(value, context) {
18515
+ const refuse = (message, details = {}) => {
18516
+ throw prepareAmendmentRefusal("invalid-worktree", message, details);
18517
+ };
18518
+ if (!isNonEmptyString2(value) || !isAbsolute122(value)) {
18519
+ return refuse(`integrationWorktreePath must be an absolute path \u2014 got ${JSON.stringify(value ?? null)}`, {
18520
+ actual: value ?? null
18521
+ });
18522
+ }
18523
+ const path2 = canonicalTarget2(value);
18524
+ if (!existsSync152(path2) || !statSync62(path2).isDirectory()) {
18525
+ return refuse(`integration checkout ${path2} does not exist`, { path: path2, expected: value });
18526
+ }
18527
+ const mainRoot = canonicalTarget2(context.main.root);
18528
+ const control = canonicalizeNearestExisting2(context.harnessRoot);
18529
+ const controlRepo = readMainWorktree2(control);
18530
+ if (controlRepo === null) {
18531
+ return refuse(`the control harness root ${control} has no readable Git main worktree \u2014 the integration checkout cannot be proven to be a checkout of this repository`, { path: path2, harness_root: control });
18532
+ }
18533
+ const controlMainRoot = canonicalTarget2(controlRepo.root);
18534
+ if (controlMainRoot !== mainRoot) {
18535
+ return refuse(`this call runs from the main worktree of ${mainRoot}, not the repository owning the control harness root ${control} (${controlMainRoot}) \u2014 the recorded checkout must belong to that repository`, { path: path2, expected: controlMainRoot, actual: mainRoot });
18536
+ }
18537
+ if (path2 === mainRoot || path2 === control) {
18538
+ return refuse(`integration checkout ${path2} is the main/control checkout \u2014 a dedicated integration worktree is required`, {
18539
+ path: path2,
18540
+ expected: `a checkout distinct from ${mainRoot}`
18541
+ });
18542
+ }
18543
+ const repo = readMainWorktree2(path2);
18544
+ if (repo === null || canonicalTarget2(repo.root) !== controlMainRoot) {
18545
+ return refuse(`integration checkout ${path2} is not a checkout of the repository owning the control harness root ${control} (${controlMainRoot})`, {
18546
+ path: path2,
18547
+ expected: controlMainRoot,
18548
+ actual: repo === null ? null : canonicalTarget2(repo.root)
18549
+ });
18550
+ }
18551
+ if (!isDistinctCheckout2(context.main.root, path2)) {
18552
+ return refuse(`integration checkout ${path2} is not a distinct checkout (same Git checkout as ${mainRoot})`, {
18553
+ path: path2,
18554
+ expected: `a checkout distinct from ${mainRoot}`
18555
+ });
18556
+ }
18557
+ const integrationBranch = context.snapshot.branch?.integration;
18558
+ if (!isNonEmptyString2(integrationBranch)) {
18559
+ return refuse(`workflow ${context.snapshot.id} records no branch.integration \u2014 the integration checkout cannot be verified`, { workflow_id: context.snapshot.id, path: path2 });
18560
+ }
18561
+ const branch = gitRead(path2, ["rev-parse", "--abbrev-ref", "HEAD"]);
18562
+ if (branch !== integrationBranch) {
18563
+ return refuse(`integration checkout ${path2} is on ${branch === undefined ? "an unreadable checkout" : branch || "a detached HEAD"}, not the recorded ${integrationBranch}`, { path: path2, expected: integrationBranch, actual: branch ?? null });
18564
+ }
18565
+ return path2;
18566
+ }
18567
+ function samePlanIdSet(left, right) {
18568
+ const leftSet = new Set(left);
18569
+ const rightSet = new Set(right);
18570
+ if (leftSet.size !== rightSet.size)
18571
+ return false;
18572
+ for (const id of leftSet)
18573
+ if (!rightSet.has(id))
18574
+ return false;
18575
+ return true;
18576
+ }
18577
+ function readPreparePatch(patch, context) {
18578
+ if (!isPlainObject22(patch)) {
18579
+ throw prepareAmendmentRefusal("invalid-patch", "the amendment patch must be an object", { actual: patch ?? null });
18580
+ }
18581
+ const unexpected = Object.keys(patch).filter((key) => !PREPARE_PATCH_KEYS.includes(key));
18582
+ if (unexpected.length > 0) {
18583
+ throw prepareAmendmentRefusal("invalid-patch", `the amendment patch accepts only ${PREPARE_PATCH_KEYS.join(", ")} \u2014 unexpected key(s): ${unexpected.join(", ")}`, { allowed: [...PREPARE_PATCH_KEYS], unexpected });
18584
+ }
18585
+ const mainWorktreeBranch = patch.mainWorktreeBranch;
18586
+ if (!isNonEmptyString2(mainWorktreeBranch)) {
18587
+ throw prepareAmendmentRefusal("invalid-patch", `the amendment patch requires mainWorktreeBranch as a non-empty string \u2014 got ${JSON.stringify(mainWorktreeBranch ?? null)}`, { actual: mainWorktreeBranch ?? null });
18588
+ }
18589
+ if (context.main.branch !== mainWorktreeBranch) {
18590
+ throw new CoordinationError2("coordination.scope-mismatch", `the main worktree ${context.main.root} is on ${context.main.branch === "" ? "a detached HEAD" : context.main.branch}, but this amendment declares ${mainWorktreeBranch}`, { expected: mainWorktreeBranch, actual: context.main.branch });
18591
+ }
18592
+ const rawAppends = patch.appendPlans;
18593
+ if (!Array.isArray(rawAppends)) {
18594
+ throw prepareAmendmentRefusal("invalid-patch", "the amendment patch requires appendPlans as an array", {
18595
+ actual: rawAppends ?? null
18596
+ });
18597
+ }
18598
+ const requestedParallelism = patch.planParallelism;
18599
+ if (requestedParallelism !== undefined && !(isNonEmptyString2(requestedParallelism) && PLAN_PARALLELISM_VALUES.includes(requestedParallelism))) {
18600
+ throw prepareAmendmentRefusal("invalid-patch", `planParallelism must be one of ${PLAN_PARALLELISM_VALUES.join(" | ")} \u2014 got ${JSON.stringify(requestedParallelism ?? null)}`, { allowed: [...PLAN_PARALLELISM_VALUES], actual: requestedParallelism ?? null });
18601
+ }
18602
+ const planParallelism = isNonEmptyString2(requestedParallelism) ? requestedParallelism : undefined;
18603
+ const existingIds = new Set(context.snapshot.plans.flatMap((row) => rowPlanIds2(row)));
18604
+ const declaredIds = new Set;
18605
+ for (const entry of rawAppends) {
18606
+ const id = isPlainObject22(entry) ? entry.id : undefined;
18607
+ if (!isNonEmptyString2(id))
18608
+ continue;
18609
+ if (existingIds.has(id)) {
18610
+ throw prepareAmendmentRefusal("duplicate-plan", `plan ${id} is already a row of workflow ${context.snapshot.id} \u2014 the amendment appends new rows and never replaces existing ones`, { plan_id: id, workflow_id: context.snapshot.id });
18611
+ }
18612
+ if (declaredIds.has(id)) {
18613
+ throw prepareAmendmentRefusal("duplicate-plan", `plan ${id} appears twice in one patch`, { plan_id: id });
18614
+ }
18615
+ declaredIds.add(id);
18616
+ }
18617
+ const rows = rawAppends.map((entry) => readPlanAppend(entry, {
18618
+ harnessRoot: context.harnessRoot,
18619
+ snapshot: context.snapshot,
18620
+ compass: context.compass,
18621
+ mainWorktreeBranch
18622
+ }));
18623
+ const integrationWorktreePath = patch.integrationWorktreePath === undefined ? undefined : readIntegrationWorktreePath(patch.integrationWorktreePath, context);
18624
+ const recordedPath = isNonEmptyString2(context.snapshot.integration_worktree_path) ? canonicalTarget2(context.snapshot.integration_worktree_path) : undefined;
18625
+ const recordedParallelism = isPlainObject22(context.snapshot.execution_policy) ? context.snapshot.execution_policy.plan_parallelism : undefined;
18626
+ const changesPath = integrationWorktreePath !== undefined && integrationWorktreePath !== recordedPath;
18627
+ const changesPolicy = planParallelism !== undefined && planParallelism !== recordedParallelism;
18628
+ if (rows.length === 0 && !changesPath && !changesPolicy) {
18629
+ throw prepareAmendmentRefusal("invalid-patch", `the patch changes nothing on workflow ${context.snapshot.id} \u2014 it appends no plan, records no new integration checkout and no different plan parallelism`, { workflow_id: context.snapshot.id });
18630
+ }
18631
+ if (context.compass.specIntegrationBranch !== undefined) {
18632
+ const recordedBranch = context.snapshot.branch?.integration;
18633
+ if (!isNonEmptyString2(recordedBranch) || recordedBranch !== context.compass.specIntegrationBranch) {
18634
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${context.snapshot.id} records integration branch ${JSON.stringify(recordedBranch ?? null)}, but the reviewed compass ${context.compass.path} declares ${context.compass.specIntegrationBranch}`, { expected: context.compass.specIntegrationBranch, actual: recordedBranch ?? null });
18635
+ }
18636
+ }
18637
+ if (context.compass.integrationWorktreePath !== undefined) {
18638
+ const declaredPath = canonicalTarget2(context.compass.integrationWorktreePath);
18639
+ const effectivePath = integrationWorktreePath ?? recordedPath;
18640
+ if (effectivePath !== declaredPath) {
18641
+ throw prepareAmendmentRefusal("compass-mismatch", `workflow ${context.snapshot.id} would record integration checkout ${effectivePath ?? "(none)"}, but the reviewed compass ${context.compass.path} declares ${declaredPath}`, { path: effectivePath ?? null, expected: declaredPath, actual: effectivePath ?? null });
18642
+ }
18643
+ }
18644
+ const proposedIds = [
18645
+ ...context.snapshot.plans.flatMap((row) => rowPlanIds2(row)),
18646
+ ...rows.map((row) => rowPlanIds2(row)[0] ?? "")
18647
+ ];
18648
+ if (!samePlanIdSet(context.compass.planIds, proposedIds)) {
18649
+ const missing = context.compass.planIds.filter((id) => !proposedIds.includes(id));
18650
+ const undeclared = proposedIds.filter((id) => !context.compass.planIds.includes(id));
18651
+ throw prepareAmendmentRefusal("compass-mismatch", `the amended workflow's plan ids must match the reviewed compass ${context.compass.path} exactly \u2014 missing: ${missing.join(", ") || "(none)"}; not declared by the compass: ${undeclared.join(", ") || "(none)"}`, { expected: [...context.compass.planIds], actual: proposedIds, missing, undeclared });
18652
+ }
18653
+ return {
18654
+ rows,
18655
+ ...integrationWorktreePath !== undefined ? { integrationWorktreePath } : {},
18656
+ ...planParallelism !== undefined ? { planParallelism } : {}
18657
+ };
18658
+ }
18659
+ function prepareVersionToken(value, field) {
18660
+ if (!isNonEmptyString2(value)) {
18661
+ throw invalidInput2(`prepare amendment ${field} is required \u2014 read it from \`show-prepare\``, { field });
18662
+ }
18663
+ const bare = value.startsWith("sha256:") ? value.slice("sha256:".length) : value;
18664
+ if (!/^[0-9a-f]{64}$/.test(bare)) {
18665
+ throw invalidInput2(`prepare amendment ${field} must be a raw-byte sha256 version ("sha256:<64 hex>" or "<64 hex>") \u2014 got ${JSON.stringify(value)}`, { field });
18666
+ }
18667
+ return value;
18668
+ }
18669
+ function prepareVersionDigest(token) {
18670
+ return token.startsWith("sha256:") ? token.slice("sha256:".length) : token;
18671
+ }
18672
+ async function showPrepareWorkflow(input) {
18673
+ assertExactKeys2(input, ["sessionPath", "cwd"], "prepare workflow read");
18674
+ const cwd = input.cwd ?? process.cwd();
18675
+ const scope = prepareWorkflowScope(input.sessionPath, cwd);
18676
+ const { snapshot, version } = readPrepareSnapshot(scope.snapshotPath);
18677
+ assertCoordinatorBinding(scope.session, scope.sessionPath, snapshot);
18678
+ const compass = readPrepareCompass(scope.harnessRoot, snapshot);
18679
+ const admission = prepareAdmission(scope.harnessRoot, scope.workflowId, snapshot);
18680
+ return {
18681
+ ok: true,
18682
+ operation: "show-prepare",
18683
+ session: scope.session,
18684
+ session_file: scope.sessionPath,
18685
+ view: {
18686
+ workflowId: scope.workflowId,
18687
+ snapshotVersion: version,
18688
+ compassVersion: compass.version,
18689
+ planIds: snapshot.plans.map((row) => rowPlanIds2(row)[0] ?? ""),
18690
+ allowed: admission.ok,
18691
+ blockers: admission.ok ? [] : [`${admission.reason}: ${admission.message}`]
18692
+ }
18693
+ };
18694
+ }
18695
+ async function amendPrepareWorkflow(input) {
18696
+ assertExactKeys2(input, ["sessionPath", "cwd", "expectedSnapshotVersion", "expectedCompassVersion", "patch"], "prepare amendment input");
18697
+ const cwd = input.cwd ?? process.cwd();
18698
+ const expectedSnapshotVersion = prepareVersionToken(input.expectedSnapshotVersion, "expectedSnapshotVersion");
18699
+ const expectedCompassVersion = prepareVersionToken(input.expectedCompassVersion, "expectedCompassVersion");
18700
+ const scope = prepareWorkflowScope(input.sessionPath, cwd);
18701
+ const committed = await withStatusWriteLock2(scope.snapshotPath, async () => {
18702
+ const { snapshot, version } = readPrepareSnapshot(scope.snapshotPath);
18703
+ assertCoordinatorBinding(scope.session, scope.sessionPath, snapshot);
18704
+ const main = assertCoordinatorResidency(cwd, snapshot);
18705
+ if (prepareVersionDigest(version) !== prepareVersionDigest(expectedSnapshotVersion)) {
18706
+ throw prepareAmendmentRefusal("stale", `snapshot ${scope.snapshotPath} is at ${version}, this call expected ${expectedSnapshotVersion} \u2014 re-read \`workflow show-prepare\` and review again`, { path: scope.snapshotPath, expected: expectedSnapshotVersion, actual: version });
18707
+ }
18708
+ const compass = readPrepareCompass(scope.harnessRoot, snapshot);
18709
+ if (prepareVersionDigest(compass.version) !== prepareVersionDigest(expectedCompassVersion)) {
18710
+ throw prepareAmendmentRefusal("stale", `compass ${compass.path} is at ${compass.version}, this call expected ${expectedCompassVersion} \u2014 re-read \`workflow show-prepare\` and review again`, { path: compass.path, expected: expectedCompassVersion, actual: compass.version });
18711
+ }
18712
+ const admission = prepareAdmission(scope.harnessRoot, scope.workflowId, snapshot);
18713
+ if (!admission.ok)
18714
+ throw prepareAmendmentRefusal(admission.reason, admission.message, admission.details);
18715
+ const proposal = readPreparePatch(input.patch, { harnessRoot: scope.harnessRoot, snapshot, compass, main });
18716
+ const executionPolicy = { ...snapshot.execution_policy ?? {} };
18717
+ if (proposal.planParallelism !== undefined)
18718
+ executionPolicy.plan_parallelism = proposal.planParallelism;
18719
+ const next = {
18720
+ ...snapshot,
18721
+ updated_at: nowIso(),
18722
+ plans: [...snapshot.plans, ...proposal.rows],
18723
+ ...proposal.integrationWorktreePath !== undefined ? { integration_worktree_path: proposal.integrationWorktreePath } : {},
18724
+ ...proposal.planParallelism !== undefined ? { execution_policy: executionPolicy } : {}
18725
+ };
18726
+ const rechecked = readPrepareCompass(scope.harnessRoot, snapshot);
18727
+ if (prepareVersionDigest(rechecked.version) !== prepareVersionDigest(compass.version)) {
18728
+ throw prepareAmendmentRefusal("stale", `compass ${compass.path} changed while this amendment was being applied (${compass.version} \u2192 ${rechecked.version}) \u2014 re-read \`workflow show-prepare\` and review again`, { path: compass.path, expected: compass.version, actual: rechecked.version });
18729
+ }
18730
+ await commitSnapshot(scope.harnessRoot, scope.workflowId, scope.snapshotPath, next);
18731
+ const written = readArtifactBytes2(scope.snapshotPath);
18732
+ if (written === undefined) {
18733
+ throw new CoordinationError2("coordination.store", `snapshot ${scope.snapshotPath} is unreadable after this call committed it`, { path: scope.snapshotPath });
18734
+ }
18735
+ return {
18736
+ planIds: next.plans.map((row) => rowPlanIds2(row)[0] ?? ""),
18737
+ compassVersion: compass.version,
18738
+ snapshotVersion: written.version
18739
+ };
18740
+ });
18741
+ return {
18742
+ ok: true,
18743
+ operation: "amend-prepare",
18744
+ session: scope.session,
18745
+ session_file: scope.sessionPath,
18746
+ outcome: "amended",
18747
+ view: {
18748
+ workflowId: scope.workflowId,
18749
+ snapshotVersion: committed.snapshotVersion,
18750
+ compassVersion: committed.compassVersion,
18751
+ planIds: committed.planIds,
18752
+ allowed: true,
18753
+ blockers: []
18754
+ }
18755
+ };
18756
+ }
18757
+ // src/sdd-evidence.ts
18758
+ var import_picocolors = __toESM(require_picocolors2(), 1);
18759
+ import { execFileSync as execFileSync7, spawn as spawn2 } from "node:child_process";
18760
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
18761
+ import fs from "node:fs";
18762
+ import fsp from "node:fs/promises";
18763
+ import os from "node:os";
18764
+ import { basename as basename8, delimiter, dirname as dirname10, isAbsolute as isAbsolute13, join as join14, relative as relative7, resolve as resolvePath } from "node:path";
18765
+ import { performance } from "node:perf_hooks";
18766
+ var EVIDENCE_SCHEMA2 = "mstar.sdd-evidence/v1";
18767
+ var TIMEOUT_DEFAULT_MS2 = 600000;
18768
+ var TIMEOUT_MIN_MS2 = 1;
18769
+ var TIMEOUT_MAX_MS2 = 3600000;
18770
+ var LOG_STREAM_CAP2 = 8388608;
18771
+ var INPUT_BYTES_CAP2 = 536870912;
17541
18772
  var INPUT_ENTRIES_CAP3 = 1e4;
17542
18773
  var INPUT_MS_CAP2 = 30000;
17543
18774
  var SNAPSHOT_BYTES_CAP2 = 2097152;
@@ -18928,6 +20159,7 @@ var import_picocolors2 = __toESM(require_picocolors2(), 1);
18928
20159
  import { existsSync as existsSync16, readFileSync as readFileSync14 } from "node:fs";
18929
20160
  import { isAbsolute as isAbsolute15 } from "node:path";
18930
20161
  var FAILURE_DETAIL_KEYS = ["holder", "path", "expected", "actual"];
20162
+ var WORKFLOW_FAILURE_DETAIL_KEYS = [...FAILURE_DETAIL_KEYS, "workflow_id"];
18931
20163
  function asRecord(value) {
18932
20164
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
18933
20165
  }
@@ -18944,8 +20176,9 @@ function failurePayload(verb, code, message, context, details) {
18944
20176
  payload.workflow_id = context.workflow_id;
18945
20177
  if (context.plan_id !== undefined)
18946
20178
  payload.plan_id = context.plan_id;
18947
- for (const key of FAILURE_DETAIL_KEYS) {
18948
- if (details?.[key] !== undefined)
20179
+ const detailKeys = familyOf(verb) === "workflow" ? WORKFLOW_FAILURE_DETAIL_KEYS : FAILURE_DETAIL_KEYS;
20180
+ for (const key of detailKeys) {
20181
+ if (details?.[key] !== undefined && payload[key] === undefined)
18949
20182
  payload[key] = details[key];
18950
20183
  }
18951
20184
  return JSON.stringify(payload);
@@ -18965,24 +20198,37 @@ var PLAN_VERBS = {
18965
20198
  complete: true,
18966
20199
  reconcile: true
18967
20200
  };
20201
+ var WORKFLOW_VERBS = {
20202
+ "show-prepare": true,
20203
+ "amend-prepare": true
20204
+ };
20205
+ var SCOPED_VERB_FAMILIES = [
20206
+ { family: "plan", verbs: PLAN_VERBS },
20207
+ { family: "workflow", verbs: WORKFLOW_VERBS }
20208
+ ];
20209
+ function familyOf(verb) {
20210
+ return WORKFLOW_VERBS[verb] === true ? "workflow" : "plan";
20211
+ }
20212
+ var COMMAND_POSITION = 2;
18968
20213
  function planUsageFailurePayload(argv, message) {
18969
- const planIndex = argv.indexOf("plan");
18970
- if (planIndex === -1)
20214
+ const matched = SCOPED_VERB_FAMILIES.find((entry) => entry.family === argv[COMMAND_POSITION]);
20215
+ if (matched === undefined)
18971
20216
  return null;
18972
- const verb = argv.slice(planIndex + 1).find((token) => !token.startsWith("-"));
20217
+ const verb = argv.slice(COMMAND_POSITION + 1).find((token) => !token.startsWith("-"));
18973
20218
  return JSON.stringify({
18974
20219
  ok: false,
18975
- operation: verb !== undefined && PLAN_VERBS[verb] === true ? verb : "plan",
20220
+ operation: verb !== undefined && matched.verbs[verb] === true ? verb : matched.family,
18976
20221
  code: "usage",
18977
20222
  message
18978
20223
  });
18979
20224
  }
18980
20225
  function failPlan(verb, error, json, context) {
20226
+ const family = familyOf(verb);
18981
20227
  if (error instanceof SddScriptError2) {
18982
20228
  if (json)
18983
20229
  console.log(failurePayload(verb, "usage", error.message, context));
18984
20230
  else
18985
- console.error(import_picocolors2.default.red(`plan ${verb}: ${error.message}`));
20231
+ console.error(import_picocolors2.default.red(`${family} ${verb}: ${error.message}`));
18986
20232
  process.exitCode = error.exitCode;
18987
20233
  return;
18988
20234
  }
@@ -18992,19 +20238,19 @@ function failPlan(verb, error, json, context) {
18992
20238
  if (json)
18993
20239
  console.log(failurePayload(verb, coordination.code, message, context, coordination.details));
18994
20240
  else
18995
- console.error(import_picocolors2.default.red(`plan ${verb}: ${message}`));
20241
+ console.error(import_picocolors2.default.red(`${family} ${verb}: ${message}`));
18996
20242
  process.exitCode = 1;
18997
20243
  return;
18998
20244
  }
18999
20245
  if (json)
19000
- console.log(failurePayload(verb, "plan.internal-error", message, context));
20246
+ console.log(failurePayload(verb, `${family}.internal-error`, message, context));
19001
20247
  else
19002
- console.error(import_picocolors2.default.red(`plan ${verb} failed: ${message}`));
20248
+ console.error(import_picocolors2.default.red(`${family} ${verb} failed: ${message}`));
19003
20249
  process.exitCode = 1;
19004
20250
  }
19005
20251
  function requireFlag(raw, flag, verb, what) {
19006
20252
  if (raw === undefined || raw.trim() === "") {
19007
- throw new SddScriptError2(`usage: plan ${verb} requires ${flag} <${what}>`, 2);
20253
+ throw new SddScriptError2(`usage: ${familyOf(verb)} ${verb} requires ${flag} <${what}>`, 2);
19008
20254
  }
19009
20255
  return raw;
19010
20256
  }
@@ -19315,10 +20561,71 @@ function registerPlanCommands(program2) {
19315
20561
  for (const command of [plan, ...plan.commands])
19316
20562
  command.exitOverride();
19317
20563
  }
20564
+ function parsePrepareVersion(raw, flag, verb) {
20565
+ const value = requireFlag(raw, flag, verb, "sha256-version");
20566
+ const bare = value.startsWith("sha256:") ? value.slice("sha256:".length) : value;
20567
+ if (!/^[0-9a-f]{64}$/.test(bare)) {
20568
+ throw new SddScriptError2(`${flag} must be a raw-byte sha256 version ("sha256:<64 lowercase hex>" or "<64 lowercase hex>") \u2014 got ${JSON.stringify(value)}`, 2);
20569
+ }
20570
+ return value;
20571
+ }
20572
+ function printWorkflowView(verb, result, json) {
20573
+ const view = result.view;
20574
+ if (json) {
20575
+ const payload = {
20576
+ ok: true,
20577
+ operation: verb,
20578
+ workflow_id: view.workflowId,
20579
+ session_file: result.session_file,
20580
+ session_id: result.session.session_id,
20581
+ role: result.session.role,
20582
+ snapshot_version: view.snapshotVersion,
20583
+ compass_version: view.compassVersion,
20584
+ plan_ids: view.planIds,
20585
+ allowed: view.allowed,
20586
+ blockers: view.blockers
20587
+ };
20588
+ if (result.outcome !== undefined)
20589
+ payload.outcome = result.outcome;
20590
+ console.log(JSON.stringify(payload));
20591
+ return;
20592
+ }
20593
+ console.error(import_picocolors2.default.green(`workflow ${verb}: ${result.session.role} session ${result.session.session_id} (workflow ${view.workflowId})`));
20594
+ console.error(`workflow ${verb}: session file ${result.session_file}`);
20595
+ console.error(`workflow ${verb}: snapshot ${view.snapshotVersion}, compass ${view.compassVersion}`);
20596
+ console.error(`workflow ${verb}: plans ${view.planIds.join(", ") || "(none)"}`);
20597
+ console.error(`workflow ${verb}: ${view.allowed ? "amendment admissible" : `blocked \u2014 ${view.blockers.join("; ")}`}`);
20598
+ if (result.outcome !== undefined)
20599
+ console.error(`workflow ${verb}: ${result.outcome}`);
20600
+ }
20601
+ function registerWorkflowCommands(program2) {
20602
+ const workflow = program2.command("workflow").description("Workflow-level Prepare amendment: read the current snapshot/compass byte versions and the admission view " + "(`show-prepare`), then apply one approved structural delta (`amend-prepare`) (engine-backed; JSON on stdout " + "with --json, diagnostics on stderr; exit 0 ok, 1 refusal, 2 usage)").exitOverride();
20603
+ workflow.command("show-prepare").description("Read the Prepare amendment view of one coordinator-bound workflow: both byte versions, the current plan ids " + "and whether an amendment is admissible (read-only: no lock, no write)").option("--session <path>", "Absolute coordinator session JSON envelope path").option("--json", "Machine-readable JSON on stdout").action(async (options) => runVerb("show-prepare", options, {}, async (json) => {
20604
+ const sessionPath = requireAbsolutePath(options.session, "--session", "show-prepare", "session-json-path");
20605
+ pinSessionRoot(sessionPath);
20606
+ printWorkflowView("show-prepare", await showPrepareWorkflow({ sessionPath, cwd: process.cwd() }), json);
20607
+ }));
20608
+ workflow.command("amend-prepare").description("Append approved Todo plan rows, record the reviewed integration checkout and the approved plan parallelism " + "(coordinator session; both byte versions from `workflow show-prepare` are required)").option("--session <path>", "Absolute coordinator session JSON envelope path").option("--expect-snapshot <sha256>", "Current snapshot byte version from `workflow show-prepare`").option("--expect-compass <sha256>", "Current compass byte version from `workflow show-prepare`").option("--input <path>", "Absolute path of the PrepareWorkflowPatch JSON payload").option("--json", "Machine-readable JSON on stdout").action(async (options) => runVerb("amend-prepare", options, {}, async (json) => {
20609
+ const sessionPath = requireAbsolutePath(options.session, "--session", "amend-prepare", "session-json-path");
20610
+ const expectedSnapshotVersion = parsePrepareVersion(options.expectSnapshot, "--expect-snapshot", "amend-prepare");
20611
+ const expectedCompassVersion = parsePrepareVersion(options.expectCompass, "--expect-compass", "amend-prepare");
20612
+ const patch = readJsonPayload(options.input, "--input", "amend-prepare");
20613
+ pinSessionRoot(sessionPath);
20614
+ printWorkflowView("amend-prepare", await amendPrepareWorkflow({
20615
+ sessionPath,
20616
+ cwd: process.cwd(),
20617
+ expectedSnapshotVersion,
20618
+ expectedCompassVersion,
20619
+ patch
20620
+ }), json);
20621
+ }));
20622
+ for (const command of [workflow, ...workflow.commands])
20623
+ command.exitOverride();
20624
+ }
19318
20625
 
19319
20626
  // src/commands/migrate.ts
19320
20627
  var import_picocolors3 = __toESM(require_picocolors2(), 1);
19321
- import { resolve as resolve16 } from "node:path";
20628
+ import { resolve as resolve17 } from "node:path";
19322
20629
  function validatePlannedDocs(plan) {
19323
20630
  const warnings = [];
19324
20631
  for (const snapshot of plan.snapshots) {
@@ -19340,11 +20647,17 @@ function validatePlannedDocs(plan) {
19340
20647
  return warnings;
19341
20648
  }
19342
20649
  async function runMigrateCommand(options) {
19343
- const root = options.path ? resolve16(options.path) : resolveHarnessDir2() ?? process.cwd();
20650
+ const root = options.path ? resolve17(options.path) : resolveHarnessDir2() ?? process.cwd();
19344
20651
  setArtifactStore2(createFsStore2(root));
19345
20652
  let plan;
19346
20653
  try {
19347
- plan = migrateHarnessTree(root, { dryRun: options.dryRun === true });
20654
+ plan = migrateHarnessTree(root, {
20655
+ dryRun: options.dryRun === true,
20656
+ ...options.deliveryKind !== undefined ? { deliveryKind: options.deliveryKind } : {},
20657
+ ...options.branchSource !== undefined ? { branchSource: options.branchSource } : {},
20658
+ ...options.branchTarget !== undefined ? { branchTarget: options.branchTarget } : {},
20659
+ ...options.completionPolicy !== undefined ? { completionPolicy: options.completionPolicy } : {}
20660
+ });
19348
20661
  } catch (error) {
19349
20662
  const message = error.message;
19350
20663
  if (options.json) {
@@ -19373,6 +20686,26 @@ async function runMigrateCommand(options) {
19373
20686
  }
19374
20687
  return;
19375
20688
  }
20689
+ if (plan.deliveryKindAmbiguous.length > 0) {
20690
+ const message = `a single delivery declaration cannot describe ${plan.deliveryKindAmbiguous.length} active standalone plan lifts ` + `(${plan.deliveryKindAmbiguous.join(", ")}) \u2014 migrate them in batches of one declared plan, ` + `running migrate once per plan with that plan's own --delivery-kind evidence`;
20691
+ if (options.json) {
20692
+ console.log(JSON.stringify({ ok: false, root, phase: "plan", exitCode: 2, error: message }));
20693
+ } else {
20694
+ console.error(import_picocolors3.default.red(`migrate: ${message}`));
20695
+ }
20696
+ process.exitCode = 2;
20697
+ return;
20698
+ }
20699
+ if (plan.deliveryKindRequired.length > 0) {
20700
+ const message = `${plan.deliveryKindRequired.length} active standalone plan snapshot(s) would be lifted without a declared delivery kind ` + `(${plan.deliveryKindRequired.join(", ")}) \u2014 pass --delivery-kind <${WORKFLOW_DELIVERY_KINDS2.join("|")}> with its evidence ` + `(development: --branch-source/--branch-target; verification/report-only: --completion-policy)`;
20701
+ if (options.json) {
20702
+ console.log(JSON.stringify({ ok: false, root, phase: "plan", exitCode: 2, error: message }));
20703
+ } else {
20704
+ console.error(import_picocolors3.default.red(`migrate: ${message}`));
20705
+ }
20706
+ process.exitCode = 2;
20707
+ return;
20708
+ }
19376
20709
  if (plan.dryRun) {
19377
20710
  const header = `dry-run: ${plan.steps.length} steps planned (source \u2192 destination), zero writes`;
19378
20711
  const validationWarnings = validatePlannedDocs(plan);
@@ -22431,7 +23764,7 @@ statusCommand.command("backlog-close").description("Close one project-register b
22431
23764
  process.exitCode = 1;
22432
23765
  }
22433
23766
  });
22434
- statusCommand.command("workflow-close").description("Close one workflow lifecycle after its delivery PR merged (engine-backed: closeWorkflow writes the " + "terminal snapshot under the snapshot lock, then unregisterWorkflow removes the root status.json entry " + "idempotently; dangling leases and unfinished plan rows refuse before any write; a fully closed retry " + "rewrites nothing; a failed unregister reports a partial close and a re-run finishes it. " + "Exit 0 success, 1 gate/IO refusal, 2 usage)").option("--workflow <id>", "Workflow id to close ({WORKFLOW_DIR}/<id>/snapshot.json)").option("--harness <path>", "Harness dir override (default: resolved control {HARNESS_DIR})").option("--ended-at <date>", "Terminal ended_at timestamp (YYYY-MM-DD or RFC3339; default: today)").option("--session <path>", "Absolute coordinator session JSON envelope path (required to close a coordinated workflow)").action(async (options) => {
23767
+ statusCommand.command("workflow-close").description("Close one workflow lifecycle after its delivery tail completes \u2014 type-generic: iterations and standalone " + "`type: plan` workflows close through this same verb (engine-backed: closeWorkflow consults the registered " + "delivery evidence, then writes the terminal snapshot under the snapshot lock, then unregisterWorkflow " + "removes the root status.json entry idempotently; dangling leases, unfinished plan rows and incomplete " + "delivery evidence refuse before any write; a fully closed retry rewrites nothing; a failed unregister " + "reports a partial close and a re-run finishes it. " + "Standalone plan workflows: the close consults the delivery evidence BEFORE writing \u2014 a `development` " + "workflow needs its registered source/target branches plus the recorded compound disposition, PR identity " + "and verified-merge evidence (`mstar workflow evidence --workflow <id> --file <payload.json>`, \xA74c/\xA74d/\xA74f); " + "`verification/report-only` needs its recorded completion policy plus its fulfilment record. The same " + "consultation backs the read-only check 'mstar iteration gate --phase 6 --workflow <id>', so gate and " + "close never disagree. " + "Exit 0 success, 1 gate/IO refusal, 2 usage)").option("--workflow <id>", "Workflow id to close ({WORKFLOW_DIR}/<id>/snapshot.json)").option("--harness <path>", "Harness dir override (default: resolved control {HARNESS_DIR})").option("--ended-at <date>", "Terminal ended_at timestamp (YYYY-MM-DD or RFC3339; default: today)").option("--session <path>", "Absolute coordinator session JSON envelope path (required to close a coordinated workflow)").action(async (options) => {
22435
23768
  try {
22436
23769
  const workflowId = options.workflow;
22437
23770
  if (workflowId === undefined || workflowId.trim() === "") {
@@ -22475,7 +23808,117 @@ statusCommand.command("archive-residuals").description("Removed in v3 \u2014 res
22475
23808
  console.error(import_picocolors4.default.red("status archive-residuals: removed in v3 \u2014 residuals live in project registers; close entries in " + "projects/<id>/residuals.json (set lifecycle to resolved/waived/superseded with closure fields) instead"));
22476
23809
  process.exitCode = 1;
22477
23810
  });
22478
- var migrateCommand = program2.command("migrate").description("Migrate a v1 {HARNESS_DIR} status.json tree to v2 (engine-backed; exit 0 ok/idempotent no-op, 1 plan-invalid, 2 apply-failure)").option("--dry-run", "Print the migration step plan (source \u2192 destination) + planned-document validation warnings without writing anything").option("--path <root>", "Harness root to migrate (default: resolved {HARNESS_DIR}, else cwd)").option("--json", "Machine-readable JSON output").action(async (options) => {
23811
+ var workflowCommand = new Command("workflow").description("Workflow lifecycle verbs (engine-backed): registration of standalone plan workflows and the recording of " + "their delivery evidence. " + "Terminal close stays on `status workflow-close`");
23812
+ workflowCommand.command("register").description("Register a standalone plan workflow (mstar-artifacts/references/plan-workflow-lifecycle-contract.md seam S1, engine-backed): " + "create-only `type: plan` snapshot + {HARNESS_DIR}/status.json root entry under one lock. Records the " + "owned plan (one Todo row \u2014 registration does not authorize implementation), project, delivery kind, " + "source/target branches and optional coordinator. `development` requires --branch-source/--branch-target; " + "`verification/report-only` requires --completion-policy. Re-running after a crash between snapshot " + "creation and registration recovers: the existing snapshot bytes are kept and only the root entry is " + "written. Exit 0 success, 1 gate/IO refusal (no partial activation), 2 usage").option("--workflow <id>", "Workflow id (single safe path component)").option("--plan-id <id>", "Owned plan id (one independently owned plan per workflow on the normal route)").option("--plan-title <title>", "Owned plan title").option("--plan-file <path>", "Owned plan file path recorded on the row").option("--delivery-kind <kind>", `Delivery kind declared at registration (contract \xA71): ${WORKFLOW_DELIVERY_KINDS.join(" | ")}`).option("--project <id>", "Project register id recorded on the snapshot").option("--branch-source <branch>", "Source branch (required for development)").option("--branch-target <branch>", "Target branch (required for development)").option("--completion-policy <text>", "Completion evidence policy (required for verification/report-only)").option("--started-at <timestamp>", "Registration timestamp (YYYY-MM-DD or RFC3339; default: now)").option("--harness <path>", "Harness dir override (default: resolved control {HARNESS_DIR})").action(async (options) => {
23813
+ try {
23814
+ const usage = "usage: workflow register --workflow <id> --plan-id <id> --plan-title <title> --plan-file <path> " + `--delivery-kind <${WORKFLOW_DELIVERY_KINDS.join("|")}> [--project <id>] [--branch-source <branch>] ` + "[--branch-target <branch>] [--completion-policy <text>] [--started-at <ts>] [--harness <dir>]";
23815
+ const missing = [
23816
+ ["--workflow", options.workflow],
23817
+ ["--plan-id", options.planId],
23818
+ ["--plan-title", options.planTitle],
23819
+ ["--plan-file", options.planFile],
23820
+ ["--delivery-kind", options.deliveryKind]
23821
+ ].filter(([, value]) => value === undefined || value.trim() === "").map(([flag]) => flag);
23822
+ if (missing.length > 0) {
23823
+ throw new SddScriptError(`missing required option(s): ${missing.join(", ")}
23824
+ ${usage}`, 2);
23825
+ }
23826
+ if (!WORKFLOW_DELIVERY_KINDS.includes(options.deliveryKind)) {
23827
+ throw new SddScriptError(`--delivery-kind must be one of ${WORKFLOW_DELIVERY_KINDS.join(" | ")} \u2014 got ${JSON.stringify(options.deliveryKind)}
23828
+ ${usage}`, 2);
23829
+ }
23830
+ assertWorkflowId(options.workflow);
23831
+ const harnessDir = resolveProcessHarnessDir3(options.harness);
23832
+ if (!harnessDir) {
23833
+ throw new Error(`harness dir not found from ${process.cwd()} \u2014 pass --harness <path>`);
23834
+ }
23835
+ setArtifactStore(createFsStore(harnessDir));
23836
+ const result = await registerPlanWorkflow(options.workflow, {
23837
+ harnessDir,
23838
+ plan: { id: options.planId, title: options.planTitle, file: options.planFile },
23839
+ deliveryKind: options.deliveryKind,
23840
+ ...options.project !== undefined ? { project: options.project } : {},
23841
+ ...options.branchSource !== undefined ? { branchSource: options.branchSource } : {},
23842
+ ...options.branchTarget !== undefined ? { branchTarget: options.branchTarget } : {},
23843
+ ...options.completionPolicy !== undefined ? { completionPolicy: options.completionPolicy } : {},
23844
+ ...options.startedAt !== undefined ? { startedAt: options.startedAt } : {}
23845
+ });
23846
+ console.log(import_picocolors4.default.green(result.recovered ? `workflow register: OK \u2014 ${result.workflowId} recovered (registration completed for the existing snapshot; its bytes were preserved)` : `workflow register: OK \u2014 ${result.workflowId} registered`));
23847
+ console.log(` snapshot: ${result.snapshotPath}`);
23848
+ } catch (error) {
23849
+ failScript(error, "workflow register");
23850
+ }
23851
+ });
23852
+ function readJsonPayloadFile(raw, flag, verb) {
23853
+ if (raw === undefined || raw.trim() === "") {
23854
+ throw new SddScriptError(`${flag} is required (absolute path of the delivery-evidence JSON payload)`, 2);
23855
+ }
23856
+ if (!path15.isAbsolute(raw)) {
23857
+ throw new SddScriptError(`${flag} must be an absolute path \u2014 got ${JSON.stringify(raw)}`, 2);
23858
+ }
23859
+ if (!fs12.existsSync(raw)) {
23860
+ throw new SddScriptError(`${flag} not found: ${raw}`, 2);
23861
+ }
23862
+ let parsed;
23863
+ try {
23864
+ parsed = JSON.parse(fs12.readFileSync(raw, "utf8"));
23865
+ } catch (error) {
23866
+ throw new Error(`${verb}: ${flag} payload is not valid JSON (${error.message})`);
23867
+ }
23868
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
23869
+ throw new Error(`${verb}: ${flag} payload must be a JSON object (the delivery-evidence members to record)`);
23870
+ }
23871
+ return parsed;
23872
+ }
23873
+ workflowCommand.command("evidence").description("Record the delivery-kind evidence a standalone `type: plan` workflow is closed against, or declare the delivery " + "kind of an ACTIVE kind-less snapshot (mstar-artifacts/references/plan-workflow-lifecycle-contract.md \xA71/\xA73/\xA74a/\xA74c/\xA74d/\xA74f; " + "engine-backed). With --file, the payload JSON is merged into the snapshot's `delivery` block under the " + "snapshot lock, so evidence can be recorded stage by stage: `development` records the compound disposition " + "(\xA74c, before the PR head is finalized), the PR identity (\xA74d, at submission \u2014 recorded once, pinned to " + "the registered delivery) and the PM's verified-merge record (\xA74f \u2014 the engine never verifies the remote " + "merge itself); `verification/report-only` records the fulfilment of its registered completion policy (\xA71). " + "With --declare-kind, an ACTIVE `type: plan` snapshot that carries no kind (audit promotion / v1 lift from " + "before the producers declared one) receives its kind and its per-kind evidence ONCE \u2014 a second declaration, " + "even with the same value, and any terminal snapshot, are refused. A supplied --branch-source/--branch-target " + "fills a missing delivery anchor or restates the registered one; a value conflicting with an anchor the " + "snapshot already carries is refused (the registered anchor is the delivery identity, never overwritten). " + "Authorized exactly like the close: a " + "coordinated workflow's snapshot is written only for its own bound coordinator envelope (--session). " + "Exit 0 success/no-op, 1 gate/IO refusal, 2 usage").option("--workflow <id>", "Workflow id ({WORKFLOW_DIR}/<id>/snapshot.json)").option("--file <path>", "Absolute path of the delivery-evidence JSON payload (record mode)").option("--declare-kind <kind>", `Declare the delivery kind of an ACTIVE kind-less plan snapshot (one-time): ${WORKFLOW_DELIVERY_KINDS.join(" | ")}`).option("--branch-source <branch>", "Delivery source branch recorded as branch.source (declare mode; required for development)").option("--branch-target <branch>", "Delivery target branch recorded as branch.target (declare mode; required for development)").option("--completion-policy <text>", "Completion policy for verification/report-only (declare mode; required for that kind)").option("--session <path>", "Absolute coordinator session JSON envelope path (required to write a coordinated workflow)").option("--at <timestamp>", "Recording/declaration timestamp (YYYY-MM-DD or RFC3339; default: now)").option("--harness <path>", "Harness dir override (default: resolved control {HARNESS_DIR})").action(async (options) => {
23874
+ try {
23875
+ const workflowId = options.workflow;
23876
+ const usage = "usage: workflow evidence --workflow <id> (--file <payload.json> | --declare-kind <kind> " + "[--branch-source <branch> --branch-target <branch> | --completion-policy <text>]) " + "[--session <path>] [--at <ts>] [--harness <path>]";
23877
+ if (workflowId === undefined || workflowId.trim() === "") {
23878
+ throw new SddScriptError(usage, 2);
23879
+ }
23880
+ const declareKind = options.declareKind;
23881
+ const declaring = declareKind !== undefined;
23882
+ if (declaring && options.file !== undefined) {
23883
+ throw new SddScriptError(`pass either --file (record evidence) or --declare-kind (one-time declaration), not both
23884
+ ${usage}`, 2);
23885
+ }
23886
+ if (declaring && !WORKFLOW_DELIVERY_KINDS.includes(declareKind)) {
23887
+ throw new SddScriptError(`--declare-kind must be one of ${WORKFLOW_DELIVERY_KINDS.join(" | ")} \u2014 got ${JSON.stringify(declareKind)}
23888
+ ${usage}`, 2);
23889
+ }
23890
+ const evidence = declaring ? undefined : readJsonPayloadFile(options.file, "--file", "workflow evidence");
23891
+ const sessionPath = resolveSessionFlag(options.session);
23892
+ assertWorkflowId(workflowId);
23893
+ const harnessDir = resolveProcessHarnessDir3(options.harness);
23894
+ if (!harnessDir) {
23895
+ throw new Error(`harness dir not found from ${process.cwd()} \u2014 pass --harness <path>`);
23896
+ }
23897
+ setArtifactStore(createFsStore(harnessDir));
23898
+ const snapshotDir = path15.join(resolveWorkflowDir(harnessDir, { harnessDir }), workflowId);
23899
+ if (declaring) {
23900
+ const declared = await declareWorkflowDeliveryKind(workflowId, snapshotDir, {
23901
+ deliveryKind: declareKind,
23902
+ ...options.branchSource !== undefined ? { branchSource: options.branchSource } : {},
23903
+ ...options.branchTarget !== undefined ? { branchTarget: options.branchTarget } : {},
23904
+ ...options.completionPolicy !== undefined ? { completionPolicy: options.completionPolicy } : {},
23905
+ ...sessionPath !== undefined ? { sessionPath } : {},
23906
+ ...options.at !== undefined ? { at: options.at } : {}
23907
+ });
23908
+ console.log(import_picocolors4.default.green(`workflow evidence: OK \u2014 ${workflowId} delivery kind declared (${String(declared.delivery_kind)}; declared once, never re-declared)`));
23909
+ return;
23910
+ }
23911
+ const result = await recordWorkflowDelivery(workflowId, snapshotDir, {
23912
+ evidence,
23913
+ ...sessionPath !== undefined ? { sessionPath } : {},
23914
+ ...options.at !== undefined ? { at: options.at } : {}
23915
+ });
23916
+ console.log(import_picocolors4.default.green(result.written ? `workflow evidence: OK \u2014 ${workflowId} delivery evidence recorded (${Object.keys(evidence).join(", ")})` : `workflow evidence: OK \u2014 ${workflowId} already carries this delivery evidence (nothing rewritten)`));
23917
+ } catch (error) {
23918
+ failScript(error, "workflow evidence");
23919
+ }
23920
+ });
23921
+ var migrateCommand = program2.command("migrate").description("Migrate a v1 {HARNESS_DIR} status.json tree to v2 (engine-backed; exit 0 ok/idempotent no-op, 1 plan-invalid, " + "2 usage (missing --delivery-kind for an ACTIVE standalone plan lift, or one declaration for 2+ such lifts) / " + "apply-failure). " + "--delivery-kind declares the lifted ACTIVE plan workflows' kind (contract \xA71/\xA74a); " + "`development` needs --branch-source/--branch-target, `verification/report-only` --completion-policy. " + "It is ONE delivery identity, so a tree whose lift creates 2+ ACTIVE standalone plans is refused (exit 2, ids " + "listed) \u2014 migrate in batches of one declared plan").option("--dry-run", "Print the migration step plan (source \u2192 destination) + planned-document validation warnings without writing anything").option("--path <root>", "Harness root to migrate (default: resolved {HARNESS_DIR}, else cwd)").option("--delivery-kind <kind>", `Delivery kind for lifted ACTIVE standalone plan snapshots (exactly one such lift per run): ${WORKFLOW_DELIVERY_KINDS.join(" | ")}`).option("--branch-source <branch>", "Delivery source branch recorded as branch.source (required for development)").option("--branch-target <branch>", "Delivery target branch recorded as branch.target (required for development)").option("--completion-policy <text>", "Completion policy for verification/report-only lifts (required for that kind)").option("--json", "Machine-readable JSON output").action(async (options) => {
22479
23922
  await runMigrateCommand(options);
22480
23923
  });
22481
23924
  var persistCommand = program2.command("persist").description("Persist one JSON coordination doc through the ArtifactStore (status / snapshot / residuals / review / json). " + "Faces: put (default), get [--validate], list (keys only, no header), delete (idempotent). " + "The default FsStore resolves the harness dir from the cwd / MSTAR_HARNESS_DIR; --store <module> or " + "MSTAR_STORE_MODULE injects a module-backed store (filesystem paths only) for the process.");
@@ -24018,14 +25461,23 @@ auditCommand.command("scaffold").description("Scaffold an audit-<date>/ plan dir
24018
25461
  failScript(error, "audit scaffold");
24019
25462
  }
24020
25463
  });
24021
- auditCommand.command("promote").description("Promote selected audit plans into the v2 workflow lifecycle: write the workflow snapshot " + "(type plan, Todo rows) then register the workflow in {HARNESS_DIR}/status.json " + "(exit 2 on usage, 1 when the harness dir cannot be resolved)").argument("[audit-dir]", "audit-<date>/ directory under {PLAN_DIR}").option("--plans <ids>", "Comma-separated selected plan ids (README Plan column `001`, stem, or basename)").option("--workflow <id>", "Workflow id (default: audit-<date> basename)").option("--harness <dir>", "Harness dir containing status.json (default: resolveHarnessDir() / MSTAR_HARNESS_DIR)").action(async (auditDir, options) => {
25464
+ auditCommand.command("promote").description("Promote selected audit plans into the v2 workflow lifecycle: write the workflow snapshot " + "(type plan, Todo rows, the declared delivery kind + its evidence) then register the workflow in " + "{HARNESS_DIR}/status.json. --delivery-kind is required: the promoted lifecycle declares its kind at " + "registration (mstar-artifacts/references/plan-workflow-lifecycle-contract.md \xA71/\xA74a), never inferred and never defaulted \u2014 " + "`development` requires --branch-source/--branch-target, `verification/report-only` --completion-policy. " + "(exit 2 on usage, 1 when the harness dir cannot be resolved)").argument("[audit-dir]", "audit-<date>/ directory under {PLAN_DIR}").option("--plans <ids>", "Comma-separated selected plan ids (README Plan column `001`, stem, or basename)").option("--workflow <id>", "Workflow id (default: audit-<date> basename)").option("--delivery-kind <kind>", `Delivery kind declared for the promoted plans (required): ${WORKFLOW_DELIVERY_KINDS.join(" | ")}`).option("--branch-source <branch>", "Delivery source branch recorded as branch.source (required for development)").option("--branch-target <branch>", "Delivery target branch recorded as branch.target (required for development)").option("--completion-policy <text>", "Completion policy naming the evidence that completes the workflow (required for verification/report-only)").option("--harness <dir>", "Harness dir containing status.json (default: resolveHarnessDir() / MSTAR_HARNESS_DIR)").action(async (auditDir, options) => {
24022
25465
  try {
25466
+ const usage = "usage: audit promote <audit-dir> --plans <ids> --delivery-kind <kind> [--workflow <id>] " + "[--branch-source <branch> --branch-target <branch> | --completion-policy <text>] [--harness <dir>]";
24023
25467
  if (!auditDir) {
24024
- throw new SddScriptError("usage: audit promote <audit-dir> --plans <ids> [--workflow <id>] [--harness <dir>]", 2);
25468
+ throw new SddScriptError(usage, 2);
24025
25469
  }
24026
25470
  const selected = parseCsv(options.plans);
24027
25471
  if (!selected || selected.length === 0) {
24028
- throw new SddScriptError("usage: audit promote <audit-dir> --plans <ids> [--workflow <id>] [--harness <dir>]", 2);
25472
+ throw new SddScriptError(usage, 2);
25473
+ }
25474
+ if (options.deliveryKind === undefined || options.deliveryKind.trim() === "") {
25475
+ throw new SddScriptError(`missing required option: --delivery-kind <${WORKFLOW_DELIVERY_KINDS.join("|")}>
25476
+ ${usage}`, 2);
25477
+ }
25478
+ if (!WORKFLOW_DELIVERY_KINDS.includes(options.deliveryKind)) {
25479
+ throw new SddScriptError(`--delivery-kind must be one of ${WORKFLOW_DELIVERY_KINDS.join(" | ")} \u2014 got ${JSON.stringify(options.deliveryKind)}
25480
+ ${usage}`, 2);
24029
25481
  }
24030
25482
  const outDir = resolveCliPath(auditDir);
24031
25483
  if (!fs12.existsSync(outDir)) {
@@ -24035,7 +25487,11 @@ auditCommand.command("promote").description("Promote selected audit plans into t
24035
25487
  setArtifactStore(createFsStore(harnessDir));
24036
25488
  const result = await promoteAuditPlans(outDir, selected, {
24037
25489
  harnessDir,
24038
- ...options.workflow !== undefined ? { workflowId: options.workflow } : {}
25490
+ deliveryKind: options.deliveryKind,
25491
+ ...options.workflow !== undefined ? { workflowId: options.workflow } : {},
25492
+ ...options.branchSource !== undefined ? { branchSource: options.branchSource } : {},
25493
+ ...options.branchTarget !== undefined ? { branchTarget: options.branchTarget } : {},
25494
+ ...options.completionPolicy !== undefined ? { completionPolicy: options.completionPolicy } : {}
24039
25495
  });
24040
25496
  console.log(import_picocolors4.default.green(`audit promote: OK \u2014 workflow ${result.workflowId} registered`));
24041
25497
  console.log(` snapshot: ${result.snapshotPath}`);
@@ -25104,6 +26560,17 @@ prReviewCommand.command("budget").description("Print the per-tier time-budget ta
25104
26560
  }
25105
26561
  });
25106
26562
  registerPlanCommands(program2);
26563
+ registerWorkflowCommands(program2);
26564
+ function attachWorkflowGroup(target) {
26565
+ const existing = target.commands.find((command) => command.name() === "workflow");
26566
+ if (existing === undefined) {
26567
+ target.addCommand(workflowCommand);
26568
+ return;
26569
+ }
26570
+ for (const verb of workflowCommand.commands)
26571
+ existing.addCommand(verb);
26572
+ }
26573
+ attachWorkflowGroup(program2);
25107
26574
  program2.parseAsync(process.argv).catch((error) => {
25108
26575
  if (error instanceof CommanderError) {
25109
26576
  if (process.argv.includes("--json")) {