@mstar-harness/cli 3.6.3 → 3.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/mstar-harness.js +1423 -387
  2. package/package.json +1 -1
@@ -2432,8 +2432,8 @@ var require_picocolors2 = __commonJS(function(exports, module) {
2432
2432
  // src/index.ts
2433
2433
  import { execFileSync as execFileSync10 } from "child_process";
2434
2434
  import { createHash, randomUUID as randomUUID3 } from "crypto";
2435
- import fs8 from "fs";
2436
- import path12 from "path";
2435
+ import fs9 from "fs";
2436
+ import path14 from "path";
2437
2437
  // ../../node_modules/.bun/@inquirer+core@12.0.2+1c220d1d55e2409f/node_modules/@inquirer/core/dist/lib/key.js
2438
2438
  var keybindings = ["emacs", "vim"];
2439
2439
  var keybindingLookup = new Set(keybindings);
@@ -4104,20 +4104,21 @@ import { isAbsolute as isAbsolute3, join as join5, resolve as resolve4 } from "n
4104
4104
  import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync3, realpathSync } from "node:fs";
4105
4105
  import { dirname as dirname4, join as join7, resolve as resolve5, sep } from "node:path";
4106
4106
  import { execFileSync as execFileSync2 } from "node:child_process";
4107
- import { existsSync as existsSync7 } from "node:fs";
4108
- import { isAbsolute as isAbsolute5, resolve as resolve8 } from "node:path";
4109
- import { execFileSync as execFileSync3 } from "node:child_process";
4110
- import { mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as readFileSync7, realpathSync as realpathSync3, statSync as statSync4, writeFileSync as writeFileSync4 } from "node:fs";
4111
- import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute6, join as join10, resolve as resolve9 } from "node:path";
4107
+ import { existsSync as existsSync7, realpathSync as realpathSync3 } from "node:fs";
4108
+ import { isAbsolute as isAbsolute5, join as join10, resolve as resolve8 } from "node:path";
4109
+ import { execFileSync as execFileSync3, spawn } from "node:child_process";
4110
+ import { mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as readFileSync7, realpathSync as realpathSync4, statSync as statSync4, writeFileSync as writeFileSync4 } from "node:fs";
4111
+ import { constants as osConstants } from "node:os";
4112
+ import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute6, join as join11, relative as relative3, resolve as resolve9 } from "node:path";
4112
4113
  import { execFileSync as execFileSync4 } from "node:child_process";
4113
- import { existsSync as existsSync8, mkdirSync as mkdirSync8, readdirSync as readdirSync8, readFileSync as readFileSync9, rmdirSync as rmdirSync2, rmSync, writeFileSync as writeFileSync6 } from "node:fs";
4114
- import { basename as basename5, join as join12, resolve as resolve11, sep as sep3 } from "node:path";
4115
- import { existsSync as existsSync9, readdirSync as readdirSync9, readFileSync as readFileSync10 } from "node:fs";
4116
- import { basename as basename6, isAbsolute as isAbsolute8, join as join13, relative as relative4, resolve as resolve12, sep as sep4 } from "node:path";
4117
- import { existsSync as existsSync10 } from "node:fs";
4118
- import { join as join14 } from "node:path";
4114
+ import { existsSync as existsSync9, mkdirSync as mkdirSync8, readdirSync as readdirSync8, readFileSync as readFileSync9, rmdirSync as rmdirSync2, rmSync, writeFileSync as writeFileSync6 } from "node:fs";
4115
+ import { basename as basename6, join as join14, resolve as resolve12, sep as sep3 } from "node:path";
4116
+ import { existsSync as existsSync10, readdirSync as readdirSync9, readFileSync as readFileSync10 } from "node:fs";
4117
+ import { basename as basename7, isAbsolute as isAbsolute8, join as join15, relative as relative6, resolve as resolve13, sep as sep4 } from "node:path";
4118
+ import { existsSync as existsSync11 } from "node:fs";
4119
+ import { join as join16 } from "node:path";
4119
4120
  import { readdirSync as readdirSync10 } from "node:fs";
4120
- import { isAbsolute as isAbsolute9, join as join15 } from "node:path";
4121
+ import { isAbsolute as isAbsolute9, join as join17 } from "node:path";
4121
4122
  var SEVERITY_ORDER = ["critical", "high", "medium", "low", "nit"];
4122
4123
  function readJson(filePath) {
4123
4124
  if (!existsSync(filePath))
@@ -4590,6 +4591,32 @@ function validateIntegrationMergeLease(lease) {
4590
4591
  }
4591
4592
  return { ok: violations.length === 0, violations };
4592
4593
  }
4594
+ function planExecutionLeaseLocations(row) {
4595
+ return { row: row.execution_lease };
4596
+ }
4597
+ function verifyPlanExecutionLease(row, planId) {
4598
+ const { row: rowLease } = planExecutionLeaseLocations(row);
4599
+ const lease = rowLease;
4600
+ if (lease === undefined) {
4601
+ if (row.status === "InProgress") {
4602
+ return {
4603
+ ok: false,
4604
+ violations: [
4605
+ violation2("high", "lease.verify.orphan", "plan is InProgress without an execution_lease \u2014 orphan: STOP, no writable dispatch until recovery (status-and-residuals.md \u00a7 Orphan recovery)")
4606
+ ]
4607
+ };
4608
+ }
4609
+ return {
4610
+ ok: false,
4611
+ violations: [
4612
+ violation2("high", "lease.verify.missing", `plan ${planId} has no execution_lease at the SSOT location plans[].execution_lease`)
4613
+ ]
4614
+ };
4615
+ }
4616
+ const violations = [];
4617
+ violations.push(...validateExecutionLease(lease).violations);
4618
+ return { ok: violations.length === 0, violations, lease };
4619
+ }
4593
4620
  var STATUS_WRITE_LOCKDIR = ".status-write.lockdir";
4594
4621
  var LOCKDIR_HOLDER_PID = "holder.pid";
4595
4622
  var heldLockDirs = new AsyncLocalStorage2;
@@ -5664,11 +5691,40 @@ function resolveSpecsDir(harnessDir, opts = {}) {
5664
5691
  mkdirSync5(fallback, { recursive: true });
5665
5692
  return fallback;
5666
5693
  }
5694
+ function resolvePlanDir(harnessDir) {
5695
+ const declared = mstarcDirOverride(harnessDir, "planDir");
5696
+ if (declared !== null)
5697
+ return declared;
5698
+ const dir = resolve7(harnessDir);
5699
+ const name = basename3(dir);
5700
+ if (name === ".plans" || name === "plans")
5701
+ return dir;
5702
+ return join9(dir, "plans");
5703
+ }
5667
5704
  function assertSafePathComponent(value, what) {
5668
5705
  if (value === "" || value === "." || value === ".." || !/^[A-Za-z0-9._-]+$/.test(value)) {
5669
5706
  throw new Error(`${what} must be a single safe path component ([A-Za-z0-9._-]+; not "", ".", "..", or containing "/" or "\\") \u2014 got ${JSON.stringify(value)}`);
5670
5707
  }
5671
5708
  }
5709
+ function canonicalizeNearestExisting(path2) {
5710
+ const abs = resolve7(path2);
5711
+ let dir = abs;
5712
+ const tail = [];
5713
+ for (;; ) {
5714
+ if (existsSync6(dir)) {
5715
+ try {
5716
+ return join9(realpathSync2(dir), ...tail);
5717
+ } catch {
5718
+ return abs;
5719
+ }
5720
+ }
5721
+ const parent = dirname5(dir);
5722
+ if (parent === dir)
5723
+ return abs;
5724
+ tail.unshift(basename3(dir));
5725
+ dir = parent;
5726
+ }
5727
+ }
5672
5728
  function resolveSddDir(harnessDir, planId) {
5673
5729
  assertSafePathComponent(planId, "planId");
5674
5730
  const base = resolve7(harnessDir);
@@ -5783,6 +5839,53 @@ function detectHarnessKind(harnessDir) {
5783
5839
  return "agents";
5784
5840
  return null;
5785
5841
  }
5842
+ function assertPlanWritingPath(planPath, harnessDir) {
5843
+ const planAbs = resolve7(planPath);
5844
+ if (!harnessDir) {
5845
+ return {
5846
+ ok: false,
5847
+ severity: "high",
5848
+ code: "plan-path.no-harness",
5849
+ message: `persistent plan tracking is not enabled \u2014 cannot place plan ${planAbs} under {PLAN_DIR}`,
5850
+ fix: "initialize the harness (scaffoldHarness) so plans land in {PLAN_DIR}"
5851
+ };
5852
+ }
5853
+ const planDir = resolvePlanDir(harnessDir);
5854
+ const rel = relative2(planDir, planAbs);
5855
+ const inside = rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
5856
+ if (!inside) {
5857
+ return {
5858
+ ok: false,
5859
+ severity: "high",
5860
+ code: "plan-path.outside-plan-dir",
5861
+ message: `plan file ${planAbs} is outside {PLAN_DIR} (${planDir})`,
5862
+ fix: `write the plan under ${planDir}`
5863
+ };
5864
+ }
5865
+ if (existsSync6(planAbs)) {
5866
+ try {
5867
+ const canonicalPlan = realpathSync2(planAbs);
5868
+ const canonicalPlanDir = existsSync6(planDir) ? realpathSync2(planDir) : resolve7(planDir);
5869
+ const canonicalRel = relative2(canonicalPlanDir, canonicalPlan);
5870
+ const canonicalInside = canonicalRel === "" || !canonicalRel.startsWith("..") && !isAbsolute4(canonicalRel);
5871
+ if (!canonicalInside) {
5872
+ return {
5873
+ ok: false,
5874
+ severity: "high",
5875
+ code: "plan-path.symlink-escape",
5876
+ message: `plan file ${planAbs} resolves to ${canonicalPlan}, outside {PLAN_DIR} (${canonicalPlanDir})`,
5877
+ fix: `write the plan under ${planDir}`
5878
+ };
5879
+ }
5880
+ } catch {}
5881
+ }
5882
+ return {
5883
+ ok: true,
5884
+ severity: "low",
5885
+ code: "plan-path.ok",
5886
+ message: `plan file ${planAbs} lives under {PLAN_DIR} (${planDir})`
5887
+ };
5888
+ }
5786
5889
  function isDirectory(dir) {
5787
5890
  try {
5788
5891
  return statSync3(dir).isDirectory();
@@ -5843,6 +5946,51 @@ function probeBranch(worktreePath, opts) {
5843
5946
  return { error: detail };
5844
5947
  }
5845
5948
  }
5949
+ function probeCheckout(worktreePath, opts) {
5950
+ const timeout = opts.timeoutMs ?? probeTimeoutMs();
5951
+ try {
5952
+ const stdout = execFileSync2(opts.gitPath ?? "git", ["-C", worktreePath, "rev-parse", "--git-dir"], {
5953
+ encoding: "utf8",
5954
+ stdio: ["ignore", "pipe", "pipe"],
5955
+ timeout
5956
+ });
5957
+ const raw = stdout.trim();
5958
+ if (raw === "")
5959
+ return { error: `no git dir reported at "${worktreePath}"` };
5960
+ const abs = isAbsolute5(raw) ? raw : join10(worktreePath, raw);
5961
+ return { gitDir: realpathSync3(abs) };
5962
+ } catch (err) {
5963
+ const e = err;
5964
+ if (e.killed === true || e.signal !== undefined) {
5965
+ return { error: `git probe timed out after ${timeout}ms (killed by ${e.signal ?? "SIGTERM"})` };
5966
+ }
5967
+ const detail = (e.stderr !== undefined ? e.stderr.toString().trim() : "") || e.message || "git probe failed";
5968
+ return { error: detail };
5969
+ }
5970
+ }
5971
+ function isDistinctCheckout(controlPath, candidatePath, opts = {}) {
5972
+ const control = probeCheckout(controlPath, opts);
5973
+ const candidate = probeCheckout(candidatePath, opts);
5974
+ if ("error" in control || "error" in candidate)
5975
+ return false;
5976
+ return control.gitDir !== candidate.gitDir;
5977
+ }
5978
+ function probeCheckoutRoot(path2, opts = {}) {
5979
+ const timeout = opts.timeoutMs ?? probeTimeoutMs();
5980
+ try {
5981
+ const stdout = execFileSync2(opts.gitPath ?? "git", ["-C", path2, "rev-parse", "--show-toplevel"], {
5982
+ encoding: "utf8",
5983
+ stdio: ["ignore", "pipe", "pipe"],
5984
+ timeout
5985
+ });
5986
+ const raw = stdout.trim();
5987
+ if (raw === "")
5988
+ return null;
5989
+ return realpathSync3(raw);
5990
+ } catch {
5991
+ return null;
5992
+ }
5993
+ }
5846
5994
  function l1PreDispatchCheck(input, opts = {}) {
5847
5995
  const violations = [];
5848
5996
  const { controlWorktreePath, leaseWorktreePath, leaseWorkingBranch, planId } = input;
@@ -5855,8 +6003,20 @@ function l1PreDispatchCheck(input, opts = {}) {
5855
6003
  if (leaseWorkingBranch.trim() === "") {
5856
6004
  violations.push(violation7("high", "worktree.l1.lease-branch-missing", `execution_lease.working_branch is empty for plan "${planId}"`, "record the lease working_branch before dispatch"));
5857
6005
  }
5858
- if (controlWorktreePath !== "" && leaseWorktreePath !== "" && resolve8(controlWorktreePath) === resolve8(leaseWorktreePath)) {
5859
- violations.push(violation7("critical", "worktree.l1.lease-equals-control", `execution_lease.worktree_path "${leaseWorktreePath}" equals metadata.control_worktree_path \u2014 the feature worktree MUST differ from the control worktree (L1 isolation; product edits never land in the control checkout)`, "use a distinct feature worktree for the plan (git worktree add <path> <branch>) and update the lease"));
6006
+ if (controlWorktreePath !== "" && leaseWorktreePath !== "") {
6007
+ if (resolve8(controlWorktreePath) === resolve8(leaseWorktreePath)) {
6008
+ violations.push(violation7("critical", "worktree.l1.lease-equals-control", `execution_lease.worktree_path "${leaseWorktreePath}" equals metadata.control_worktree_path \u2014 the feature worktree MUST differ from the control worktree (L1 isolation; product edits never land in the control checkout)`, "use a distinct feature worktree for the plan (git worktree add <path> <branch>) and update the lease"));
6009
+ } else if (existsSync7(leaseWorktreePath)) {
6010
+ const controlProbe = probeCheckout(controlWorktreePath, opts);
6011
+ const leaseProbe = probeCheckout(leaseWorktreePath, opts);
6012
+ if ("error" in controlProbe) {
6013
+ violations.push(violation7("high", "worktree.l1.checkout-probe-failed", `cannot establish the lease worktree "${leaseWorktreePath}" is a distinct Git checkout from the control worktree "${controlWorktreePath}" for plan "${planId}": ${controlProbe.error}`, "verify the control worktree path is a git checkout (integration-branch checkout)"));
6014
+ } else if ("error" in leaseProbe) {
6015
+ violations.push(violation7("high", "worktree.l1.checkout-probe-failed", `cannot establish the lease worktree "${leaseWorktreePath}" is a distinct Git checkout from the control worktree "${controlWorktreePath}" for plan "${planId}": ${leaseProbe.error}`, "verify the lease worktree path is a git checkout (git worktree add <path> <branch>)"));
6016
+ } else if (controlProbe.gitDir === leaseProbe.gitDir) {
6017
+ violations.push(violation7("critical", "worktree.l1.lease-equals-control", `execution_lease.worktree_path "${leaseWorktreePath}" is the same Git checkout as metadata.control_worktree_path "${controlWorktreePath}" \u2014 a plain subdirectory or symlink alias of the control checkout is not isolation; the feature worktree MUST be a distinct checkout`, "use a distinct feature worktree for the plan (git worktree add <path> <branch>) and update the lease"));
6018
+ }
6019
+ }
5860
6020
  }
5861
6021
  if (leaseWorktreePath !== "" && !existsSync7(leaseWorktreePath)) {
5862
6022
  violations.push(violation7("high", "worktree.l1.feature-missing", `feature worktree directory "${leaseWorktreePath}" does not exist for plan "${planId}"`, `create it before dispatch: git worktree add ${leaseWorktreePath} <working-branch>`));
@@ -5905,6 +6065,16 @@ function l2PreDispatchCheck(input, opts = {}) {
5905
6065
  });
5906
6066
  return gate(violations);
5907
6067
  }
6068
+ function assertBranchAlignment(worktreePath, expectedBranch, opts = {}) {
6069
+ const violations = [];
6070
+ const probe = probeBranch(worktreePath, opts);
6071
+ if ("error" in probe) {
6072
+ violations.push(violation7("high", "worktree.branch-probe-failed", `cannot probe branch at "${worktreePath}": ${probe.error}`, "verify the path is a git worktree checkout on the expected branch (not detached)"));
6073
+ } else if (probe.branch !== expectedBranch) {
6074
+ violations.push(violation7("high", "worktree.branch-mismatch", `worktree "${worktreePath}" is on branch "${probe.branch}", expected "${expectedBranch}" (Assignment Working branch)`, `checkout ${expectedBranch} in that worktree`));
6075
+ }
6076
+ return gate(violations);
6077
+ }
5908
6078
  var QC_ALIGNMENT_FIELDS = [
5909
6079
  { key: "planId", label: "plan_id" },
5910
6080
  { key: "reviewRange", label: "Review range" },
@@ -5957,14 +6127,14 @@ function gitOut(cwd, args) {
5957
6127
  }
5958
6128
  }
5959
6129
  function probeHarnessWithStatus(root) {
5960
- if (isFile2(join10(root, ".mstar", "status.json")))
5961
- return join10(root, ".mstar");
5962
- if (isFile2(join10(root, ".agents", "status.json")))
5963
- return join10(root, ".agents");
5964
- if (hasWorkflowSnapshot(join10(root, ".mstar")))
5965
- return join10(root, ".mstar");
5966
- if (hasWorkflowSnapshot(join10(root, ".agents")))
5967
- return join10(root, ".agents");
6130
+ if (isFile2(join11(root, ".mstar", "status.json")))
6131
+ return join11(root, ".mstar");
6132
+ if (isFile2(join11(root, ".agents", "status.json")))
6133
+ return join11(root, ".agents");
6134
+ if (hasWorkflowSnapshot(join11(root, ".mstar")))
6135
+ return join11(root, ".mstar");
6136
+ if (hasWorkflowSnapshot(join11(root, ".agents")))
6137
+ return join11(root, ".agents");
5968
6138
  return null;
5969
6139
  }
5970
6140
  function hasWorkflowSnapshot(harnessDir) {
@@ -5972,13 +6142,13 @@ function hasWorkflowSnapshot(harnessDir) {
5972
6142
  try {
5973
6143
  workflowsDir = resolveWorkflowDir(harnessDir, { harnessDir });
5974
6144
  } catch {
5975
- workflowsDir = join10(harnessDir, "workflows");
6145
+ workflowsDir = join11(harnessDir, "workflows");
5976
6146
  }
5977
6147
  if (!isDirectory2(workflowsDir))
5978
6148
  return false;
5979
6149
  try {
5980
6150
  for (const entry of readdirSync6(workflowsDir, { withFileTypes: true })) {
5981
- if (entry.isDirectory() && isFile2(join10(workflowsDir, entry.name, "snapshot.json")))
6151
+ if (entry.isDirectory() && isFile2(join11(workflowsDir, entry.name, "snapshot.json")))
5982
6152
  return true;
5983
6153
  }
5984
6154
  } catch {
@@ -5991,14 +6161,14 @@ function isLinkedWorktree(root) {
5991
6161
  const commonRaw = gitOut(root, ["rev-parse", "--git-common-dir"]);
5992
6162
  if (gitDirRaw === null || commonRaw === null)
5993
6163
  return false;
5994
- const gitDir = isAbsolute6(gitDirRaw) ? gitDirRaw : join10(root, gitDirRaw);
5995
- const common2 = isAbsolute6(commonRaw) ? commonRaw : join10(root, commonRaw);
6164
+ const gitDir = isAbsolute6(gitDirRaw) ? gitDirRaw : join11(root, gitDirRaw);
6165
+ const common2 = isAbsolute6(commonRaw) ? commonRaw : join11(root, commonRaw);
5996
6166
  if (gitDir.includes("/.git/worktrees/") || gitDir.includes("/worktrees/"))
5997
6167
  return true;
5998
6168
  try {
5999
- const gdParent = realpathSync3(dirname6(gitDir));
6000
- const cmAbs = realpathSync3(common2);
6001
- return join10(gdParent, basename4(gitDir)) !== cmAbs && gitDir !== cmAbs;
6169
+ const gdParent = realpathSync4(dirname6(gitDir));
6170
+ const cmAbs = realpathSync4(common2);
6171
+ return join11(gdParent, basename4(gitDir)) !== cmAbs && gitDir !== cmAbs;
6002
6172
  } catch {
6003
6173
  return false;
6004
6174
  }
@@ -6015,10 +6185,10 @@ function sddWorkspace(planId, opts = {}) {
6015
6185
  if (!isDirectory2(controlRoot)) {
6016
6186
  throw new SddScriptError(`mstar sdd workspace: CONTROL_ROOT / MSTAR_CONTROL_ROOT is not a directory: ${controlRoot}`, 1);
6017
6187
  }
6018
- root = realpathSync3(controlRoot);
6188
+ root = realpathSync4(controlRoot);
6019
6189
  } else {
6020
6190
  const topLevel = gitOut(cwd, ["rev-parse", "--show-toplevel"]);
6021
- root = realpathSync3(topLevel ?? cwd);
6191
+ root = realpathSync4(topLevel ?? cwd);
6022
6192
  }
6023
6193
  if (!controlRoot && isLinkedWorktree(root)) {
6024
6194
  throw new SddScriptError(`mstar sdd workspace: linked worktree at ${root} has no {HARNESS_DIR}/status.json (default gitignore).
@@ -6039,25 +6209,35 @@ function sddWorkspace(planId, opts = {}) {
6039
6209
  const probed = probeHarnessWithStatus(root);
6040
6210
  if (probed) {
6041
6211
  harnessDir = probed;
6042
- } else if (isDirectory2(join10(root, ".mstar"))) {
6043
- harnessDir = join10(root, ".mstar");
6044
- } else if (isDirectory2(join10(root, ".agents"))) {
6045
- harnessDir = join10(root, ".agents");
6212
+ } else if (isDirectory2(join11(root, ".mstar"))) {
6213
+ harnessDir = join11(root, ".mstar");
6214
+ } else if (isDirectory2(join11(root, ".agents"))) {
6215
+ harnessDir = join11(root, ".agents");
6046
6216
  } else {
6047
- harnessDir = join10(root, ".mstar");
6217
+ harnessDir = join11(root, ".mstar");
6048
6218
  }
6049
6219
  }
6050
6220
  }
6051
6221
  const sddDir = resolveSddDir(harnessDir, planId);
6052
6222
  mkdirSync6(sddDir, { recursive: true });
6053
- writeFileSync4(join10(sddDir, ".gitignore"), `*
6223
+ writeFileSync4(join11(sddDir, ".gitignore"), `*
6054
6224
  `);
6055
- return realpathSync3(sddDir);
6225
+ return realpathSync4(sddDir);
6056
6226
  }
6057
6227
  function taskBrief(planFile, taskN, outFile, opts = {}) {
6058
6228
  if (!planFile || !Number.isInteger(taskN) || taskN < 1) {
6059
6229
  throw new SddScriptError("usage: mstar sdd task-brief PLAN_FILE TASK_NUMBER [OUTFILE]", 2);
6060
6230
  }
6231
+ const bound = opts.context;
6232
+ const observedCwd = opts.cwd ?? process.cwd();
6233
+ if (bound) {
6234
+ const inputPlan = canonicalizeNearestExisting(resolve9(observedCwd, planFile));
6235
+ if (inputPlan !== canonicalizeNearestExisting(bound.planFile)) {
6236
+ throwGateFail([
6237
+ 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")
6238
+ ]);
6239
+ }
6240
+ }
6061
6241
  let content;
6062
6242
  try {
6063
6243
  content = readFileSync7(planFile, "utf8");
@@ -6065,15 +6245,26 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
6065
6245
  throw new SddScriptError(`no such plan file: ${planFile}`, 2);
6066
6246
  }
6067
6247
  let out;
6248
+ let mkdirAfterGate = null;
6068
6249
  if (outFile) {
6069
- out = outFile;
6250
+ out = bound ? resolve9(observedCwd, outFile) : outFile;
6251
+ } else if (bound) {
6252
+ out = join11(bound.sddDir, `task-${taskN}-brief.md`);
6253
+ mkdirAfterGate = bound.sddDir;
6070
6254
  } else {
6071
6255
  const sddDir = opts.sddDir ?? process.env.SDD_DIR;
6072
6256
  if (!sddDir) {
6073
6257
  throw new SddScriptError("mstar sdd task-brief: set SDD_DIR or pass OUTFILE (run mstar sdd workspace PLAN_ID first)", 2);
6074
6258
  }
6075
6259
  mkdirSync6(sddDir, { recursive: true });
6076
- out = join10(sddDir, `task-${taskN}-brief.md`);
6260
+ out = join11(sddDir, `task-${taskN}-brief.md`);
6261
+ }
6262
+ if (bound) {
6263
+ const gate2 = checkSddAction(bound, { kind: "artifact", cwd: observedCwd, target: out });
6264
+ if (!gate2.ok)
6265
+ throwGateFail(gate2.violations);
6266
+ if (mkdirAfterGate !== null)
6267
+ mkdirSync6(mkdirAfterGate, { recursive: true });
6077
6268
  }
6078
6269
  const records = content.endsWith(`
6079
6270
  `) ? content.split(`
@@ -6099,13 +6290,15 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
6099
6290
  if (printed.length === 0) {
6100
6291
  throw new SddScriptError(`task ${taskN} not found in ${planFile} (no heading matching Task ${taskN})`, 3);
6101
6292
  }
6102
- return out;
6293
+ return bound ? resolve9(observedCwd, out) : out;
6103
6294
  }
6104
6295
  function reviewPackage(base, head, outFile, opts = {}) {
6105
6296
  if (!base || !head) {
6106
6297
  throw new SddScriptError("usage: mstar sdd review-package BASE HEAD [OUTFILE]", 2);
6107
6298
  }
6108
- const cwd = opts.cwd ?? process.cwd();
6299
+ const bound = opts.context;
6300
+ const cwd = bound && opts.cwd === undefined ? bound.featureCwd : opts.cwd ?? process.cwd();
6301
+ const observedCwd = opts.cwd ?? process.cwd();
6109
6302
  const verifyRef = (ref, what) => {
6110
6303
  try {
6111
6304
  execFileSync3("git", ["rev-parse", "--verify", "--quiet", ref], { cwd, stdio: ["ignore", "pipe", "pipe"] });
@@ -6116,8 +6309,14 @@ function reviewPackage(base, head, outFile, opts = {}) {
6116
6309
  verifyRef(base, "BASE");
6117
6310
  verifyRef(head, "HEAD");
6118
6311
  let out;
6312
+ let mkdirAfterGate = null;
6119
6313
  if (outFile) {
6120
- out = outFile;
6314
+ out = bound ? resolve9(observedCwd, outFile) : outFile;
6315
+ } else if (bound) {
6316
+ const shortBase = gitOut(cwd, ["rev-parse", "--short", base]) ?? base;
6317
+ const shortHead = gitOut(cwd, ["rev-parse", "--short", head]) ?? head;
6318
+ out = join11(bound.sddDir, `review-${shortBase}..${shortHead}.diff`);
6319
+ mkdirAfterGate = bound.sddDir;
6121
6320
  } else {
6122
6321
  const sddDir = opts.sddDir ?? process.env.SDD_DIR;
6123
6322
  if (!sddDir) {
@@ -6126,7 +6325,14 @@ function reviewPackage(base, head, outFile, opts = {}) {
6126
6325
  mkdirSync6(sddDir, { recursive: true });
6127
6326
  const shortBase = gitOut(cwd, ["rev-parse", "--short", base]) ?? base;
6128
6327
  const shortHead = gitOut(cwd, ["rev-parse", "--short", head]) ?? head;
6129
- out = join10(sddDir, `review-${shortBase}..${shortHead}.diff`);
6328
+ out = join11(sddDir, `review-${shortBase}..${shortHead}.diff`);
6329
+ }
6330
+ if (bound) {
6331
+ const gate2 = checkSddAction(bound, { kind: "artifact", cwd: observedCwd, target: out });
6332
+ if (!gate2.ok)
6333
+ throwGateFail(gate2.violations);
6334
+ if (mkdirAfterGate !== null)
6335
+ mkdirSync6(mkdirAfterGate, { recursive: true });
6130
6336
  }
6131
6337
  const run = (args) => execFileSync3("git", args, { cwd, maxBuffer: GIT_CAPTURE_MAX_BYTES });
6132
6338
  const parts = [
@@ -6145,7 +6351,359 @@ function reviewPackage(base, head, outFile, opts = {}) {
6145
6351
  run(["diff", "-U10", `${base}..${head}`])
6146
6352
  ];
6147
6353
  writeFileSync4(out, Buffer.concat(parts));
6148
- return out;
6354
+ return bound ? resolve9(observedCwd, out) : out;
6355
+ }
6356
+ function isPlainObject6(value) {
6357
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6358
+ }
6359
+ function isInside(child, ancestor) {
6360
+ const rel = relative3(ancestor, child);
6361
+ return rel === "" || !rel.startsWith("..") && !isAbsolute6(rel);
6362
+ }
6363
+ function canonicalDir(path2) {
6364
+ try {
6365
+ return statSync4(path2).isDirectory() ? realpathSync4(path2) : null;
6366
+ } catch {
6367
+ return null;
6368
+ }
6369
+ }
6370
+ function contextViolation(severity, code, message, fix) {
6371
+ return { ok: false, severity, code, message, fix };
6372
+ }
6373
+ function throwGateFail(violations) {
6374
+ const detail = violations.map((v) => `${v.code}: ${v.message}${v.fix ? ` (fix: ${v.fix})` : ""}`).join(`
6375
+ `);
6376
+ throw new SddScriptError(`SDD execution context rejected:
6377
+ ${detail}`, 1);
6378
+ }
6379
+ function throwUsage(message) {
6380
+ throw new SddScriptError(message, 2);
6381
+ }
6382
+ function readActiveWorkflowIds(controlHarnessRoot) {
6383
+ const statusPath = join11(controlHarnessRoot, "status.json");
6384
+ if (!isFile2(statusPath))
6385
+ return null;
6386
+ let doc;
6387
+ try {
6388
+ doc = readJson(statusPath);
6389
+ } catch {
6390
+ return null;
6391
+ }
6392
+ if (!isPlainObject6(doc) || doc.version !== 2 || !Array.isArray(doc.workflows))
6393
+ return null;
6394
+ const ids = new Set;
6395
+ for (const entry of doc.workflows) {
6396
+ if (isPlainObject6(entry) && typeof entry.id === "string")
6397
+ ids.add(entry.id);
6398
+ }
6399
+ return ids;
6400
+ }
6401
+ function findWorkflowPlanRow(controlHarnessRoot, planId) {
6402
+ let workflowsDir;
6403
+ try {
6404
+ workflowsDir = resolveWorkflowDir(controlHarnessRoot, { harnessDir: controlHarnessRoot });
6405
+ } catch {
6406
+ return { kind: "none" };
6407
+ }
6408
+ if (!isDirectory2(workflowsDir))
6409
+ return { kind: "none" };
6410
+ let workflowIds;
6411
+ try {
6412
+ workflowIds = readdirSync6(workflowsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
6413
+ } catch {
6414
+ return { kind: "none" };
6415
+ }
6416
+ const matches = [];
6417
+ for (const id of workflowIds) {
6418
+ const snapshotPath = join11(workflowsDir, id, WORKFLOW_SNAPSHOT_FILE);
6419
+ if (!isFile2(snapshotPath))
6420
+ continue;
6421
+ let doc;
6422
+ try {
6423
+ doc = readJson(snapshotPath);
6424
+ } catch {
6425
+ continue;
6426
+ }
6427
+ const plans = doc.plans;
6428
+ if (!Array.isArray(plans))
6429
+ continue;
6430
+ for (const row of plans) {
6431
+ if (isPlainObject6(row) && (row.id === planId || row.plan_id === planId)) {
6432
+ matches.push({ workflowId: id, row });
6433
+ break;
6434
+ }
6435
+ }
6436
+ }
6437
+ if (matches.length === 0)
6438
+ return { kind: "none" };
6439
+ const registeredActive = readActiveWorkflowIds(controlHarnessRoot);
6440
+ if (registeredActive === null) {
6441
+ return { kind: "row", workflowId: matches[0].workflowId, row: matches[0].row };
6442
+ }
6443
+ const active = matches.filter((m) => registeredActive.has(m.workflowId));
6444
+ if (active.length === 0)
6445
+ return { kind: "none" };
6446
+ if (active.length > 1) {
6447
+ return { kind: "ambiguous", workflowIds: active.map((m) => m.workflowId) };
6448
+ }
6449
+ return { kind: "row", workflowId: active[0].workflowId, row: active[0].row };
6450
+ }
6451
+ function resolveSddExecutionContext(input) {
6452
+ const { planId, workingBranch } = input;
6453
+ if (typeof planId !== "string" || planId.trim() === "") {
6454
+ throwUsage("SddExecutionContext.planId must be a non-empty string");
6455
+ }
6456
+ if (typeof workingBranch !== "string" || workingBranch.trim() === "") {
6457
+ throwUsage("SddExecutionContext.workingBranch must be a non-empty string");
6458
+ }
6459
+ for (const field of ["controlHarnessRoot", "featureCwd", "planFile", "sddDir"]) {
6460
+ const value = input[field];
6461
+ if (typeof value !== "string" || value.trim() === "") {
6462
+ throwUsage(`SddExecutionContext.${field} must be a non-empty string`);
6463
+ }
6464
+ if (!isAbsolute6(value)) {
6465
+ throwUsage(`SddExecutionContext.${field} must be an absolute path (A3: all paths normalized absolute); got ${JSON.stringify(value)}`);
6466
+ }
6467
+ }
6468
+ try {
6469
+ assertSafePathComponent(planId, "SddExecutionContext.planId");
6470
+ } catch (err) {
6471
+ throwUsage(`SddExecutionContext rejected: ${err.message}`);
6472
+ }
6473
+ const canonicalControlHarnessRoot = canonicalDir(input.controlHarnessRoot);
6474
+ if (canonicalControlHarnessRoot === null) {
6475
+ throwGateFail([
6476
+ contextViolation("high", "sdd.context.control-root-missing", `controlHarnessRoot "${input.controlHarnessRoot}" does not exist or is not a directory \u2014 a declared control root is authoritative and is never re-inferred from the feature cwd (A3)`)
6477
+ ]);
6478
+ }
6479
+ const stem = basename4(input.planFile).replace(/\.md$/, "");
6480
+ if (stem !== planId) {
6481
+ throwUsage(`SddExecutionContext.planFile "${input.planFile}" does not match plan "${planId}" \u2014 the plan file must be {PLAN_DIR}/<plan-id>.md under the declared control harness`);
6482
+ }
6483
+ if (!isFile2(input.planFile)) {
6484
+ throwUsage(`no such plan file: ${input.planFile}`);
6485
+ }
6486
+ const planGate = assertPlanWritingPath(input.planFile, input.controlHarnessRoot);
6487
+ if (!planGate.ok) {
6488
+ if (planGate.code === "plan-path.symlink-escape") {
6489
+ throwGateFail([planGate]);
6490
+ }
6491
+ throwUsage(`SddExecutionContext.planFile rejected: ${planGate.code}: ${planGate.message}`);
6492
+ }
6493
+ const composedSddDir = resolveSddDir(canonicalControlHarnessRoot, planId);
6494
+ const canonicalComposedSddDir = canonicalizeNearestExisting(composedSddDir);
6495
+ const canonicalSddDir = canonicalizeNearestExisting(input.sddDir);
6496
+ if (canonicalSddDir !== canonicalComposedSddDir) {
6497
+ if (!isInside(canonicalSddDir, canonicalControlHarnessRoot)) {
6498
+ throwGateFail([
6499
+ contextViolation("high", "sdd.context.sdd-dir-escape", `sddDir "${input.sddDir}" canonicalizes to "${canonicalSddDir}", outside the control harness "${canonicalControlHarnessRoot}" \u2014 symlink escape refused (environmental gate failure)`)
6500
+ ]);
6501
+ }
6502
+ throwUsage(`SddExecutionContext.sddDir "${input.sddDir}" does not match plan "${planId}" \u2014 expected the {SDD_DIR} composition ${composedSddDir}`);
6503
+ }
6504
+ const canonicalFeatureCwd = canonicalDir(input.featureCwd);
6505
+ if (canonicalFeatureCwd === null) {
6506
+ throwGateFail([
6507
+ contextViolation("high", "sdd.context.feature-cwd-missing", `featureCwd "${input.featureCwd}" does not exist or is not a directory \u2014 the feature worktree is the required cwd for product edits`, `create the feature worktree first (git worktree add ${input.featureCwd} ${workingBranch})`)
6508
+ ]);
6509
+ }
6510
+ if (isInside(canonicalControlHarnessRoot, canonicalFeatureCwd)) {
6511
+ throwGateFail([
6512
+ contextViolation("critical", "sdd.context.control-inside-feature", `controlHarnessRoot "${canonicalControlHarnessRoot}" is inside featureCwd "${canonicalFeatureCwd}" \u2014 a feature worktree's same-looking {HARNESS_DIR} is not the SSOT; the control harness must live outside the feature checkout`)
6513
+ ]);
6514
+ }
6515
+ const controlCheckout = probeCheckoutRoot(canonicalControlHarnessRoot);
6516
+ if (controlCheckout === null) {
6517
+ throwGateFail([
6518
+ contextViolation("high", "sdd.context.control-root-unresolvable", `cannot resolve the control checkout root for controlHarnessRoot "${canonicalControlHarnessRoot}" (git rev-parse --show-toplevel failed) \u2014 the control harness must live inside a git checkout`, "verify the control harness root is inside the control worktree checkout")
6519
+ ]);
6520
+ }
6521
+ if (isInside(canonicalFeatureCwd, controlCheckout) && !isDistinctCheckout(canonicalControlHarnessRoot, canonicalFeatureCwd)) {
6522
+ throwGateFail([
6523
+ 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>)")
6524
+ ]);
6525
+ }
6526
+ const match = findWorkflowPlanRow(canonicalControlHarnessRoot, planId);
6527
+ if (match.kind === "ambiguous") {
6528
+ throwGateFail([
6529
+ contextViolation("high", "sdd.context.workflow-plan-ambiguous", `plan "${planId}" appears in multiple registered active workflows (${match.workflowIds.join(", ")}) \u2014 ` + "the governing execution_lease is undecidable; resolve the duplicate registration before dispatch")
6530
+ ]);
6531
+ }
6532
+ const row = match.kind === "row" ? match.row : null;
6533
+ if (row !== null && row.execution_lease !== undefined) {
6534
+ const leaseVerify = verifyPlanExecutionLease(row, planId);
6535
+ if (!leaseVerify.ok)
6536
+ throwGateFail(leaseVerify.violations);
6537
+ const lease = leaseVerify.lease;
6538
+ const l1 = l1PreDispatchCheck({
6539
+ controlWorktreePath: controlCheckout,
6540
+ leaseWorktreePath: lease.worktree_path,
6541
+ leaseWorkingBranch: lease.working_branch,
6542
+ planId
6543
+ });
6544
+ if (!l1.ok)
6545
+ throwGateFail(l1.violations);
6546
+ if (canonicalizeNearestExisting(lease.worktree_path) !== canonicalFeatureCwd) {
6547
+ throwGateFail([
6548
+ contextViolation("high", "sdd.context.lease-worktree-mismatch", `SddExecutionContext.featureCwd "${canonicalFeatureCwd}" does not match the verified execution_lease.worktree_path "${String(lease.worktree_path)}" \u2014 the context must match the verified lease (A3)`)
6549
+ ]);
6550
+ }
6551
+ if (workingBranch !== lease.working_branch) {
6552
+ throwGateFail([
6553
+ contextViolation("high", "sdd.context.lease-branch-mismatch", `SddExecutionContext.workingBranch "${workingBranch}" does not match the verified execution_lease.working_branch "${String(lease.working_branch)}" (plan "${planId}")`)
6554
+ ]);
6555
+ }
6556
+ } else if (row !== null && row.status === "InProgress") {
6557
+ throwGateFail(verifyPlanExecutionLease(row, planId).violations);
6558
+ } else {
6559
+ const branchGate = assertBranchAlignment(canonicalFeatureCwd, workingBranch);
6560
+ if (!branchGate.ok)
6561
+ throwGateFail(branchGate.violations);
6562
+ }
6563
+ return {
6564
+ planId,
6565
+ controlHarnessRoot: canonicalControlHarnessRoot,
6566
+ featureCwd: canonicalFeatureCwd,
6567
+ workingBranch,
6568
+ planFile: realpathSync4(input.planFile),
6569
+ sddDir: canonicalSddDir
6570
+ };
6571
+ }
6572
+ function checkSddAction(context, action) {
6573
+ const violations = [];
6574
+ const add = (code, message, fix) => {
6575
+ violations.push(contextViolation("high", code, message, fix));
6576
+ };
6577
+ if (action.kind !== "source" && action.kind !== "artifact" && action.kind !== "launch") {
6578
+ add("sdd.context.kind-unknown", `unknown action kind ${JSON.stringify(action.kind)} \u2014 expected "source" | "artifact" | "launch"`);
6579
+ return { ok: false, violations };
6580
+ }
6581
+ if (typeof action.cwd !== "string" || action.cwd.trim() === "") {
6582
+ add("sdd.context.cwd-missing", "action.cwd (the observed invocation cwd) is required \u2014 never an Assignment echo");
6583
+ return { ok: false, violations };
6584
+ }
6585
+ const featureReal = canonicalDir(context.featureCwd);
6586
+ const canonicalSddDir = canonicalizeNearestExisting(context.sddDir);
6587
+ const canonicalPlanFile = canonicalizeNearestExisting(context.planFile);
6588
+ const cwdResolved = resolve9(action.cwd);
6589
+ const checkTarget = (baseDir, target, kind) => {
6590
+ if (featureReal === null)
6591
+ return;
6592
+ const targetAbs = resolve9(baseDir, target);
6593
+ const canonical = canonicalizeNearestExisting(targetAbs);
6594
+ if (!isInside(canonical, featureReal)) {
6595
+ const declaredPrefix = targetAbs === featureReal || targetAbs.startsWith(`${featureReal}/`);
6596
+ if (declaredPrefix) {
6597
+ add("sdd.context.target-symlink-escape", `${kind} target "${target}" canonicalizes to "${canonical}", outside the feature worktree \u2014 symlink escape refused before mutation`);
6598
+ } else {
6599
+ add(`sdd.context.${kind}-target-outside-feature`, `${kind} target "${target}" resolves to "${targetAbs}", outside the feature worktree "${featureReal}" \u2014 refused before mutation`);
6600
+ }
6601
+ }
6602
+ };
6603
+ if (action.kind === "source") {
6604
+ const cwdReal = canonicalDir(cwdResolved);
6605
+ if (cwdReal === null) {
6606
+ add("sdd.context.cwd-missing", `observed source cwd "${action.cwd}" does not exist or is not a directory`);
6607
+ return { ok: false, violations };
6608
+ }
6609
+ if (featureReal === null || !isInside(cwdReal, featureReal)) {
6610
+ add("sdd.context.source-cwd-outside-feature", `observed source cwd "${cwdReal}" is outside the feature worktree "${context.featureCwd}" \u2014 a declared-correct context does not make a wrong-checkout write safe (A3)`, `run the source action from inside ${context.featureCwd}`);
6611
+ return { ok: false, violations };
6612
+ }
6613
+ if (action.target !== undefined)
6614
+ checkTarget(cwdReal, action.target, "source");
6615
+ } else if (action.kind === "artifact") {
6616
+ if (typeof action.target !== "string" || action.target.trim() === "") {
6617
+ add("sdd.context.target-missing", "artifact checks require the destination target");
6618
+ return { ok: false, violations };
6619
+ }
6620
+ const targetAbs = resolve9(cwdResolved, action.target);
6621
+ const canonical = canonicalizeNearestExisting(targetAbs);
6622
+ if (!isInside(canonical, canonicalSddDir) && canonical !== canonicalPlanFile) {
6623
+ const rawSddDir = resolve9(context.sddDir);
6624
+ const declaredPrefix = targetAbs === rawSddDir || targetAbs.startsWith(`${rawSddDir}/`) || targetAbs === canonicalSddDir || targetAbs.startsWith(`${canonicalSddDir}/`) || targetAbs === canonicalPlanFile;
6625
+ if (declaredPrefix) {
6626
+ add("sdd.context.artifact-symlink-escape", `artifact target "${targetAbs}" canonicalizes to "${canonical}", outside the plan's control sddDir \u2014 symlink escape refused before write`);
6627
+ } else {
6628
+ add("sdd.context.artifact-outside-plan", `artifact target "${targetAbs}" is outside the plan's control sddDir "${context.sddDir}" and is not the declared planFile "${context.planFile}" \u2014 legitimate control artifact edits stay inside the plan's artifacts; arbitrary control source edits are not allowed (A3)`);
6629
+ }
6630
+ }
6631
+ } else {
6632
+ if (featureReal === null) {
6633
+ add("sdd.context.launch-cwd-missing", `feature worktree "${context.featureCwd}" does not exist or is not a directory \u2014 cannot bind the child's starting cwd`);
6634
+ } else {
6635
+ violations.push(...assertBranchAlignment(featureReal, context.workingBranch).violations);
6636
+ }
6637
+ if (action.target !== undefined && action.target.trim() !== "" && featureReal !== null) {
6638
+ checkTarget(featureReal, action.target, "launch");
6639
+ }
6640
+ }
6641
+ return { ok: violations.length === 0, violations };
6642
+ }
6643
+ function signalExitNumber(signal) {
6644
+ return osConstants.signals[signal] ?? 0;
6645
+ }
6646
+ async function runInSddContext(context, argv) {
6647
+ if (!Array.isArray(argv) || argv.length === 0 || typeof argv[0] !== "string" || argv[0].trim() === "") {
6648
+ throwUsage("runInSddContext: argv must be [executable, ...args] with a non-empty executable \u2014 the array is passed to the child literally (no shell)");
6649
+ }
6650
+ const resolved = resolveSddExecutionContext(context);
6651
+ const gate2 = checkSddAction(resolved, { kind: "launch", cwd: process.cwd() });
6652
+ if (!gate2.ok)
6653
+ throwGateFail(gate2.violations);
6654
+ return await new Promise((settle, reject) => {
6655
+ let child;
6656
+ try {
6657
+ child = spawn(argv[0], argv.slice(1), {
6658
+ cwd: resolved.featureCwd,
6659
+ shell: false,
6660
+ stdio: "inherit"
6661
+ });
6662
+ } catch (err) {
6663
+ if (err.code === "ENOENT") {
6664
+ settle(127);
6665
+ return;
6666
+ }
6667
+ throw err;
6668
+ }
6669
+ let done = false;
6670
+ let spawnError = null;
6671
+ const forward = (signal) => {
6672
+ if (!done && child.exitCode === null && child.signalCode === null)
6673
+ child.kill(signal);
6674
+ };
6675
+ const cleanup = () => {
6676
+ process.removeListener("SIGINT", forward);
6677
+ process.removeListener("SIGTERM", forward);
6678
+ };
6679
+ process.on("SIGINT", forward);
6680
+ process.on("SIGTERM", forward);
6681
+ child.on("error", (err) => {
6682
+ spawnError = err;
6683
+ if (err.code !== "ENOENT" && !done) {
6684
+ done = true;
6685
+ cleanup();
6686
+ reject(err);
6687
+ }
6688
+ });
6689
+ child.on("close", (code, signal) => {
6690
+ if (done)
6691
+ return;
6692
+ done = true;
6693
+ cleanup();
6694
+ if (spawnError !== null) {
6695
+ if (spawnError.code === "ENOENT")
6696
+ settle(127);
6697
+ else
6698
+ reject(spawnError);
6699
+ return;
6700
+ }
6701
+ if (signal !== null)
6702
+ settle(128 + signalExitNumber(signal));
6703
+ else
6704
+ settle(code ?? 0);
6705
+ });
6706
+ });
6149
6707
  }
6150
6708
  function violation8(severity, code, message, fix) {
6151
6709
  return { ok: false, severity, code, message, fix };
@@ -6814,7 +7372,7 @@ function scanSecrets(files) {
6814
7372
  unreadableFiles++;
6815
7373
  continue;
6816
7374
  }
6817
- const base = basename5(file);
7375
+ const base = basename6(file);
6818
7376
  for (const entry of NEVER_COMMIT_FILENAMES) {
6819
7377
  if (entry.re.test(base))
6820
7378
  findings.push({ file, line: 1, type: entry.type });
@@ -6871,7 +7429,7 @@ function rootLockfiles(root) {
6871
7429
  return [];
6872
7430
  }
6873
7431
  const names = new Set(LOCKFILE_NAMES);
6874
- const present = entries.filter((entry) => entry.isFile() && names.has(entry.name)).map((entry) => join12(root, entry.name));
7432
+ const present = entries.filter((entry) => entry.isFile() && names.has(entry.name)).map((entry) => join14(root, entry.name));
6875
7433
  if (present.length === 0)
6876
7434
  return [];
6877
7435
  try {
@@ -6880,7 +7438,7 @@ function rootLockfiles(root) {
6880
7438
  encoding: "utf8",
6881
7439
  stdio: ["ignore", "pipe", "ignore"]
6882
7440
  }).split("\x00").filter((f) => f !== ""));
6883
- return present.filter((p) => tracked.has(basename5(p)));
7441
+ return present.filter((p) => tracked.has(basename6(p)));
6884
7442
  } catch {
6885
7443
  return present;
6886
7444
  }
@@ -6896,7 +7454,7 @@ function supplyChainChecks(repoRoot) {
6896
7454
  findings.push({ kind: "lockfile-duplicate", file: lockfiles.map((f) => f.replace(`${repoRoot}/`, "")).join(", ") });
6897
7455
  violations.push(violation9("medium", "audit.supply.lockfile-duplicate", `multiple lockfiles at ${repoRoot}: ${lockfiles.join(", ")}`, "keep exactly one lockfile per package manager"));
6898
7456
  }
6899
- const workflowsDir = join12(repoRoot, ".github", "workflows");
7457
+ const workflowsDir = join14(repoRoot, ".github", "workflows");
6900
7458
  let wfEntries = [];
6901
7459
  try {
6902
7460
  wfEntries = readdirSync8(workflowsDir, { withFileTypes: true });
@@ -6906,7 +7464,7 @@ function supplyChainChecks(repoRoot) {
6906
7464
  for (const entry of wfEntries) {
6907
7465
  if (!entry.isFile() || !/\.(?:ya?ml)$/.test(entry.name))
6908
7466
  continue;
6909
- const wfPath = join12(workflowsDir, entry.name);
7467
+ const wfPath = join14(workflowsDir, entry.name);
6910
7468
  const relPath = `.github/workflows/${entry.name}`;
6911
7469
  let text;
6912
7470
  try {
@@ -7063,8 +7621,8 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7063
7621
  const date = options.date ?? new Date().toISOString().slice(0, 10);
7064
7622
  const plannedAt = options.plannedAt ?? { commit: options.repoShortSha ?? "unknown", date };
7065
7623
  mkdirSync8(outDir, { recursive: true });
7066
- const existingReadme = join12(outDir, "README.md");
7067
- const carried = existsSync8(existingReadme) ? extractSecurityDispositionSections(readFileSync9(existingReadme, "utf8")) : { needsVerification: [], hardeningChecked: [] };
7624
+ const existingReadme = join14(outDir, "README.md");
7625
+ const carried = existsSync9(existingReadme) ? extractSecurityDispositionSections(readFileSync9(existingReadme, "utf8")) : { needsVerification: [], hardeningChecked: [] };
7068
7626
  const existing = readdirSync8(outDir).filter((f) => /^\d{3}-.*\.md$/.test(f));
7069
7627
  let next = existing.reduce((max, f) => Math.max(max, Number(f.slice(0, 3))), 0) + 1;
7070
7628
  const redactedFindings = findings.map(redactFinding);
@@ -7081,13 +7639,13 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7081
7639
  }
7082
7640
  usedSlugs.add(slug);
7083
7641
  const file = `${num}-${slug}.md`;
7084
- writeFileSync6(join12(outDir, file), renderPlanFile(finding, plannedAt));
7642
+ writeFileSync6(join14(outDir, file), renderPlanFile(finding, plannedAt));
7085
7643
  written.push(file);
7086
7644
  next++;
7087
7645
  }
7088
7646
  const all = [...existing, ...written].sort();
7089
7647
  const rows = all.map((file) => {
7090
- const summary = readPlanFileSummary(join12(outDir, file));
7648
+ const summary = readPlanFileSummary(join14(outDir, file));
7091
7649
  const fields = summary.fields;
7092
7650
  return {
7093
7651
  num: file.slice(0, 3),
@@ -7121,7 +7679,7 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7121
7679
  });
7122
7680
  const needsVerificationLines = options.needsVerification !== undefined ? options.needsVerification.map((nv) => `- ${escapeCell(redactText(nv.lead))}: ${escapeCell(redactText(nv.how))}${nv.evidence ? ` (${escapeCell(redactText(nv.evidence))})` : ""}`) : carried.needsVerification;
7123
7681
  const hardeningCheckedLines = options.hardeningChecked !== undefined ? options.hardeningChecked.map((hc) => `- ${hc.kind}: ${escapeCell(redactText(hc.text))}`) : carried.hardeningChecked;
7124
- writeFileSync6(join12(outDir, "README.md"), renderIndex({
7682
+ writeFileSync6(join14(outDir, "README.md"), renderIndex({
7125
7683
  date,
7126
7684
  repoName: options.repoName ?? "repo",
7127
7685
  repoShortSha: options.repoShortSha ?? "unknown",
@@ -7130,7 +7688,7 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7130
7688
  needsVerification: needsVerificationLines,
7131
7689
  hardeningChecked: hardeningCheckedLines
7132
7690
  }));
7133
- return { outDir: resolve11(outDir), date, files: written, nextNumber: next };
7691
+ return { outDir: resolve12(outDir), date, files: written, nextNumber: next };
7134
7692
  }
7135
7693
  async function promoteAuditPlans(outDir, selected, options) {
7136
7694
  if (selected.length === 0) {
@@ -7139,19 +7697,19 @@ async function promoteAuditPlans(outDir, selected, options) {
7139
7697
  if (typeof options.harnessDir !== "string" || options.harnessDir.trim() === "") {
7140
7698
  throw new Error("promoteAuditPlans: options.harnessDir is required (must contain status.json + workflows/)");
7141
7699
  }
7142
- const workflowId = options.workflowId ?? basename5(resolve11(outDir));
7700
+ const workflowId = options.workflowId ?? basename6(resolve12(outDir));
7143
7701
  assertSafePathComponent(workflowId, "workflow id");
7144
- const harnessDir = resolve11(options.harnessDir);
7145
- const statusPath = join12(harnessDir, "status.json");
7146
- const workflowDir = join12(harnessDir, "workflows", workflowId);
7147
- const snapshotPath = join12(workflowDir, WORKFLOW_SNAPSHOT_FILE);
7702
+ const harnessDir = resolve12(options.harnessDir);
7703
+ const statusPath = join14(harnessDir, "status.json");
7704
+ const workflowDir = join14(harnessDir, "workflows", workflowId);
7705
+ const snapshotPath = join14(workflowDir, WORKFLOW_SNAPSHOT_FILE);
7148
7706
  const planFiles = resolveSelectedPlanFiles(outDir, selected);
7149
7707
  const indexRows = readExecutionOrderIndex(outDir);
7150
7708
  const plans = planFiles.map((planFile) => {
7151
7709
  const stem = planFile.replace(/\.md$/, "");
7152
7710
  const num = stem.slice(0, 3);
7153
7711
  const indexRow = indexRows.get(num);
7154
- const title = indexRow?.title ?? readPlanFileSummary(join12(outDir, planFile)).title;
7712
+ const title = indexRow?.title ?? readPlanFileSummary(join14(outDir, planFile)).title;
7155
7713
  return {
7156
7714
  id: stem,
7157
7715
  title,
@@ -7180,7 +7738,7 @@ async function promoteAuditPlans(outDir, selected, options) {
7180
7738
  throw new Error(`refusing to register invalid workflow entry: ${entryGate.violations.map((v) => v.message).join("; ")}`);
7181
7739
  }
7182
7740
  await withStatusWriteLock(statusPath, async () => {
7183
- if (existsSync8(snapshotPath)) {
7741
+ if (existsSync9(snapshotPath)) {
7184
7742
  throw new Error(`refusing to promote audit plans: workflow ${JSON.stringify(workflowId)} already exists (snapshot at ${snapshotPath}) \u2014 re-promote would drop its registered plan rows; ` + `remove that workflow before promoting again`);
7185
7743
  }
7186
7744
  mkdirSync8(workflowDir, { recursive: true });
@@ -7216,7 +7774,7 @@ function resolveSelectedPlanFiles(outDir, selected) {
7216
7774
  for (const id of selected) {
7217
7775
  const file = byNum.get(id) ?? byStem.get(id) ?? byStem.get(id.replace(/\.md$/, ""));
7218
7776
  if (file === undefined) {
7219
- throw new Error(`promoteAuditPlans: selected plan ${JSON.stringify(id)} does not match any NNN-*.md file in ${resolve11(outDir)}`);
7777
+ throw new Error(`promoteAuditPlans: selected plan ${JSON.stringify(id)} does not match any NNN-*.md file in ${resolve12(outDir)}`);
7220
7778
  }
7221
7779
  if (!seen.has(file)) {
7222
7780
  seen.add(file);
@@ -7226,7 +7784,7 @@ function resolveSelectedPlanFiles(outDir, selected) {
7226
7784
  return resolved;
7227
7785
  }
7228
7786
  function readExecutionOrderIndex(outDir) {
7229
- const readmePath = join12(outDir, "README.md");
7787
+ const readmePath = join14(outDir, "README.md");
7230
7788
  let text;
7231
7789
  try {
7232
7790
  text = readFileSync9(readmePath, "utf8");
@@ -7255,7 +7813,7 @@ function readExecutionOrderIndex(outDir) {
7255
7813
  return rows;
7256
7814
  }
7257
7815
  function planFileRel(outDir, planFile) {
7258
- const resolved = resolve11(outDir);
7816
+ const resolved = resolve12(outDir);
7259
7817
  const parts = resolved.split(sep3);
7260
7818
  const plansIdx = parts.lastIndexOf("plans");
7261
7819
  if (plansIdx >= 0) {
@@ -7514,11 +8072,11 @@ function collectKnowledgeDocs(dir) {
7514
8072
  for (const entry of entries) {
7515
8073
  if (entry.isSymbolicLink())
7516
8074
  continue;
7517
- const full = join13(current, entry.name);
8075
+ const full = join15(current, entry.name);
7518
8076
  if (entry.isDirectory()) {
7519
8077
  stack.push(full);
7520
8078
  } else if (entry.name.endsWith(".md") && entry.name !== "README.md" && entry.name !== "index.md") {
7521
- docs.push(relative4(dir, full).split(sep4).join("/"));
8079
+ docs.push(relative6(dir, full).split(sep4).join("/"));
7522
8080
  }
7523
8081
  }
7524
8082
  }
@@ -7534,8 +8092,8 @@ function normalizeIndexRef(cell) {
7534
8092
  }
7535
8093
  function assertIndexRows(knowledgeDir) {
7536
8094
  const violations = [];
7537
- const readmePath = join13(knowledgeDir, "README.md");
7538
- if (!existsSync9(readmePath)) {
8095
+ const readmePath = join15(knowledgeDir, "README.md");
8096
+ if (!existsSync10(readmePath)) {
7539
8097
  violations.push(violation10("medium", "compound.index.missing-readme", `missing ${readmePath} \u2014 the knowledge index is required (mstar-compound Phase 6: every doc gets a README.md row)`, "create knowledge/README.md with a Document / Source Plan / Description / Status table"));
7540
8098
  return { ok: false, violations };
7541
8099
  }
@@ -7559,12 +8117,12 @@ function assertIndexRows(knowledgeDir) {
7559
8117
  return { ok: violations.length === 0, violations };
7560
8118
  }
7561
8119
  function isFileLikeRoot(root) {
7562
- return /^[^.]*\.[A-Za-z0-9]{1,10}$/.test(basename6(root));
8120
+ return /^[^.]*\.[A-Za-z0-9]{1,10}$/.test(basename7(root));
7563
8121
  }
7564
8122
  function scopeGuard(path2, allowedRoots) {
7565
- const resolved = resolve12(path2);
8123
+ const resolved = resolve13(path2);
7566
8124
  for (const root of allowedRoots) {
7567
- const r = resolve12(root);
8125
+ const r = resolve13(root);
7568
8126
  if (isFileLikeRoot(r)) {
7569
8127
  if (resolved === r)
7570
8128
  return { ok: true, violations: [] };
@@ -7622,7 +8180,7 @@ function findTemporaryMarkers(fileText) {
7622
8180
  }
7623
8181
  markers.push({ line: i + 1, text, removalPath });
7624
8182
  if (removalPath === null) {
7625
- violations.push(violation11("medium", "lint.temporary.no-removal-path", `temporary marker at line ${i + 1} records no removal path (plan/status artifact reference) \u2014 record one before claiming the task complete (mstar-coding-behavior \u00a7 Simplification markers)`, 'add a plan/status reference to the marker, e.g. "removal tracked in status.json" or "plan 20260808-slice2 removes this"'));
8183
+ violations.push(violation11("medium", "lint.temporary.no-removal-path", `temporary marker at line ${i + 1} records no removal path (plan/status artifact reference) \u2014 record one before claiming the task complete (mstar-coding-behavior \u00a7 Simplification markers)`, 'add a plan/status reference to the marker, e.g. "removal tracked in status.json" or "plan 20991231-example-plan removes this"'));
7626
8184
  }
7627
8185
  }
7628
8186
  return { ok: violations.length === 0, violations, markers };
@@ -7865,8 +8423,8 @@ function validateRoleMapping(rolesDir, options = {}) {
7865
8423
  const violations = [];
7866
8424
  const referenceById = new Map(mapping.map((m) => [m.agentId, m.reference]));
7867
8425
  for (const { agentId, reference } of mapping) {
7868
- if (!existsSync10(join14(rolesDir, reference))) {
7869
- violations.push(violation12("medium", "roles.mapping.reference.missing", `role "${agentId}" maps to ${reference} which does not exist under ${rolesDir} (mstar-roles \u00a7 Role Reference Mapping)`, `create ${join14(rolesDir, reference)} or fix the mapping row`));
8426
+ if (!existsSync11(join16(rolesDir, reference))) {
8427
+ violations.push(violation12("medium", "roles.mapping.reference.missing", `role "${agentId}" maps to ${reference} which does not exist under ${rolesDir} (mstar-roles \u00a7 Role Reference Mapping)`, `create ${join16(rolesDir, reference)} or fix the mapping row`));
7870
8428
  }
7871
8429
  }
7872
8430
  for (const { family, memberIds } of families) {
@@ -7918,6 +8476,14 @@ function validateRoleMapping(rolesDir, options = {}) {
7918
8476
  return { ok: violations.length === 0, violations };
7919
8477
  }
7920
8478
  var LOAD_ORDER_HEADING_RE = /^#{1,6}\s+[^\r\n]*\b(?:load[\s-]*order|first\s+action)\b[^\r\n]*$/i;
8479
+ var HUB_BOOTSTRAP_ASSERTIONS = [
8480
+ { marker: "identity-first", why: "identity boundary before any skill list" },
8481
+ { marker: "skill presets", why: "Assignment Skill presets decision field" },
8482
+ { marker: "none", why: "explicit none => identity only, no optional topic preset" },
8483
+ { marker: "standard", why: "omitted on a substantive round => standard preset" },
8484
+ { marker: "role-owned", why: "role-owned methods / evidence obligations load regardless of preset" },
8485
+ { marker: "unknown preset", why: "unknown preset / missing identity => Needs Context / Blocked, never infer PM" }
8486
+ ];
7921
8487
  function extractLoadOrderSection(text) {
7922
8488
  const lines = text.split(/\r?\n/);
7923
8489
  let start = -1;
@@ -7951,11 +8517,22 @@ function lintLoadOrder(skillTexts) {
7951
8517
  continue;
7952
8518
  const section = extractLoadOrderSection(text);
7953
8519
  if (section === null) {
7954
- violations.push(violation12("medium", "roles.loadorder.section.missing", `skill "${name}" has no Load Order / First action section \u2014 every mstar-* topic skill must declare its first read (mstar-harness-core \u00a7 \u52a0\u8f7d\u7ea6\u5b9a; mstar-roles \u00a7 Load Order (Required))`, `add a "## Load Order" section naming mstar-harness-core as the first read`));
8520
+ violations.push(violation12("medium", "roles.loadorder.section.missing", `skill "${name}" has no Load Order / First action section \u2014 every mstar-* topic skill must declare its first read (mstar-harness-core \u00a7 \u52a0\u8f7d\u5951\u7ea6; mstar-roles \u00a7 Load Order = single load-selection authority)`, `add a "## Load Order" section: topics name mstar-harness-core first; mstar-roles declares the Skill presets decision matrix`));
8521
+ continue;
8522
+ }
8523
+ if (name === "mstar-roles") {
8524
+ const lower = section.toLowerCase();
8525
+ const missing = HUB_BOOTSTRAP_ASSERTIONS.filter((a) => !lower.includes(a.marker.toLowerCase()));
8526
+ if (missing.length > 0) {
8527
+ violations.push(violation12("medium", "roles.loadorder.hub.bootstrap.missing", `skill "${name}" Load Order section is missing the hub bootstrap decision matrix: ${missing.map((m) => `"${m.marker}" (${m.why})`).join("; ")} (mstar-roles \u00a7 Load Order = single load-selection authority)`, "declare identity-first, the Skill presets none/standard decision, role-owned methods, and the unknown-preset / missing-identity refusal in the Load Order section"));
8528
+ }
8529
+ if (!section.includes("mstar-harness-core")) {
8530
+ violations.push(violation12("medium", "roles.loadorder.core.missing", `skill "${name}" Load Order section does not point at mstar-harness-core \u2014 the hub bootstrap is exempt from core-first, but core remains the lifecycle/authorization conflict authority and global entry whenever loaded`, "keep the conditional mstar-harness-core pointer (global entry / conflict authority) in the Load Order section"));
8531
+ }
7955
8532
  continue;
7956
8533
  }
7957
8534
  if (!section.includes("mstar-harness-core")) {
7958
- violations.push(violation12("medium", "roles.loadorder.core.missing", `skill "${name}" Load Order section does not declare mstar-harness-core as its first dependency (mstar-harness-core \u00a7 \u52a0\u8f7d\u7ea6\u5b9a: \u51e1 mstar-*\uff08name \u2260 mstar-harness-core\uff09\u5047\u5b9a\u8bfb\u8005\u5df2 Read \u672c skill)`, "name mstar-harness-core first in the Load Order section"));
8535
+ violations.push(violation12("medium", "roles.loadorder.core.missing", `skill "${name}" Load Order section does not declare mstar-harness-core as its first dependency (mstar-harness-core \u00a7 \u52a0\u8f7d\u5951\u7ea6: directly-invoked topics keep core as first dependency; the mstar-roles hub bootstrap is the only exception)`, "name mstar-harness-core first in the Load Order section"));
7959
8536
  }
7960
8537
  }
7961
8538
  return { ok: violations.length === 0, violations };
@@ -8035,6 +8612,16 @@ function collectHeadings(bodyText) {
8035
8612
  }
8036
8613
  return headings;
8037
8614
  }
8615
+ function classifySkillLint(skillId) {
8616
+ const id = skillId ?? "";
8617
+ if (id === "mstar-harness-core")
8618
+ return { kind: "core", mode: null };
8619
+ if (id === "mstar-skill-authoring")
8620
+ return { kind: "authoring", mode: "authoring" };
8621
+ if (id.startsWith("mstar-"))
8622
+ return { kind: "runtime", mode: "runtime" };
8623
+ return { kind: "authoring", mode: "authoring" };
8624
+ }
8038
8625
  var RUNTIME_HEADING_ALIASES = {
8039
8626
  workflow: ["process", "playbook"],
8040
8627
  "decision-rules": [
@@ -8098,7 +8685,7 @@ must-fix=${mustFix} should-fix=${shouldFix} nit=${nit} unverified=${unverified}`
8098
8685
  var REVIEW_SCHEMA_ID = "mstar.review/v1";
8099
8686
  var INSPECTOR_VERDICTS = ["comment", "request_changes", "approve"];
8100
8687
  var INSPECTOR_SEVERITIES = ["critical", "warning", "suggestion", "info"];
8101
- function isPlainObject7(value) {
8688
+ function isPlainObject8(value) {
8102
8689
  return typeof value === "object" && value !== null && !Array.isArray(value);
8103
8690
  }
8104
8691
  var TALLY_COUNT_KEYS = ["mustFix", "shouldFix", "nit", "unverified"];
@@ -8109,7 +8696,7 @@ function checkProvidedTallyShape(tally, violations) {
8109
8696
  if (typeof tally.scorePct !== "number" || !Number.isInteger(tally.scorePct) || tally.scorePct < 0 || tally.scorePct > 100) {
8110
8697
  violations.push(violation14("high", "review.tally-malformed", `tally.scorePct must be an integer in [0, 100] - got ${String(tally.scorePct)}`));
8111
8698
  }
8112
- if (!isPlainObject7(tally.tally)) {
8699
+ if (!isPlainObject8(tally.tally)) {
8113
8700
  violations.push(violation14("high", "review.tally-malformed", "tally.tally must be an object carrying the four class counts"));
8114
8701
  } else {
8115
8702
  for (const key of TALLY_COUNT_KEYS) {
@@ -8125,7 +8712,7 @@ function checkProvidedTallyShape(tally, violations) {
8125
8712
  }
8126
8713
  function validateMstarReviewV1(doc) {
8127
8714
  const violations = [];
8128
- if (!isPlainObject7(doc)) {
8715
+ if (!isPlainObject8(doc)) {
8129
8716
  return {
8130
8717
  ok: false,
8131
8718
  violations: [violation14("high", "review.not-object", "review document must be a JSON object")]
@@ -8152,7 +8739,7 @@ function validateMstarReviewV1(doc) {
8152
8739
  violations.push(violation14("high", "review.findings-not-array", "findings must be an array"));
8153
8740
  } else {
8154
8741
  doc.findings.forEach((finding, index) => {
8155
- if (!isPlainObject7(finding)) {
8742
+ if (!isPlainObject8(finding)) {
8156
8743
  violations.push(violation14("high", "review.invalid-finding", `findings[${index}] must be an object`));
8157
8744
  return;
8158
8745
  }
@@ -8192,7 +8779,7 @@ function validateMstarReviewV1(doc) {
8192
8779
  });
8193
8780
  }
8194
8781
  if (doc.tally !== undefined) {
8195
- if (!isPlainObject7(doc.tally)) {
8782
+ if (!isPlainObject8(doc.tally)) {
8196
8783
  violations.push(violation14("high", "review.invalid-tally", "tally must be a PrTallyResult object"));
8197
8784
  } else {
8198
8785
  checkProvidedTallyShape(doc.tally, violations);
@@ -8202,7 +8789,7 @@ function validateMstarReviewV1(doc) {
8202
8789
  }
8203
8790
  }
8204
8791
  if (doc.target !== undefined) {
8205
- if (!isPlainObject7(doc.target)) {
8792
+ if (!isPlainObject8(doc.target)) {
8206
8793
  violations.push(violation14("high", "review.invalid-target", "target must be an object"));
8207
8794
  } else {
8208
8795
  if (doc.target.owner !== undefined && typeof doc.target.owner !== "string") {
@@ -8284,7 +8871,7 @@ function prReviewReportPath(opts) {
8284
8871
  }
8285
8872
  const revision = maxRevision + 1;
8286
8873
  const name = revision === 1 ? `${finalStem}.md` : `${finalStem}-r${revision}.md`;
8287
- return join15(opts.reportsDir, name);
8874
+ return join17(opts.reportsDir, name);
8288
8875
  }
8289
8876
  var PR_TIERS = ["quick", "default", "deep"];
8290
8877
  function violation14(severity, code, message, fix) {
@@ -8601,7 +9188,7 @@ function prReviewSeatPrompt(opts) {
8601
9188
  lines.push("");
8602
9189
  lines.push("## Read first");
8603
9190
  lines.push("");
8604
- const prReviewRef = join15(skillRoot, "references", "pr-review.md");
9191
+ const prReviewRef = join17(skillRoot, "references", "pr-review.md");
8605
9192
  const sections = opts.stage === 1 ? tier === "quick" ? "Scoping, Evidence rules" : "Review pipeline, Worktree isolation, Scoping, Evidence rules" : "Merge class, Attack and vet, Evidence rules, Sizing & change shape";
8606
9193
  lines.push(`1. \`${prReviewRef}\` \u2014 read at least these sections: ${sections}.`);
8607
9194
  lines.push(`2. The review worktree: \`${worktreePath}\` \u2014 your ONLY working directory this session; read-only (no edits, no fixes, no stash, no commits, no posts).`);
@@ -8609,9 +9196,9 @@ function prReviewSeatPrompt(opts) {
8609
9196
  lines.push(`- Read the pinned diff snapshot FIRST: \`${opts.diffFile}\` \u2014 it is the review's diff basis (already computed at setup); read it before opening files.`);
8610
9197
  }
8611
9198
  if (opts.stage === 2) {
8612
- lines.push(`3. \`${join15(skillRoot, "references", "finding-format.md")}\` \u2014 the template every finding follows.`);
9199
+ lines.push(`3. \`${join17(skillRoot, "references", "finding-format.md")}\` \u2014 the template every finding follows.`);
8613
9200
  if (opts.securitySeat === true) {
8614
- lines.push(`4. \`${join15(skillRoot, "references", "security-review.md")}\` \u2014 the security lens.`);
9201
+ lines.push(`4. \`${join17(skillRoot, "references", "security-review.md")}\` \u2014 the security lens.`);
8615
9202
  }
8616
9203
  }
8617
9204
  const budget = PR_REVIEW_TIER_BUDGETS[tier];
@@ -8794,12 +9381,12 @@ function resolvePrReviewTier(input) {
8794
9381
  }
8795
9382
 
8796
9383
  // ../engine/dist/engine.js
8797
- import { existsSync as existsSync11, mkdirSync as mkdirSync3, readFileSync as readFileSync8, renameSync as renameSync2, unlinkSync as unlinkSync4, writeFileSync as writeFileSync5 } from "node:fs";
9384
+ import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync8, renameSync as renameSync2, unlinkSync as unlinkSync4, writeFileSync as writeFileSync5 } from "node:fs";
8798
9385
  import { randomUUID as randomUUID2 } from "node:crypto";
8799
- import { basename as basename7, dirname as dirname7, join as join3, resolve as resolve10 } from "node:path";
9386
+ import { basename as basename5, dirname as dirname7, join as join3, resolve as resolve10 } from "node:path";
8800
9387
  import { fileURLToPath } from "node:url";
8801
9388
  import { readFileSync as readFileSync22, statSync as statSync5 } from "node:fs";
8802
- import { dirname as dirname22, isAbsolute as isAbsolute7, join as join22, relative as relative3, resolve as resolve22 } from "node:path";
9389
+ import { dirname as dirname22, isAbsolute as isAbsolute7, join as join22, relative as relative4, resolve as resolve22 } from "node:path";
8803
9390
  import { existsSync as existsSync62, mkdirSync as mkdirSync52, readdirSync as readdirSync52, readFileSync as readFileSync62, realpathSync as realpathSync22, statSync as statSync32, writeFileSync as writeFileSync32 } from "node:fs";
8804
9391
  import { execFileSync as execFileSync5 } from "node:child_process";
8805
9392
  import { basename as basename32, dirname as dirname52, isAbsolute as isAbsolute42, join as join92, relative as relative22, resolve as resolve72 } from "node:path";
@@ -8809,15 +9396,15 @@ import { setTimeout as sleep2 } from "node:timers/promises";
8809
9396
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
8810
9397
  import { existsSync as existsSync32, readdirSync as readdirSync22, unlinkSync as unlinkSync32 } from "node:fs";
8811
9398
  import { isAbsolute as isAbsolute32, join as join52, resolve as resolve42 } from "node:path";
8812
- import { existsSync as existsSync42, readFileSync as readFileSync42, readdirSync as readdirSync32, realpathSync as realpathSync4 } from "node:fs";
9399
+ import { existsSync as existsSync42, readFileSync as readFileSync42, readdirSync as readdirSync32, realpathSync as realpathSync5 } from "node:fs";
8813
9400
  import { dirname as dirname42, join as join72, resolve as resolve52, sep as sep2 } from "node:path";
8814
9401
  import { mkdirSync as mkdirSync32 } from "node:fs";
8815
9402
  import { join as join6 } from "node:path";
8816
9403
  import { copyFileSync, mkdirSync as mkdirSync7, readFileSync as readFileSync82, readdirSync as readdirSync7, writeFileSync as writeFileSync52 } from "node:fs";
8817
- import { dirname as dirname72, isAbsolute as isAbsolute72, join as join11, relative as relative32, resolve as resolve102, sep as sep22 } from "node:path";
9404
+ import { dirname as dirname8, isAbsolute as isAbsolute72, join as join13, relative as relative5, resolve as resolve11, sep as sep22 } from "node:path";
8818
9405
  var SEVERITY_ORDER2 = ["critical", "high", "medium", "low", "nit"];
8819
9406
  function readJson2(filePath) {
8820
- if (!existsSync11(filePath))
9407
+ if (!existsSync8(filePath))
8821
9408
  return {};
8822
9409
  const content = readFileSync8(filePath, "utf8").trim();
8823
9410
  if (!content)
@@ -8831,7 +9418,7 @@ function readJson2(filePath) {
8831
9418
  function writeJson2(filePath, value) {
8832
9419
  const parent = dirname7(filePath);
8833
9420
  mkdirSync3(parent, { recursive: true });
8834
- const tmp = join3(parent, `.${basename7(filePath)}.${process.pid}.${randomUUID2()}.tmp`);
9421
+ const tmp = join3(parent, `.${basename5(filePath)}.${process.pid}.${randomUUID2()}.tmp`);
8835
9422
  try {
8836
9423
  writeFileSync5(tmp, `${JSON.stringify(value, null, 2)}
8837
9424
  `, "utf8");
@@ -8847,7 +9434,7 @@ function resolveProjectRoot(startDir = process.cwd()) {
8847
9434
  const start = resolve10(startDir);
8848
9435
  let dir = start;
8849
9436
  for (;; ) {
8850
- if (existsSync11(join3(dir, "package.json")) || existsSync11(join3(dir, "bun.lock")))
9437
+ if (existsSync8(join3(dir, "package.json")) || existsSync8(join3(dir, "bun.lock")))
8851
9438
  return dir;
8852
9439
  const parent = dirname7(dir);
8853
9440
  if (parent === dir)
@@ -8972,7 +9559,7 @@ function loadMstarc2(startDir, boundary) {
8972
9559
  return { file, dir: dirname22(file), config: parseMstarc2(readFileSync22(file, "utf8")) };
8973
9560
  }
8974
9561
  function isAtOrBelow3(dir, root) {
8975
- const rel = relative3(root, dir);
9562
+ const rel = relative4(root, dir);
8976
9563
  return rel === "" || !rel.startsWith("..") && !isAbsolute7(rel);
8977
9564
  }
8978
9565
  function parseCompassFrontmatterText2(content, filePath) {
@@ -9108,11 +9695,11 @@ function validateIntegrationMergeLease2(lease) {
9108
9695
  }
9109
9696
  return { ok: violations.length === 0, violations };
9110
9697
  }
9111
- function planExecutionLeaseLocations(row) {
9698
+ function planExecutionLeaseLocations2(row) {
9112
9699
  return { row: row.execution_lease };
9113
9700
  }
9114
- function verifyPlanExecutionLease(row, planId) {
9115
- const { row: rowLease } = planExecutionLeaseLocations(row);
9701
+ function verifyPlanExecutionLease2(row, planId) {
9702
+ const { row: rowLease } = planExecutionLeaseLocations2(row);
9116
9703
  const lease = rowLease;
9117
9704
  if (lease === undefined) {
9118
9705
  if (row.status === "InProgress") {
@@ -9648,7 +10235,7 @@ function validateStatusV22(docOrPath, opts = {}) {
9648
10235
  if (harnessDir !== undefined && Array.isArray(doc.workflows)) {
9649
10236
  let realHarnessDir = null;
9650
10237
  try {
9651
- realHarnessDir = realpathSync4(harnessDir);
10238
+ realHarnessDir = realpathSync5(harnessDir);
9652
10239
  } catch {}
9653
10240
  for (const entry of doc.workflows) {
9654
10241
  if (!isPlainObject42(entry) || typeof entry.dir !== "string")
@@ -9658,7 +10245,7 @@ function validateStatusV22(docOrPath, opts = {}) {
9658
10245
  const label = typeof entry.id === "string" ? entry.id : relSnapshot;
9659
10246
  let physical;
9660
10247
  try {
9661
- physical = realpathSync4(snapshotPath);
10248
+ physical = realpathSync5(snapshotPath);
9662
10249
  } catch {
9663
10250
  violations.push(violation52("high", "status.workflow.snapshot-missing", `workflows[] lists ${JSON.stringify(label)} but its snapshot does not exist at ${JSON.stringify(relSnapshot)} \u2014 the root holds active lifecycles only; unregister the id when its snapshot is removed`));
9664
10251
  continue;
@@ -9866,7 +10453,7 @@ var ROOT_METADATA_LIFT_KEYS = {
9866
10453
  program_roadmap: true,
9867
10454
  updated_at: true
9868
10455
  };
9869
- function isPlainObject6(value) {
10456
+ function isPlainObject7(value) {
9870
10457
  return typeof value === "object" && value !== null && !Array.isArray(value);
9871
10458
  }
9872
10459
  function dateString(value) {
@@ -9889,7 +10476,7 @@ function todayString3() {
9889
10476
  return `${now.getFullYear()}-${month}-${day}`;
9890
10477
  }
9891
10478
  function scanCompasses(harnessDir) {
9892
- const iterationsDir = join11(harnessDir, "iterations");
10479
+ const iterationsDir = join13(harnessDir, "iterations");
9893
10480
  const out = [];
9894
10481
  let entries;
9895
10482
  try {
@@ -9900,7 +10487,7 @@ function scanCompasses(harnessDir) {
9900
10487
  for (const entry of entries) {
9901
10488
  if (!entry.isDirectory())
9902
10489
  continue;
9903
- const compassPath = join11(iterationsDir, entry.name, "delivery-compass.md");
10490
+ const compassPath = join13(iterationsDir, entry.name, "delivery-compass.md");
9904
10491
  let content;
9905
10492
  try {
9906
10493
  content = readFileSync82(compassPath, "utf8");
@@ -9980,8 +10567,8 @@ function buildIterationSnapshot(compass, rowById, rootUpdatedAt) {
9980
10567
  id: compass.id,
9981
10568
  type: "iteration",
9982
10569
  status,
9983
- file: join11("workflows", compass.id, WORKFLOW_SNAPSHOT_FILE2),
9984
- source: join11("iterations", compass.id, "delivery-compass.md"),
10570
+ file: join13("workflows", compass.id, WORKFLOW_SNAPSHOT_FILE2),
10571
+ source: join13("iterations", compass.id, "delivery-compass.md"),
9985
10572
  data: snapshot
9986
10573
  };
9987
10574
  }
@@ -10016,7 +10603,7 @@ function buildStandaloneSnapshot(row, rootUpdatedAt, migrationNotes) {
10016
10603
  id,
10017
10604
  type: "plan",
10018
10605
  status,
10019
- file: join11("workflows", id, WORKFLOW_SNAPSHOT_FILE2),
10606
+ file: join13("workflows", id, WORKFLOW_SNAPSHOT_FILE2),
10020
10607
  source: "status.json plans[] row",
10021
10608
  data: snapshot
10022
10609
  };
@@ -10046,10 +10633,10 @@ function applyRootMetadataLift(snapshot, metadata, migrationNotes, activeIterati
10046
10633
  if (typeof metadata.control_worktree_path === "string" && metadata.control_worktree_path !== "") {
10047
10634
  data.control_worktree_path = metadata.control_worktree_path;
10048
10635
  }
10049
- if (isPlainObject6(metadata.integration_merge_lease)) {
10636
+ if (isPlainObject7(metadata.integration_merge_lease)) {
10050
10637
  data.integration_merge_lease = metadata.integration_merge_lease;
10051
10638
  }
10052
- const legacyMetadata = isPlainObject6(data.legacy_metadata) ? { ...data.legacy_metadata } : {};
10639
+ const legacyMetadata = isPlainObject7(data.legacy_metadata) ? { ...data.legacy_metadata } : {};
10053
10640
  for (const [key, value] of Object.entries(metadata)) {
10054
10641
  if (key === "harness_root")
10055
10642
  continue;
@@ -10105,7 +10692,7 @@ function buildRegister(residualFindings, byPlan, projectId, migratedAt) {
10105
10692
  const raw = residualFindings[planId];
10106
10693
  if (!Array.isArray(raw))
10107
10694
  continue;
10108
- const open = raw.filter((entry) => isPlainObject6(entry) && isOpenResidual2(entry)).sort((a, b) => {
10695
+ const open = raw.filter((entry) => isPlainObject7(entry) && isOpenResidual2(entry)).sort((a, b) => {
10109
10696
  const aId = typeof a.id === "string" ? a.id : "";
10110
10697
  const bId = typeof b.id === "string" ? b.id : "";
10111
10698
  return compareIds(aId, bId);
@@ -10124,7 +10711,7 @@ function buildRegister(residualFindings, byPlan, projectId, migratedAt) {
10124
10711
  return null;
10125
10712
  const doc = { entries };
10126
10713
  return {
10127
- file: join11("projects", projectId, PROJECT_REGISTER_FILE2),
10714
+ file: join13("projects", projectId, PROJECT_REGISTER_FILE2),
10128
10715
  source: "status.json residual_findings",
10129
10716
  data: doc
10130
10717
  };
@@ -10155,7 +10742,7 @@ function collectNotesFiles(snapshots) {
10155
10742
  if (lines.length === 0)
10156
10743
  continue;
10157
10744
  out.push({
10158
- file: join11(dirname72(snapshot.file), NOTES_LEDGER_FILE),
10745
+ file: join13(dirname8(snapshot.file), NOTES_LEDGER_FILE),
10159
10746
  source,
10160
10747
  lines
10161
10748
  });
@@ -10163,11 +10750,11 @@ function collectNotesFiles(snapshots) {
10163
10750
  return out;
10164
10751
  }
10165
10752
  function migrateHarnessTree(root, opts = {}) {
10166
- const harnessDir = resolve102(root);
10753
+ const harnessDir = resolve11(root);
10167
10754
  const workflowDir = resolveWorkflowDir2(harnessDir, { harnessDir });
10168
10755
  const projectDir = resolveProjectDir2(harnessDir, { harnessDir });
10169
10756
  const projectId = opts.projectId ?? _DEFAULT_PROJECT2;
10170
- const statusPath = join11(harnessDir, MIGRATE_STATUS_FILE);
10757
+ const statusPath = join13(harnessDir, MIGRATE_STATUS_FILE);
10171
10758
  const legacy = readJson2(statusPath);
10172
10759
  if (legacy.version === 2) {
10173
10760
  const updatedAt = typeof legacy.updated_at === "string" && legacy.updated_at !== "" ? legacy.updated_at : "1970-01-01";
@@ -10194,12 +10781,12 @@ function migrateHarnessTree(root, opts = {}) {
10194
10781
  if (legacy.version === undefined) {
10195
10782
  throw new Error(`refusing to migrate: no v1 status.json found at ${statusPath} (nothing to migrate)`);
10196
10783
  }
10197
- const rows = Array.isArray(legacy.plans) ? legacy.plans.filter(isPlainObject6) : [];
10784
+ const rows = Array.isArray(legacy.plans) ? legacy.plans.filter(isPlainObject7) : [];
10198
10785
  if (Array.isArray(legacy.plans)) {
10199
10786
  const unLiftable = [];
10200
10787
  const idCounts = new Map;
10201
10788
  for (const row of legacy.plans) {
10202
- if (!isPlainObject6(row) || rowIdOf(row) === null) {
10789
+ if (!isPlainObject7(row) || rowIdOf(row) === null) {
10203
10790
  unLiftable.push(row);
10204
10791
  continue;
10205
10792
  }
@@ -10215,7 +10802,7 @@ function migrateHarnessTree(root, opts = {}) {
10215
10802
  throw new Error(`refusing to migrate: ${duplicates.length} duplicate plan id(s) (${duplicates.join(", ")}) \u2014 every v1 row must land in exactly one snapshot`);
10216
10803
  }
10217
10804
  }
10218
- const metadata = isPlainObject6(legacy.metadata) ? legacy.metadata : {};
10805
+ const metadata = isPlainObject7(legacy.metadata) ? legacy.metadata : {};
10219
10806
  const rootUpdatedAt = dateString(legacy.updated_at) ?? dateString(metadata.updated_at) ?? todayString3();
10220
10807
  const migratedAt = dateString(metadata.updated_at) ?? rootUpdatedAt;
10221
10808
  const migrationNotes = [];
@@ -10252,9 +10839,9 @@ function migrateHarnessTree(root, opts = {}) {
10252
10839
  migrationNotes.push("no active iteration snapshot found \u2014 root metadata execution-policy/branch keys have no lift home and stay unmapped (visible here, not silently dropped)");
10253
10840
  }
10254
10841
  const notesFiles = collectNotesFiles(snapshots);
10255
- const residualFindings = isPlainObject6(legacy.residual_findings) ? legacy.residual_findings : {};
10842
+ const residualFindings = isPlainObject7(legacy.residual_findings) ? legacy.residual_findings : {};
10256
10843
  const register = buildRegister(residualFindings, byPlan, projectId, migratedAt);
10257
- const programRoadmap = isPlainObject6(metadata.program_roadmap) ? metadata.program_roadmap : null;
10844
+ const programRoadmap = isPlainObject7(metadata.program_roadmap) ? metadata.program_roadmap : null;
10258
10845
  let roadmap = null;
10259
10846
  if (programRoadmap) {
10260
10847
  const rawTitle = typeof programRoadmap.title === "string" && programRoadmap.title !== "" ? programRoadmap.title : "Program roadmap";
@@ -10263,7 +10850,7 @@ function migrateHarnessTree(root, opts = {}) {
10263
10850
  migrationNotes.push(`roadmap title sanitized for frontmatter (line breaks replaced with spaces): ${JSON.stringify(rawTitle)}`);
10264
10851
  }
10265
10852
  roadmap = {
10266
- file: join11("projects", projectId, PROJECT_ROADMAP_FILE2),
10853
+ file: join13("projects", projectId, PROJECT_ROADMAP_FILE2),
10267
10854
  source: "status.json metadata.program_roadmap",
10268
10855
  content: buildRoadmap({ ...programRoadmap, title: sanitizedTitle }, projectId, migratedAt)
10269
10856
  };
@@ -10312,19 +10899,19 @@ async function applyMigratePlan(plan) {
10312
10899
  if (plan.dryRun) {
10313
10900
  return { applied: false, message: `dry-run: ${plan.steps.length} steps planned (source \u2192 destination), zero writes` };
10314
10901
  }
10315
- const statusPath = join11(plan.root, MIGRATE_STATUS_FILE);
10902
+ const statusPath = join13(plan.root, MIGRATE_STATUS_FILE);
10316
10903
  const current = readJson2(statusPath);
10317
10904
  if (current.version === 2) {
10318
10905
  return { applied: false, message: "no-op: status.json already at schema version 2 (migrated) \u2014 nothing to do" };
10319
10906
  }
10320
- const harnessRoot = resolve102(plan.root);
10321
- const workflowRoot = resolve102(plan.workflowDir);
10322
- const projectRoot = resolve102(plan.projectDir);
10907
+ const harnessRoot = resolve11(plan.root);
10908
+ const workflowRoot = resolve11(plan.workflowDir);
10909
+ const projectRoot = resolve11(plan.projectDir);
10323
10910
  if (!isAbsolute72(plan.workflowDir) || !isAbsolute72(plan.projectDir)) {
10324
10911
  throw new Error(`refusing to apply migration: plan workflowDir/projectDir must be absolute (got ${JSON.stringify(plan.workflowDir)} / ${JSON.stringify(plan.projectDir)})`);
10325
10912
  }
10326
- const workflowTargetOf = (canonicalFile) => join11(workflowRoot, relative32("workflows", canonicalFile));
10327
- const projectTargetOf = (canonicalFile) => join11(projectRoot, relative32("projects", canonicalFile));
10913
+ const workflowTargetOf = (canonicalFile) => join13(workflowRoot, relative5("workflows", canonicalFile));
10914
+ const projectTargetOf = (canonicalFile) => join13(projectRoot, relative5("projects", canonicalFile));
10328
10915
  const allDestinations = [
10329
10916
  plan.archive.file,
10330
10917
  ...plan.snapshots.map((snapshot) => snapshot.file),
@@ -10333,20 +10920,20 @@ async function applyMigratePlan(plan) {
10333
10920
  ...plan.roadmap !== null ? [plan.roadmap.file] : []
10334
10921
  ];
10335
10922
  for (const destination of allDestinations) {
10336
- const resolvedDest = resolve102(join11(plan.root, destination));
10923
+ const resolvedDest = resolve11(join13(plan.root, destination));
10337
10924
  const inside = (dir) => resolvedDest === dir || resolvedDest.startsWith(`${dir}${sep22}`);
10338
10925
  if (!inside(harnessRoot) && !inside(workflowRoot) && !inside(projectRoot)) {
10339
10926
  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)})`);
10340
10927
  }
10341
10928
  }
10342
- mkdirSync7(join11(plan.root, dirname72(plan.archive.file)), { recursive: true });
10343
- copyFileSync(statusPath, join11(plan.root, plan.archive.file));
10929
+ mkdirSync7(join13(plan.root, dirname8(plan.archive.file)), { recursive: true });
10930
+ copyFileSync(statusPath, join13(plan.root, plan.archive.file));
10344
10931
  for (const snapshot of plan.snapshots) {
10345
- await writeWorkflowSnapshot(snapshot.data, dirname72(workflowTargetOf(snapshot.file)));
10932
+ await writeWorkflowSnapshot(snapshot.data, dirname8(workflowTargetOf(snapshot.file)));
10346
10933
  }
10347
10934
  for (const notes of plan.notesFiles) {
10348
10935
  const filePath = workflowTargetOf(notes.file);
10349
- mkdirSync7(dirname72(filePath), { recursive: true });
10936
+ mkdirSync7(dirname8(filePath), { recursive: true });
10350
10937
  const content = notes.lines.length > 0 ? `${notes.lines.join(`
10351
10938
  `)}
10352
10939
  ` : "";
@@ -10359,13 +10946,13 @@ async function applyMigratePlan(plan) {
10359
10946
  }
10360
10947
  if (Object.keys(plan.register.data.entries ?? {}).length > 0) {
10361
10948
  const filePath = projectTargetOf(plan.register.file);
10362
- mkdirSync7(dirname72(filePath), { recursive: true });
10949
+ mkdirSync7(dirname8(filePath), { recursive: true });
10363
10950
  writeJson2(filePath, plan.register.data);
10364
10951
  }
10365
10952
  }
10366
10953
  if (plan.roadmap !== null) {
10367
10954
  const filePath = projectTargetOf(plan.roadmap.file);
10368
- mkdirSync7(dirname72(filePath), { recursive: true });
10955
+ mkdirSync7(dirname8(filePath), { recursive: true });
10369
10956
  writeFileSync52(filePath, plan.roadmap.content, "utf8");
10370
10957
  }
10371
10958
  const rootGate = validateStatusV22(plan.rootV2.data, { harnessDir: plan.root });
@@ -10401,7 +10988,7 @@ var RISK_ENUM_RE2 = new RegExp(`^(?:${AUDIT_RISKS2.join("|")})(?:\\b|$)`);
10401
10988
  var CONFIDENCE_ENUM_RE2 = new RegExp(`^(${[...AUDIT_CONFIDENCES2, "MEDIUM"].join("|")})\\b`, "i");
10402
10989
  // src/commands/migrate.ts
10403
10990
  var import_picocolors = __toESM(require_picocolors2(), 1);
10404
- import { resolve as resolve13 } from "node:path";
10991
+ import { resolve as resolve14 } from "node:path";
10405
10992
  function validatePlannedDocs(plan) {
10406
10993
  const warnings = [];
10407
10994
  for (const snapshot of plan.snapshots) {
@@ -10423,7 +11010,7 @@ function validatePlannedDocs(plan) {
10423
11010
  return warnings;
10424
11011
  }
10425
11012
  async function runMigrateCommand(options) {
10426
- const root = options.path ? resolve13(options.path) : resolveHarnessDir2() ?? process.cwd();
11013
+ const root = options.path ? resolve14(options.path) : resolveHarnessDir2() ?? process.cwd();
10427
11014
  setArtifactStore2(createFsStore2(root));
10428
11015
  let plan;
10429
11016
  try {
@@ -10514,7 +11101,7 @@ async function runMigrateCommand(options) {
10514
11101
  }
10515
11102
 
10516
11103
  // src/agent-plugins.ts
10517
- import fs from "node:fs";
11104
+ import fs, { realpathSync as realpathSync7 } from "node:fs";
10518
11105
  import path3 from "node:path";
10519
11106
 
10520
11107
  // src/utils.ts
@@ -10579,7 +11166,7 @@ function describeType(value) {
10579
11166
  return "array";
10580
11167
  return typeof value;
10581
11168
  }
10582
- function isPlainObject8(value) {
11169
+ function isPlainObject9(value) {
10583
11170
  return typeof value === "object" && value !== null && !Array.isArray(value);
10584
11171
  }
10585
11172
  function parseScalar3(raw) {
@@ -10623,7 +11210,7 @@ function isValidMcpUrl(raw) {
10623
11210
  return true;
10624
11211
  }
10625
11212
  function validateManifest(manifest, errors2, warnings) {
10626
- if (!isPlainObject8(manifest)) {
11213
+ if (!isPlainObject9(manifest)) {
10627
11214
  errors2.push("plugin.json: manifest must be a JSON object");
10628
11215
  return;
10629
11216
  }
@@ -10659,7 +11246,7 @@ function validateManifest(manifest, errors2, warnings) {
10659
11246
  }
10660
11247
  }
10661
11248
  if (doc.author !== undefined) {
10662
- if (!isPlainObject8(doc.author)) {
11249
+ if (!isPlainObject9(doc.author)) {
10663
11250
  errors2.push('plugin.json: "author" must be an object with optional string fields name/email/url');
10664
11251
  } else {
10665
11252
  const author = doc.author;
@@ -10682,11 +11269,11 @@ function validateManifest(manifest, errors2, warnings) {
10682
11269
  }
10683
11270
  }
10684
11271
  if (doc.extensions !== undefined) {
10685
- if (!isPlainObject8(doc.extensions)) {
11272
+ if (!isPlainObject9(doc.extensions)) {
10686
11273
  warnings.push('plugin.json: "extensions" is not an object \u2014 ignored');
10687
11274
  } else {
10688
11275
  for (const [namespace, value] of Object.entries(doc.extensions)) {
10689
- if (!isPlainObject8(value)) {
11276
+ if (!isPlainObject9(value)) {
10690
11277
  warnings.push(`plugin.json: "extensions.${namespace}" is not an object \u2014 ignored`);
10691
11278
  }
10692
11279
  }
@@ -10695,7 +11282,7 @@ function validateManifest(manifest, errors2, warnings) {
10695
11282
  }
10696
11283
  function validateMcpServer(name, entry, errors2) {
10697
11284
  const prefix = `mcp.json: mcpServers.${name}`;
10698
- if (!isPlainObject8(entry)) {
11285
+ if (!isPlainObject9(entry)) {
10699
11286
  errors2.push(`${prefix} must be an object`);
10700
11287
  return;
10701
11288
  }
@@ -10729,7 +11316,7 @@ function validateMcpServer(name, entry, errors2) {
10729
11316
  }
10730
11317
  }
10731
11318
  if (server.env !== undefined) {
10732
- if (!isPlainObject8(server.env)) {
11319
+ if (!isPlainObject9(server.env)) {
10733
11320
  errors2.push(`${prefix}: "env" must be an object of strings`);
10734
11321
  } else {
10735
11322
  for (const [key, value] of Object.entries(server.env)) {
@@ -10768,7 +11355,7 @@ function validateMcpServer(name, entry, errors2) {
10768
11355
  errors2.push(`${prefix}: "url" must be an absolute http(s) URL without user info or fragment; non-loopback endpoints must use https`);
10769
11356
  }
10770
11357
  if (server.headers !== undefined) {
10771
- if (!isPlainObject8(server.headers)) {
11358
+ if (!isPlainObject9(server.headers)) {
10772
11359
  errors2.push(`${prefix}: "headers" must be an object of strings`);
10773
11360
  } else {
10774
11361
  const seen = new Set;
@@ -10795,7 +11382,7 @@ function validateMcpServer(name, entry, errors2) {
10795
11382
  }
10796
11383
  }
10797
11384
  function validateMcp(root, manifestSchema, errors2) {
10798
- const mcpPath = path3.join(root, "mcp.json");
11385
+ const mcpPath = `${root}${path3.sep}mcp.json`;
10799
11386
  if (!fs.existsSync(mcpPath))
10800
11387
  return;
10801
11388
  let parsed;
@@ -10805,7 +11392,7 @@ function validateMcp(root, manifestSchema, errors2) {
10805
11392
  errors2.push(`mcp.json: ${error.message}`);
10806
11393
  return;
10807
11394
  }
10808
- if (!isPlainObject8(parsed)) {
11395
+ if (!isPlainObject9(parsed)) {
10809
11396
  errors2.push("mcp.json: configuration must be a JSON object");
10810
11397
  return;
10811
11398
  }
@@ -10828,7 +11415,7 @@ function validateMcp(root, manifestSchema, errors2) {
10828
11415
  }
10829
11416
  }
10830
11417
  const servers = doc.mcpServers;
10831
- if (!isPlainObject8(servers)) {
11418
+ if (!isPlainObject9(servers)) {
10832
11419
  errors2.push('mcp.json: "mcpServers" is required and must be an object');
10833
11420
  return;
10834
11421
  }
@@ -10837,7 +11424,7 @@ function validateMcp(root, manifestSchema, errors2) {
10837
11424
  }
10838
11425
  }
10839
11426
  function validateSkills(root, errors2, warnings) {
10840
- const skillsPath = path3.join(root, "skills");
11427
+ const skillsPath = `${root}${path3.sep}skills`;
10841
11428
  try {
10842
11429
  if (!fs.existsSync(skillsPath))
10843
11430
  return;
@@ -10846,29 +11433,41 @@ function validateSkills(root, errors2, warnings) {
10846
11433
  return;
10847
11434
  }
10848
11435
  const entries = fs.readdirSync(skillsPath, { withFileTypes: true });
10849
- const realRoot = fs.realpathSync(root);
11436
+ const realRoot = realpathSync7(root);
10850
11437
  for (const entry of entries) {
10851
11438
  if (!entry.isDirectory() && !entry.isSymbolicLink())
10852
11439
  continue;
10853
11440
  const skillDir = entry.name;
10854
11441
  let realSkillPath;
10855
11442
  try {
10856
- realSkillPath = fs.realpathSync(path3.join(skillsPath, skillDir));
11443
+ realSkillPath = realpathSync7(`${skillsPath}${path3.sep}${skillDir}`);
10857
11444
  } catch (error) {
10858
11445
  warnings.push(`skills: ${skillDir}/ cannot be resolved (${error.message}; skill skipped)`);
10859
11446
  continue;
10860
11447
  }
10861
- const relative5 = path3.relative(realRoot, realSkillPath);
10862
- if (relative5 === ".." || relative5.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative5)) {
11448
+ const insideRoot = realSkillPath === realRoot || realSkillPath.startsWith(realRoot + path3.sep) || realRoot.endsWith(path3.sep) && realSkillPath.startsWith(realRoot);
11449
+ if (!insideRoot) {
10863
11450
  warnings.push(`skills: ${skillDir}/ resolves outside the plugin root (${realSkillPath}; skill skipped)`);
10864
11451
  continue;
10865
11452
  }
10866
- const skillMdPath = path3.join(skillsPath, skillDir, "SKILL.md");
11453
+ const skillMdPath = `${skillsPath}${path3.sep}${skillDir}${path3.sep}SKILL.md`;
10867
11454
  if (!fs.existsSync(skillMdPath) || !fs.statSync(skillMdPath).isFile()) {
10868
11455
  warnings.push(`skills: ${skillDir}/ has no SKILL.md (directory is not a skill; ignored)`);
10869
11456
  continue;
10870
11457
  }
10871
- const frontmatter = parseFrontmatter2(skillMdPath);
11458
+ let realSkillMdPath;
11459
+ try {
11460
+ realSkillMdPath = realpathSync7(skillMdPath);
11461
+ } catch (error) {
11462
+ warnings.push(`skills: ${skillDir}/SKILL.md cannot be resolved (${error.message}; skill skipped)`);
11463
+ continue;
11464
+ }
11465
+ const skillMdInsideRoot = realSkillMdPath.startsWith(realRoot + path3.sep) || realRoot.endsWith(path3.sep) && realSkillMdPath.startsWith(realRoot);
11466
+ if (!skillMdInsideRoot) {
11467
+ warnings.push(`skills: ${skillDir}/SKILL.md resolves outside the plugin root (${realSkillMdPath}; skill skipped)`);
11468
+ continue;
11469
+ }
11470
+ const frontmatter = parseFrontmatter2(realSkillMdPath);
10872
11471
  if (!frontmatter) {
10873
11472
  warnings.push(`skills: ${skillDir}/SKILL.md is missing YAML frontmatter (name and description are required; skill skipped)`);
10874
11473
  continue;
@@ -10900,7 +11499,11 @@ function validateSkills(root, errors2, warnings) {
10900
11499
  function validateAgentPlugin(root) {
10901
11500
  const errors2 = [];
10902
11501
  const warnings = [];
10903
- const manifestPath = path3.join(root, "plugin.json");
11502
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
11503
+ errors2.push(`plugin root: not a directory: ${root}`);
11504
+ return { ok: false, errors: errors2, warnings };
11505
+ }
11506
+ const manifestPath = `${root}${path3.sep}plugin.json`;
10904
11507
  if (!fs.existsSync(manifestPath)) {
10905
11508
  errors2.push(`plugin.json: manifest not found at ${manifestPath} (plugin root must contain plugin.json)`);
10906
11509
  return { ok: false, errors: errors2, warnings };
@@ -10913,7 +11516,7 @@ function validateAgentPlugin(root) {
10913
11516
  return { ok: false, errors: errors2, warnings };
10914
11517
  }
10915
11518
  validateManifest(manifest, errors2, warnings);
10916
- const manifestSchema = isPlainObject8(manifest) ? manifest["$schema"] : undefined;
11519
+ const manifestSchema = isPlainObject9(manifest) ? manifest["$schema"] : undefined;
10917
11520
  validateMcp(root, manifestSchema, errors2);
10918
11521
  validateSkills(root, errors2, warnings);
10919
11522
  return { ok: errors2.length === 0, errors: errors2, warnings };
@@ -11230,13 +11833,28 @@ function configuredMarketplaceNames(dryRun) {
11230
11833
  const list = Array.isArray(parsed.marketplaces) ? parsed.marketplaces : [];
11231
11834
  return list.map((entry) => entry && typeof entry.name === "string" ? entry.name : "").filter((name) => name !== "");
11232
11835
  }
11836
+ function parseCodexInstalledEntries(dump) {
11837
+ const parsed = JSON.parse(dump);
11838
+ const list = Array.isArray(parsed.installed) ? parsed.installed : [];
11839
+ return list.filter((entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry));
11840
+ }
11233
11841
  function installedPluginIds(dryRun) {
11234
11842
  if (dryRun)
11235
11843
  return [];
11236
11844
  const dump = runCodex(["plugin", "list", "--json"], false, CODEX_LOCAL_TIMEOUT_MS);
11237
- const parsed = JSON.parse(dump);
11238
- const list = Array.isArray(parsed.installed) ? parsed.installed : [];
11239
- return list.map((entry) => entry && typeof entry.pluginId === "string" ? entry.pluginId : "").filter((pluginId) => pluginId !== "");
11845
+ return parseCodexInstalledEntries(dump).map((entry) => typeof entry.pluginId === "string" ? entry.pluginId : "").filter((pluginId) => pluginId !== "");
11846
+ }
11847
+ function detectCodexPluginVersion() {
11848
+ let entries;
11849
+ try {
11850
+ entries = parseCodexInstalledEntries(runCodex(["plugin", "list", "--json"], false, CODEX_LOCAL_TIMEOUT_MS));
11851
+ } catch {
11852
+ return null;
11853
+ }
11854
+ const pluginId = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;
11855
+ const entry = entries.find((candidate) => candidate.pluginId === pluginId);
11856
+ const version = typeof entry?.version === "string" ? entry.version : "";
11857
+ return version === "" ? null : version;
11240
11858
  }
11241
11859
  function legacyPersonalMarketplaceNote() {
11242
11860
  const legacyPath = path5.join(os2.homedir(), ".agents", "plugins", "marketplace.json");
@@ -11657,6 +12275,67 @@ var dshAdapter = {
11657
12275
  runInstallDoctor: (scope) => runDoctor2(scope)
11658
12276
  };
11659
12277
 
12278
+ // src/plugin-version-alignment.ts
12279
+ import os5 from "node:os";
12280
+ import path9 from "node:path";
12281
+
12282
+ // src/version-compare.ts
12283
+ function splitVersion(v) {
12284
+ const dash = v.indexOf("-");
12285
+ if (dash === -1)
12286
+ return [v, undefined];
12287
+ return [v.slice(0, dash), v.slice(dash + 1)];
12288
+ }
12289
+ function compareCore(a, b) {
12290
+ const pa = a.split(".").map((n) => parseInt(n, 10) || 0);
12291
+ const pb = b.split(".").map((n) => parseInt(n, 10) || 0);
12292
+ for (let i = 0;i < 3; i++) {
12293
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
12294
+ if (d !== 0)
12295
+ return d;
12296
+ }
12297
+ return 0;
12298
+ }
12299
+ function comparePrerelease(a, b) {
12300
+ if (a === undefined && b === undefined)
12301
+ return 0;
12302
+ if (a === undefined)
12303
+ return 1;
12304
+ if (b === undefined)
12305
+ return -1;
12306
+ const ia = a.split(".");
12307
+ const ib = b.split(".");
12308
+ const n = Math.min(ia.length, ib.length);
12309
+ for (let i = 0;i < n; i++) {
12310
+ const d = compareIdentifier(ia[i], ib[i]);
12311
+ if (d !== 0)
12312
+ return d;
12313
+ }
12314
+ return ia.length - ib.length;
12315
+ }
12316
+ function compareIdentifier(a, b) {
12317
+ const aNum = /^\d+$/.test(a);
12318
+ const bNum = /^\d+$/.test(b);
12319
+ if (aNum && bNum) {
12320
+ const na = BigInt(a);
12321
+ const nb = BigInt(b);
12322
+ return na < nb ? -1 : na > nb ? 1 : 0;
12323
+ }
12324
+ if (aNum)
12325
+ return -1;
12326
+ if (bNum)
12327
+ return 1;
12328
+ return a < b ? -1 : a > b ? 1 : 0;
12329
+ }
12330
+ function compareSemver(a, b) {
12331
+ const [coreA, preA] = splitVersion(a);
12332
+ const [coreB, preB] = splitVersion(b);
12333
+ const coreDiff = compareCore(coreA, coreB);
12334
+ if (coreDiff !== 0)
12335
+ return coreDiff;
12336
+ return comparePrerelease(preA, preB);
12337
+ }
12338
+
11660
12339
  // src/adapters/omp.ts
11661
12340
  import fs5 from "node:fs";
11662
12341
  import path8 from "node:path";
@@ -11676,34 +12355,39 @@ function ompAvailable() {
11676
12355
  function runOmp(args, dryRun) {
11677
12356
  runCliCommand(["omp", ...args], { dryRun });
11678
12357
  }
11679
- function listInstalledPlugins() {
12358
+ var OMP_LIST_TIMEOUT_MS = 1e4;
12359
+ function parseOmpPluginList(raw) {
12360
+ const parsed = JSON.parse(raw);
12361
+ if (Array.isArray(parsed))
12362
+ return parsed;
12363
+ if (parsed && typeof parsed === "object") {
12364
+ const record = parsed;
12365
+ if (Array.isArray(record.plugins)) {
12366
+ return record.plugins;
12367
+ }
12368
+ const entries = [];
12369
+ for (const key of ["npm", "marketplace"]) {
12370
+ const group = record[key];
12371
+ if (Array.isArray(group)) {
12372
+ for (const item of group) {
12373
+ if (item && typeof item === "object")
12374
+ entries.push(item);
12375
+ }
12376
+ }
12377
+ }
12378
+ if (entries.length > 0)
12379
+ return entries;
12380
+ }
12381
+ return [];
12382
+ }
12383
+ function listInstalledPlugins(timeoutMs = OMP_LIST_TIMEOUT_MS) {
11680
12384
  try {
11681
12385
  const raw = execFileSync8("omp", ["plugin", "list", "--json"], {
11682
12386
  stdio: "pipe",
11683
- encoding: "utf8"
12387
+ encoding: "utf8",
12388
+ timeout: timeoutMs
11684
12389
  });
11685
- const parsed = JSON.parse(raw);
11686
- if (Array.isArray(parsed))
11687
- return parsed;
11688
- if (parsed && typeof parsed === "object") {
11689
- const record = parsed;
11690
- if (Array.isArray(record.plugins)) {
11691
- return record.plugins;
11692
- }
11693
- const entries = [];
11694
- for (const key of ["npm", "marketplace"]) {
11695
- const group = record[key];
11696
- if (Array.isArray(group)) {
11697
- for (const item of group) {
11698
- if (item && typeof item === "object")
11699
- entries.push(item);
11700
- }
11701
- }
11702
- }
11703
- if (entries.length > 0)
11704
- return entries;
11705
- }
11706
- return [];
12390
+ return parseOmpPluginList(raw);
11707
12391
  } catch {
11708
12392
  return [];
11709
12393
  }
@@ -11872,9 +12556,43 @@ var ompAdapter = {
11872
12556
  runInstallDoctor: (scope) => runDoctor3(scope)
11873
12557
  };
11874
12558
 
12559
+ // src/plugin-version-alignment.ts
12560
+ var ZCODE_PLUGINS_CACHE_ROOT = path9.join(os5.homedir(), ".zcode", "cli", "plugins", "cache");
12561
+ var KIMI_CODE_HOME_ENV = "KIMI_CODE_HOME";
12562
+ var KIMI_PLUGINS_DIR = "plugins";
12563
+ var KIMI_MANAGED_DIR = "managed";
12564
+ function defaultKimiCodeHome() {
12565
+ return process.env[KIMI_CODE_HOME_ENV] ?? path9.join(os5.homedir(), ".kimi-code");
12566
+ }
12567
+ function kimiManagedRoot(kimiCodeHome = defaultKimiCodeHome()) {
12568
+ return path9.join(kimiCodeHome, KIMI_PLUGINS_DIR, KIMI_MANAGED_DIR);
12569
+ }
12570
+
12571
+ // src/adapters/kimi.ts
12572
+ var KIMI_INSTALL_HINT = "Install via Kimi TUI: /plugins install";
12573
+ function runInit4(_scope, _dryRun) {
12574
+ return {
12575
+ location: kimiManagedRoot(),
12576
+ notes: [KIMI_INSTALL_HINT]
12577
+ };
12578
+ }
12579
+ function runDoctor4(_scope) {
12580
+ return {
12581
+ location: kimiManagedRoot(),
12582
+ errors: [],
12583
+ notes: []
12584
+ };
12585
+ }
12586
+ var kimiAdapter = {
12587
+ target: "kimi",
12588
+ mode: "install",
12589
+ runInstallInit: (scope, dryRun) => runInit4(scope, dryRun),
12590
+ runInstallDoctor: (scope) => runDoctor4(scope)
12591
+ };
12592
+
11875
12593
  // src/adapters/opencode.ts
11876
- import os5 from "node:os";
11877
- import path9 from "node:path";
12594
+ import os6 from "node:os";
12595
+ import path10 from "node:path";
11878
12596
  var OPENCODE_CONFIG_SCHEMA = "https://opencode.ai/config.json";
11879
12597
  var MSTAR_OPENCODE_PLUGIN = "@mstar-harness/opencode@latest";
11880
12598
  function isLegacyMorningStarGitPlugin(plugin) {
@@ -11895,11 +12613,20 @@ function isAnyMstarHarnessOpencodeSlot(plugin) {
11895
12613
  function resolveOpencodeConfigPath(scope, outputPath) {
11896
12614
  if (outputPath && outputPath.trim()) {
11897
12615
  const raw = outputPath.trim();
11898
- return path9.isAbsolute(raw) ? raw : path9.join(resolveProjectRoot2(), raw);
12616
+ if (path10.isAbsolute(raw))
12617
+ return raw;
12618
+ if (raw.split(/[\\/]/).includes("..")) {
12619
+ throw new Error(`--output must not contain ".." segments: ${raw}`);
12620
+ }
12621
+ const root2 = resolveProjectRoot2();
12622
+ return root2.endsWith(path10.sep) ? root2 + raw : root2 + path10.sep + raw;
12623
+ }
12624
+ if (scope === "global") {
12625
+ const home = os6.homedir();
12626
+ return `${home}${path10.sep}.config${path10.sep}opencode${path10.sep}opencode.json`;
11899
12627
  }
11900
- if (scope === "global")
11901
- return path9.join(os5.homedir(), ".config", "opencode", "opencode.json");
11902
- return path9.join(resolveProjectRoot2(), "opencode.json");
12628
+ const root = resolveProjectRoot2();
12629
+ return root.endsWith(path10.sep) ? `${root}opencode.json` : `${root}${path10.sep}opencode.json`;
11903
12630
  }
11904
12631
  function ensureConfigSchema(config) {
11905
12632
  const next = ensureObject(config);
@@ -11993,22 +12720,24 @@ var opencodeAdapter = {
11993
12720
 
11994
12721
  // src/adapters/zcode.ts
11995
12722
  import fs6 from "node:fs";
11996
- import os6 from "node:os";
11997
- import path10 from "node:path";
12723
+ import os7 from "node:os";
12724
+ import path11 from "node:path";
11998
12725
  var MARKETPLACE_ID = "mstar-local";
11999
12726
  var MARKETPLACE_NAME2 = "mstar-local";
12000
12727
  var MARKETPLACE_DESCRIPTION = "Morning Star harness marketplace (GitHub source).";
12001
12728
  var PLUGIN_DESCRIPTION = "Multi-agent code harness framework with unified skills for OpenCode, Cursor, Codex, Kimi Code, and ZCode.";
12002
12729
  var PLUGIN_CATEGORY = "Productivity";
12730
+ var PLUGIN_DISPLAY_NAME = "Morning Star Harness";
12731
+ var PLUGIN_ICON_URL = "https://raw.githubusercontent.com/btspoony/mstar-harness/main/assets/icon.png";
12003
12732
  var GITHUB_REPO = "btspoony/mstar-harness";
12004
12733
  var GITHUB_REF = "main";
12005
12734
  var ZCODE_PLUGIN_MARKER = ".zcode-plugin/plugin.json";
12006
12735
  var ZCODE_PLUGIN_CHECKOUT_PROJECT = ".zcode/plugin-checkout";
12007
12736
  var ZCODE_AGENT_SMOKE_NAMES = ["fullstack-dev", "qc-specialist"];
12008
- var ZCODE_PLUGINS_ROOT = path10.join(os6.homedir(), ".zcode", "cli", "plugins");
12009
- var KNOWN_MARKETPLACES_PATH = path10.join(ZCODE_PLUGINS_ROOT, "known_marketplaces.json");
12010
- var MARKETPLACE_DIR = path10.join(ZCODE_PLUGINS_ROOT, "marketplaces", MARKETPLACE_ID);
12011
- var MARKETPLACE_JSON_PATH = path10.join(MARKETPLACE_DIR, "marketplace.json");
12737
+ var ZCODE_PLUGINS_ROOT = path11.join(os7.homedir(), ".zcode", "cli", "plugins");
12738
+ var KNOWN_MARKETPLACES_PATH = path11.join(ZCODE_PLUGINS_ROOT, "known_marketplaces.json");
12739
+ var MARKETPLACE_DIR = path11.join(ZCODE_PLUGINS_ROOT, "marketplaces", MARKETPLACE_ID);
12740
+ var MARKETPLACE_JSON_PATH = path11.join(MARKETPLACE_DIR, "marketplace.json");
12012
12741
  var GITHUB_SOURCE = { source: "github", repo: GITHUB_REPO, ref: GITHUB_REF };
12013
12742
  function nowIso() {
12014
12743
  return new Date().toISOString();
@@ -12016,7 +12745,10 @@ function nowIso() {
12016
12745
  function marketplacePluginEntry() {
12017
12746
  return {
12018
12747
  name: PLUGIN_NAME,
12748
+ version: readHarnessVersion(),
12019
12749
  source: { ...GITHUB_SOURCE },
12750
+ displayName: PLUGIN_DISPLAY_NAME,
12751
+ icon: PLUGIN_ICON_URL,
12020
12752
  description: PLUGIN_DESCRIPTION,
12021
12753
  category: PLUGIN_CATEGORY
12022
12754
  };
@@ -12084,10 +12816,6 @@ function validateMarketplaceJson() {
12084
12816
  if (source.repo !== expected.source.repo) {
12085
12817
  errors2.push(`ZCode marketplace plugin source.repo must be ${expected.source.repo}.`);
12086
12818
  }
12087
- const expectedVersion = readHarnessVersion();
12088
- if (entry.version !== undefined && entry.version !== expectedVersion) {
12089
- errors2.push(`ZCode marketplace plugin version must be ${expectedVersion}.`);
12090
- }
12091
12819
  return errors2;
12092
12820
  }
12093
12821
  function validateKnownMarketplaces() {
@@ -12115,13 +12843,13 @@ function validateKnownMarketplaces() {
12115
12843
  }
12116
12844
  function validatePluginAgents2(pluginRoot) {
12117
12845
  const errors2 = [];
12118
- const agentsDir = path10.join(pluginRoot, "agents");
12846
+ const agentsDir = path11.join(pluginRoot, "agents");
12119
12847
  if (!fs6.existsSync(agentsDir)) {
12120
12848
  errors2.push(`Missing plugin agents directory: ${agentsDir}`);
12121
12849
  return errors2;
12122
12850
  }
12123
12851
  for (const agentName of ZCODE_AGENT_SMOKE_NAMES) {
12124
- const agentPath = path10.join(agentsDir, `${agentName}.md`);
12852
+ const agentPath = path11.join(agentsDir, `${agentName}.md`);
12125
12853
  if (!fs6.existsSync(agentPath)) {
12126
12854
  errors2.push(`Missing plugin agent file: ${agentPath}`);
12127
12855
  }
@@ -12135,11 +12863,11 @@ function buildMarketplaceJson() {
12135
12863
  plugins: [marketplacePluginEntry()]
12136
12864
  };
12137
12865
  }
12138
- function runInit4(scope, dryRun) {
12866
+ function runInit5(scope, dryRun) {
12139
12867
  const notes = ensureLocalHarnessRepo(dryRun);
12140
12868
  const projectRoot = resolveProjectRoot2();
12141
12869
  if (scope === "project") {
12142
- const checkoutPath = path10.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT);
12870
+ const checkoutPath = path11.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT);
12143
12871
  notes.push(...ensureGitCheckout(REPO_URL, checkoutPath, dryRun));
12144
12872
  notes.push(...appendGitignore(projectRoot, [ZCODE_PLUGIN_CHECKOUT_PROJECT], dryRun));
12145
12873
  notes.push(...appendHarnessProjectGitignore(projectRoot, dryRun));
@@ -12162,14 +12890,14 @@ function runInit4(scope, dryRun) {
12162
12890
  notes
12163
12891
  };
12164
12892
  }
12165
- function runDoctor4(scope) {
12893
+ function runDoctor5(scope) {
12166
12894
  const errors2 = [];
12167
12895
  errors2.push(...validateLocalHarnessRepo());
12168
12896
  if (scope === "project") {
12169
12897
  const projectRoot = resolveProjectRoot2();
12170
- const checkoutPath = path10.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT);
12898
+ const checkoutPath = path11.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT);
12171
12899
  errors2.push(...validateGitCheckout(checkoutPath, ZCODE_PLUGIN_MARKER));
12172
- const gitignorePath = path10.join(projectRoot, ".gitignore");
12900
+ const gitignorePath = path11.join(projectRoot, ".gitignore");
12173
12901
  const gitignore = fs6.existsSync(gitignorePath) ? fs6.readFileSync(gitignorePath, "utf8") : "";
12174
12902
  if (!gitignore.split(/\r?\n/).includes(ZCODE_PLUGIN_CHECKOUT_PROJECT)) {
12175
12903
  errors2.push(`Missing .gitignore entry: ${ZCODE_PLUGIN_CHECKOUT_PROJECT}`);
@@ -12188,8 +12916,8 @@ function runDoctor4(scope) {
12188
12916
  var zcodeAdapter = {
12189
12917
  target: "zcode",
12190
12918
  mode: "install",
12191
- runInstallInit: (scope, dryRun) => runInit4(scope, dryRun),
12192
- runInstallDoctor: (scope) => runDoctor4(scope)
12919
+ runInstallInit: (scope, dryRun) => runInit5(scope, dryRun),
12920
+ runInstallDoctor: (scope) => runDoctor5(scope)
12193
12921
  };
12194
12922
 
12195
12923
  // src/adapters/index.ts
@@ -12199,7 +12927,8 @@ var adapters = {
12199
12927
  codex: codexAdapter,
12200
12928
  zcode: zcodeAdapter,
12201
12929
  omp: ompAdapter,
12202
- dsh: dshAdapter
12930
+ dsh: dshAdapter,
12931
+ kimi: kimiAdapter
12203
12932
  };
12204
12933
  function getAdapter(target) {
12205
12934
  const adapter = adapters[target];
@@ -12270,12 +12999,241 @@ function formatCliDoctorNote(detected, expected) {
12270
12999
  return `CLI on PATH: ${CLI_NAME} ${detected} (matching)`;
12271
13000
  }
12272
13001
 
13002
+ // src/plugin-version-alignment.ts
13003
+ import fs7 from "node:fs";
13004
+ import os8 from "node:os";
13005
+ import path12 from "node:path";
13006
+ var PLUGIN_VERSION_SHAPE_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
13007
+ function highestVersion(current, candidate) {
13008
+ if (candidate === null)
13009
+ return current;
13010
+ if (current === null || compareSemver(candidate, current) > 0)
13011
+ return candidate;
13012
+ return current;
13013
+ }
13014
+ function versionFromJsonFile(filePath) {
13015
+ let raw;
13016
+ try {
13017
+ raw = fs7.readFileSync(filePath, "utf8");
13018
+ } catch {
13019
+ return null;
13020
+ }
13021
+ try {
13022
+ const version = JSON.parse(raw).version;
13023
+ if (typeof version === "string" && PLUGIN_VERSION_SHAPE_RE.test(version.trim()))
13024
+ return version.trim();
13025
+ } catch {}
13026
+ return null;
13027
+ }
13028
+ function readTolerantVersion(dir, manifestRelPaths) {
13029
+ for (const rel of manifestRelPaths) {
13030
+ const version = versionFromJsonFile(path12.join(dir, rel));
13031
+ if (version !== null)
13032
+ return version;
13033
+ }
13034
+ return null;
13035
+ }
13036
+ function defaultOpencodePackagesRoot() {
13037
+ return path12.join(os8.homedir(), ".cache", "opencode", "packages");
13038
+ }
13039
+ function detectOpencodePluginVersion(packagesRoot = defaultOpencodePackagesRoot()) {
13040
+ let specs;
13041
+ try {
13042
+ specs = fs7.readdirSync(path12.join(packagesRoot, "@mstar-harness"), { withFileTypes: true });
13043
+ } catch {
13044
+ return null;
13045
+ }
13046
+ let highest = null;
13047
+ for (const spec of specs) {
13048
+ if (!spec.isDirectory())
13049
+ continue;
13050
+ const pkgJson = path12.join(packagesRoot, "@mstar-harness", spec.name, "node_modules", "@mstar-harness", "opencode", "package.json");
13051
+ highest = highestVersion(highest, versionFromJsonFile(pkgJson));
13052
+ }
13053
+ return highest;
13054
+ }
13055
+ var CURSOR_MANIFEST_PATHS = [".cursor-plugin/plugin.json", "package.json"];
13056
+ function detectCursorPluginVersion(pluginRoot) {
13057
+ return readTolerantVersion(pluginRoot, CURSOR_MANIFEST_PATHS);
13058
+ }
13059
+ function detectCursorPluginVersionForScope(scope, paths) {
13060
+ if (scope !== "global") {
13061
+ const projectVersion = detectCursorPluginVersion(paths?.project ?? projectInstallPath());
13062
+ if (projectVersion !== null)
13063
+ return projectVersion;
13064
+ }
13065
+ return detectCursorPluginVersion(paths?.global ?? globalInstallPath());
13066
+ }
13067
+ var ZCODE_PLUGINS_CACHE_ROOT2 = path12.join(os8.homedir(), ".zcode", "cli", "plugins", "cache");
13068
+ var ZCODE_MANIFEST_PATHS = [".zcode-plugin/plugin.json", "plugin.json"];
13069
+ function readZcodeManifestVersion(versionDir) {
13070
+ return readTolerantVersion(versionDir, ZCODE_MANIFEST_PATHS);
13071
+ }
13072
+ function detectZcodePluginVersion(cacheRoot = ZCODE_PLUGINS_CACHE_ROOT2) {
13073
+ let marketplaceEntries;
13074
+ try {
13075
+ marketplaceEntries = fs7.readdirSync(cacheRoot, { withFileTypes: true });
13076
+ } catch {
13077
+ return null;
13078
+ }
13079
+ let highest = null;
13080
+ for (const marketplace of marketplaceEntries) {
13081
+ if (!marketplace.isDirectory())
13082
+ continue;
13083
+ const pluginRoot = path12.join(cacheRoot, marketplace.name, PLUGIN_NAME);
13084
+ let versionEntries;
13085
+ try {
13086
+ versionEntries = fs7.readdirSync(pluginRoot, { withFileTypes: true });
13087
+ } catch {
13088
+ continue;
13089
+ }
13090
+ for (const versionEntry of versionEntries) {
13091
+ if (!versionEntry.isDirectory())
13092
+ continue;
13093
+ const manifest = readZcodeManifestVersion(path12.join(pluginRoot, versionEntry.name));
13094
+ const candidate = manifest ?? (PLUGIN_VERSION_SHAPE_RE.test(versionEntry.name) ? versionEntry.name : null);
13095
+ highest = highestVersion(highest, candidate);
13096
+ }
13097
+ }
13098
+ return highest;
13099
+ }
13100
+ function defaultDshHome() {
13101
+ return process.env[DSH_HOME_ENV] ?? path12.join(os8.homedir(), DSH_HOME_SUBDIR);
13102
+ }
13103
+ function detectDshPluginVersion(dshHome = defaultDshHome()) {
13104
+ return versionFromJsonFile(path12.join(dshHome, DSH_PROFILES_DIR, DSH_PROFILE, "node_modules", "@mstar-harness", "dsh", "package.json"));
13105
+ }
13106
+ var KIMI_CODE_HOME_ENV2 = "KIMI_CODE_HOME";
13107
+ var KIMI_PLUGINS_DIR2 = "plugins";
13108
+ var KIMI_MANAGED_DIR2 = "managed";
13109
+ var KIMI_SCAN_DEPTH = 3;
13110
+ var KIMI_MANIFEST_PATHS = [".kimi-plugin/plugin.json", "plugin.json", "package.json"];
13111
+ function defaultKimiCodeHome2() {
13112
+ return process.env[KIMI_CODE_HOME_ENV2] ?? path12.join(os8.homedir(), ".kimi-code");
13113
+ }
13114
+ function kimiManagedRoot2(kimiCodeHome = defaultKimiCodeHome2()) {
13115
+ return path12.join(kimiCodeHome, KIMI_PLUGINS_DIR2, KIMI_MANAGED_DIR2);
13116
+ }
13117
+ function listDirsToDepth(root, maxDepth) {
13118
+ const out = [];
13119
+ const visit = (dir, depth) => {
13120
+ let entries;
13121
+ try {
13122
+ entries = fs7.readdirSync(dir, { withFileTypes: true });
13123
+ } catch {
13124
+ return;
13125
+ }
13126
+ for (const entry of entries) {
13127
+ if (!entry.isDirectory())
13128
+ continue;
13129
+ const child = path12.join(dir, entry.name);
13130
+ out.push(child);
13131
+ if (depth + 1 < maxDepth)
13132
+ visit(child, depth + 1);
13133
+ }
13134
+ };
13135
+ visit(root, 0);
13136
+ return out;
13137
+ }
13138
+ function detectKimiPluginVersion(kimiCodeHome = defaultKimiCodeHome2()) {
13139
+ const managedRoot = kimiManagedRoot2(kimiCodeHome);
13140
+ let highest = null;
13141
+ for (const dir of listDirsToDepth(managedRoot, KIMI_SCAN_DEPTH)) {
13142
+ if (path12.basename(dir) !== PLUGIN_NAME)
13143
+ continue;
13144
+ highest = highestVersion(highest, readTolerantVersion(dir, KIMI_MANIFEST_PATHS));
13145
+ }
13146
+ return highest;
13147
+ }
13148
+ function ompEntryVersion(entry) {
13149
+ const direct = typeof entry.version === "string" ? entry.version.trim() : "";
13150
+ if (PLUGIN_VERSION_SHAPE_RE.test(direct))
13151
+ return direct;
13152
+ const manifest = entry.manifest && typeof entry.manifest === "object" ? entry.manifest : null;
13153
+ const manifestVersion = typeof manifest?.version === "string" ? manifest.version.trim() : "";
13154
+ if (PLUGIN_VERSION_SHAPE_RE.test(manifestVersion))
13155
+ return manifestVersion;
13156
+ const entryPath = typeof entry.path === "string" ? entry.path : "";
13157
+ if (entryPath === "")
13158
+ return null;
13159
+ return versionFromJsonFile(path12.join(entryPath, "package.json"));
13160
+ }
13161
+ function detectOmpPluginVersion() {
13162
+ const entry = findInstalledPlugin(listInstalledPlugins());
13163
+ if (!entry)
13164
+ return null;
13165
+ return ompEntryVersion(entry);
13166
+ }
13167
+ function detectInstalledPluginVersion(target, scope = "project") {
13168
+ let discovered;
13169
+ switch (target) {
13170
+ case "opencode":
13171
+ discovered = detectOpencodePluginVersion();
13172
+ break;
13173
+ case "cursor":
13174
+ discovered = detectCursorPluginVersionForScope(scope);
13175
+ break;
13176
+ case "codex":
13177
+ discovered = detectCodexPluginVersion();
13178
+ break;
13179
+ case "zcode":
13180
+ discovered = detectZcodePluginVersion();
13181
+ break;
13182
+ case "omp":
13183
+ discovered = detectOmpPluginVersion();
13184
+ break;
13185
+ case "dsh":
13186
+ discovered = detectDshPluginVersion();
13187
+ break;
13188
+ case "kimi":
13189
+ discovered = detectKimiPluginVersion();
13190
+ break;
13191
+ default:
13192
+ discovered = null;
13193
+ break;
13194
+ }
13195
+ if (discovered === null)
13196
+ return null;
13197
+ const version = discovered.trim();
13198
+ return PLUGIN_VERSION_SHAPE_RE.test(version) ? version : null;
13199
+ }
13200
+ var PLUGIN_UPDATE_HINTS = {
13201
+ opencode: "update the Morning Star plugin (@mstar-harness/opencode) and restart OpenCode.",
13202
+ cursor: "update the Morning Star plugin checkout (git pull, or re-run mstar-harness init --target cursor).",
13203
+ codex: "update the Morning Star plugin: codex plugin marketplace upgrade, then codex plugin add morning-star-harness@mstar-repo.",
13204
+ zcode: "update the Morning Star plugin in ZCode (Settings \u2192 Plugin Management \u2192 update from the mstar-local marketplace).",
13205
+ omp: "update the Morning Star plugin: omp plugin install @mstar-harness/omp.",
13206
+ dsh: "update the Morning Star plugin: re-run mstar-harness init --target dsh (re-adds @mstar-harness/dsh in the web profile).",
13207
+ kimi: "update the Morning Star plugin via the Kimi TUI: /plugins install."
13208
+ };
13209
+ var NOT_INSTALLED_NOTES = {
13210
+ opencode: "No installed Morning Star plugin found under ~/.cache/opencode/packages/ (run mstar-harness init --target opencode to add @mstar-harness/opencode).",
13211
+ cursor: "No installed Morning Star plugin found under ~/.cursor/plugins/ (run mstar-harness init --target cursor).",
13212
+ codex: "No installed Morning Star plugin found in `codex plugin list` (install: codex plugin add morning-star-harness@mstar-repo).",
13213
+ zcode: "No installed Morning Star plugin found under ~/.zcode/cli/plugins/cache/ (install from the mstar-local marketplace).",
13214
+ omp: "No installed Morning Star plugin found in `omp plugin list` (install: omp plugin install @mstar-harness/omp).",
13215
+ dsh: "No installed Morning Star plugin found under ~/.dsh/profiles/ (run mstar-harness init --target dsh to add @mstar-harness/dsh).",
13216
+ kimi: "No installed Morning Star plugin found under $KIMI_CODE_HOME/plugins/managed (install via the Kimi TUI: /plugins install)."
13217
+ };
13218
+ function formatPluginVersionDoctorNote(target, cliVersion, installed) {
13219
+ if (installed === null) {
13220
+ return NOT_INSTALLED_NOTES[target];
13221
+ }
13222
+ const diff = compareSemver(cliVersion, installed);
13223
+ if (diff === 0)
13224
+ return `Plugin/CLI versions aligned (${installed}).`;
13225
+ if (diff > 0) {
13226
+ return `CLI ${cliVersion} is newer than installed plugin ${installed} \u2014 ${PLUGIN_UPDATE_HINTS[target]}`;
13227
+ }
13228
+ return `Installed plugin ${installed} is newer than CLI ${cliVersion} \u2014 update the global CLI: npm i -g @mstar-harness/cli@latest (or @${installed}).`;
13229
+ }
13230
+
12273
13231
  // src/types.ts
12274
- var SUPPORTED_TARGETS = ["opencode", "cursor", "codex", "zcode", "omp", "dsh"];
13232
+ var SUPPORTED_TARGETS = ["opencode", "cursor", "codex", "zcode", "omp", "dsh", "kimi"];
12275
13233
 
12276
13234
  // src/utils.ts
12277
- import fs7 from "node:fs";
12278
- import path11 from "node:path";
13235
+ import fs8 from "node:fs";
13236
+ import path13 from "node:path";
12279
13237
  function parseCsv(raw) {
12280
13238
  if (!raw)
12281
13239
  return;
@@ -12284,18 +13242,27 @@ function parseCsv(raw) {
12284
13242
  function resolveProjectRoot3() {
12285
13243
  const candidate = process.env.MSTAR_CLI_PROJECT_ROOT || process.env.INIT_CWD || process.env.PWD;
12286
13244
  if (candidate && candidate.trim())
12287
- return path11.resolve(candidate);
13245
+ return path13.resolve(candidate);
12288
13246
  return resolveProjectRoot();
12289
13247
  }
13248
+ function joinWithinRoot(root, ...segments) {
13249
+ const base = path13.resolve(root);
13250
+ const resolved = path13.resolve(base, ...segments);
13251
+ const withinRoot = resolved === base || resolved.startsWith(base + path13.sep) || base.endsWith(path13.sep) && resolved.startsWith(base);
13252
+ if (!withinRoot) {
13253
+ throw new Error(`path escapes ${base}: ${segments.join(path13.sep)}`);
13254
+ }
13255
+ return resolved;
13256
+ }
12290
13257
  function findUpPackageRoot(startDir, predicate) {
12291
- let dir = path11.resolve(startDir);
13258
+ let dir = path13.resolve(startDir);
12292
13259
  for (;; ) {
12293
13260
  try {
12294
- const manifest = JSON.parse(fs7.readFileSync(path11.join(dir, "package.json"), "utf8"));
13261
+ const manifest = JSON.parse(fs8.readFileSync(joinWithinRoot(dir, "package.json"), "utf8"));
12295
13262
  if (predicate(manifest))
12296
13263
  return dir;
12297
13264
  } catch {}
12298
- const parent = path11.dirname(dir);
13265
+ const parent = path13.dirname(dir);
12299
13266
  if (parent === dir)
12300
13267
  return null;
12301
13268
  dir = parent;
@@ -12307,7 +13274,7 @@ function declaresWorkspaces(manifest) {
12307
13274
  function resolveCliProjectRoot() {
12308
13275
  const override = process.env.MSTAR_CLI_PROJECT_ROOT;
12309
13276
  if (override && override.trim())
12310
- return path11.resolve(override);
13277
+ return path13.resolve(override);
12311
13278
  const monorepoRoot = findUpPackageRoot(process.cwd(), declaresWorkspaces);
12312
13279
  if (monorepoRoot)
12313
13280
  return monorepoRoot;
@@ -12317,9 +13284,10 @@ function resolveCliProjectRoot() {
12317
13284
  return process.cwd();
12318
13285
  }
12319
13286
  function resolveCliPath(userPath) {
12320
- if (path11.isAbsolute(userPath))
13287
+ if (path13.isAbsolute(userPath))
12321
13288
  return userPath;
12322
- return path11.resolve(resolveCliProjectRoot(), userPath);
13289
+ const root = resolveCliProjectRoot();
13290
+ return root.endsWith(path13.sep) ? root + userPath : root + path13.sep + userPath;
12323
13291
  }
12324
13292
 
12325
13293
  // src/index.ts
@@ -12356,7 +13324,7 @@ function resolveExplicitModelAssignments(options) {
12356
13324
  others: allow("other-models", parseCsv(options.otherModels), 3, true)
12357
13325
  });
12358
13326
  }
12359
- async function runInit5(options) {
13327
+ async function runInit6(options) {
12360
13328
  const target = options.target || (options.yes ? "opencode" : await pickTargetInteractive());
12361
13329
  const scope = options.scope || "project";
12362
13330
  const adapter = getAdapter(target);
@@ -12421,12 +13389,13 @@ async function runInit5(options) {
12421
13389
  }
12422
13390
  ensureGlobalCli({ version: packageVersion, dryRun: !!options.dryRun, noGlobalCli: !!options.noGlobalCli });
12423
13391
  }
12424
- function runDoctor5(options) {
13392
+ function runDoctor6(options) {
12425
13393
  const target = options.target || "opencode";
12426
13394
  const adapter = getAdapter(target);
12427
13395
  const scope = options.scope || "project";
12428
13396
  console.log(`Target: ${target}`);
12429
13397
  console.log(formatCliDoctorNote(defaultDetectVersion(), packageVersion));
13398
+ console.log(formatPluginVersionDoctorNote(target, packageVersion, detectInstalledPluginVersion(target, scope)));
12430
13399
  if (adapter.mode === "install") {
12431
13400
  const result = adapter.runInstallDoctor?.(scope);
12432
13401
  if (!result) {
@@ -12470,10 +13439,10 @@ function runDoctor5(options) {
12470
13439
  }
12471
13440
  function resolvePluginRoot(options) {
12472
13441
  if (options.root)
12473
- return path12.resolve(options.root);
13442
+ return path14.resolve(options.root);
12474
13443
  let candidate = resolveProjectRoot3();
12475
- while (!fs8.existsSync(path12.join(candidate, "plugin.json"))) {
12476
- const parent = path12.dirname(candidate);
13444
+ while (!fs9.existsSync(path14.join(candidate, "plugin.json"))) {
13445
+ const parent = path14.dirname(candidate);
12477
13446
  if (parent === candidate)
12478
13447
  break;
12479
13448
  candidate = parent;
@@ -12524,24 +13493,25 @@ function gitWorkspaceRoot(startDir) {
12524
13493
  let boundary = startDir;
12525
13494
  for (const segment of cdup.split(/[\\/]/)) {
12526
13495
  if (segment && segment !== ".")
12527
- boundary = path12.dirname(boundary);
13496
+ boundary = path14.dirname(boundary);
12528
13497
  }
12529
- return path12.resolve(boundary);
13498
+ return boundary;
12530
13499
  } catch {}
12531
13500
  return startDir;
12532
13501
  }
12533
13502
  function runScaffold(pathArg) {
12534
- const root = pathArg ? path12.resolve(pathArg) : process.cwd();
13503
+ const root = pathArg ? path14.resolve(pathArg) : process.cwd();
12535
13504
  const harnessDir = scaffoldHarness(root);
12536
13505
  const projectDir = resolveProjectDir(root, { harnessDir });
12537
13506
  const created = [];
12538
13507
  const skipped = [];
12539
13508
  const workspaceRoot = gitWorkspaceRoot(root);
12540
13509
  const harnessKind = detectHarnessKind(harnessDir);
12541
- if (harnessKind === "mstar" && path12.resolve(harnessDir) === path12.join(workspaceRoot, ".mstar")) {
12542
- const gitignorePath = path12.join(workspaceRoot, ".gitignore");
13510
+ const mstarDirAtWorkspaceRoot = workspaceRoot.endsWith(path14.sep) ? `${workspaceRoot}.mstar` : `${workspaceRoot}${path14.sep}.mstar`;
13511
+ if (harnessKind === "mstar" && path14.resolve(harnessDir) === mstarDirAtWorkspaceRoot) {
13512
+ const gitignorePath = workspaceRoot.endsWith(path14.sep) ? `${workspaceRoot}.gitignore` : `${workspaceRoot}${path14.sep}.gitignore`;
12543
13513
  const snippet = emitGitignoreSnippet("mstar");
12544
- const current = fs8.existsSync(gitignorePath) ? fs8.readFileSync(gitignorePath, "utf8") : "";
13514
+ const current = fs9.existsSync(gitignorePath) ? fs9.readFileSync(gitignorePath, "utf8") : "";
12545
13515
  const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));
12546
13516
  const snippetLines = snippet.split(`
12547
13517
  `).map((line) => line.trim());
@@ -12563,18 +13533,18 @@ function runScaffold(pathArg) {
12563
13533
  `) ? "" : `
12564
13534
  `}.mstarc
12565
13535
  `;
12566
- fs8.writeFileSync(gitignorePath, next, "utf8");
13536
+ fs9.writeFileSync(gitignorePath, next, "utf8");
12567
13537
  } else {
12568
13538
  const prefix = current && !current.endsWith(`
12569
13539
  `) ? `
12570
13540
  ` : "";
12571
- fs8.appendFileSync(gitignorePath, `${prefix}${[...missingComments, ...missing].join(`
13541
+ fs9.appendFileSync(gitignorePath, `${prefix}${[...missingComments, ...missing].join(`
12572
13542
  `)}
12573
13543
  `, "utf8");
12574
13544
  }
12575
13545
  created.push(".gitignore (canonical harness snippet)");
12576
13546
  }
12577
- const finalLines = fs8.readFileSync(gitignorePath, "utf8").split(/\r?\n/);
13547
+ const finalLines = fs9.readFileSync(gitignorePath, "utf8").split(/\r?\n/);
12578
13548
  const broadIndexes = finalLines.map((line, index) => line.trim() === ".mstar/**" ? index : -1).filter((index) => index !== -1);
12579
13549
  const canonicalNegationIndexes = finalLines.map((line, index) => CANONICAL_NEGATIONS[line.trim()] === true ? index : -1).filter((index) => index !== -1);
12580
13550
  const firstCanonicalNegationIndex = canonicalNegationIndexes[0] ?? -1;
@@ -12736,7 +13706,7 @@ function runScaffold(pathArg) {
12736
13706
  finalLines.push("");
12737
13707
  }
12738
13708
  if (normalized) {
12739
- fs8.writeFileSync(gitignorePath, finalLines.join(`
13709
+ fs9.writeFileSync(gitignorePath, finalLines.join(`
12740
13710
  `), "utf8");
12741
13711
  created.push(".gitignore (canonical harness snippet reordered)");
12742
13712
  } else if (missing.length === 0) {
@@ -12745,10 +13715,10 @@ function runScaffold(pathArg) {
12745
13715
  } else {
12746
13716
  skipped.push(".gitignore (canonical harness snippet) \u2014 custom harness layout manages its own ignore rules");
12747
13717
  }
12748
- const agentsPath = path12.join(harnessDir, "AGENTS.md");
12749
- const agentsLabel = `${path12.basename(harnessDir)}/AGENTS.md`;
12750
- if (!fs8.existsSync(agentsPath)) {
12751
- fs8.writeFileSync(agentsPath, HARNESS_AGENTS_TEMPLATE, "utf8");
13718
+ const agentsPath = path14.join(harnessDir, "AGENTS.md");
13719
+ const agentsLabel = `${path14.basename(harnessDir)}/AGENTS.md`;
13720
+ if (!fs9.existsSync(agentsPath)) {
13721
+ fs9.writeFileSync(agentsPath, HARNESS_AGENTS_TEMPLATE, "utf8");
12752
13722
  created.push(agentsLabel);
12753
13723
  } else {
12754
13724
  skipped.push(`${agentsLabel} (already present)`);
@@ -12764,7 +13734,7 @@ function runScaffold(pathArg) {
12764
13734
  }
12765
13735
  program2.name("mstar-harness").description("Morning Star harness CLI for target-based agent bootstrap").version(packageVersion);
12766
13736
  program2.command("init").description("Interactive/non-interactive setup for target agent bootstrap").option("-y, --yes", "Non-interactive mode").option("--target <target>", "Install target", "opencode").option("--scope <scope>", "Config scope: global|project (default: project)").option("--output <path>", "Config file path override, relative to project root").option("--dry-run", "Preview result without writing config").option("--no-fallbacks", "Skip installing the dsh-llm-fallbacks plugin (dsh target only)").option("--no-global-cli", "Skip installing the matching-version @mstar-harness/cli globally after init").option("--pm-model <model>", "Optional: model for project-manager (advanced override)").option("--strategic-models <a,b,c>", "Optional: models for architect/product-manager/prompt-engineer").option("--dev-models <a,b,c>", "Optional: models for fullstack-dev/fullstack-dev-2/frontend-dev").option("--qc-models <a,b,c>", "Optional: models for qc trio").option("--other-models <a,b,c>", "Optional: models for remaining roles").action(async (options) => {
12767
- await runInit5({
13737
+ await runInit6({
12768
13738
  ...options,
12769
13739
  noFallbacks: options.fallbacks === false,
12770
13740
  noGlobalCli: options.globalCli === false
@@ -12775,7 +13745,7 @@ harnessCommand.command("scaffold").description("One-shot harness bootstrap: crea
12775
13745
  runScaffold(pathArg);
12776
13746
  });
12777
13747
  program2.command("doctor").description("Validate Morning Star setup for a target agent config").option("--target <target>", "Target agent for doctor checks", "opencode").option("--scope <scope>", "Config scope: global|project", "project").option("--output <path>", "Config file path override, relative to project root").action((options) => {
12778
- runDoctor5(options);
13748
+ runDoctor6(options);
12779
13749
  });
12780
13750
  var pluginCommand = program2.command("plugin").description("Agent Plugins v1.0.0 portable package commands");
12781
13751
  pluginCommand.command("validate").description("Validate a plugin package against Agent Plugins v1.0.0").option("--root <path>", "Plugin root directory to validate (default: project root)").action((options) => {
@@ -12783,7 +13753,7 @@ pluginCommand.command("validate").description("Validate a plugin package against
12783
13753
  });
12784
13754
  var pathCommand = program2.command("path").description("harness/specs dir resolution checks (engine-backed)");
12785
13755
  pathCommand.command("resolve").description("Resolve {HARNESS_DIR} + {SPECS_DIR} + {WORKFLOW_DIR} + {PROJECT_DIR} from a start dir (exit 1 when no harness dir resolves)").argument("[path]", "Start dir to resolve from (default: cwd)").option("--json", "Machine-readable JSON output (ok, harnessDir, specsDir, workflowDir, projectDir, guidance on failure)").action((pathArg, options) => {
12786
- const startDir = pathArg ? path12.resolve(pathArg) : process.cwd();
13756
+ const startDir = pathArg ? path14.resolve(pathArg) : process.cwd();
12787
13757
  const harnessDir = resolveHarnessDir(startDir);
12788
13758
  if (!harnessDir) {
12789
13759
  const guidance = "no harness dir found \u2014 the bounded probe (.mstar/, .agents/, .plans/, plans/) walked up from " + `${startDir} only within the workspace root (git top-level of the start dir; non-git start probes only itself) \u2014 run \`mstar harness scaffold\` to bootstrap, or pass a start dir inside a harness-enabled project`;
@@ -12811,21 +13781,21 @@ pathCommand.command("resolve").description("Resolve {HARNESS_DIR} + {SPECS_DIR}
12811
13781
  var statusCommand = program2.command("status").description("v2 status.json root / workflow snapshot / project-register checks (engine-backed)");
12812
13782
  function resolveStatusFilePath(pathArg) {
12813
13783
  if (pathArg)
12814
- return path12.resolve(pathArg);
13784
+ return path14.resolve(pathArg);
12815
13785
  const harnessDir = resolveHarnessDir();
12816
13786
  if (!harnessDir) {
12817
13787
  throw new Error(`harness dir not found from ${process.cwd()} \u2014 pass a status.json path or set MSTAR_HARNESS_DIR`);
12818
13788
  }
12819
- return path12.join(harnessDir, "status.json");
13789
+ return path14.join(harnessDir, "status.json");
12820
13790
  }
12821
13791
  statusCommand.command("validate").description("Validate a v2 status.json root or workflow snapshot (root: version 2 + updated_at + active workflows[] with per-entry snapshot invariants; snapshot: schema_version 1 + plan rows + lease shapes; v1 input fails closed with the mstar migrate hint)").argument("[path]", "status.json or workflows/<id>/snapshot.json path (default: {HARNESS_DIR}/status.json)").action((pathArg) => {
12822
13792
  let statusPath;
12823
13793
  try {
12824
13794
  statusPath = resolveStatusFilePath(pathArg);
12825
- if (!fs8.existsSync(statusPath)) {
13795
+ if (!fs9.existsSync(statusPath)) {
12826
13796
  throw new Error(`status file not found: ${statusPath}`);
12827
13797
  }
12828
- const gate2 = path12.basename(statusPath) === WORKFLOW_SNAPSHOT_FILE ? validateWorkflowSnapshot(readJson2(statusPath)) : validateStatus(statusPath);
13798
+ const gate2 = path14.basename(statusPath) === WORKFLOW_SNAPSHOT_FILE ? validateWorkflowSnapshot(readJson2(statusPath)) : validateStatus(statusPath);
12829
13799
  if (gate2.ok) {
12830
13800
  console.log(import_picocolors2.default.green(`${statusPath}: OK`));
12831
13801
  return;
@@ -12845,8 +13815,8 @@ statusCommand.command("validate").description("Validate a v2 status.json root or
12845
13815
  });
12846
13816
  statusCommand.command("tech-debt").description("Print the residual tech-debt rollup aggregated over every {PROJECT_DIR}/<id>/residuals.json register " + "(total_open / by_severity / by_target / by_plan; the project register is the source of truth \u2014 " + "no stored-summary drift check, informational exit 0)").argument("[path]", "Project dir (default: resolved {PROJECT_DIR})").action((pathArg) => {
12847
13817
  try {
12848
- const projectDir = pathArg ? path12.resolve(pathArg) : resolveProjectDir();
12849
- if (!fs8.existsSync(projectDir)) {
13818
+ const projectDir = pathArg ? path14.resolve(pathArg) : resolveProjectDir();
13819
+ if (!fs9.existsSync(projectDir)) {
12850
13820
  throw new Error(`project dir not found: ${projectDir}`);
12851
13821
  }
12852
13822
  const rollup = techDebtRollup(projectDir);
@@ -12864,8 +13834,8 @@ statusCommand.command("tech-debt").description("Print the residual tech-debt rol
12864
13834
  statusCommand.command("findings-cleanup").description("Enforce a plan's findings-cleanup mode on its project-register residuals (projects/<id>/residuals.json " + "entries keyed by plan id \u2014 the snapshot plan linkage; zero-residual via Assignment, else allow-residual; exit 1 on violations)").argument("<plan-id>", "Plan id whose register entries are checked against the cleanup mode").option("--harness <path>", "Harness dir override (default: resolved {HARNESS_DIR})").option("--project <id>", "Project id whose register is read (default: _default)").option("--mode <mode>", "Cleanup mode override: zero-residual | allow-residual (default: allow-residual)").action((planId, options) => {
12865
13835
  try {
12866
13836
  const projectDir = resolveProjectDir(process.cwd(), options.harness ? { harnessDir: options.harness } : {});
12867
- const registerPath = path12.join(projectDir, options.project ?? _DEFAULT_PROJECT, PROJECT_REGISTER_FILE);
12868
- if (!fs8.existsSync(registerPath)) {
13837
+ const registerPath = path14.join(projectDir, options.project ?? _DEFAULT_PROJECT, PROJECT_REGISTER_FILE);
13838
+ if (!fs9.existsSync(registerPath)) {
12869
13839
  throw new Error(`project register not found: ${registerPath}`);
12870
13840
  }
12871
13841
  const mode = options.mode === "zero-residual" || options.mode === "allow-residual" ? options.mode : undefined;
@@ -12900,7 +13870,7 @@ function sanitizeProjectId(projectId) {
12900
13870
  if (projectId === _DEFAULT_PROJECT) {
12901
13871
  return projectId;
12902
13872
  }
12903
- if (projectId === "" || projectId === "." || projectId === ".." || path12.isAbsolute(projectId) || !PROJECT_ID_RE.test(projectId)) {
13873
+ if (projectId === "" || projectId === "." || projectId === ".." || path14.isAbsolute(projectId) || !PROJECT_ID_RE.test(projectId)) {
12904
13874
  throw new Error(`invalid project id ${JSON.stringify(projectId)} \u2014 expected one path component ` + `([A-Za-z0-9][A-Za-z0-9._-]*); "." / ".." / absolute / separator-containing ids would escape {PROJECT_DIR}`);
12905
13875
  }
12906
13876
  return projectId;
@@ -12915,7 +13885,7 @@ statusCommand.command("backlog-register").description("Register deferred-PR back
12915
13885
  const projectRoot = resolveProjectDir(process.cwd(), options.harness ? { harnessDir: options.harness } : {});
12916
13886
  if (options.harness)
12917
13887
  setArtifactStore(createFsStore(options.harness));
12918
- const projectDir = path12.join(projectRoot, projectId);
13888
+ const projectDir = path14.join(projectRoot, projectId);
12919
13889
  const registeredAt = todayString5();
12920
13890
  const entries = entriesRaw.map((raw, index) => {
12921
13891
  let parsed;
@@ -12942,7 +13912,7 @@ statusCommand.command("backlog-close").description("Close one project-register b
12942
13912
  const projectRoot = resolveProjectDir(process.cwd(), options.harness ? { harnessDir: options.harness } : {});
12943
13913
  if (options.harness)
12944
13914
  setArtifactStore(createFsStore(options.harness));
12945
- const projectDir = path12.join(projectRoot, projectId);
13915
+ const projectDir = path14.join(projectRoot, projectId);
12946
13916
  await closeProjectRegisterEntry({
12947
13917
  projectDir,
12948
13918
  planKey: options.key,
@@ -12984,13 +13954,13 @@ function readPersistPayload(options) {
12984
13954
  throw new SddScriptError("usage: persist --file <path> and --stdin are mutually exclusive", 2);
12985
13955
  }
12986
13956
  if (options.file !== undefined) {
12987
- const filePath = path12.resolve(options.file);
12988
- if (!fs8.existsSync(filePath)) {
12989
- throw new Error(`persist payload file not found: ${filePath}`);
13957
+ const requested = path14.isAbsolute(options.file) ? options.file : `${process.cwd()}${path14.sep}${options.file}`;
13958
+ if (!fs9.existsSync(requested)) {
13959
+ throw new Error(`persist payload file not found: ${requested}`);
12990
13960
  }
12991
- return fs8.readFileSync(filePath, "utf8");
13961
+ return fs9.readFileSync(requested, "utf8");
12992
13962
  }
12993
- return fs8.readFileSync(0, "utf8");
13963
+ return fs9.readFileSync(0, "utf8");
12994
13964
  }
12995
13965
  function validatePersistPayload(kind, payload) {
12996
13966
  let gate2;
@@ -13102,7 +14072,7 @@ persistCommand.command("delete").description("Delete the stored document for <ki
13102
14072
  var leaseCommand = program2.command("lease").description("execution_lease / integration_merge_lease checks (engine-backed)");
13103
14073
  function resolveLeaseHarnessDir(harnessArg) {
13104
14074
  if (harnessArg)
13105
- return path12.resolve(harnessArg);
14075
+ return path14.resolve(harnessArg);
13106
14076
  const harnessDir = resolveHarnessDir();
13107
14077
  if (!harnessDir) {
13108
14078
  throw new Error(`harness dir not found from ${process.cwd()} \u2014 pass --harness or set MSTAR_HARNESS_DIR`);
@@ -13115,7 +14085,7 @@ function resolveSnapshotPath(workflowId, harnessArg) {
13115
14085
  }
13116
14086
  const harnessDir = resolveLeaseHarnessDir(harnessArg);
13117
14087
  const workflowDir = resolveWorkflowDir(harnessDir, { harnessDir });
13118
- return path12.join(workflowDir, workflowId, WORKFLOW_SNAPSHOT_FILE);
14088
+ return path14.join(workflowDir, workflowId, WORKFLOW_SNAPSHOT_FILE);
13119
14089
  }
13120
14090
  function solePlanRow(plans, label) {
13121
14091
  if (plans.length === 0) {
@@ -13127,7 +14097,7 @@ function solePlanRow(plans, label) {
13127
14097
  return { row: plans[0] };
13128
14098
  }
13129
14099
  function verifyLeaseRow(row, planId, snapshotPath) {
13130
- const result = verifyPlanExecutionLease(row, planId);
14100
+ const result = verifyPlanExecutionLease2(row, planId);
13131
14101
  if (result.ok) {
13132
14102
  const holder = String(result.lease.holder ?? "");
13133
14103
  console.log(import_picocolors2.default.green(`${snapshotPath}: OK plan ${planId} \u2014 execution_lease valid (holder ${holder})`));
@@ -13148,7 +14118,7 @@ leaseCommand.command("verify").description("Verify a plan's execution_lease on t
13148
14118
  throw new SddScriptError("usage: lease verify --workflow <id> [--plan <plan-id>] [--harness <path>]", 2);
13149
14119
  }
13150
14120
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
13151
- if (!fs8.existsSync(snapshotPath)) {
14121
+ if (!fs9.existsSync(snapshotPath)) {
13152
14122
  throw new Error(`workflow snapshot not found: ${snapshotPath}`);
13153
14123
  }
13154
14124
  const doc = readJson2(snapshotPath);
@@ -13186,7 +14156,7 @@ leaseCommand.command("verify-integration").description("Verify the workflow snap
13186
14156
  throw new SddScriptError("usage: lease verify-integration --workflow <id> [--harness <path>]", 2);
13187
14157
  }
13188
14158
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
13189
- if (!fs8.existsSync(snapshotPath)) {
14159
+ if (!fs9.existsSync(snapshotPath)) {
13190
14160
  throw new Error(`workflow snapshot not found: ${snapshotPath}`);
13191
14161
  }
13192
14162
  const doc = readJson2(snapshotPath);
@@ -13215,7 +14185,28 @@ function failScript(error, context) {
13215
14185
  console.error(import_picocolors2.default.red(`${context} failed: ${error.message}`));
13216
14186
  process.exitCode = 1;
13217
14187
  }
13218
- var sddCommand = program2.command("sdd").description("SDD workspace / task-brief / review-package helpers (engine-backed)");
14188
+ function loadSddContextFile(pathValue) {
14189
+ if (!pathValue || !path14.isAbsolute(pathValue)) {
14190
+ throw new SddScriptError(`--context must be an absolute path to a SddExecutionContext JSON file; got ${JSON.stringify(pathValue ?? "")}`, 2);
14191
+ }
14192
+ let raw;
14193
+ try {
14194
+ raw = fs9.readFileSync(pathValue, "utf8");
14195
+ } catch {
14196
+ throw new SddScriptError(`no such context file: ${pathValue}`, 2);
14197
+ }
14198
+ let doc;
14199
+ try {
14200
+ doc = JSON.parse(raw);
14201
+ } catch (error) {
14202
+ throw new SddScriptError(`context file is not valid JSON: ${pathValue} (${error.message})`, 2);
14203
+ }
14204
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) {
14205
+ throw new SddScriptError(`context file must contain a JSON object: ${pathValue}`, 2);
14206
+ }
14207
+ return doc;
14208
+ }
14209
+ var sddCommand = program2.command("sdd").description("SDD workspace / task-brief / review-package / check-context / exec helpers (engine-backed; " + "check-context + exec + --context are the spec-A3 bound execution surface)");
13219
14210
  sddCommand.command("workspace").description("Resolve and ensure {SDD_DIR} for a plan (exit 1 on resolution failures, 2 on usage errors)").argument("[plan-id]", "Plan id whose SDD dir is resolved/created").argument("[control-root]", "Control worktree root (default: MSTAR_CONTROL_ROOT or the cwd's git top-level)").action((planId, controlRoot) => {
13220
14211
  try {
13221
14212
  if (!planId) {
@@ -13228,28 +14219,68 @@ sddCommand.command("workspace").description("Resolve and ensure {SDD_DIR} for a
13228
14219
  failScript(error, "sdd workspace");
13229
14220
  }
13230
14221
  });
13231
- sddCommand.command("task-brief").description("Extract the `## Task N` section of a plan into a brief file (exit 3 when task N is missing)").argument("[plan-file]", "Plan markdown file").argument("[task-number]", "Task number whose brief is extracted").argument("[outfile]", "Output file (default: {SDD_DIR}/task-N-brief.md)").action((planFile, taskNumber, outfile) => {
14222
+ sddCommand.command("task-brief").description("Extract the `## Task N` section of a plan into a brief file (exit 3 when task N is missing). " + "With --context the artifact destination is gate-checked before mkdir/write and the emitted path is absolute").argument("[plan-file]", "Plan markdown file").argument("[task-number]", "Task number whose brief is extracted").argument("[outfile]", "Output file (default: {SDD_DIR}/task-N-brief.md)").option("--context <path>", "Absolute path to a SddExecutionContext JSON \u2014 binds the artifact write (spec A3)").action((planFile, taskNumber, outfile, options = {}) => {
13232
14223
  try {
13233
14224
  if (!planFile || !taskNumber) {
13234
- throw new SddScriptError("usage: mstar sdd task-brief PLAN_FILE TASK_NUMBER [OUTFILE]", 2);
14225
+ throw new SddScriptError("usage: mstar sdd task-brief PLAN_FILE TASK_NUMBER [OUTFILE] [--context <absolute.json>]", 2);
13235
14226
  }
13236
- const out = taskBrief(planFile, Number(taskNumber), outfile);
14227
+ const bound = options.context ? { context: resolveSddExecutionContext(loadSddContextFile(options.context)) } : undefined;
14228
+ const out = taskBrief(planFile, Number(taskNumber), outfile, bound);
13237
14229
  console.log(import_picocolors2.default.green(`task ${taskNumber} brief: ${out}`));
13238
14230
  } catch (error) {
13239
14231
  failScript(error, "sdd task-brief");
13240
14232
  }
13241
14233
  });
13242
- sddCommand.command("review-package").description("Write commits + stat + diff -U10 for BASE..HEAD into a review file (exit 2 on bad refs)").argument("[base]", "Base ref (commit SHA)").argument("[head]", "Head ref (commit SHA)").argument("[outfile]", "Output file (default: {SDD_DIR}/review-<short-base>..<short-head>.diff)").action((base, head, outfile) => {
14234
+ sddCommand.command("review-package").description("Write commits + stat + diff -U10 for BASE..HEAD into a review file (exit 2 on bad refs). " + "With --context the review range is probed in the feature worktree and the package is gate-checked into the plan's control artifacts").argument("[base]", "Base ref (commit SHA)").argument("[head]", "Head ref (commit SHA)").argument("[outfile]", "Output file (default: {SDD_DIR}/review-<short-base>..<short-head>.diff)").option("--context <path>", "Absolute path to a SddExecutionContext JSON \u2014 binds the artifact write (spec A3)").action((base, head, outfile, options = {}) => {
13243
14235
  try {
13244
14236
  if (!base || !head) {
13245
- throw new SddScriptError("usage: mstar sdd review-package BASE HEAD [OUTFILE]", 2);
14237
+ throw new SddScriptError("usage: mstar sdd review-package BASE HEAD [OUTFILE] [--context <absolute.json>]", 2);
13246
14238
  }
13247
- const out = reviewPackage(base, head, outfile);
14239
+ const bound = options.context ? { context: resolveSddExecutionContext(loadSddContextFile(options.context)) } : undefined;
14240
+ const out = reviewPackage(base, head, outfile, bound);
13248
14241
  console.log(import_picocolors2.default.green(`review package: ${out}`));
13249
14242
  } catch (error) {
13250
14243
  failScript(error, "sdd review-package");
13251
14244
  }
13252
14245
  });
14246
+ sddCommand.command("check-context").description("Gate one action seam against a resolved SDD execution context (spec A3): the observed cwd is this process's cwd. " + "Exit 0 pass, 1 gate fail, 2 usage; a refused action performs no write").option("--context <path>", "Absolute path to the SddExecutionContext JSON file").option("--kind <kind>", "Action seam kind: source | artifact | launch").option("--target <path>", "Path the action would touch (required for artifact; optional for source/launch)").action((options) => {
14247
+ try {
14248
+ if (!options.context) {
14249
+ throw new SddScriptError("usage: mstar sdd check-context --context <absolute.json> --kind source|artifact|launch [--target <path>]", 2);
14250
+ }
14251
+ if (!options.kind) {
14252
+ throw new SddScriptError("usage: mstar sdd check-context --context <absolute.json> --kind source|artifact|launch [--target <path>]", 2);
14253
+ }
14254
+ if (options.kind !== "source" && options.kind !== "artifact" && options.kind !== "launch") {
14255
+ throw new SddScriptError(`usage: --kind must be source|artifact|launch; got ${JSON.stringify(options.kind)}`, 2);
14256
+ }
14257
+ const resolved = resolveSddExecutionContext(loadSddContextFile(options.context));
14258
+ const gate2 = checkSddAction(resolved, { kind: options.kind, cwd: process.cwd(), target: options.target });
14259
+ if (!gate2.ok) {
14260
+ printChecklist("sdd check-context", gate2);
14261
+ process.exitCode = 1;
14262
+ return;
14263
+ }
14264
+ console.log(import_picocolors2.default.green(`check-context: OK \u2014 ${options.kind} action allowed under plan "${resolved.planId}"`));
14265
+ } catch (error) {
14266
+ failScript(error, "sdd check-context");
14267
+ }
14268
+ });
14269
+ sddCommand.command("exec").description("Run an argv child bound to a resolved SDD execution context (spec A3): spawn cwd = the context's feature worktree, " + "no shell (the argv after -- reaches the child literally), inherited env + stdio. " + "Gate failure exits 1, usage 2, spawn-not-found 127, child exit preserved, signal termination 128+signal (SIGINT/SIGTERM forwarded)").option("--context <path>", "Absolute path to the SddExecutionContext JSON file").argument("[argv...]", "Child executable + args placed after -- (passed through unchanged)").action(async (argv, options) => {
14270
+ try {
14271
+ if (!options.context) {
14272
+ throw new SddScriptError("usage: mstar sdd exec --context <absolute.json> -- <executable> [args...]", 2);
14273
+ }
14274
+ if (argv.length === 0) {
14275
+ throw new SddScriptError(`usage: mstar sdd exec --context <absolute.json> -- <executable> [args...]
14276
+ The argv after -- is passed to the child literally (no shell).`, 2);
14277
+ }
14278
+ const code = await runInSddContext(loadSddContextFile(options.context), argv);
14279
+ process.exitCode = code;
14280
+ } catch (error) {
14281
+ failScript(error, "sdd exec");
14282
+ }
14283
+ });
13253
14284
  var iterationCommand = program2.command("iteration").description("iteration phase-gate + push-cadence checks (engine-backed)");
13254
14285
  function printChecklist(label, gate2) {
13255
14286
  if (gate2.ok) {
@@ -13264,13 +14295,13 @@ function printChecklist(label, gate2) {
13264
14295
  console.error(` fix: ${violation15.fix}`);
13265
14296
  }
13266
14297
  }
13267
- iterationCommand.command("gate").description("Evaluate the phase-transition gate: prints the transition (phase-2-execute / phase-3-close / phase-4-pr-delivery) " + "plus the \xA73.1 entry and \xA73.5 exit checklists. Exit 1 when the gate verdict fails \u2014 during the Phase-3 window " + "(transition: phase-3-close) exit 1 is EXPECTED until the \xA73.4 close items (status: completed + end_date) are " + "written: the exit checklist gates Phase 4, not the Phase-3 entry (qc2 F-003)").requiredOption("--workflow <id>", "Workflow id whose snapshot is evaluated").requiredOption("--compass <path>", "delivery-compass.md path").option("--harness <path>", "Harness dir override (default: resolved {HARNESS_DIR})").option("--branch <branch>", "Current branch probe (exit \xA73.5 item 5)").option("--integration <branch>", "Spec integration branch probe (exit \xA73.5 item 5)").option("--target <branch>", "PR base branch probe (exit \xA73.5 item 6)").action((options) => {
14298
+ iterationCommand.command("gate").description("Evaluate the phase-transition gate: prints the transition (phase-2-execute / phase-3-close / phase-4-pr-delivery) " + "plus the \xA73.1 entry and \xA73.5 exit checklists. Exit 1 when the gate verdict fails \u2014 during the Phase-3 window " + "(transition: phase-3-close) exit 1 is EXPECTED until the \xA73.4 close items (status: completed + end_date) are " + "written: the exit checklist gates Phase 4, not the Phase-3 entry").requiredOption("--workflow <id>", "Workflow id whose snapshot is evaluated").requiredOption("--compass <path>", "delivery-compass.md path").option("--harness <path>", "Harness dir override (default: resolved {HARNESS_DIR})").option("--branch <branch>", "Current branch probe (exit \xA73.5 item 5)").option("--integration <branch>", "Spec integration branch probe (exit \xA73.5 item 5)").option("--target <branch>", "PR base branch probe (exit \xA73.5 item 6)").action((options) => {
13268
14299
  try {
13269
14300
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
13270
- const compassPath = path12.resolve(options.compass);
13271
- if (!fs8.existsSync(snapshotPath))
14301
+ const compassPath = path14.resolve(options.compass);
14302
+ if (!fs9.existsSync(snapshotPath))
13272
14303
  throw new Error(`workflow snapshot not found: ${snapshotPath}`);
13273
- if (!fs8.existsSync(compassPath))
14304
+ if (!fs9.existsSync(compassPath))
13274
14305
  throw new Error(`compass file not found: ${compassPath}`);
13275
14306
  const result = evaluatePhaseGate(readJson2(snapshotPath), parseCompassFrontmatter(compassPath), {
13276
14307
  currentBranch: options.branch,
@@ -13309,10 +14340,10 @@ dispatchCommand.command("validate").description("Validate an Assignment markdown
13309
14340
  throw new SddScriptError("usage: dispatch validate <assignment-file> [--branch <branch>]", 2);
13310
14341
  }
13311
14342
  const file = resolveCliPath(assignmentFile);
13312
- if (!fs8.existsSync(file)) {
14343
+ if (!fs9.existsSync(file)) {
13313
14344
  throw new Error(`assignment file not found: ${file}`);
13314
14345
  }
13315
- const text = fs8.readFileSync(file, "utf8");
14346
+ const text = fs9.readFileSync(file, "utf8");
13316
14347
  const readOnly = isReadOnlyAssignmentRole(parseAssignmentFields(text).executeAs ?? "");
13317
14348
  const violations = [...validateAssignmentFields(text, { writable: readOnly ? false : undefined }).violations];
13318
14349
  if (!readOnly) {
@@ -13371,7 +14402,7 @@ worktreeCommand.command("check").description("L1: verify the plan's execution_le
13371
14402
  throw new SddScriptError("usage: worktree check <plan-id> --workflow <id> [--harness <path>] [--control <path>] (or --plan <plan-id>)", 2);
13372
14403
  }
13373
14404
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
13374
- if (!fs8.existsSync(snapshotPath)) {
14405
+ if (!fs9.existsSync(snapshotPath)) {
13375
14406
  throw new Error(`workflow snapshot not found: ${snapshotPath}`);
13376
14407
  }
13377
14408
  const doc = readJson2(snapshotPath);
@@ -13392,7 +14423,7 @@ worktreeCommand.command("check").description("L1: verify the plan's execution_le
13392
14423
  const row = matches[0];
13393
14424
  const lease = row.execution_lease ?? {};
13394
14425
  const input = {
13395
- controlWorktreePath: options.control ? path12.resolve(options.control) : String(doc.control_worktree_path ?? ""),
14426
+ controlWorktreePath: options.control ? path14.resolve(options.control) : String(doc.control_worktree_path ?? ""),
13396
14427
  leaseWorktreePath: String(lease.worktree_path ?? ""),
13397
14428
  leaseWorkingBranch: String(lease.working_branch ?? ""),
13398
14429
  planId: plan
@@ -13428,11 +14459,11 @@ worktreeCommand.command("qc-alignment").description("Assert the QC/QA alignment
13428
14459
  }
13429
14460
  const assignments = [];
13430
14461
  for (const fileArg of files) {
13431
- const file = path12.resolve(fileArg);
13432
- if (!fs8.existsSync(file)) {
14462
+ const file = path14.isAbsolute(fileArg) ? fileArg : `${process.cwd()}${path14.sep}${fileArg}`;
14463
+ if (!fs9.existsSync(file)) {
13433
14464
  throw new Error(`assignment file not found: ${file}`);
13434
14465
  }
13435
- const text = fs8.readFileSync(file, "utf8");
14466
+ const text = fs9.readFileSync(file, "utf8");
13436
14467
  const combinedRange = parseAssignmentHeaderField(text, "Review range / Diff basis");
13437
14468
  const planId = parseAssignmentHeaderField(text, "plan_id");
13438
14469
  const reviewRange = parseAssignmentHeaderField(text, "Review range") || combinedRange;
@@ -13474,11 +14505,11 @@ reviewCommand.command("seats").description("Map an Assignment's execution mode t
13474
14505
  if (!assignmentFile) {
13475
14506
  throw new SddScriptError("usage: review seats <assignment-file> [--mode sdd|inline|targeted] [--reviewers <role1,role2,...>]", 2);
13476
14507
  }
13477
- const file = path12.resolve(assignmentFile);
13478
- if (!fs8.existsSync(file)) {
14508
+ const file = path14.isAbsolute(assignmentFile) ? assignmentFile : `${process.cwd()}${path14.sep}${assignmentFile}`;
14509
+ if (!fs9.existsSync(file)) {
13479
14510
  throw new Error(`assignment file not found: ${file}`);
13480
14511
  }
13481
- const text = fs8.readFileSync(file, "utf8");
14512
+ const text = fs9.readFileSync(file, "utf8");
13482
14513
  const mode = options.mode ?? parseAssignmentExecutionMode(text);
13483
14514
  const reviewers = (options.reviewers ?? "").split(",").map((role) => role.trim()).filter((role) => role !== "");
13484
14515
  const result = executionModeToN(mode, { seats: reviewers });
@@ -13535,43 +14566,49 @@ var LINT_CODE_EXTENSIONS = {
13535
14566
  ".swift": true
13536
14567
  };
13537
14568
  function lintTargetType(filePath) {
13538
- const base = path12.basename(filePath);
14569
+ const base = path14.basename(filePath);
13539
14570
  if (base === "STRATEGY.md")
13540
14571
  return "strategy";
13541
14572
  if (base === "SKILL.md")
13542
14573
  return "skill";
13543
14574
  if (/^task-\d+-report\.md$/i.test(base))
13544
14575
  return "report";
13545
- const dir = path12.dirname(filePath);
13546
- if (dir.includes(`${path12.sep}plans${path12.sep}`) || dir.endsWith(`${path12.sep}plans`))
14576
+ const dir = path14.dirname(filePath);
14577
+ if (dir.includes(`${path14.sep}plans${path14.sep}`) || dir.endsWith(`${path14.sep}plans`))
13547
14578
  return "plan";
13548
14579
  if (/^\d{8}-[a-z0-9.-]+\.md$/i.test(base))
13549
14580
  return "plan";
13550
- if (LINT_CODE_EXTENSIONS[path12.extname(base).toLowerCase()] === true)
14581
+ if (LINT_CODE_EXTENSIONS[path14.extname(base).toLowerCase()] === true)
13551
14582
  return "code";
13552
14583
  return null;
13553
14584
  }
13554
14585
  function collectLintTargets(dir) {
13555
14586
  const targets = [];
13556
- const walk = (current) => {
13557
- for (const entry of fs8.readdirSync(current, { withFileTypes: true })) {
14587
+ const visit = (current) => {
14588
+ for (const entry of fs9.readdirSync(current, { withFileTypes: true })) {
14589
+ if (entry.name.includes(path14.sep))
14590
+ continue;
14591
+ const child = current + entry.name;
13558
14592
  if (entry.isDirectory()) {
13559
14593
  if (LINT_SKIP_DIRS[entry.name] !== true)
13560
- walk(path12.join(current, entry.name));
13561
- } else if (entry.isFile() && lintTargetType(path12.join(current, entry.name)) !== null) {
13562
- targets.push(path12.join(current, entry.name));
14594
+ visit(child + path14.sep);
14595
+ } else if (entry.isFile() && lintTargetType(child) !== null) {
14596
+ targets.push(child);
13563
14597
  }
13564
14598
  }
13565
14599
  };
13566
- walk(dir);
14600
+ const root = dir.endsWith(path14.sep) ? `${dir}` : `${dir}${path14.sep}`;
14601
+ visit(root);
13567
14602
  return targets;
13568
14603
  }
13569
- function lintOneFile(filePath, forcedType, prVariant) {
13570
- const abs = path12.resolve(filePath);
13571
- const text = fs8.readFileSync(abs, "utf8");
14604
+ var lintIo = {
14605
+ readText: async (resolvedPath) => fs9.promises.readFile(resolvedPath, "utf8")
14606
+ };
14607
+ async function lintOneFile(filePath, forcedType, prVariant) {
14608
+ const text = await lintIo.readText(filePath);
13572
14609
  const violations = [];
13573
14610
  const markers = [];
13574
- const effective = forcedType ?? lintTargetType(abs);
14611
+ const effective = forcedType ?? lintTargetType(filePath);
13575
14612
  switch (effective) {
13576
14613
  case "plan":
13577
14614
  violations.push(...planQualityBar(text).violations);
@@ -13601,12 +14638,12 @@ function lintOneFile(filePath, forcedType, prVariant) {
13601
14638
  violations.push(...validateFindingDoc(text, { ...prVariant ? { prVariant: true } : {} }).violations);
13602
14639
  break;
13603
14640
  default:
13604
- throw new SddScriptError(`usage: lint <target> \u2014 unsupported file type "${path12.basename(abs)}" (lintable: plan files, SKILL.md, STRATEGY.md, task-N-report.md, code files)`, 2);
14641
+ throw new SddScriptError(`usage: lint <target> \u2014 unsupported file type "${path14.basename(filePath)}" (lintable: plan files, SKILL.md, STRATEGY.md, task-N-report.md, code files)`, 2);
13605
14642
  }
13606
14643
  return { violations, markers };
13607
14644
  }
13608
14645
  var lintCommand = program2.command("lint").description("lint harness artifacts by content type (engine-backed): plan files \u2192 quality bar, SKILL.md \u2192 frontmatter, " + "STRATEGY.md \u2192 required sections, task-N-report.md \u2192 SDD TDD triple, code files \u2192 simplify:/temporary markers");
13609
- lintCommand.description("Lint <target> (file or dir) \u2014 exit 1 on violations, 2 on usage. --type forces one content type " + "(plan | skill | strategy | report | code | finding); finding docs are explicit-only").argument("[target]", "File or directory to lint").option("--type <type>", "Force the content type (plan | skill | strategy | report | code | finding)").option("--pr-variant", "With --type finding: enforce the PR-only Merge class contract (presence, enum, placement after Confidence)").action((target, options) => {
14646
+ lintCommand.description("Lint <target> (file or dir) \u2014 exit 1 on violations, 2 on usage. --type forces one content type " + "(plan | skill | strategy | report | code | finding); finding docs are explicit-only").argument("[target]", "File or directory to lint").option("--type <type>", "Force the content type (plan | skill | strategy | report | code | finding)").option("--pr-variant", "With --type finding: enforce the PR-only Merge class contract (presence, enum, placement after Confidence)").action(async (target, options) => {
13610
14647
  try {
13611
14648
  if (!target)
13612
14649
  throw new SddScriptError("usage: lint <target> (file or dir)", 2);
@@ -13620,9 +14657,9 @@ lintCommand.description("Lint <target> (file or dir) \u2014 exit 1 on violations
13620
14657
  forcedType = forced;
13621
14658
  }
13622
14659
  const abs = resolveCliPath(target);
13623
- if (!fs8.existsSync(abs))
14660
+ if (!fs9.existsSync(abs))
13624
14661
  throw new Error(`lint target not found: ${abs}`);
13625
- const targets = fs8.statSync(abs).isDirectory() ? collectLintTargets(abs) : [abs];
14662
+ const targets = fs9.statSync(abs).isDirectory() ? collectLintTargets(abs) : [abs];
13626
14663
  if (targets.length === 0) {
13627
14664
  console.log(import_picocolors2.default.yellow(`lint: no lintable files under ${target}`));
13628
14665
  return;
@@ -13632,7 +14669,7 @@ lintCommand.description("Lint <target> (file or dir) \u2014 exit 1 on violations
13632
14669
  const label = `lint ${file}`;
13633
14670
  let result;
13634
14671
  try {
13635
- result = lintOneFile(file, forcedType ?? undefined, options.prVariant === true);
14672
+ result = await lintOneFile(file, forcedType ?? undefined, options.prVariant === true);
13636
14673
  } catch (error) {
13637
14674
  if (error instanceof SddScriptError)
13638
14675
  throw error;
@@ -13667,17 +14704,17 @@ designMdCommand.command("validate").description("Validate DESIGN.md in <dir>: to
13667
14704
  if (!dir)
13668
14705
  throw new SddScriptError("usage: design-md validate <dir>", 2);
13669
14706
  const abs = resolveCliPath(dir);
13670
- const lightPath = path12.join(abs, "DESIGN.md");
13671
- if (!fs8.existsSync(lightPath))
14707
+ const lightPath = `${abs}${path14.sep}DESIGN.md`;
14708
+ if (!fs9.existsSync(lightPath))
13672
14709
  throw new Error(`design file not found: ${lightPath}`);
13673
- const light = fs8.readFileSync(lightPath, "utf8");
14710
+ const light = fs9.readFileSync(lightPath, "utf8");
13674
14711
  const violations = [];
13675
14712
  const tokens = validateDesignTokenFrontmatter(light);
13676
14713
  printChecklist("design-md validate (tokens)", tokens);
13677
14714
  violations.push(...tokens.violations);
13678
- const darkPath = path12.join(abs, "DESIGN.dark.md");
13679
- if (fs8.existsSync(darkPath)) {
13680
- const parity = assertLightDarkParity(light, fs8.readFileSync(darkPath, "utf8"));
14715
+ const darkPath = `${abs}${path14.sep}DESIGN.dark.md`;
14716
+ if (fs9.existsSync(darkPath)) {
14717
+ const parity = assertLightDarkParity(light, fs9.readFileSync(darkPath, "utf8"));
13681
14718
  printChecklist("design-md validate (light/dark parity)", parity);
13682
14719
  violations.push(...parity.violations);
13683
14720
  }
@@ -13825,7 +14862,7 @@ auditCommand.command("scaffold").description("Scaffold an audit-<date>/ plan dir
13825
14862
  if (!findingsFile)
13826
14863
  throw new SddScriptError("usage: audit scaffold <findings-file> [--dir <out-dir>]", 2);
13827
14864
  const abs = resolveCliPath(findingsFile);
13828
- if (!fs8.existsSync(abs))
14865
+ if (!fs9.existsSync(abs))
13829
14866
  throw new Error(`findings file not found: ${abs}`);
13830
14867
  if (options.date !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(options.date)) {
13831
14868
  throw new SddScriptError("usage: audit scaffold \u2014 --date must be YYYY-MM-DD", 2);
@@ -13835,7 +14872,7 @@ auditCommand.command("scaffold").description("Scaffold an audit-<date>/ plan dir
13835
14872
  }
13836
14873
  const date = options.date ?? new Date().toISOString().slice(0, 10);
13837
14874
  const outDir = options.dir !== undefined ? resolveCliPath(options.dir) : resolveCliPath(`audit-${date}`);
13838
- const input = parseAuditScaffoldInput(fs8.readFileSync(abs, "utf8"));
14875
+ const input = parseAuditScaffoldInput(fs9.readFileSync(abs, "utf8"));
13839
14876
  const sha = resolveAuditShortSha(process.cwd(), options.sha);
13840
14877
  const result = scaffoldAuditPlan(outDir, input.findings, {
13841
14878
  date,
@@ -13862,7 +14899,7 @@ auditCommand.command("promote").description("Promote selected audit plans into t
13862
14899
  throw new SddScriptError("usage: audit promote <audit-dir> --plans <ids> [--workflow <id>] [--harness <dir>]", 2);
13863
14900
  }
13864
14901
  const outDir = resolveCliPath(auditDir);
13865
- if (!fs8.existsSync(outDir)) {
14902
+ if (!fs9.existsSync(outDir)) {
13866
14903
  throw new Error(`audit dir not found: ${outDir}`);
13867
14904
  }
13868
14905
  const harnessDir = resolveLeaseHarnessDir(options.harness);
@@ -13888,12 +14925,12 @@ function listTrackedFiles(root) {
13888
14925
  } catch {
13889
14926
  throw new SddScriptError("not a git repository or git unavailable \u2014 refusing to report an empty scan as clean", 2);
13890
14927
  }
13891
- return out.split("\x00").filter((f) => f !== "").map((f) => path12.join(root, f));
14928
+ return out.split("\x00").filter((f) => f !== "").map((f) => root.endsWith(path14.sep) ? root + f : root + path14.sep + f);
13892
14929
  }
13893
14930
  auditCommand.command("secret-scan").description("Read-only credential-pattern scan over git-tracked files under [path] " + "(default cwd): prints {file, line, type} findings; never prints values. " + "Exit 1 on findings, 0 when clean, 2 when the tracked-file walk or reads fail").argument("[path]", "Directory to scan (default: cwd)").action((scanPath) => {
13894
14931
  try {
13895
14932
  const root = scanPath !== undefined ? resolveCliPath(scanPath) : process.cwd();
13896
- if (!fs8.existsSync(root) || !fs8.statSync(root).isDirectory()) {
14933
+ if (!fs9.existsSync(root) || !fs9.statSync(root).isDirectory()) {
13897
14934
  throw new SddScriptError(`usage: audit secret-scan [path] \u2014 not a directory: ${root}`, 2);
13898
14935
  }
13899
14936
  const files = listTrackedFiles(root);
@@ -13920,7 +14957,7 @@ auditCommand.command("secret-scan").description("Read-only credential-pattern sc
13920
14957
  auditCommand.command("supply-chain").description("Supply-chain checks over a repo root (read-only): root lockfile presence/duplication, " + "unpinned GitHub Actions refs, pull_request_target PR-head checkout. " + "Exit 1 on findings, 0 when clean").argument("[path]", "Repository root (default: cwd)").action((repoPath) => {
13921
14958
  try {
13922
14959
  const root = repoPath !== undefined ? resolveCliPath(repoPath) : process.cwd();
13923
- if (!fs8.existsSync(root) || !fs8.statSync(root).isDirectory()) {
14960
+ if (!fs9.existsSync(root) || !fs9.statSync(root).isDirectory()) {
13924
14961
  throw new SddScriptError(`usage: audit supply-chain [path] \u2014 not a directory: ${root}`, 2);
13925
14962
  }
13926
14963
  const result = supplyChainChecks(root);
@@ -13947,9 +14984,9 @@ compoundCommand.command("validate").description("Validate a knowledge doc frontm
13947
14984
  if (!docPath)
13948
14985
  throw new SddScriptError("usage: compound validate <doc-path> [--knowledge-dir <dir>]", 2);
13949
14986
  const abs = resolveCliPath(docPath);
13950
- if (!fs8.existsSync(abs))
14987
+ if (!fs9.existsSync(abs))
13951
14988
  throw new Error(`knowledge doc not found: ${abs}`);
13952
- const text = fs8.readFileSync(abs, "utf8");
14989
+ const text = fs9.readFileSync(abs, "utf8");
13953
14990
  const violations = [];
13954
14991
  const schema = validateSchemaYaml(text);
13955
14992
  printChecklist("compound validate (schema)", schema);
@@ -14039,21 +15076,19 @@ skillCommand.command("lint").description("Lint <skill-dir>/SKILL.md: frontmatter
14039
15076
  try {
14040
15077
  if (!skillDir)
14041
15078
  throw new SddScriptError("usage: skill lint <skill-dir>", 2);
14042
- const skillFile = path12.join(resolveCliPath(skillDir), "SKILL.md");
14043
- if (!fs8.existsSync(skillFile))
15079
+ const skillFile = path14.join(resolveCliPath(skillDir), "SKILL.md");
15080
+ if (!fs9.existsSync(skillFile))
14044
15081
  throw new Error(`SKILL.md not found: ${skillFile}`);
14045
- const text = fs8.readFileSync(skillFile, "utf8");
15082
+ const text = fs9.readFileSync(skillFile, "utf8");
14046
15083
  const violations = [];
14047
15084
  const frontmatter = lintSkillFrontmatter(text);
14048
15085
  printChecklist("skill lint (frontmatter)", frontmatter);
14049
15086
  violations.push(...frontmatter.violations);
14050
- const skillBase = path12.basename(path12.dirname(skillFile));
14051
- const isCore = skillBase === "mstar-harness-core";
14052
- const fiveQuestionMode = skillBase.startsWith("mstar-") && !isCore && skillBase !== "mstar-skill-authoring" ? "runtime" : "authoring";
14053
- if (isCore) {
15087
+ const profile = classifySkillLint(path14.basename(path14.dirname(skillFile)));
15088
+ if (profile.mode === null) {
14054
15089
  console.log(import_picocolors2.default.yellow("skill lint (five questions): EXEMPT \u2014 mstar-harness-core is exempt by design (hub headings)"));
14055
15090
  } else {
14056
- const fiveQuestion = lintFiveQuestion(stripFrontmatter(text), fiveQuestionMode);
15091
+ const fiveQuestion = lintFiveQuestion(stripFrontmatter(text), profile.mode);
14057
15092
  printChecklist("skill lint (five questions)", fiveQuestion);
14058
15093
  violations.push(...fiveQuestion.violations);
14059
15094
  }
@@ -14080,20 +15115,20 @@ var rolesCommand = program2.command("roles").description("mstar-roles mapping /
14080
15115
  rolesCommand.command("validate").description("Validate the mstar-roles skill-dir state: role mapping / parameter tables against the on-disk " + "references layout plus load-order declarations across sibling mstar-* skills " + "(exit 1 on violations)").option("--roles-dir <dir>", "mstar-roles skill directory (default: skills/mstar-roles, resolved against the project root)").option("--skills-dir <dir>", "Skills root scanned for sibling mstar-* skills (default: parent of the roles dir)").action((options) => {
14081
15116
  try {
14082
15117
  const rolesDir = resolveCliPath(options.rolesDir ?? "skills/mstar-roles");
14083
- const skillsRoot = options.skillsDir ? resolveCliPath(options.skillsDir) : path12.dirname(rolesDir);
15118
+ const skillsRoot = options.skillsDir ? resolveCliPath(options.skillsDir) : path14.dirname(rolesDir);
14084
15119
  const violations = [];
14085
15120
  const mapping = validateRoleMapping(rolesDir);
14086
15121
  printChecklist("roles validate (mapping)", mapping);
14087
15122
  violations.push(...mapping.violations);
14088
15123
  const skillTexts = {};
14089
- for (const entry of fs8.readdirSync(skillsRoot, { withFileTypes: true })) {
15124
+ for (const entry of fs9.readdirSync(skillsRoot, { withFileTypes: true })) {
14090
15125
  if (!entry.isDirectory() || !entry.name.startsWith("mstar-"))
14091
15126
  continue;
14092
- const skillFile = path12.join(skillsRoot, entry.name, "SKILL.md");
14093
- if (!fs8.existsSync(skillFile))
15127
+ const skillFile = path14.join(skillsRoot, entry.name, "SKILL.md");
15128
+ if (!fs9.existsSync(skillFile))
14094
15129
  continue;
14095
15130
  try {
14096
- skillTexts[entry.name] = fs8.readFileSync(skillFile, "utf8");
15131
+ skillTexts[entry.name] = fs9.readFileSync(skillFile, "utf8");
14097
15132
  } catch {}
14098
15133
  }
14099
15134
  const loadOrder = lintLoadOrder(skillTexts);
@@ -14135,11 +15170,11 @@ function parsePrReviewTarget(raw) {
14135
15170
  prReviewCommand.command("tally").description("Compute the locked-formula tally, verdict and score from accepted findings JSON ([{mergeClass}]) plus the " + "leftover unmet-AC / unverified counts; prints the two-line chat header + structured result (pr-review.md \xA7 Tally)").requiredOption("--findings <file.json>", "Accepted findings JSON \u2014 array of {mergeClass: must-fix|should-fix|nit}").option("--unverified <n>", "Count of residual - unverified: items (default 0)").option("--unmet-ac-unsafe <n>", "Leftover unmet ACs that are unsafe-to-ship (each \u2192 must_fix + 1)").option("--unmet-ac-safe <n>", "Leftover unmet ACs that are ship-safe (each \u2192 should_fix + 1)").action((options) => {
14136
15171
  try {
14137
15172
  const findingsPath = resolveCliPath(options.findings);
14138
- if (!fs8.existsSync(findingsPath))
15173
+ if (!fs9.existsSync(findingsPath))
14139
15174
  throw new Error(`findings file not found: ${findingsPath}`);
14140
15175
  let parsed;
14141
15176
  try {
14142
- parsed = JSON.parse(fs8.readFileSync(findingsPath, "utf8"));
15177
+ parsed = JSON.parse(fs9.readFileSync(findingsPath, "utf8"));
14143
15178
  } catch (error) {
14144
15179
  throw new Error(`--findings is not valid JSON: ${error.message}`);
14145
15180
  }
@@ -14217,9 +15252,9 @@ prReviewCommand.command("report-path").description("Resolve the local-report (or
14217
15252
  prReviewCommand.command("validate-report").description("Validate a saved local PR-review report against the machine-readable contract (frontmatter fields, verdict-from-tally, " + "locked-formula score recompute, comments tri-state; exit 1 with violations printed)").argument("<file.md>", "Saved report markdown file").action((reportFile) => {
14218
15253
  try {
14219
15254
  const abs = resolveCliPath(reportFile);
14220
- if (!fs8.existsSync(abs))
15255
+ if (!fs9.existsSync(abs))
14221
15256
  throw new Error(`report file not found: ${abs}`);
14222
- const gate2 = validatePrReviewReport(fs8.readFileSync(abs, "utf8"));
15257
+ const gate2 = validatePrReviewReport(fs9.readFileSync(abs, "utf8"));
14223
15258
  printChecklist(abs, gate2);
14224
15259
  if (!gate2.ok)
14225
15260
  process.exitCode = 1;
@@ -14312,13 +15347,13 @@ function parseFindingEntry(entry, index) {
14312
15347
  const rec = entry;
14313
15348
  if (rec.path === undefined && rec.body === undefined && rec.line === undefined)
14314
15349
  return null;
14315
- const path13 = typeof rec.path === "string" ? rec.path : "";
15350
+ const path15 = typeof rec.path === "string" ? rec.path : "";
14316
15351
  const body = typeof rec.body === "string" ? rec.body : "";
14317
15352
  const line = typeof rec.line === "number" ? rec.line : Number.NaN;
14318
- if (!path13.trim() || !body.trim() || !Number.isInteger(line) || line < 1) {
15353
+ if (!path15.trim() || !body.trim() || !Number.isInteger(line) || line < 1) {
14319
15354
  throw new Error(`findings[${index}] must be an object {path: string, line: number >= 1, body: string} - got ${JSON.stringify(entry)}`);
14320
15355
  }
14321
- return { path: path13, line, side: "RIGHT", body };
15356
+ return { path: path15, line, side: "RIGHT", body };
14322
15357
  }
14323
15358
  prReviewCommand.command("post").description("Build and POST the GitHub Review per pr-review.md \xA7 Comment posting procedure: resolves the BASE owner/repo " + "from the PR url only (never headRepository), event is always COMMENT, posts via gh api with the payload on stdin, " + "applies the at-most-once 422 fallback (drop rejected inline entries and fold them into the body); prints review_url " + "(exit 1 = auth/API failure -> comments: failed)").requiredOption("--pr <n>", "PR number").requiredOption("--body-file <path>", "Review body markdown file").option("--findings <file.json>", "Optional inline comments JSON \u2014 array of {path, line, body} entries").action((options) => {
14324
15359
  try {
@@ -14327,17 +15362,17 @@ prReviewCommand.command("post").description("Build and POST the GitHub Review pe
14327
15362
  }
14328
15363
  const prNumber = Number(options.pr);
14329
15364
  const bodyPath = resolveCliPath(options.bodyFile);
14330
- if (!fs8.existsSync(bodyPath))
15365
+ if (!fs9.existsSync(bodyPath))
14331
15366
  throw new Error(`body file not found: ${bodyPath}`);
14332
- const body = fs8.readFileSync(bodyPath, "utf8");
15367
+ const body = fs9.readFileSync(bodyPath, "utf8");
14333
15368
  let comments = [];
14334
15369
  if (options.findings !== undefined) {
14335
15370
  const findingsPath = resolveCliPath(options.findings);
14336
- if (!fs8.existsSync(findingsPath))
15371
+ if (!fs9.existsSync(findingsPath))
14337
15372
  throw new Error(`findings file not found: ${findingsPath}`);
14338
15373
  let parsed;
14339
15374
  try {
14340
- parsed = JSON.parse(fs8.readFileSync(findingsPath, "utf8"));
15375
+ parsed = JSON.parse(fs9.readFileSync(findingsPath, "utf8"));
14341
15376
  } catch (error) {
14342
15377
  throw new Error(`--findings is not valid JSON: ${error.message}`);
14343
15378
  }
@@ -14441,7 +15476,7 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
14441
15476
  throw new SddScriptError("usage: pr-review worktree-setup \u2014 the five input modes are mutually exclusive", 2);
14442
15477
  }
14443
15478
  const startDir = process.cwd();
14444
- if (!fs8.existsSync(path12.join(startDir, ".git")) && gitIf(["rev-parse", "--git-dir"], startDir) === "") {
15479
+ if (!fs9.existsSync(path14.join(startDir, ".git")) && gitIf(["rev-parse", "--git-dir"], startDir) === "") {
14445
15480
  throw new Error(`not a git repository: ${startDir}`);
14446
15481
  }
14447
15482
  const repoRoot = gitSync(["rev-parse", "--show-toplevel"], startDir);
@@ -14515,15 +15550,15 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
14515
15550
  const baseCandidate = mode === "pr" ? namePrNumber : Number(String(Math.abs([...headSpec].reduce((h, ch) => (h * 31 + ch.charCodeAt(0)) % 1000003, 7))));
14516
15551
  const reviewBranch = pickReviewBranchName(existing, baseCandidate === 0 ? 1 : baseCandidate, cliToday().replace(/-/g, ""));
14517
15552
  const branchSuffix = mode === "pr" ? "" : `-${headSpec.slice(0, 8)}`;
14518
- const worktreePath = path12.resolve(options.path ?? path12.join(repoRoot, ".worktrees", `review-${reviewBranch}${branchSuffix}`));
15553
+ const worktreePath = path14.resolve(options.path ?? path14.join(repoRoot, ".worktrees", `review-${reviewBranch}${branchSuffix}`));
14519
15554
  if (options.path === undefined) {
14520
- fs8.mkdirSync(path12.join(repoRoot, ".worktrees"), { recursive: true });
15555
+ fs9.mkdirSync(path14.join(repoRoot, ".worktrees"), { recursive: true });
14521
15556
  if (gitIf(["check-ignore", ".worktrees/"], repoRoot) === "") {
14522
- const excludePath = path12.join(repoRoot, ".git", "info", "exclude");
14523
- const existing2 = fs8.existsSync(excludePath) ? fs8.readFileSync(excludePath, "utf8") : "";
15557
+ const excludePath = path14.join(repoRoot, ".git", "info", "exclude");
15558
+ const existing2 = fs9.existsSync(excludePath) ? fs9.readFileSync(excludePath, "utf8") : "";
14524
15559
  if (!existing2.split(`
14525
15560
  `).some((line) => line.trim() === ".worktrees/")) {
14526
- fs8.appendFileSync(excludePath, `${existing2 === "" || existing2.endsWith(`
15561
+ fs9.appendFileSync(excludePath, `${existing2 === "" || existing2.endsWith(`
14527
15562
  `) ? "" : `
14528
15563
  `}.worktrees/
14529
15564
  `);
@@ -14551,7 +15586,7 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
14551
15586
  let sidecarFd;
14552
15587
  const cleanupOnFailure = (branchToDelete) => {
14553
15588
  try {
14554
- if (fs8.existsSync(worktreePath))
15589
+ if (fs9.existsSync(worktreePath))
14555
15590
  gitSync(["worktree", "remove", "--force", worktreePath], repoRoot);
14556
15591
  gitSync(["worktree", "prune"], repoRoot);
14557
15592
  if (branchToDelete !== "" && !existing.has(branchToDelete)) {
@@ -14642,7 +15677,7 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
14642
15677
  diffFileSha256: createHash("sha256").update(snapshot).digest("hex")
14643
15678
  };
14644
15679
  try {
14645
- sidecarFd = fs8.openSync(sidecarPath, "wx+");
15680
+ sidecarFd = fs9.openSync(sidecarPath, "wx+");
14646
15681
  } catch (error) {
14647
15682
  if (error.code !== "EEXIST" && error.code !== "EISDIR")
14648
15683
  throw error;
@@ -14651,21 +15686,21 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
14651
15686
  writeFdSync(sidecarFd, Buffer.from(JSON.stringify(sidecar2, null, 2), "utf8"));
14652
15687
  wroteSidecar = true;
14653
15688
  try {
14654
- fs8.writeFileSync(diffFile, snapshot, { flag: "wx" });
15689
+ fs9.writeFileSync(diffFile, snapshot, { flag: "wx" });
14655
15690
  } catch (error) {
14656
15691
  if (error.code !== "EEXIST" && error.code !== "EISDIR")
14657
15692
  throw error;
14658
15693
  throw new Error(`refusing to overwrite pre-existing non-snapshot path ${diffFile}`);
14659
15694
  }
14660
15695
  wroteSnapshot = true;
14661
- const snapshotStat = fs8.lstatSync(diffFile);
15696
+ const snapshotStat = fs9.lstatSync(diffFile);
14662
15697
  sidecar2.diffFileDev = snapshotStat.dev;
14663
15698
  sidecar2.diffFileIno = String(snapshotStat.ino);
14664
15699
  sidecar2.diffFileMtimeMs = snapshotStat.mtimeMs;
14665
15700
  pendingSidecar = sidecar2;
14666
- fs8.ftruncateSync(sidecarFd, 0);
15701
+ fs9.ftruncateSync(sidecarFd, 0);
14667
15702
  writeFdSync(sidecarFd, Buffer.from(JSON.stringify(sidecar2, null, 2), "utf8"));
14668
- fs8.closeSync(sidecarFd);
15703
+ fs9.closeSync(sidecarFd);
14669
15704
  sidecarFd = undefined;
14670
15705
  return sidecar2;
14671
15706
  };
@@ -14689,20 +15724,21 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
14689
15724
  }
14690
15725
  });
14691
15726
  function prReviewArtifactPathFor(worktreePath, suffix) {
14692
- const parent = path12.dirname(path12.resolve(worktreePath));
14693
- const name = path12.basename(path12.resolve(worktreePath));
14694
- return path12.join(parent, `.${name}.prreview.${suffix}`);
15727
+ const parent = path14.dirname(worktreePath);
15728
+ const name = path14.basename(worktreePath);
15729
+ const prefix = parent.endsWith(path14.sep) ? parent : parent + path14.sep;
15730
+ return `${prefix}.${name}.prreview.${suffix}`;
14695
15731
  }
14696
15732
  function writeFdSync(fd, buf) {
14697
15733
  let written = 0;
14698
15734
  while (written < buf.length)
14699
- written += fs8.writeSync(fd, buf, written, buf.length - written, written);
15735
+ written += fs9.writeSync(fd, buf, written, buf.length - written, written);
14700
15736
  }
14701
15737
  function removeOwnedSnapshotFile(worktreePath, sidecar) {
14702
15738
  const snapshotPath = prReviewArtifactPathFor(worktreePath, "diff");
14703
15739
  let fd;
14704
15740
  try {
14705
- fd = fs8.openSync(snapshotPath, "r");
15741
+ fd = fs9.openSync(snapshotPath, "r");
14706
15742
  } catch (error) {
14707
15743
  if (error.code === "ENOENT")
14708
15744
  return;
@@ -14710,7 +15746,7 @@ function removeOwnedSnapshotFile(worktreePath, sidecar) {
14710
15746
  return;
14711
15747
  }
14712
15748
  try {
14713
- const st = fs8.fstatSync(fd);
15749
+ const st = fs9.fstatSync(fd);
14714
15750
  if (!st.isFile())
14715
15751
  return;
14716
15752
  const recordedIno = sidecar.diffFileIno;
@@ -14727,28 +15763,28 @@ function removeOwnedSnapshotFile(worktreePath, sidecar) {
14727
15763
  }
14728
15764
  const tmp = `${snapshotPath}.cleanup.${process.pid}.${randomUUID3()}`;
14729
15765
  try {
14730
- fs8.renameSync(snapshotPath, tmp);
15766
+ fs9.renameSync(snapshotPath, tmp);
14731
15767
  } catch (error) {
14732
15768
  console.error(import_picocolors2.default.yellow(`worktree-cleanup: snapshot at ${snapshotPath} left in place (cannot detach: ${error.message})`));
14733
15769
  return;
14734
15770
  }
14735
- const st2 = fs8.fstatSync(fd);
15771
+ const st2 = fs9.fstatSync(fd);
14736
15772
  let tmpStat;
14737
15773
  try {
14738
- tmpStat = fs8.lstatSync(tmp);
15774
+ tmpStat = fs9.lstatSync(tmp);
14739
15775
  } catch {
14740
15776
  tmpStat = undefined;
14741
15777
  }
14742
15778
  if (tmpStat !== undefined && tmpStat.ino === st2.ino && tmpStat.dev === st2.dev && st2.nlink === 1 && tmpStat.nlink === 1) {
14743
- fs8.unlinkSync(tmp);
14744
- const st3 = fs8.fstatSync(fd);
15779
+ fs9.unlinkSync(tmp);
15780
+ const st3 = fs9.fstatSync(fd);
14745
15781
  if (st3.nlink !== 0) {
14746
15782
  console.error(import_picocolors2.default.yellow(`worktree-cleanup: unlink at ${tmp} detached a pathname replacement, not the verified snapshot inode (${snapshotPath} still holds ${st3.nlink} link(s)) - the replacement is gone, the verified snapshot was NOT deleted`));
14747
15783
  }
14748
15784
  } else {
14749
15785
  try {
14750
- fs8.linkSync(tmp, snapshotPath);
14751
- fs8.unlinkSync(tmp);
15786
+ fs9.linkSync(tmp, snapshotPath);
15787
+ fs9.unlinkSync(tmp);
14752
15788
  } catch (error) {
14753
15789
  if (error.code === "EEXIST") {
14754
15790
  console.error(import_picocolors2.default.yellow(`worktree-cleanup: snapshot replacement left at ${tmp} (snapshot path was recreated concurrently)`));
@@ -14758,41 +15794,41 @@ function removeOwnedSnapshotFile(worktreePath, sidecar) {
14758
15794
  }
14759
15795
  }
14760
15796
  } finally {
14761
- fs8.closeSync(fd);
15797
+ fs9.closeSync(fd);
14762
15798
  }
14763
15799
  }
14764
15800
  function removeOwnedFreshSidecarFile(sidecarFd, worktreePath) {
14765
15801
  const sidecarPath = prReviewArtifactPathFor(worktreePath, "json");
14766
15802
  try {
14767
- const st = fs8.fstatSync(sidecarFd);
15803
+ const st = fs9.fstatSync(sidecarFd);
14768
15804
  if (!st.isFile() || st.nlink !== 1) {
14769
15805
  console.error(import_picocolors2.default.yellow(`worktree-setup rollback: sidecar at ${sidecarPath} left in place (identity no longer held)`));
14770
15806
  return;
14771
15807
  }
14772
15808
  const tmp = `${sidecarPath}.cleanup.${process.pid}.${randomUUID3()}`;
14773
15809
  try {
14774
- fs8.renameSync(sidecarPath, tmp);
15810
+ fs9.renameSync(sidecarPath, tmp);
14775
15811
  } catch (error) {
14776
15812
  console.error(import_picocolors2.default.yellow(`worktree-setup rollback: sidecar at ${sidecarPath} left in place (cannot detach: ${error.message})`));
14777
15813
  return;
14778
15814
  }
14779
- const st2 = fs8.fstatSync(sidecarFd);
15815
+ const st2 = fs9.fstatSync(sidecarFd);
14780
15816
  let tmpStat;
14781
15817
  try {
14782
- tmpStat = fs8.lstatSync(tmp);
15818
+ tmpStat = fs9.lstatSync(tmp);
14783
15819
  } catch {
14784
15820
  tmpStat = undefined;
14785
15821
  }
14786
15822
  if (tmpStat !== undefined && tmpStat.ino === st2.ino && tmpStat.dev === st2.dev) {
14787
- fs8.unlinkSync(tmp);
14788
- const st3 = fs8.fstatSync(sidecarFd);
15823
+ fs9.unlinkSync(tmp);
15824
+ const st3 = fs9.fstatSync(sidecarFd);
14789
15825
  if (st3.nlink !== 0) {
14790
15826
  console.error(import_picocolors2.default.yellow(`worktree-setup rollback: unlink at ${tmp} detached a pathname replacement, not the verified sidecar inode (${sidecarPath} still holds ${st3.nlink} link(s)) - the replacement is gone, the verified sidecar was NOT deleted`));
14791
15827
  }
14792
15828
  } else {
14793
15829
  try {
14794
- fs8.linkSync(tmp, sidecarPath);
14795
- fs8.unlinkSync(tmp);
15830
+ fs9.linkSync(tmp, sidecarPath);
15831
+ fs9.unlinkSync(tmp);
14796
15832
  } catch (error) {
14797
15833
  if (error.code === "EEXIST") {
14798
15834
  console.error(import_picocolors2.default.yellow(`worktree-setup rollback: sidecar replacement left at ${tmp} (sidecar path was recreated concurrently)`));
@@ -14803,24 +15839,24 @@ function removeOwnedFreshSidecarFile(sidecarFd, worktreePath) {
14803
15839
  }
14804
15840
  } finally {
14805
15841
  try {
14806
- fs8.closeSync(sidecarFd);
15842
+ fs9.closeSync(sidecarFd);
14807
15843
  } catch {}
14808
15844
  }
14809
15845
  }
14810
15846
  prReviewCommand.command("worktree-cleanup").description("Remove the review worktree per pr-review.md \xA7 Worktree isolation cleanup: refuses unless --report-saved is given OR the " + "setup sidecar records report-saved; removes the worktree, prunes, and deletes EXACTLY the recorded review branch \u2014 a " + "--branch argument that disagrees with the sidecar is refused (never delete a foreign/pre-existing branch)").requiredOption("--path <dir>", "Worktree directory created by worktree-setup").requiredOption("--branch <name>", "The recorded review branch (must match the setup sidecar for PR mode)").option("--report-saved", "Assert the local report has been saved before removal").action((options) => {
14811
15847
  try {
14812
- const worktreePath = path12.resolve(resolveCliPath(options.path));
15848
+ const worktreePath = path14.resolve(resolveCliPath(options.path));
14813
15849
  const sidecarPath = prReviewArtifactPathFor(worktreePath, "json");
14814
- if (!fs8.existsSync(sidecarPath)) {
15850
+ if (!fs9.existsSync(sidecarPath)) {
14815
15851
  throw new Error(`no setup sidecar found at ${sidecarPath} - run pr-review worktree-setup first (foreign worktrees are never cleaned here)`);
14816
15852
  }
14817
15853
  let sidecar;
14818
15854
  try {
14819
- sidecar = JSON.parse(fs8.readFileSync(sidecarPath, "utf8"));
15855
+ sidecar = JSON.parse(fs9.readFileSync(sidecarPath, "utf8"));
14820
15856
  } catch (error) {
14821
15857
  throw new Error(`setup sidecar at ${sidecarPath} is not valid JSON: ${error.message}`);
14822
15858
  }
14823
- const gitRoot = typeof sidecar.repoRoot === "string" && sidecar.repoRoot !== "" ? sidecar.repoRoot : path12.dirname(worktreePath);
15859
+ const gitRoot = typeof sidecar.repoRoot === "string" && sidecar.repoRoot !== "" ? sidecar.repoRoot : path14.dirname(worktreePath);
14824
15860
  if (sidecar.reviewBranch === "") {
14825
15861
  if (options.branch !== "") {
14826
15862
  throw new Error(`this setup recorded no review branch (detached review) - refusing ${JSON.stringify(options.branch)} as a foreign branch`);
@@ -14832,7 +15868,7 @@ prReviewCommand.command("worktree-cleanup").description("Remove the review workt
14832
15868
  if (!savedOk) {
14833
15869
  throw new Error("refusing cleanup: the local report is not saved yet - save it first or pass --report-saved (\xA7 Local report archive)");
14834
15870
  }
14835
- if (fs8.existsSync(worktreePath)) {
15871
+ if (fs9.existsSync(worktreePath)) {
14836
15872
  gitSync(["worktree", "remove", worktreePath], gitRoot);
14837
15873
  }
14838
15874
  gitSync(["worktree", "prune"], gitRoot);
@@ -14843,7 +15879,7 @@ prReviewCommand.command("worktree-cleanup").description("Remove the review workt
14843
15879
  gitSync(["branch", "-D", sidecar.reviewBranch], gitRoot);
14844
15880
  }
14845
15881
  removeOwnedSnapshotFile(worktreePath, sidecar);
14846
- fs8.rmSync(sidecarPath, { force: true });
15882
+ fs9.rmSync(sidecarPath, { force: true });
14847
15883
  console.log(import_picocolors2.default.green(`worktree-cleanup: removed ${worktreePath}${sidecar.reviewBranch !== "" ? ` + deleted ${sidecar.reviewBranch}` : " (no local branch to delete)"}`));
14848
15884
  } catch (error) {
14849
15885
  failScript(error, "pr-review worktree-cleanup");
@@ -14901,17 +15937,17 @@ prReviewCommand.command("seat-prompt").description("Generate the read-only audit
14901
15937
  if (tier !== undefined && tier !== "quick" && tier !== "default" && tier !== "deep") {
14902
15938
  throw new SddScriptError(`usage: pr-review seat-prompt \u2014 --tier must be quick | default | deep, got ${JSON.stringify(tier)}`, 2);
14903
15939
  }
14904
- const auditSkillRoot = options.skillRoot !== undefined ? path12.resolve(resolveCliPath(options.skillRoot)) : path12.resolve(resolveCliPath("skills/mstar-audit"));
15940
+ const auditSkillRoot = options.skillRoot !== undefined ? path14.resolve(resolveCliPath(options.skillRoot)) : path14.resolve(resolveCliPath("skills/mstar-audit"));
14905
15941
  const prompt = prReviewSeatPrompt({
14906
15942
  stage: options.stage === "1" ? 1 : 2,
14907
15943
  domain: options.domain,
14908
15944
  seat: options.seat,
14909
15945
  skillRoot: auditSkillRoot,
14910
- worktreePath: path12.resolve(options.worktree),
15946
+ worktreePath: path14.resolve(options.worktree),
14911
15947
  reconFacts: options.recon ?? [],
14912
15948
  ...options.security === true ? { securitySeat: true } : {},
14913
15949
  ...tier !== undefined ? { tier } : {},
14914
- ...options.diffFile !== undefined && options.diffFile !== "" ? { diffFile: path12.resolve(resolveCliPath(options.diffFile)) } : {},
15950
+ ...options.diffFile !== undefined && options.diffFile !== "" ? { diffFile: path14.resolve(resolveCliPath(options.diffFile)) } : {},
14915
15951
  ...options.collectFolded === true ? { collectFolded: true } : {}
14916
15952
  });
14917
15953
  console.log(prompt);