@mstar-harness/cli 3.7.0 → 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 +743 -338
  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,21 +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";
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
4109
  import { execFileSync as execFileSync3, spawn } 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";
4110
+ import { mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as readFileSync7, realpathSync as realpathSync4, statSync as statSync4, writeFileSync as writeFileSync4 } from "node:fs";
4111
4111
  import { constants as osConstants } from "node:os";
4112
- import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute6, join as join10, relative as relative3, resolve as resolve9 } from "node:path";
4112
+ import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute6, join as join11, relative as relative3, resolve as resolve9 } from "node:path";
4113
4113
  import { execFileSync as execFileSync4 } from "node:child_process";
4114
- import { existsSync as existsSync8, mkdirSync as mkdirSync8, readdirSync as readdirSync8, readFileSync as readFileSync9, rmdirSync as rmdirSync2, rmSync, writeFileSync as writeFileSync6 } from "node:fs";
4115
- import { basename as basename5, join as join12, resolve as resolve11, sep as sep3 } from "node:path";
4116
- import { existsSync as existsSync9, readdirSync as readdirSync9, readFileSync as readFileSync10 } from "node:fs";
4117
- import { basename as basename6, isAbsolute as isAbsolute8, join as join13, relative as relative5, resolve as resolve12, sep as sep4 } from "node:path";
4118
- import { existsSync as existsSync10 } from "node:fs";
4119
- 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";
4120
4120
  import { readdirSync as readdirSync10 } from "node:fs";
4121
- import { isAbsolute as isAbsolute9, join as join15 } from "node:path";
4121
+ import { isAbsolute as isAbsolute9, join as join17 } from "node:path";
4122
4122
  var SEVERITY_ORDER = ["critical", "high", "medium", "low", "nit"];
4123
4123
  function readJson(filePath) {
4124
4124
  if (!existsSync(filePath))
@@ -5946,6 +5946,51 @@ function probeBranch(worktreePath, opts) {
5946
5946
  return { error: detail };
5947
5947
  }
5948
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
+ }
5949
5994
  function l1PreDispatchCheck(input, opts = {}) {
5950
5995
  const violations = [];
5951
5996
  const { controlWorktreePath, leaseWorktreePath, leaseWorkingBranch, planId } = input;
@@ -5958,8 +6003,20 @@ function l1PreDispatchCheck(input, opts = {}) {
5958
6003
  if (leaseWorkingBranch.trim() === "") {
5959
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"));
5960
6005
  }
5961
- if (controlWorktreePath !== "" && leaseWorktreePath !== "" && resolve8(controlWorktreePath) === resolve8(leaseWorktreePath)) {
5962
- 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
+ }
5963
6020
  }
5964
6021
  if (leaseWorktreePath !== "" && !existsSync7(leaseWorktreePath)) {
5965
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>`));
@@ -6070,14 +6127,14 @@ function gitOut(cwd, args) {
6070
6127
  }
6071
6128
  }
6072
6129
  function probeHarnessWithStatus(root) {
6073
- if (isFile2(join10(root, ".mstar", "status.json")))
6074
- return join10(root, ".mstar");
6075
- if (isFile2(join10(root, ".agents", "status.json")))
6076
- return join10(root, ".agents");
6077
- if (hasWorkflowSnapshot(join10(root, ".mstar")))
6078
- return join10(root, ".mstar");
6079
- if (hasWorkflowSnapshot(join10(root, ".agents")))
6080
- 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");
6081
6138
  return null;
6082
6139
  }
6083
6140
  function hasWorkflowSnapshot(harnessDir) {
@@ -6085,13 +6142,13 @@ function hasWorkflowSnapshot(harnessDir) {
6085
6142
  try {
6086
6143
  workflowsDir = resolveWorkflowDir(harnessDir, { harnessDir });
6087
6144
  } catch {
6088
- workflowsDir = join10(harnessDir, "workflows");
6145
+ workflowsDir = join11(harnessDir, "workflows");
6089
6146
  }
6090
6147
  if (!isDirectory2(workflowsDir))
6091
6148
  return false;
6092
6149
  try {
6093
6150
  for (const entry of readdirSync6(workflowsDir, { withFileTypes: true })) {
6094
- if (entry.isDirectory() && isFile2(join10(workflowsDir, entry.name, "snapshot.json")))
6151
+ if (entry.isDirectory() && isFile2(join11(workflowsDir, entry.name, "snapshot.json")))
6095
6152
  return true;
6096
6153
  }
6097
6154
  } catch {
@@ -6104,14 +6161,14 @@ function isLinkedWorktree(root) {
6104
6161
  const commonRaw = gitOut(root, ["rev-parse", "--git-common-dir"]);
6105
6162
  if (gitDirRaw === null || commonRaw === null)
6106
6163
  return false;
6107
- const gitDir = isAbsolute6(gitDirRaw) ? gitDirRaw : join10(root, gitDirRaw);
6108
- 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);
6109
6166
  if (gitDir.includes("/.git/worktrees/") || gitDir.includes("/worktrees/"))
6110
6167
  return true;
6111
6168
  try {
6112
- const gdParent = realpathSync3(dirname6(gitDir));
6113
- const cmAbs = realpathSync3(common2);
6114
- 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;
6115
6172
  } catch {
6116
6173
  return false;
6117
6174
  }
@@ -6128,10 +6185,10 @@ function sddWorkspace(planId, opts = {}) {
6128
6185
  if (!isDirectory2(controlRoot)) {
6129
6186
  throw new SddScriptError(`mstar sdd workspace: CONTROL_ROOT / MSTAR_CONTROL_ROOT is not a directory: ${controlRoot}`, 1);
6130
6187
  }
6131
- root = realpathSync3(controlRoot);
6188
+ root = realpathSync4(controlRoot);
6132
6189
  } else {
6133
6190
  const topLevel = gitOut(cwd, ["rev-parse", "--show-toplevel"]);
6134
- root = realpathSync3(topLevel ?? cwd);
6191
+ root = realpathSync4(topLevel ?? cwd);
6135
6192
  }
6136
6193
  if (!controlRoot && isLinkedWorktree(root)) {
6137
6194
  throw new SddScriptError(`mstar sdd workspace: linked worktree at ${root} has no {HARNESS_DIR}/status.json (default gitignore).
@@ -6152,20 +6209,20 @@ function sddWorkspace(planId, opts = {}) {
6152
6209
  const probed = probeHarnessWithStatus(root);
6153
6210
  if (probed) {
6154
6211
  harnessDir = probed;
6155
- } else if (isDirectory2(join10(root, ".mstar"))) {
6156
- harnessDir = join10(root, ".mstar");
6157
- } else if (isDirectory2(join10(root, ".agents"))) {
6158
- 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");
6159
6216
  } else {
6160
- harnessDir = join10(root, ".mstar");
6217
+ harnessDir = join11(root, ".mstar");
6161
6218
  }
6162
6219
  }
6163
6220
  }
6164
6221
  const sddDir = resolveSddDir(harnessDir, planId);
6165
6222
  mkdirSync6(sddDir, { recursive: true });
6166
- writeFileSync4(join10(sddDir, ".gitignore"), `*
6223
+ writeFileSync4(join11(sddDir, ".gitignore"), `*
6167
6224
  `);
6168
- return realpathSync3(sddDir);
6225
+ return realpathSync4(sddDir);
6169
6226
  }
6170
6227
  function taskBrief(planFile, taskN, outFile, opts = {}) {
6171
6228
  if (!planFile || !Number.isInteger(taskN) || taskN < 1) {
@@ -6192,7 +6249,7 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
6192
6249
  if (outFile) {
6193
6250
  out = bound ? resolve9(observedCwd, outFile) : outFile;
6194
6251
  } else if (bound) {
6195
- out = join10(bound.sddDir, `task-${taskN}-brief.md`);
6252
+ out = join11(bound.sddDir, `task-${taskN}-brief.md`);
6196
6253
  mkdirAfterGate = bound.sddDir;
6197
6254
  } else {
6198
6255
  const sddDir = opts.sddDir ?? process.env.SDD_DIR;
@@ -6200,7 +6257,7 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
6200
6257
  throw new SddScriptError("mstar sdd task-brief: set SDD_DIR or pass OUTFILE (run mstar sdd workspace PLAN_ID first)", 2);
6201
6258
  }
6202
6259
  mkdirSync6(sddDir, { recursive: true });
6203
- out = join10(sddDir, `task-${taskN}-brief.md`);
6260
+ out = join11(sddDir, `task-${taskN}-brief.md`);
6204
6261
  }
6205
6262
  if (bound) {
6206
6263
  const gate2 = checkSddAction(bound, { kind: "artifact", cwd: observedCwd, target: out });
@@ -6258,7 +6315,7 @@ function reviewPackage(base, head, outFile, opts = {}) {
6258
6315
  } else if (bound) {
6259
6316
  const shortBase = gitOut(cwd, ["rev-parse", "--short", base]) ?? base;
6260
6317
  const shortHead = gitOut(cwd, ["rev-parse", "--short", head]) ?? head;
6261
- out = join10(bound.sddDir, `review-${shortBase}..${shortHead}.diff`);
6318
+ out = join11(bound.sddDir, `review-${shortBase}..${shortHead}.diff`);
6262
6319
  mkdirAfterGate = bound.sddDir;
6263
6320
  } else {
6264
6321
  const sddDir = opts.sddDir ?? process.env.SDD_DIR;
@@ -6268,7 +6325,7 @@ function reviewPackage(base, head, outFile, opts = {}) {
6268
6325
  mkdirSync6(sddDir, { recursive: true });
6269
6326
  const shortBase = gitOut(cwd, ["rev-parse", "--short", base]) ?? base;
6270
6327
  const shortHead = gitOut(cwd, ["rev-parse", "--short", head]) ?? head;
6271
- out = join10(sddDir, `review-${shortBase}..${shortHead}.diff`);
6328
+ out = join11(sddDir, `review-${shortBase}..${shortHead}.diff`);
6272
6329
  }
6273
6330
  if (bound) {
6274
6331
  const gate2 = checkSddAction(bound, { kind: "artifact", cwd: observedCwd, target: out });
@@ -6305,7 +6362,7 @@ function isInside(child, ancestor) {
6305
6362
  }
6306
6363
  function canonicalDir(path2) {
6307
6364
  try {
6308
- return statSync4(path2).isDirectory() ? realpathSync3(path2) : null;
6365
+ return statSync4(path2).isDirectory() ? realpathSync4(path2) : null;
6309
6366
  } catch {
6310
6367
  return null;
6311
6368
  }
@@ -6323,7 +6380,7 @@ function throwUsage(message) {
6323
6380
  throw new SddScriptError(message, 2);
6324
6381
  }
6325
6382
  function readActiveWorkflowIds(controlHarnessRoot) {
6326
- const statusPath = join10(controlHarnessRoot, "status.json");
6383
+ const statusPath = join11(controlHarnessRoot, "status.json");
6327
6384
  if (!isFile2(statusPath))
6328
6385
  return null;
6329
6386
  let doc;
@@ -6358,7 +6415,7 @@ function findWorkflowPlanRow(controlHarnessRoot, planId) {
6358
6415
  }
6359
6416
  const matches = [];
6360
6417
  for (const id of workflowIds) {
6361
- const snapshotPath = join10(workflowsDir, id, WORKFLOW_SNAPSHOT_FILE);
6418
+ const snapshotPath = join11(workflowsDir, id, WORKFLOW_SNAPSHOT_FILE);
6362
6419
  if (!isFile2(snapshotPath))
6363
6420
  continue;
6364
6421
  let doc;
@@ -6450,15 +6507,20 @@ function resolveSddExecutionContext(input) {
6450
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})`)
6451
6508
  ]);
6452
6509
  }
6453
- const controlCheckout = dirname6(canonicalControlHarnessRoot);
6454
- if (isInside(canonicalFeatureCwd, controlCheckout)) {
6510
+ if (isInside(canonicalControlHarnessRoot, canonicalFeatureCwd)) {
6455
6511
  throwGateFail([
6456
- contextViolation("critical", "sdd.context.feature-in-control", `featureCwd "${canonicalFeatureCwd}" is inside the control checkout "${controlCheckout}" \u2014 product edits never land in the control checkout (execution_lease.worktree_path MUST differ from metadata.control_worktree_path)`, "use a distinct feature worktree for the plan")
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`)
6457
6513
  ]);
6458
6514
  }
6459
- if (isInside(canonicalControlHarnessRoot, canonicalFeatureCwd)) {
6515
+ const controlCheckout = probeCheckoutRoot(canonicalControlHarnessRoot);
6516
+ if (controlCheckout === null) {
6460
6517
  throwGateFail([
6461
- 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`)
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>)")
6462
6524
  ]);
6463
6525
  }
6464
6526
  const match = findWorkflowPlanRow(canonicalControlHarnessRoot, planId);
@@ -6503,7 +6565,7 @@ function resolveSddExecutionContext(input) {
6503
6565
  controlHarnessRoot: canonicalControlHarnessRoot,
6504
6566
  featureCwd: canonicalFeatureCwd,
6505
6567
  workingBranch,
6506
- planFile: realpathSync3(input.planFile),
6568
+ planFile: realpathSync4(input.planFile),
6507
6569
  sddDir: canonicalSddDir
6508
6570
  };
6509
6571
  }
@@ -7310,7 +7372,7 @@ function scanSecrets(files) {
7310
7372
  unreadableFiles++;
7311
7373
  continue;
7312
7374
  }
7313
- const base = basename5(file);
7375
+ const base = basename6(file);
7314
7376
  for (const entry of NEVER_COMMIT_FILENAMES) {
7315
7377
  if (entry.re.test(base))
7316
7378
  findings.push({ file, line: 1, type: entry.type });
@@ -7367,7 +7429,7 @@ function rootLockfiles(root) {
7367
7429
  return [];
7368
7430
  }
7369
7431
  const names = new Set(LOCKFILE_NAMES);
7370
- 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));
7371
7433
  if (present.length === 0)
7372
7434
  return [];
7373
7435
  try {
@@ -7376,7 +7438,7 @@ function rootLockfiles(root) {
7376
7438
  encoding: "utf8",
7377
7439
  stdio: ["ignore", "pipe", "ignore"]
7378
7440
  }).split("\x00").filter((f) => f !== ""));
7379
- return present.filter((p) => tracked.has(basename5(p)));
7441
+ return present.filter((p) => tracked.has(basename6(p)));
7380
7442
  } catch {
7381
7443
  return present;
7382
7444
  }
@@ -7392,7 +7454,7 @@ function supplyChainChecks(repoRoot) {
7392
7454
  findings.push({ kind: "lockfile-duplicate", file: lockfiles.map((f) => f.replace(`${repoRoot}/`, "")).join(", ") });
7393
7455
  violations.push(violation9("medium", "audit.supply.lockfile-duplicate", `multiple lockfiles at ${repoRoot}: ${lockfiles.join(", ")}`, "keep exactly one lockfile per package manager"));
7394
7456
  }
7395
- const workflowsDir = join12(repoRoot, ".github", "workflows");
7457
+ const workflowsDir = join14(repoRoot, ".github", "workflows");
7396
7458
  let wfEntries = [];
7397
7459
  try {
7398
7460
  wfEntries = readdirSync8(workflowsDir, { withFileTypes: true });
@@ -7402,7 +7464,7 @@ function supplyChainChecks(repoRoot) {
7402
7464
  for (const entry of wfEntries) {
7403
7465
  if (!entry.isFile() || !/\.(?:ya?ml)$/.test(entry.name))
7404
7466
  continue;
7405
- const wfPath = join12(workflowsDir, entry.name);
7467
+ const wfPath = join14(workflowsDir, entry.name);
7406
7468
  const relPath = `.github/workflows/${entry.name}`;
7407
7469
  let text;
7408
7470
  try {
@@ -7559,8 +7621,8 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7559
7621
  const date = options.date ?? new Date().toISOString().slice(0, 10);
7560
7622
  const plannedAt = options.plannedAt ?? { commit: options.repoShortSha ?? "unknown", date };
7561
7623
  mkdirSync8(outDir, { recursive: true });
7562
- const existingReadme = join12(outDir, "README.md");
7563
- 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: [] };
7564
7626
  const existing = readdirSync8(outDir).filter((f) => /^\d{3}-.*\.md$/.test(f));
7565
7627
  let next = existing.reduce((max, f) => Math.max(max, Number(f.slice(0, 3))), 0) + 1;
7566
7628
  const redactedFindings = findings.map(redactFinding);
@@ -7577,13 +7639,13 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7577
7639
  }
7578
7640
  usedSlugs.add(slug);
7579
7641
  const file = `${num}-${slug}.md`;
7580
- writeFileSync6(join12(outDir, file), renderPlanFile(finding, plannedAt));
7642
+ writeFileSync6(join14(outDir, file), renderPlanFile(finding, plannedAt));
7581
7643
  written.push(file);
7582
7644
  next++;
7583
7645
  }
7584
7646
  const all = [...existing, ...written].sort();
7585
7647
  const rows = all.map((file) => {
7586
- const summary = readPlanFileSummary(join12(outDir, file));
7648
+ const summary = readPlanFileSummary(join14(outDir, file));
7587
7649
  const fields = summary.fields;
7588
7650
  return {
7589
7651
  num: file.slice(0, 3),
@@ -7617,7 +7679,7 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7617
7679
  });
7618
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;
7619
7681
  const hardeningCheckedLines = options.hardeningChecked !== undefined ? options.hardeningChecked.map((hc) => `- ${hc.kind}: ${escapeCell(redactText(hc.text))}`) : carried.hardeningChecked;
7620
- writeFileSync6(join12(outDir, "README.md"), renderIndex({
7682
+ writeFileSync6(join14(outDir, "README.md"), renderIndex({
7621
7683
  date,
7622
7684
  repoName: options.repoName ?? "repo",
7623
7685
  repoShortSha: options.repoShortSha ?? "unknown",
@@ -7626,7 +7688,7 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7626
7688
  needsVerification: needsVerificationLines,
7627
7689
  hardeningChecked: hardeningCheckedLines
7628
7690
  }));
7629
- return { outDir: resolve11(outDir), date, files: written, nextNumber: next };
7691
+ return { outDir: resolve12(outDir), date, files: written, nextNumber: next };
7630
7692
  }
7631
7693
  async function promoteAuditPlans(outDir, selected, options) {
7632
7694
  if (selected.length === 0) {
@@ -7635,19 +7697,19 @@ async function promoteAuditPlans(outDir, selected, options) {
7635
7697
  if (typeof options.harnessDir !== "string" || options.harnessDir.trim() === "") {
7636
7698
  throw new Error("promoteAuditPlans: options.harnessDir is required (must contain status.json + workflows/)");
7637
7699
  }
7638
- const workflowId = options.workflowId ?? basename5(resolve11(outDir));
7700
+ const workflowId = options.workflowId ?? basename6(resolve12(outDir));
7639
7701
  assertSafePathComponent(workflowId, "workflow id");
7640
- const harnessDir = resolve11(options.harnessDir);
7641
- const statusPath = join12(harnessDir, "status.json");
7642
- const workflowDir = join12(harnessDir, "workflows", workflowId);
7643
- 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);
7644
7706
  const planFiles = resolveSelectedPlanFiles(outDir, selected);
7645
7707
  const indexRows = readExecutionOrderIndex(outDir);
7646
7708
  const plans = planFiles.map((planFile) => {
7647
7709
  const stem = planFile.replace(/\.md$/, "");
7648
7710
  const num = stem.slice(0, 3);
7649
7711
  const indexRow = indexRows.get(num);
7650
- const title = indexRow?.title ?? readPlanFileSummary(join12(outDir, planFile)).title;
7712
+ const title = indexRow?.title ?? readPlanFileSummary(join14(outDir, planFile)).title;
7651
7713
  return {
7652
7714
  id: stem,
7653
7715
  title,
@@ -7676,7 +7738,7 @@ async function promoteAuditPlans(outDir, selected, options) {
7676
7738
  throw new Error(`refusing to register invalid workflow entry: ${entryGate.violations.map((v) => v.message).join("; ")}`);
7677
7739
  }
7678
7740
  await withStatusWriteLock(statusPath, async () => {
7679
- if (existsSync8(snapshotPath)) {
7741
+ if (existsSync9(snapshotPath)) {
7680
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`);
7681
7743
  }
7682
7744
  mkdirSync8(workflowDir, { recursive: true });
@@ -7712,7 +7774,7 @@ function resolveSelectedPlanFiles(outDir, selected) {
7712
7774
  for (const id of selected) {
7713
7775
  const file = byNum.get(id) ?? byStem.get(id) ?? byStem.get(id.replace(/\.md$/, ""));
7714
7776
  if (file === undefined) {
7715
- 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)}`);
7716
7778
  }
7717
7779
  if (!seen.has(file)) {
7718
7780
  seen.add(file);
@@ -7722,7 +7784,7 @@ function resolveSelectedPlanFiles(outDir, selected) {
7722
7784
  return resolved;
7723
7785
  }
7724
7786
  function readExecutionOrderIndex(outDir) {
7725
- const readmePath = join12(outDir, "README.md");
7787
+ const readmePath = join14(outDir, "README.md");
7726
7788
  let text;
7727
7789
  try {
7728
7790
  text = readFileSync9(readmePath, "utf8");
@@ -7751,7 +7813,7 @@ function readExecutionOrderIndex(outDir) {
7751
7813
  return rows;
7752
7814
  }
7753
7815
  function planFileRel(outDir, planFile) {
7754
- const resolved = resolve11(outDir);
7816
+ const resolved = resolve12(outDir);
7755
7817
  const parts = resolved.split(sep3);
7756
7818
  const plansIdx = parts.lastIndexOf("plans");
7757
7819
  if (plansIdx >= 0) {
@@ -8010,11 +8072,11 @@ function collectKnowledgeDocs(dir) {
8010
8072
  for (const entry of entries) {
8011
8073
  if (entry.isSymbolicLink())
8012
8074
  continue;
8013
- const full = join13(current, entry.name);
8075
+ const full = join15(current, entry.name);
8014
8076
  if (entry.isDirectory()) {
8015
8077
  stack.push(full);
8016
8078
  } else if (entry.name.endsWith(".md") && entry.name !== "README.md" && entry.name !== "index.md") {
8017
- docs.push(relative5(dir, full).split(sep4).join("/"));
8079
+ docs.push(relative6(dir, full).split(sep4).join("/"));
8018
8080
  }
8019
8081
  }
8020
8082
  }
@@ -8030,8 +8092,8 @@ function normalizeIndexRef(cell) {
8030
8092
  }
8031
8093
  function assertIndexRows(knowledgeDir) {
8032
8094
  const violations = [];
8033
- const readmePath = join13(knowledgeDir, "README.md");
8034
- if (!existsSync9(readmePath)) {
8095
+ const readmePath = join15(knowledgeDir, "README.md");
8096
+ if (!existsSync10(readmePath)) {
8035
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"));
8036
8098
  return { ok: false, violations };
8037
8099
  }
@@ -8055,12 +8117,12 @@ function assertIndexRows(knowledgeDir) {
8055
8117
  return { ok: violations.length === 0, violations };
8056
8118
  }
8057
8119
  function isFileLikeRoot(root) {
8058
- return /^[^.]*\.[A-Za-z0-9]{1,10}$/.test(basename6(root));
8120
+ return /^[^.]*\.[A-Za-z0-9]{1,10}$/.test(basename7(root));
8059
8121
  }
8060
8122
  function scopeGuard(path2, allowedRoots) {
8061
- const resolved = resolve12(path2);
8123
+ const resolved = resolve13(path2);
8062
8124
  for (const root of allowedRoots) {
8063
- const r = resolve12(root);
8125
+ const r = resolve13(root);
8064
8126
  if (isFileLikeRoot(r)) {
8065
8127
  if (resolved === r)
8066
8128
  return { ok: true, violations: [] };
@@ -8361,8 +8423,8 @@ function validateRoleMapping(rolesDir, options = {}) {
8361
8423
  const violations = [];
8362
8424
  const referenceById = new Map(mapping.map((m) => [m.agentId, m.reference]));
8363
8425
  for (const { agentId, reference } of mapping) {
8364
- if (!existsSync10(join14(rolesDir, reference))) {
8365
- 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`));
8366
8428
  }
8367
8429
  }
8368
8430
  for (const { family, memberIds } of families) {
@@ -8809,7 +8871,7 @@ function prReviewReportPath(opts) {
8809
8871
  }
8810
8872
  const revision = maxRevision + 1;
8811
8873
  const name = revision === 1 ? `${finalStem}.md` : `${finalStem}-r${revision}.md`;
8812
- return join15(opts.reportsDir, name);
8874
+ return join17(opts.reportsDir, name);
8813
8875
  }
8814
8876
  var PR_TIERS = ["quick", "default", "deep"];
8815
8877
  function violation14(severity, code, message, fix) {
@@ -9126,7 +9188,7 @@ function prReviewSeatPrompt(opts) {
9126
9188
  lines.push("");
9127
9189
  lines.push("## Read first");
9128
9190
  lines.push("");
9129
- const prReviewRef = join15(skillRoot, "references", "pr-review.md");
9191
+ const prReviewRef = join17(skillRoot, "references", "pr-review.md");
9130
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";
9131
9193
  lines.push(`1. \`${prReviewRef}\` \u2014 read at least these sections: ${sections}.`);
9132
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).`);
@@ -9134,9 +9196,9 @@ function prReviewSeatPrompt(opts) {
9134
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.`);
9135
9197
  }
9136
9198
  if (opts.stage === 2) {
9137
- 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.`);
9138
9200
  if (opts.securitySeat === true) {
9139
- 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.`);
9140
9202
  }
9141
9203
  }
9142
9204
  const budget = PR_REVIEW_TIER_BUDGETS[tier];
@@ -9319,9 +9381,9 @@ function resolvePrReviewTier(input) {
9319
9381
  }
9320
9382
 
9321
9383
  // ../engine/dist/engine.js
9322
- 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";
9323
9385
  import { randomUUID as randomUUID2 } from "node:crypto";
9324
- 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";
9325
9387
  import { fileURLToPath } from "node:url";
9326
9388
  import { readFileSync as readFileSync22, statSync as statSync5 } from "node:fs";
9327
9389
  import { dirname as dirname22, isAbsolute as isAbsolute7, join as join22, relative as relative4, resolve as resolve22 } from "node:path";
@@ -9334,15 +9396,15 @@ import { setTimeout as sleep2 } from "node:timers/promises";
9334
9396
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
9335
9397
  import { existsSync as existsSync32, readdirSync as readdirSync22, unlinkSync as unlinkSync32 } from "node:fs";
9336
9398
  import { isAbsolute as isAbsolute32, join as join52, resolve as resolve42 } from "node:path";
9337
- 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";
9338
9400
  import { dirname as dirname42, join as join72, resolve as resolve52, sep as sep2 } from "node:path";
9339
9401
  import { mkdirSync as mkdirSync32 } from "node:fs";
9340
9402
  import { join as join6 } from "node:path";
9341
9403
  import { copyFileSync, mkdirSync as mkdirSync7, readFileSync as readFileSync82, readdirSync as readdirSync7, writeFileSync as writeFileSync52 } from "node:fs";
9342
- import { dirname as dirname72, isAbsolute as isAbsolute72, join as join11, relative as relative42, 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";
9343
9405
  var SEVERITY_ORDER2 = ["critical", "high", "medium", "low", "nit"];
9344
9406
  function readJson2(filePath) {
9345
- if (!existsSync11(filePath))
9407
+ if (!existsSync8(filePath))
9346
9408
  return {};
9347
9409
  const content = readFileSync8(filePath, "utf8").trim();
9348
9410
  if (!content)
@@ -9356,7 +9418,7 @@ function readJson2(filePath) {
9356
9418
  function writeJson2(filePath, value) {
9357
9419
  const parent = dirname7(filePath);
9358
9420
  mkdirSync3(parent, { recursive: true });
9359
- const tmp = join3(parent, `.${basename7(filePath)}.${process.pid}.${randomUUID2()}.tmp`);
9421
+ const tmp = join3(parent, `.${basename5(filePath)}.${process.pid}.${randomUUID2()}.tmp`);
9360
9422
  try {
9361
9423
  writeFileSync5(tmp, `${JSON.stringify(value, null, 2)}
9362
9424
  `, "utf8");
@@ -9372,7 +9434,7 @@ function resolveProjectRoot(startDir = process.cwd()) {
9372
9434
  const start = resolve10(startDir);
9373
9435
  let dir = start;
9374
9436
  for (;; ) {
9375
- if (existsSync11(join3(dir, "package.json")) || existsSync11(join3(dir, "bun.lock")))
9437
+ if (existsSync8(join3(dir, "package.json")) || existsSync8(join3(dir, "bun.lock")))
9376
9438
  return dir;
9377
9439
  const parent = dirname7(dir);
9378
9440
  if (parent === dir)
@@ -10173,7 +10235,7 @@ function validateStatusV22(docOrPath, opts = {}) {
10173
10235
  if (harnessDir !== undefined && Array.isArray(doc.workflows)) {
10174
10236
  let realHarnessDir = null;
10175
10237
  try {
10176
- realHarnessDir = realpathSync4(harnessDir);
10238
+ realHarnessDir = realpathSync5(harnessDir);
10177
10239
  } catch {}
10178
10240
  for (const entry of doc.workflows) {
10179
10241
  if (!isPlainObject42(entry) || typeof entry.dir !== "string")
@@ -10183,7 +10245,7 @@ function validateStatusV22(docOrPath, opts = {}) {
10183
10245
  const label = typeof entry.id === "string" ? entry.id : relSnapshot;
10184
10246
  let physical;
10185
10247
  try {
10186
- physical = realpathSync4(snapshotPath);
10248
+ physical = realpathSync5(snapshotPath);
10187
10249
  } catch {
10188
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`));
10189
10251
  continue;
@@ -10414,7 +10476,7 @@ function todayString3() {
10414
10476
  return `${now.getFullYear()}-${month}-${day}`;
10415
10477
  }
10416
10478
  function scanCompasses(harnessDir) {
10417
- const iterationsDir = join11(harnessDir, "iterations");
10479
+ const iterationsDir = join13(harnessDir, "iterations");
10418
10480
  const out = [];
10419
10481
  let entries;
10420
10482
  try {
@@ -10425,7 +10487,7 @@ function scanCompasses(harnessDir) {
10425
10487
  for (const entry of entries) {
10426
10488
  if (!entry.isDirectory())
10427
10489
  continue;
10428
- const compassPath = join11(iterationsDir, entry.name, "delivery-compass.md");
10490
+ const compassPath = join13(iterationsDir, entry.name, "delivery-compass.md");
10429
10491
  let content;
10430
10492
  try {
10431
10493
  content = readFileSync82(compassPath, "utf8");
@@ -10505,8 +10567,8 @@ function buildIterationSnapshot(compass, rowById, rootUpdatedAt) {
10505
10567
  id: compass.id,
10506
10568
  type: "iteration",
10507
10569
  status,
10508
- file: join11("workflows", compass.id, WORKFLOW_SNAPSHOT_FILE2),
10509
- 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"),
10510
10572
  data: snapshot
10511
10573
  };
10512
10574
  }
@@ -10541,7 +10603,7 @@ function buildStandaloneSnapshot(row, rootUpdatedAt, migrationNotes) {
10541
10603
  id,
10542
10604
  type: "plan",
10543
10605
  status,
10544
- file: join11("workflows", id, WORKFLOW_SNAPSHOT_FILE2),
10606
+ file: join13("workflows", id, WORKFLOW_SNAPSHOT_FILE2),
10545
10607
  source: "status.json plans[] row",
10546
10608
  data: snapshot
10547
10609
  };
@@ -10649,7 +10711,7 @@ function buildRegister(residualFindings, byPlan, projectId, migratedAt) {
10649
10711
  return null;
10650
10712
  const doc = { entries };
10651
10713
  return {
10652
- file: join11("projects", projectId, PROJECT_REGISTER_FILE2),
10714
+ file: join13("projects", projectId, PROJECT_REGISTER_FILE2),
10653
10715
  source: "status.json residual_findings",
10654
10716
  data: doc
10655
10717
  };
@@ -10680,7 +10742,7 @@ function collectNotesFiles(snapshots) {
10680
10742
  if (lines.length === 0)
10681
10743
  continue;
10682
10744
  out.push({
10683
- file: join11(dirname72(snapshot.file), NOTES_LEDGER_FILE),
10745
+ file: join13(dirname8(snapshot.file), NOTES_LEDGER_FILE),
10684
10746
  source,
10685
10747
  lines
10686
10748
  });
@@ -10688,11 +10750,11 @@ function collectNotesFiles(snapshots) {
10688
10750
  return out;
10689
10751
  }
10690
10752
  function migrateHarnessTree(root, opts = {}) {
10691
- const harnessDir = resolve102(root);
10753
+ const harnessDir = resolve11(root);
10692
10754
  const workflowDir = resolveWorkflowDir2(harnessDir, { harnessDir });
10693
10755
  const projectDir = resolveProjectDir2(harnessDir, { harnessDir });
10694
10756
  const projectId = opts.projectId ?? _DEFAULT_PROJECT2;
10695
- const statusPath = join11(harnessDir, MIGRATE_STATUS_FILE);
10757
+ const statusPath = join13(harnessDir, MIGRATE_STATUS_FILE);
10696
10758
  const legacy = readJson2(statusPath);
10697
10759
  if (legacy.version === 2) {
10698
10760
  const updatedAt = typeof legacy.updated_at === "string" && legacy.updated_at !== "" ? legacy.updated_at : "1970-01-01";
@@ -10788,7 +10850,7 @@ function migrateHarnessTree(root, opts = {}) {
10788
10850
  migrationNotes.push(`roadmap title sanitized for frontmatter (line breaks replaced with spaces): ${JSON.stringify(rawTitle)}`);
10789
10851
  }
10790
10852
  roadmap = {
10791
- file: join11("projects", projectId, PROJECT_ROADMAP_FILE2),
10853
+ file: join13("projects", projectId, PROJECT_ROADMAP_FILE2),
10792
10854
  source: "status.json metadata.program_roadmap",
10793
10855
  content: buildRoadmap({ ...programRoadmap, title: sanitizedTitle }, projectId, migratedAt)
10794
10856
  };
@@ -10837,19 +10899,19 @@ async function applyMigratePlan(plan) {
10837
10899
  if (plan.dryRun) {
10838
10900
  return { applied: false, message: `dry-run: ${plan.steps.length} steps planned (source \u2192 destination), zero writes` };
10839
10901
  }
10840
- const statusPath = join11(plan.root, MIGRATE_STATUS_FILE);
10902
+ const statusPath = join13(plan.root, MIGRATE_STATUS_FILE);
10841
10903
  const current = readJson2(statusPath);
10842
10904
  if (current.version === 2) {
10843
10905
  return { applied: false, message: "no-op: status.json already at schema version 2 (migrated) \u2014 nothing to do" };
10844
10906
  }
10845
- const harnessRoot = resolve102(plan.root);
10846
- const workflowRoot = resolve102(plan.workflowDir);
10847
- const projectRoot = resolve102(plan.projectDir);
10907
+ const harnessRoot = resolve11(plan.root);
10908
+ const workflowRoot = resolve11(plan.workflowDir);
10909
+ const projectRoot = resolve11(plan.projectDir);
10848
10910
  if (!isAbsolute72(plan.workflowDir) || !isAbsolute72(plan.projectDir)) {
10849
10911
  throw new Error(`refusing to apply migration: plan workflowDir/projectDir must be absolute (got ${JSON.stringify(plan.workflowDir)} / ${JSON.stringify(plan.projectDir)})`);
10850
10912
  }
10851
- const workflowTargetOf = (canonicalFile) => join11(workflowRoot, relative42("workflows", canonicalFile));
10852
- const projectTargetOf = (canonicalFile) => join11(projectRoot, relative42("projects", canonicalFile));
10913
+ const workflowTargetOf = (canonicalFile) => join13(workflowRoot, relative5("workflows", canonicalFile));
10914
+ const projectTargetOf = (canonicalFile) => join13(projectRoot, relative5("projects", canonicalFile));
10853
10915
  const allDestinations = [
10854
10916
  plan.archive.file,
10855
10917
  ...plan.snapshots.map((snapshot) => snapshot.file),
@@ -10858,20 +10920,20 @@ async function applyMigratePlan(plan) {
10858
10920
  ...plan.roadmap !== null ? [plan.roadmap.file] : []
10859
10921
  ];
10860
10922
  for (const destination of allDestinations) {
10861
- const resolvedDest = resolve102(join11(plan.root, destination));
10923
+ const resolvedDest = resolve11(join13(plan.root, destination));
10862
10924
  const inside = (dir) => resolvedDest === dir || resolvedDest.startsWith(`${dir}${sep22}`);
10863
10925
  if (!inside(harnessRoot) && !inside(workflowRoot) && !inside(projectRoot)) {
10864
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)})`);
10865
10927
  }
10866
10928
  }
10867
- mkdirSync7(join11(plan.root, dirname72(plan.archive.file)), { recursive: true });
10868
- 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));
10869
10931
  for (const snapshot of plan.snapshots) {
10870
- await writeWorkflowSnapshot(snapshot.data, dirname72(workflowTargetOf(snapshot.file)));
10932
+ await writeWorkflowSnapshot(snapshot.data, dirname8(workflowTargetOf(snapshot.file)));
10871
10933
  }
10872
10934
  for (const notes of plan.notesFiles) {
10873
10935
  const filePath = workflowTargetOf(notes.file);
10874
- mkdirSync7(dirname72(filePath), { recursive: true });
10936
+ mkdirSync7(dirname8(filePath), { recursive: true });
10875
10937
  const content = notes.lines.length > 0 ? `${notes.lines.join(`
10876
10938
  `)}
10877
10939
  ` : "";
@@ -10884,13 +10946,13 @@ async function applyMigratePlan(plan) {
10884
10946
  }
10885
10947
  if (Object.keys(plan.register.data.entries ?? {}).length > 0) {
10886
10948
  const filePath = projectTargetOf(plan.register.file);
10887
- mkdirSync7(dirname72(filePath), { recursive: true });
10949
+ mkdirSync7(dirname8(filePath), { recursive: true });
10888
10950
  writeJson2(filePath, plan.register.data);
10889
10951
  }
10890
10952
  }
10891
10953
  if (plan.roadmap !== null) {
10892
10954
  const filePath = projectTargetOf(plan.roadmap.file);
10893
- mkdirSync7(dirname72(filePath), { recursive: true });
10955
+ mkdirSync7(dirname8(filePath), { recursive: true });
10894
10956
  writeFileSync52(filePath, plan.roadmap.content, "utf8");
10895
10957
  }
10896
10958
  const rootGate = validateStatusV22(plan.rootV2.data, { harnessDir: plan.root });
@@ -10926,7 +10988,7 @@ var RISK_ENUM_RE2 = new RegExp(`^(?:${AUDIT_RISKS2.join("|")})(?:\\b|$)`);
10926
10988
  var CONFIDENCE_ENUM_RE2 = new RegExp(`^(${[...AUDIT_CONFIDENCES2, "MEDIUM"].join("|")})\\b`, "i");
10927
10989
  // src/commands/migrate.ts
10928
10990
  var import_picocolors = __toESM(require_picocolors2(), 1);
10929
- import { resolve as resolve13 } from "node:path";
10991
+ import { resolve as resolve14 } from "node:path";
10930
10992
  function validatePlannedDocs(plan) {
10931
10993
  const warnings = [];
10932
10994
  for (const snapshot of plan.snapshots) {
@@ -10948,7 +11010,7 @@ function validatePlannedDocs(plan) {
10948
11010
  return warnings;
10949
11011
  }
10950
11012
  async function runMigrateCommand(options) {
10951
- const root = options.path ? resolve13(options.path) : resolveHarnessDir2() ?? process.cwd();
11013
+ const root = options.path ? resolve14(options.path) : resolveHarnessDir2() ?? process.cwd();
10952
11014
  setArtifactStore2(createFsStore2(root));
10953
11015
  let plan;
10954
11016
  try {
@@ -11039,7 +11101,7 @@ async function runMigrateCommand(options) {
11039
11101
  }
11040
11102
 
11041
11103
  // src/agent-plugins.ts
11042
- import fs, { realpathSync as realpathSync6 } from "node:fs";
11104
+ import fs, { realpathSync as realpathSync7 } from "node:fs";
11043
11105
  import path3 from "node:path";
11044
11106
 
11045
11107
  // src/utils.ts
@@ -11371,14 +11433,14 @@ function validateSkills(root, errors2, warnings) {
11371
11433
  return;
11372
11434
  }
11373
11435
  const entries = fs.readdirSync(skillsPath, { withFileTypes: true });
11374
- const realRoot = realpathSync6(root);
11436
+ const realRoot = realpathSync7(root);
11375
11437
  for (const entry of entries) {
11376
11438
  if (!entry.isDirectory() && !entry.isSymbolicLink())
11377
11439
  continue;
11378
11440
  const skillDir = entry.name;
11379
11441
  let realSkillPath;
11380
11442
  try {
11381
- realSkillPath = realpathSync6(`${skillsPath}${path3.sep}${skillDir}`);
11443
+ realSkillPath = realpathSync7(`${skillsPath}${path3.sep}${skillDir}`);
11382
11444
  } catch (error) {
11383
11445
  warnings.push(`skills: ${skillDir}/ cannot be resolved (${error.message}; skill skipped)`);
11384
11446
  continue;
@@ -11395,7 +11457,7 @@ function validateSkills(root, errors2, warnings) {
11395
11457
  }
11396
11458
  let realSkillMdPath;
11397
11459
  try {
11398
- realSkillMdPath = realpathSync6(skillMdPath);
11460
+ realSkillMdPath = realpathSync7(skillMdPath);
11399
11461
  } catch (error) {
11400
11462
  warnings.push(`skills: ${skillDir}/SKILL.md cannot be resolved (${error.message}; skill skipped)`);
11401
11463
  continue;
@@ -11771,13 +11833,28 @@ function configuredMarketplaceNames(dryRun) {
11771
11833
  const list = Array.isArray(parsed.marketplaces) ? parsed.marketplaces : [];
11772
11834
  return list.map((entry) => entry && typeof entry.name === "string" ? entry.name : "").filter((name) => name !== "");
11773
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
+ }
11774
11841
  function installedPluginIds(dryRun) {
11775
11842
  if (dryRun)
11776
11843
  return [];
11777
11844
  const dump = runCodex(["plugin", "list", "--json"], false, CODEX_LOCAL_TIMEOUT_MS);
11778
- const parsed = JSON.parse(dump);
11779
- const list = Array.isArray(parsed.installed) ? parsed.installed : [];
11780
- 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;
11781
11858
  }
11782
11859
  function legacyPersonalMarketplaceNote() {
11783
11860
  const legacyPath = path5.join(os2.homedir(), ".agents", "plugins", "marketplace.json");
@@ -12198,6 +12275,67 @@ var dshAdapter = {
12198
12275
  runInstallDoctor: (scope) => runDoctor2(scope)
12199
12276
  };
12200
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
+
12201
12339
  // src/adapters/omp.ts
12202
12340
  import fs5 from "node:fs";
12203
12341
  import path8 from "node:path";
@@ -12217,34 +12355,39 @@ function ompAvailable() {
12217
12355
  function runOmp(args, dryRun) {
12218
12356
  runCliCommand(["omp", ...args], { dryRun });
12219
12357
  }
12220
- 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) {
12221
12384
  try {
12222
12385
  const raw = execFileSync8("omp", ["plugin", "list", "--json"], {
12223
12386
  stdio: "pipe",
12224
- encoding: "utf8"
12387
+ encoding: "utf8",
12388
+ timeout: timeoutMs
12225
12389
  });
12226
- const parsed = JSON.parse(raw);
12227
- if (Array.isArray(parsed))
12228
- return parsed;
12229
- if (parsed && typeof parsed === "object") {
12230
- const record = parsed;
12231
- if (Array.isArray(record.plugins)) {
12232
- return record.plugins;
12233
- }
12234
- const entries = [];
12235
- for (const key of ["npm", "marketplace"]) {
12236
- const group = record[key];
12237
- if (Array.isArray(group)) {
12238
- for (const item of group) {
12239
- if (item && typeof item === "object")
12240
- entries.push(item);
12241
- }
12242
- }
12243
- }
12244
- if (entries.length > 0)
12245
- return entries;
12246
- }
12247
- return [];
12390
+ return parseOmpPluginList(raw);
12248
12391
  } catch {
12249
12392
  return [];
12250
12393
  }
@@ -12413,9 +12556,43 @@ var ompAdapter = {
12413
12556
  runInstallDoctor: (scope) => runDoctor3(scope)
12414
12557
  };
12415
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
+
12416
12593
  // src/adapters/opencode.ts
12417
- import os5 from "node:os";
12418
- import path9 from "node:path";
12594
+ import os6 from "node:os";
12595
+ import path10 from "node:path";
12419
12596
  var OPENCODE_CONFIG_SCHEMA = "https://opencode.ai/config.json";
12420
12597
  var MSTAR_OPENCODE_PLUGIN = "@mstar-harness/opencode@latest";
12421
12598
  function isLegacyMorningStarGitPlugin(plugin) {
@@ -12436,20 +12613,20 @@ function isAnyMstarHarnessOpencodeSlot(plugin) {
12436
12613
  function resolveOpencodeConfigPath(scope, outputPath) {
12437
12614
  if (outputPath && outputPath.trim()) {
12438
12615
  const raw = outputPath.trim();
12439
- if (path9.isAbsolute(raw))
12616
+ if (path10.isAbsolute(raw))
12440
12617
  return raw;
12441
12618
  if (raw.split(/[\\/]/).includes("..")) {
12442
12619
  throw new Error(`--output must not contain ".." segments: ${raw}`);
12443
12620
  }
12444
12621
  const root2 = resolveProjectRoot2();
12445
- return root2.endsWith(path9.sep) ? root2 + raw : root2 + path9.sep + raw;
12622
+ return root2.endsWith(path10.sep) ? root2 + raw : root2 + path10.sep + raw;
12446
12623
  }
12447
12624
  if (scope === "global") {
12448
- const home = os5.homedir();
12449
- return `${home}${path9.sep}.config${path9.sep}opencode${path9.sep}opencode.json`;
12625
+ const home = os6.homedir();
12626
+ return `${home}${path10.sep}.config${path10.sep}opencode${path10.sep}opencode.json`;
12450
12627
  }
12451
12628
  const root = resolveProjectRoot2();
12452
- return root.endsWith(path9.sep) ? `${root}opencode.json` : `${root}${path9.sep}opencode.json`;
12629
+ return root.endsWith(path10.sep) ? `${root}opencode.json` : `${root}${path10.sep}opencode.json`;
12453
12630
  }
12454
12631
  function ensureConfigSchema(config) {
12455
12632
  const next = ensureObject(config);
@@ -12543,8 +12720,8 @@ var opencodeAdapter = {
12543
12720
 
12544
12721
  // src/adapters/zcode.ts
12545
12722
  import fs6 from "node:fs";
12546
- import os6 from "node:os";
12547
- import path10 from "node:path";
12723
+ import os7 from "node:os";
12724
+ import path11 from "node:path";
12548
12725
  var MARKETPLACE_ID = "mstar-local";
12549
12726
  var MARKETPLACE_NAME2 = "mstar-local";
12550
12727
  var MARKETPLACE_DESCRIPTION = "Morning Star harness marketplace (GitHub source).";
@@ -12557,10 +12734,10 @@ var GITHUB_REF = "main";
12557
12734
  var ZCODE_PLUGIN_MARKER = ".zcode-plugin/plugin.json";
12558
12735
  var ZCODE_PLUGIN_CHECKOUT_PROJECT = ".zcode/plugin-checkout";
12559
12736
  var ZCODE_AGENT_SMOKE_NAMES = ["fullstack-dev", "qc-specialist"];
12560
- var ZCODE_PLUGINS_ROOT = path10.join(os6.homedir(), ".zcode", "cli", "plugins");
12561
- var KNOWN_MARKETPLACES_PATH = path10.join(ZCODE_PLUGINS_ROOT, "known_marketplaces.json");
12562
- var MARKETPLACE_DIR = path10.join(ZCODE_PLUGINS_ROOT, "marketplaces", MARKETPLACE_ID);
12563
- 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");
12564
12741
  var GITHUB_SOURCE = { source: "github", repo: GITHUB_REPO, ref: GITHUB_REF };
12565
12742
  function nowIso() {
12566
12743
  return new Date().toISOString();
@@ -12568,6 +12745,7 @@ function nowIso() {
12568
12745
  function marketplacePluginEntry() {
12569
12746
  return {
12570
12747
  name: PLUGIN_NAME,
12748
+ version: readHarnessVersion(),
12571
12749
  source: { ...GITHUB_SOURCE },
12572
12750
  displayName: PLUGIN_DISPLAY_NAME,
12573
12751
  icon: PLUGIN_ICON_URL,
@@ -12638,10 +12816,6 @@ function validateMarketplaceJson() {
12638
12816
  if (source.repo !== expected.source.repo) {
12639
12817
  errors2.push(`ZCode marketplace plugin source.repo must be ${expected.source.repo}.`);
12640
12818
  }
12641
- const expectedVersion = readHarnessVersion();
12642
- if (entry.version !== undefined && entry.version !== expectedVersion) {
12643
- errors2.push(`ZCode marketplace plugin version must be ${expectedVersion}.`);
12644
- }
12645
12819
  return errors2;
12646
12820
  }
12647
12821
  function validateKnownMarketplaces() {
@@ -12669,13 +12843,13 @@ function validateKnownMarketplaces() {
12669
12843
  }
12670
12844
  function validatePluginAgents2(pluginRoot) {
12671
12845
  const errors2 = [];
12672
- const agentsDir = path10.join(pluginRoot, "agents");
12846
+ const agentsDir = path11.join(pluginRoot, "agents");
12673
12847
  if (!fs6.existsSync(agentsDir)) {
12674
12848
  errors2.push(`Missing plugin agents directory: ${agentsDir}`);
12675
12849
  return errors2;
12676
12850
  }
12677
12851
  for (const agentName of ZCODE_AGENT_SMOKE_NAMES) {
12678
- const agentPath = path10.join(agentsDir, `${agentName}.md`);
12852
+ const agentPath = path11.join(agentsDir, `${agentName}.md`);
12679
12853
  if (!fs6.existsSync(agentPath)) {
12680
12854
  errors2.push(`Missing plugin agent file: ${agentPath}`);
12681
12855
  }
@@ -12689,11 +12863,11 @@ function buildMarketplaceJson() {
12689
12863
  plugins: [marketplacePluginEntry()]
12690
12864
  };
12691
12865
  }
12692
- function runInit4(scope, dryRun) {
12866
+ function runInit5(scope, dryRun) {
12693
12867
  const notes = ensureLocalHarnessRepo(dryRun);
12694
12868
  const projectRoot = resolveProjectRoot2();
12695
12869
  if (scope === "project") {
12696
- const checkoutPath = path10.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT);
12870
+ const checkoutPath = path11.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT);
12697
12871
  notes.push(...ensureGitCheckout(REPO_URL, checkoutPath, dryRun));
12698
12872
  notes.push(...appendGitignore(projectRoot, [ZCODE_PLUGIN_CHECKOUT_PROJECT], dryRun));
12699
12873
  notes.push(...appendHarnessProjectGitignore(projectRoot, dryRun));
@@ -12716,14 +12890,14 @@ function runInit4(scope, dryRun) {
12716
12890
  notes
12717
12891
  };
12718
12892
  }
12719
- function runDoctor4(scope) {
12893
+ function runDoctor5(scope) {
12720
12894
  const errors2 = [];
12721
12895
  errors2.push(...validateLocalHarnessRepo());
12722
12896
  if (scope === "project") {
12723
12897
  const projectRoot = resolveProjectRoot2();
12724
- const checkoutPath = path10.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT);
12898
+ const checkoutPath = path11.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT);
12725
12899
  errors2.push(...validateGitCheckout(checkoutPath, ZCODE_PLUGIN_MARKER));
12726
- const gitignorePath = path10.join(projectRoot, ".gitignore");
12900
+ const gitignorePath = path11.join(projectRoot, ".gitignore");
12727
12901
  const gitignore = fs6.existsSync(gitignorePath) ? fs6.readFileSync(gitignorePath, "utf8") : "";
12728
12902
  if (!gitignore.split(/\r?\n/).includes(ZCODE_PLUGIN_CHECKOUT_PROJECT)) {
12729
12903
  errors2.push(`Missing .gitignore entry: ${ZCODE_PLUGIN_CHECKOUT_PROJECT}`);
@@ -12742,8 +12916,8 @@ function runDoctor4(scope) {
12742
12916
  var zcodeAdapter = {
12743
12917
  target: "zcode",
12744
12918
  mode: "install",
12745
- runInstallInit: (scope, dryRun) => runInit4(scope, dryRun),
12746
- runInstallDoctor: (scope) => runDoctor4(scope)
12919
+ runInstallInit: (scope, dryRun) => runInit5(scope, dryRun),
12920
+ runInstallDoctor: (scope) => runDoctor5(scope)
12747
12921
  };
12748
12922
 
12749
12923
  // src/adapters/index.ts
@@ -12753,7 +12927,8 @@ var adapters = {
12753
12927
  codex: codexAdapter,
12754
12928
  zcode: zcodeAdapter,
12755
12929
  omp: ompAdapter,
12756
- dsh: dshAdapter
12930
+ dsh: dshAdapter,
12931
+ kimi: kimiAdapter
12757
12932
  };
12758
12933
  function getAdapter(target) {
12759
12934
  const adapter = adapters[target];
@@ -12824,12 +12999,241 @@ function formatCliDoctorNote(detected, expected) {
12824
12999
  return `CLI on PATH: ${CLI_NAME} ${detected} (matching)`;
12825
13000
  }
12826
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
+
12827
13231
  // src/types.ts
12828
- var SUPPORTED_TARGETS = ["opencode", "cursor", "codex", "zcode", "omp", "dsh"];
13232
+ var SUPPORTED_TARGETS = ["opencode", "cursor", "codex", "zcode", "omp", "dsh", "kimi"];
12829
13233
 
12830
13234
  // src/utils.ts
12831
- import fs7 from "node:fs";
12832
- import path11 from "node:path";
13235
+ import fs8 from "node:fs";
13236
+ import path13 from "node:path";
12833
13237
  function parseCsv(raw) {
12834
13238
  if (!raw)
12835
13239
  return;
@@ -12838,27 +13242,27 @@ function parseCsv(raw) {
12838
13242
  function resolveProjectRoot3() {
12839
13243
  const candidate = process.env.MSTAR_CLI_PROJECT_ROOT || process.env.INIT_CWD || process.env.PWD;
12840
13244
  if (candidate && candidate.trim())
12841
- return path11.resolve(candidate);
13245
+ return path13.resolve(candidate);
12842
13246
  return resolveProjectRoot();
12843
13247
  }
12844
13248
  function joinWithinRoot(root, ...segments) {
12845
- const base = path11.resolve(root);
12846
- const resolved = path11.resolve(base, ...segments);
12847
- const withinRoot = resolved === base || resolved.startsWith(base + path11.sep) || base.endsWith(path11.sep) && resolved.startsWith(base);
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);
12848
13252
  if (!withinRoot) {
12849
- throw new Error(`path escapes ${base}: ${segments.join(path11.sep)}`);
13253
+ throw new Error(`path escapes ${base}: ${segments.join(path13.sep)}`);
12850
13254
  }
12851
13255
  return resolved;
12852
13256
  }
12853
13257
  function findUpPackageRoot(startDir, predicate) {
12854
- let dir = path11.resolve(startDir);
13258
+ let dir = path13.resolve(startDir);
12855
13259
  for (;; ) {
12856
13260
  try {
12857
- const manifest = JSON.parse(fs7.readFileSync(joinWithinRoot(dir, "package.json"), "utf8"));
13261
+ const manifest = JSON.parse(fs8.readFileSync(joinWithinRoot(dir, "package.json"), "utf8"));
12858
13262
  if (predicate(manifest))
12859
13263
  return dir;
12860
13264
  } catch {}
12861
- const parent = path11.dirname(dir);
13265
+ const parent = path13.dirname(dir);
12862
13266
  if (parent === dir)
12863
13267
  return null;
12864
13268
  dir = parent;
@@ -12870,7 +13274,7 @@ function declaresWorkspaces(manifest) {
12870
13274
  function resolveCliProjectRoot() {
12871
13275
  const override = process.env.MSTAR_CLI_PROJECT_ROOT;
12872
13276
  if (override && override.trim())
12873
- return path11.resolve(override);
13277
+ return path13.resolve(override);
12874
13278
  const monorepoRoot = findUpPackageRoot(process.cwd(), declaresWorkspaces);
12875
13279
  if (monorepoRoot)
12876
13280
  return monorepoRoot;
@@ -12880,10 +13284,10 @@ function resolveCliProjectRoot() {
12880
13284
  return process.cwd();
12881
13285
  }
12882
13286
  function resolveCliPath(userPath) {
12883
- if (path11.isAbsolute(userPath))
13287
+ if (path13.isAbsolute(userPath))
12884
13288
  return userPath;
12885
13289
  const root = resolveCliProjectRoot();
12886
- return root.endsWith(path11.sep) ? root + userPath : root + path11.sep + userPath;
13290
+ return root.endsWith(path13.sep) ? root + userPath : root + path13.sep + userPath;
12887
13291
  }
12888
13292
 
12889
13293
  // src/index.ts
@@ -12920,7 +13324,7 @@ function resolveExplicitModelAssignments(options) {
12920
13324
  others: allow("other-models", parseCsv(options.otherModels), 3, true)
12921
13325
  });
12922
13326
  }
12923
- async function runInit5(options) {
13327
+ async function runInit6(options) {
12924
13328
  const target = options.target || (options.yes ? "opencode" : await pickTargetInteractive());
12925
13329
  const scope = options.scope || "project";
12926
13330
  const adapter = getAdapter(target);
@@ -12985,12 +13389,13 @@ async function runInit5(options) {
12985
13389
  }
12986
13390
  ensureGlobalCli({ version: packageVersion, dryRun: !!options.dryRun, noGlobalCli: !!options.noGlobalCli });
12987
13391
  }
12988
- function runDoctor5(options) {
13392
+ function runDoctor6(options) {
12989
13393
  const target = options.target || "opencode";
12990
13394
  const adapter = getAdapter(target);
12991
13395
  const scope = options.scope || "project";
12992
13396
  console.log(`Target: ${target}`);
12993
13397
  console.log(formatCliDoctorNote(defaultDetectVersion(), packageVersion));
13398
+ console.log(formatPluginVersionDoctorNote(target, packageVersion, detectInstalledPluginVersion(target, scope)));
12994
13399
  if (adapter.mode === "install") {
12995
13400
  const result = adapter.runInstallDoctor?.(scope);
12996
13401
  if (!result) {
@@ -13034,10 +13439,10 @@ function runDoctor5(options) {
13034
13439
  }
13035
13440
  function resolvePluginRoot(options) {
13036
13441
  if (options.root)
13037
- return path12.resolve(options.root);
13442
+ return path14.resolve(options.root);
13038
13443
  let candidate = resolveProjectRoot3();
13039
- while (!fs8.existsSync(path12.join(candidate, "plugin.json"))) {
13040
- const parent = path12.dirname(candidate);
13444
+ while (!fs9.existsSync(path14.join(candidate, "plugin.json"))) {
13445
+ const parent = path14.dirname(candidate);
13041
13446
  if (parent === candidate)
13042
13447
  break;
13043
13448
  candidate = parent;
@@ -13088,25 +13493,25 @@ function gitWorkspaceRoot(startDir) {
13088
13493
  let boundary = startDir;
13089
13494
  for (const segment of cdup.split(/[\\/]/)) {
13090
13495
  if (segment && segment !== ".")
13091
- boundary = path12.dirname(boundary);
13496
+ boundary = path14.dirname(boundary);
13092
13497
  }
13093
13498
  return boundary;
13094
13499
  } catch {}
13095
13500
  return startDir;
13096
13501
  }
13097
13502
  function runScaffold(pathArg) {
13098
- const root = pathArg ? path12.resolve(pathArg) : process.cwd();
13503
+ const root = pathArg ? path14.resolve(pathArg) : process.cwd();
13099
13504
  const harnessDir = scaffoldHarness(root);
13100
13505
  const projectDir = resolveProjectDir(root, { harnessDir });
13101
13506
  const created = [];
13102
13507
  const skipped = [];
13103
13508
  const workspaceRoot = gitWorkspaceRoot(root);
13104
13509
  const harnessKind = detectHarnessKind(harnessDir);
13105
- const mstarDirAtWorkspaceRoot = workspaceRoot.endsWith(path12.sep) ? `${workspaceRoot}.mstar` : `${workspaceRoot}${path12.sep}.mstar`;
13106
- if (harnessKind === "mstar" && path12.resolve(harnessDir) === mstarDirAtWorkspaceRoot) {
13107
- const gitignorePath = workspaceRoot.endsWith(path12.sep) ? `${workspaceRoot}.gitignore` : `${workspaceRoot}${path12.sep}.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`;
13108
13513
  const snippet = emitGitignoreSnippet("mstar");
13109
- const current = fs8.existsSync(gitignorePath) ? fs8.readFileSync(gitignorePath, "utf8") : "";
13514
+ const current = fs9.existsSync(gitignorePath) ? fs9.readFileSync(gitignorePath, "utf8") : "";
13110
13515
  const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));
13111
13516
  const snippetLines = snippet.split(`
13112
13517
  `).map((line) => line.trim());
@@ -13128,18 +13533,18 @@ function runScaffold(pathArg) {
13128
13533
  `) ? "" : `
13129
13534
  `}.mstarc
13130
13535
  `;
13131
- fs8.writeFileSync(gitignorePath, next, "utf8");
13536
+ fs9.writeFileSync(gitignorePath, next, "utf8");
13132
13537
  } else {
13133
13538
  const prefix = current && !current.endsWith(`
13134
13539
  `) ? `
13135
13540
  ` : "";
13136
- fs8.appendFileSync(gitignorePath, `${prefix}${[...missingComments, ...missing].join(`
13541
+ fs9.appendFileSync(gitignorePath, `${prefix}${[...missingComments, ...missing].join(`
13137
13542
  `)}
13138
13543
  `, "utf8");
13139
13544
  }
13140
13545
  created.push(".gitignore (canonical harness snippet)");
13141
13546
  }
13142
- const finalLines = fs8.readFileSync(gitignorePath, "utf8").split(/\r?\n/);
13547
+ const finalLines = fs9.readFileSync(gitignorePath, "utf8").split(/\r?\n/);
13143
13548
  const broadIndexes = finalLines.map((line, index) => line.trim() === ".mstar/**" ? index : -1).filter((index) => index !== -1);
13144
13549
  const canonicalNegationIndexes = finalLines.map((line, index) => CANONICAL_NEGATIONS[line.trim()] === true ? index : -1).filter((index) => index !== -1);
13145
13550
  const firstCanonicalNegationIndex = canonicalNegationIndexes[0] ?? -1;
@@ -13301,7 +13706,7 @@ function runScaffold(pathArg) {
13301
13706
  finalLines.push("");
13302
13707
  }
13303
13708
  if (normalized) {
13304
- fs8.writeFileSync(gitignorePath, finalLines.join(`
13709
+ fs9.writeFileSync(gitignorePath, finalLines.join(`
13305
13710
  `), "utf8");
13306
13711
  created.push(".gitignore (canonical harness snippet reordered)");
13307
13712
  } else if (missing.length === 0) {
@@ -13310,10 +13715,10 @@ function runScaffold(pathArg) {
13310
13715
  } else {
13311
13716
  skipped.push(".gitignore (canonical harness snippet) \u2014 custom harness layout manages its own ignore rules");
13312
13717
  }
13313
- const agentsPath = path12.join(harnessDir, "AGENTS.md");
13314
- const agentsLabel = `${path12.basename(harnessDir)}/AGENTS.md`;
13315
- if (!fs8.existsSync(agentsPath)) {
13316
- 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");
13317
13722
  created.push(agentsLabel);
13318
13723
  } else {
13319
13724
  skipped.push(`${agentsLabel} (already present)`);
@@ -13329,7 +13734,7 @@ function runScaffold(pathArg) {
13329
13734
  }
13330
13735
  program2.name("mstar-harness").description("Morning Star harness CLI for target-based agent bootstrap").version(packageVersion);
13331
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) => {
13332
- await runInit5({
13737
+ await runInit6({
13333
13738
  ...options,
13334
13739
  noFallbacks: options.fallbacks === false,
13335
13740
  noGlobalCli: options.globalCli === false
@@ -13340,7 +13745,7 @@ harnessCommand.command("scaffold").description("One-shot harness bootstrap: crea
13340
13745
  runScaffold(pathArg);
13341
13746
  });
13342
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) => {
13343
- runDoctor5(options);
13748
+ runDoctor6(options);
13344
13749
  });
13345
13750
  var pluginCommand = program2.command("plugin").description("Agent Plugins v1.0.0 portable package commands");
13346
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) => {
@@ -13348,7 +13753,7 @@ pluginCommand.command("validate").description("Validate a plugin package against
13348
13753
  });
13349
13754
  var pathCommand = program2.command("path").description("harness/specs dir resolution checks (engine-backed)");
13350
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) => {
13351
- const startDir = pathArg ? path12.resolve(pathArg) : process.cwd();
13756
+ const startDir = pathArg ? path14.resolve(pathArg) : process.cwd();
13352
13757
  const harnessDir = resolveHarnessDir(startDir);
13353
13758
  if (!harnessDir) {
13354
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`;
@@ -13376,21 +13781,21 @@ pathCommand.command("resolve").description("Resolve {HARNESS_DIR} + {SPECS_DIR}
13376
13781
  var statusCommand = program2.command("status").description("v2 status.json root / workflow snapshot / project-register checks (engine-backed)");
13377
13782
  function resolveStatusFilePath(pathArg) {
13378
13783
  if (pathArg)
13379
- return path12.resolve(pathArg);
13784
+ return path14.resolve(pathArg);
13380
13785
  const harnessDir = resolveHarnessDir();
13381
13786
  if (!harnessDir) {
13382
13787
  throw new Error(`harness dir not found from ${process.cwd()} \u2014 pass a status.json path or set MSTAR_HARNESS_DIR`);
13383
13788
  }
13384
- return path12.join(harnessDir, "status.json");
13789
+ return path14.join(harnessDir, "status.json");
13385
13790
  }
13386
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) => {
13387
13792
  let statusPath;
13388
13793
  try {
13389
13794
  statusPath = resolveStatusFilePath(pathArg);
13390
- if (!fs8.existsSync(statusPath)) {
13795
+ if (!fs9.existsSync(statusPath)) {
13391
13796
  throw new Error(`status file not found: ${statusPath}`);
13392
13797
  }
13393
- 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);
13394
13799
  if (gate2.ok) {
13395
13800
  console.log(import_picocolors2.default.green(`${statusPath}: OK`));
13396
13801
  return;
@@ -13410,8 +13815,8 @@ statusCommand.command("validate").description("Validate a v2 status.json root or
13410
13815
  });
13411
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) => {
13412
13817
  try {
13413
- const projectDir = pathArg ? path12.resolve(pathArg) : resolveProjectDir();
13414
- if (!fs8.existsSync(projectDir)) {
13818
+ const projectDir = pathArg ? path14.resolve(pathArg) : resolveProjectDir();
13819
+ if (!fs9.existsSync(projectDir)) {
13415
13820
  throw new Error(`project dir not found: ${projectDir}`);
13416
13821
  }
13417
13822
  const rollup = techDebtRollup(projectDir);
@@ -13429,8 +13834,8 @@ statusCommand.command("tech-debt").description("Print the residual tech-debt rol
13429
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) => {
13430
13835
  try {
13431
13836
  const projectDir = resolveProjectDir(process.cwd(), options.harness ? { harnessDir: options.harness } : {});
13432
- const registerPath = path12.join(projectDir, options.project ?? _DEFAULT_PROJECT, PROJECT_REGISTER_FILE);
13433
- if (!fs8.existsSync(registerPath)) {
13837
+ const registerPath = path14.join(projectDir, options.project ?? _DEFAULT_PROJECT, PROJECT_REGISTER_FILE);
13838
+ if (!fs9.existsSync(registerPath)) {
13434
13839
  throw new Error(`project register not found: ${registerPath}`);
13435
13840
  }
13436
13841
  const mode = options.mode === "zero-residual" || options.mode === "allow-residual" ? options.mode : undefined;
@@ -13465,7 +13870,7 @@ function sanitizeProjectId(projectId) {
13465
13870
  if (projectId === _DEFAULT_PROJECT) {
13466
13871
  return projectId;
13467
13872
  }
13468
- 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)) {
13469
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}`);
13470
13875
  }
13471
13876
  return projectId;
@@ -13480,7 +13885,7 @@ statusCommand.command("backlog-register").description("Register deferred-PR back
13480
13885
  const projectRoot = resolveProjectDir(process.cwd(), options.harness ? { harnessDir: options.harness } : {});
13481
13886
  if (options.harness)
13482
13887
  setArtifactStore(createFsStore(options.harness));
13483
- const projectDir = path12.join(projectRoot, projectId);
13888
+ const projectDir = path14.join(projectRoot, projectId);
13484
13889
  const registeredAt = todayString5();
13485
13890
  const entries = entriesRaw.map((raw, index) => {
13486
13891
  let parsed;
@@ -13507,7 +13912,7 @@ statusCommand.command("backlog-close").description("Close one project-register b
13507
13912
  const projectRoot = resolveProjectDir(process.cwd(), options.harness ? { harnessDir: options.harness } : {});
13508
13913
  if (options.harness)
13509
13914
  setArtifactStore(createFsStore(options.harness));
13510
- const projectDir = path12.join(projectRoot, projectId);
13915
+ const projectDir = path14.join(projectRoot, projectId);
13511
13916
  await closeProjectRegisterEntry({
13512
13917
  projectDir,
13513
13918
  planKey: options.key,
@@ -13549,13 +13954,13 @@ function readPersistPayload(options) {
13549
13954
  throw new SddScriptError("usage: persist --file <path> and --stdin are mutually exclusive", 2);
13550
13955
  }
13551
13956
  if (options.file !== undefined) {
13552
- const requested = path12.isAbsolute(options.file) ? options.file : `${process.cwd()}${path12.sep}${options.file}`;
13553
- if (!fs8.existsSync(requested)) {
13957
+ const requested = path14.isAbsolute(options.file) ? options.file : `${process.cwd()}${path14.sep}${options.file}`;
13958
+ if (!fs9.existsSync(requested)) {
13554
13959
  throw new Error(`persist payload file not found: ${requested}`);
13555
13960
  }
13556
- return fs8.readFileSync(requested, "utf8");
13961
+ return fs9.readFileSync(requested, "utf8");
13557
13962
  }
13558
- return fs8.readFileSync(0, "utf8");
13963
+ return fs9.readFileSync(0, "utf8");
13559
13964
  }
13560
13965
  function validatePersistPayload(kind, payload) {
13561
13966
  let gate2;
@@ -13667,7 +14072,7 @@ persistCommand.command("delete").description("Delete the stored document for <ki
13667
14072
  var leaseCommand = program2.command("lease").description("execution_lease / integration_merge_lease checks (engine-backed)");
13668
14073
  function resolveLeaseHarnessDir(harnessArg) {
13669
14074
  if (harnessArg)
13670
- return path12.resolve(harnessArg);
14075
+ return path14.resolve(harnessArg);
13671
14076
  const harnessDir = resolveHarnessDir();
13672
14077
  if (!harnessDir) {
13673
14078
  throw new Error(`harness dir not found from ${process.cwd()} \u2014 pass --harness or set MSTAR_HARNESS_DIR`);
@@ -13680,7 +14085,7 @@ function resolveSnapshotPath(workflowId, harnessArg) {
13680
14085
  }
13681
14086
  const harnessDir = resolveLeaseHarnessDir(harnessArg);
13682
14087
  const workflowDir = resolveWorkflowDir(harnessDir, { harnessDir });
13683
- return path12.join(workflowDir, workflowId, WORKFLOW_SNAPSHOT_FILE);
14088
+ return path14.join(workflowDir, workflowId, WORKFLOW_SNAPSHOT_FILE);
13684
14089
  }
13685
14090
  function solePlanRow(plans, label) {
13686
14091
  if (plans.length === 0) {
@@ -13713,7 +14118,7 @@ leaseCommand.command("verify").description("Verify a plan's execution_lease on t
13713
14118
  throw new SddScriptError("usage: lease verify --workflow <id> [--plan <plan-id>] [--harness <path>]", 2);
13714
14119
  }
13715
14120
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
13716
- if (!fs8.existsSync(snapshotPath)) {
14121
+ if (!fs9.existsSync(snapshotPath)) {
13717
14122
  throw new Error(`workflow snapshot not found: ${snapshotPath}`);
13718
14123
  }
13719
14124
  const doc = readJson2(snapshotPath);
@@ -13751,7 +14156,7 @@ leaseCommand.command("verify-integration").description("Verify the workflow snap
13751
14156
  throw new SddScriptError("usage: lease verify-integration --workflow <id> [--harness <path>]", 2);
13752
14157
  }
13753
14158
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
13754
- if (!fs8.existsSync(snapshotPath)) {
14159
+ if (!fs9.existsSync(snapshotPath)) {
13755
14160
  throw new Error(`workflow snapshot not found: ${snapshotPath}`);
13756
14161
  }
13757
14162
  const doc = readJson2(snapshotPath);
@@ -13781,12 +14186,12 @@ function failScript(error, context) {
13781
14186
  process.exitCode = 1;
13782
14187
  }
13783
14188
  function loadSddContextFile(pathValue) {
13784
- if (!pathValue || !path12.isAbsolute(pathValue)) {
14189
+ if (!pathValue || !path14.isAbsolute(pathValue)) {
13785
14190
  throw new SddScriptError(`--context must be an absolute path to a SddExecutionContext JSON file; got ${JSON.stringify(pathValue ?? "")}`, 2);
13786
14191
  }
13787
14192
  let raw;
13788
14193
  try {
13789
- raw = fs8.readFileSync(pathValue, "utf8");
14194
+ raw = fs9.readFileSync(pathValue, "utf8");
13790
14195
  } catch {
13791
14196
  throw new SddScriptError(`no such context file: ${pathValue}`, 2);
13792
14197
  }
@@ -13893,10 +14298,10 @@ function printChecklist(label, gate2) {
13893
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) => {
13894
14299
  try {
13895
14300
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
13896
- const compassPath = path12.resolve(options.compass);
13897
- if (!fs8.existsSync(snapshotPath))
14301
+ const compassPath = path14.resolve(options.compass);
14302
+ if (!fs9.existsSync(snapshotPath))
13898
14303
  throw new Error(`workflow snapshot not found: ${snapshotPath}`);
13899
- if (!fs8.existsSync(compassPath))
14304
+ if (!fs9.existsSync(compassPath))
13900
14305
  throw new Error(`compass file not found: ${compassPath}`);
13901
14306
  const result = evaluatePhaseGate(readJson2(snapshotPath), parseCompassFrontmatter(compassPath), {
13902
14307
  currentBranch: options.branch,
@@ -13935,10 +14340,10 @@ dispatchCommand.command("validate").description("Validate an Assignment markdown
13935
14340
  throw new SddScriptError("usage: dispatch validate <assignment-file> [--branch <branch>]", 2);
13936
14341
  }
13937
14342
  const file = resolveCliPath(assignmentFile);
13938
- if (!fs8.existsSync(file)) {
14343
+ if (!fs9.existsSync(file)) {
13939
14344
  throw new Error(`assignment file not found: ${file}`);
13940
14345
  }
13941
- const text = fs8.readFileSync(file, "utf8");
14346
+ const text = fs9.readFileSync(file, "utf8");
13942
14347
  const readOnly = isReadOnlyAssignmentRole(parseAssignmentFields(text).executeAs ?? "");
13943
14348
  const violations = [...validateAssignmentFields(text, { writable: readOnly ? false : undefined }).violations];
13944
14349
  if (!readOnly) {
@@ -13997,7 +14402,7 @@ worktreeCommand.command("check").description("L1: verify the plan's execution_le
13997
14402
  throw new SddScriptError("usage: worktree check <plan-id> --workflow <id> [--harness <path>] [--control <path>] (or --plan <plan-id>)", 2);
13998
14403
  }
13999
14404
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
14000
- if (!fs8.existsSync(snapshotPath)) {
14405
+ if (!fs9.existsSync(snapshotPath)) {
14001
14406
  throw new Error(`workflow snapshot not found: ${snapshotPath}`);
14002
14407
  }
14003
14408
  const doc = readJson2(snapshotPath);
@@ -14018,7 +14423,7 @@ worktreeCommand.command("check").description("L1: verify the plan's execution_le
14018
14423
  const row = matches[0];
14019
14424
  const lease = row.execution_lease ?? {};
14020
14425
  const input = {
14021
- 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 ?? ""),
14022
14427
  leaseWorktreePath: String(lease.worktree_path ?? ""),
14023
14428
  leaseWorkingBranch: String(lease.working_branch ?? ""),
14024
14429
  planId: plan
@@ -14054,11 +14459,11 @@ worktreeCommand.command("qc-alignment").description("Assert the QC/QA alignment
14054
14459
  }
14055
14460
  const assignments = [];
14056
14461
  for (const fileArg of files) {
14057
- const file = path12.isAbsolute(fileArg) ? fileArg : `${process.cwd()}${path12.sep}${fileArg}`;
14058
- if (!fs8.existsSync(file)) {
14462
+ const file = path14.isAbsolute(fileArg) ? fileArg : `${process.cwd()}${path14.sep}${fileArg}`;
14463
+ if (!fs9.existsSync(file)) {
14059
14464
  throw new Error(`assignment file not found: ${file}`);
14060
14465
  }
14061
- const text = fs8.readFileSync(file, "utf8");
14466
+ const text = fs9.readFileSync(file, "utf8");
14062
14467
  const combinedRange = parseAssignmentHeaderField(text, "Review range / Diff basis");
14063
14468
  const planId = parseAssignmentHeaderField(text, "plan_id");
14064
14469
  const reviewRange = parseAssignmentHeaderField(text, "Review range") || combinedRange;
@@ -14100,11 +14505,11 @@ reviewCommand.command("seats").description("Map an Assignment's execution mode t
14100
14505
  if (!assignmentFile) {
14101
14506
  throw new SddScriptError("usage: review seats <assignment-file> [--mode sdd|inline|targeted] [--reviewers <role1,role2,...>]", 2);
14102
14507
  }
14103
- const file = path12.isAbsolute(assignmentFile) ? assignmentFile : `${process.cwd()}${path12.sep}${assignmentFile}`;
14104
- if (!fs8.existsSync(file)) {
14508
+ const file = path14.isAbsolute(assignmentFile) ? assignmentFile : `${process.cwd()}${path14.sep}${assignmentFile}`;
14509
+ if (!fs9.existsSync(file)) {
14105
14510
  throw new Error(`assignment file not found: ${file}`);
14106
14511
  }
14107
- const text = fs8.readFileSync(file, "utf8");
14512
+ const text = fs9.readFileSync(file, "utf8");
14108
14513
  const mode = options.mode ?? parseAssignmentExecutionMode(text);
14109
14514
  const reviewers = (options.reviewers ?? "").split(",").map((role) => role.trim()).filter((role) => role !== "");
14110
14515
  const result = executionModeToN(mode, { seats: reviewers });
@@ -14161,43 +14566,43 @@ var LINT_CODE_EXTENSIONS = {
14161
14566
  ".swift": true
14162
14567
  };
14163
14568
  function lintTargetType(filePath) {
14164
- const base = path12.basename(filePath);
14569
+ const base = path14.basename(filePath);
14165
14570
  if (base === "STRATEGY.md")
14166
14571
  return "strategy";
14167
14572
  if (base === "SKILL.md")
14168
14573
  return "skill";
14169
14574
  if (/^task-\d+-report\.md$/i.test(base))
14170
14575
  return "report";
14171
- const dir = path12.dirname(filePath);
14172
- 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`))
14173
14578
  return "plan";
14174
14579
  if (/^\d{8}-[a-z0-9.-]+\.md$/i.test(base))
14175
14580
  return "plan";
14176
- if (LINT_CODE_EXTENSIONS[path12.extname(base).toLowerCase()] === true)
14581
+ if (LINT_CODE_EXTENSIONS[path14.extname(base).toLowerCase()] === true)
14177
14582
  return "code";
14178
14583
  return null;
14179
14584
  }
14180
14585
  function collectLintTargets(dir) {
14181
14586
  const targets = [];
14182
14587
  const visit = (current) => {
14183
- for (const entry of fs8.readdirSync(current, { withFileTypes: true })) {
14184
- if (entry.name.includes(path12.sep))
14588
+ for (const entry of fs9.readdirSync(current, { withFileTypes: true })) {
14589
+ if (entry.name.includes(path14.sep))
14185
14590
  continue;
14186
14591
  const child = current + entry.name;
14187
14592
  if (entry.isDirectory()) {
14188
14593
  if (LINT_SKIP_DIRS[entry.name] !== true)
14189
- visit(child + path12.sep);
14594
+ visit(child + path14.sep);
14190
14595
  } else if (entry.isFile() && lintTargetType(child) !== null) {
14191
14596
  targets.push(child);
14192
14597
  }
14193
14598
  }
14194
14599
  };
14195
- const root = dir.endsWith(path12.sep) ? `${dir}` : `${dir}${path12.sep}`;
14600
+ const root = dir.endsWith(path14.sep) ? `${dir}` : `${dir}${path14.sep}`;
14196
14601
  visit(root);
14197
14602
  return targets;
14198
14603
  }
14199
14604
  var lintIo = {
14200
- readText: async (resolvedPath) => fs8.promises.readFile(resolvedPath, "utf8")
14605
+ readText: async (resolvedPath) => fs9.promises.readFile(resolvedPath, "utf8")
14201
14606
  };
14202
14607
  async function lintOneFile(filePath, forcedType, prVariant) {
14203
14608
  const text = await lintIo.readText(filePath);
@@ -14233,7 +14638,7 @@ async function lintOneFile(filePath, forcedType, prVariant) {
14233
14638
  violations.push(...validateFindingDoc(text, { ...prVariant ? { prVariant: true } : {} }).violations);
14234
14639
  break;
14235
14640
  default:
14236
- throw new SddScriptError(`usage: lint <target> \u2014 unsupported file type "${path12.basename(filePath)}" (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);
14237
14642
  }
14238
14643
  return { violations, markers };
14239
14644
  }
@@ -14252,9 +14657,9 @@ lintCommand.description("Lint <target> (file or dir) \u2014 exit 1 on violations
14252
14657
  forcedType = forced;
14253
14658
  }
14254
14659
  const abs = resolveCliPath(target);
14255
- if (!fs8.existsSync(abs))
14660
+ if (!fs9.existsSync(abs))
14256
14661
  throw new Error(`lint target not found: ${abs}`);
14257
- const targets = fs8.statSync(abs).isDirectory() ? collectLintTargets(abs) : [abs];
14662
+ const targets = fs9.statSync(abs).isDirectory() ? collectLintTargets(abs) : [abs];
14258
14663
  if (targets.length === 0) {
14259
14664
  console.log(import_picocolors2.default.yellow(`lint: no lintable files under ${target}`));
14260
14665
  return;
@@ -14299,17 +14704,17 @@ designMdCommand.command("validate").description("Validate DESIGN.md in <dir>: to
14299
14704
  if (!dir)
14300
14705
  throw new SddScriptError("usage: design-md validate <dir>", 2);
14301
14706
  const abs = resolveCliPath(dir);
14302
- const lightPath = `${abs}${path12.sep}DESIGN.md`;
14303
- if (!fs8.existsSync(lightPath))
14707
+ const lightPath = `${abs}${path14.sep}DESIGN.md`;
14708
+ if (!fs9.existsSync(lightPath))
14304
14709
  throw new Error(`design file not found: ${lightPath}`);
14305
- const light = fs8.readFileSync(lightPath, "utf8");
14710
+ const light = fs9.readFileSync(lightPath, "utf8");
14306
14711
  const violations = [];
14307
14712
  const tokens = validateDesignTokenFrontmatter(light);
14308
14713
  printChecklist("design-md validate (tokens)", tokens);
14309
14714
  violations.push(...tokens.violations);
14310
- const darkPath = `${abs}${path12.sep}DESIGN.dark.md`;
14311
- if (fs8.existsSync(darkPath)) {
14312
- 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"));
14313
14718
  printChecklist("design-md validate (light/dark parity)", parity);
14314
14719
  violations.push(...parity.violations);
14315
14720
  }
@@ -14457,7 +14862,7 @@ auditCommand.command("scaffold").description("Scaffold an audit-<date>/ plan dir
14457
14862
  if (!findingsFile)
14458
14863
  throw new SddScriptError("usage: audit scaffold <findings-file> [--dir <out-dir>]", 2);
14459
14864
  const abs = resolveCliPath(findingsFile);
14460
- if (!fs8.existsSync(abs))
14865
+ if (!fs9.existsSync(abs))
14461
14866
  throw new Error(`findings file not found: ${abs}`);
14462
14867
  if (options.date !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(options.date)) {
14463
14868
  throw new SddScriptError("usage: audit scaffold \u2014 --date must be YYYY-MM-DD", 2);
@@ -14467,7 +14872,7 @@ auditCommand.command("scaffold").description("Scaffold an audit-<date>/ plan dir
14467
14872
  }
14468
14873
  const date = options.date ?? new Date().toISOString().slice(0, 10);
14469
14874
  const outDir = options.dir !== undefined ? resolveCliPath(options.dir) : resolveCliPath(`audit-${date}`);
14470
- const input = parseAuditScaffoldInput(fs8.readFileSync(abs, "utf8"));
14875
+ const input = parseAuditScaffoldInput(fs9.readFileSync(abs, "utf8"));
14471
14876
  const sha = resolveAuditShortSha(process.cwd(), options.sha);
14472
14877
  const result = scaffoldAuditPlan(outDir, input.findings, {
14473
14878
  date,
@@ -14494,7 +14899,7 @@ auditCommand.command("promote").description("Promote selected audit plans into t
14494
14899
  throw new SddScriptError("usage: audit promote <audit-dir> --plans <ids> [--workflow <id>] [--harness <dir>]", 2);
14495
14900
  }
14496
14901
  const outDir = resolveCliPath(auditDir);
14497
- if (!fs8.existsSync(outDir)) {
14902
+ if (!fs9.existsSync(outDir)) {
14498
14903
  throw new Error(`audit dir not found: ${outDir}`);
14499
14904
  }
14500
14905
  const harnessDir = resolveLeaseHarnessDir(options.harness);
@@ -14520,12 +14925,12 @@ function listTrackedFiles(root) {
14520
14925
  } catch {
14521
14926
  throw new SddScriptError("not a git repository or git unavailable \u2014 refusing to report an empty scan as clean", 2);
14522
14927
  }
14523
- return out.split("\x00").filter((f) => f !== "").map((f) => root.endsWith(path12.sep) ? root + f : root + path12.sep + f);
14928
+ return out.split("\x00").filter((f) => f !== "").map((f) => root.endsWith(path14.sep) ? root + f : root + path14.sep + f);
14524
14929
  }
14525
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) => {
14526
14931
  try {
14527
14932
  const root = scanPath !== undefined ? resolveCliPath(scanPath) : process.cwd();
14528
- if (!fs8.existsSync(root) || !fs8.statSync(root).isDirectory()) {
14933
+ if (!fs9.existsSync(root) || !fs9.statSync(root).isDirectory()) {
14529
14934
  throw new SddScriptError(`usage: audit secret-scan [path] \u2014 not a directory: ${root}`, 2);
14530
14935
  }
14531
14936
  const files = listTrackedFiles(root);
@@ -14552,7 +14957,7 @@ auditCommand.command("secret-scan").description("Read-only credential-pattern sc
14552
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) => {
14553
14958
  try {
14554
14959
  const root = repoPath !== undefined ? resolveCliPath(repoPath) : process.cwd();
14555
- if (!fs8.existsSync(root) || !fs8.statSync(root).isDirectory()) {
14960
+ if (!fs9.existsSync(root) || !fs9.statSync(root).isDirectory()) {
14556
14961
  throw new SddScriptError(`usage: audit supply-chain [path] \u2014 not a directory: ${root}`, 2);
14557
14962
  }
14558
14963
  const result = supplyChainChecks(root);
@@ -14579,9 +14984,9 @@ compoundCommand.command("validate").description("Validate a knowledge doc frontm
14579
14984
  if (!docPath)
14580
14985
  throw new SddScriptError("usage: compound validate <doc-path> [--knowledge-dir <dir>]", 2);
14581
14986
  const abs = resolveCliPath(docPath);
14582
- if (!fs8.existsSync(abs))
14987
+ if (!fs9.existsSync(abs))
14583
14988
  throw new Error(`knowledge doc not found: ${abs}`);
14584
- const text = fs8.readFileSync(abs, "utf8");
14989
+ const text = fs9.readFileSync(abs, "utf8");
14585
14990
  const violations = [];
14586
14991
  const schema = validateSchemaYaml(text);
14587
14992
  printChecklist("compound validate (schema)", schema);
@@ -14671,15 +15076,15 @@ skillCommand.command("lint").description("Lint <skill-dir>/SKILL.md: frontmatter
14671
15076
  try {
14672
15077
  if (!skillDir)
14673
15078
  throw new SddScriptError("usage: skill lint <skill-dir>", 2);
14674
- const skillFile = path12.join(resolveCliPath(skillDir), "SKILL.md");
14675
- if (!fs8.existsSync(skillFile))
15079
+ const skillFile = path14.join(resolveCliPath(skillDir), "SKILL.md");
15080
+ if (!fs9.existsSync(skillFile))
14676
15081
  throw new Error(`SKILL.md not found: ${skillFile}`);
14677
- const text = fs8.readFileSync(skillFile, "utf8");
15082
+ const text = fs9.readFileSync(skillFile, "utf8");
14678
15083
  const violations = [];
14679
15084
  const frontmatter = lintSkillFrontmatter(text);
14680
15085
  printChecklist("skill lint (frontmatter)", frontmatter);
14681
15086
  violations.push(...frontmatter.violations);
14682
- const profile = classifySkillLint(path12.basename(path12.dirname(skillFile)));
15087
+ const profile = classifySkillLint(path14.basename(path14.dirname(skillFile)));
14683
15088
  if (profile.mode === null) {
14684
15089
  console.log(import_picocolors2.default.yellow("skill lint (five questions): EXEMPT \u2014 mstar-harness-core is exempt by design (hub headings)"));
14685
15090
  } else {
@@ -14710,20 +15115,20 @@ var rolesCommand = program2.command("roles").description("mstar-roles mapping /
14710
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) => {
14711
15116
  try {
14712
15117
  const rolesDir = resolveCliPath(options.rolesDir ?? "skills/mstar-roles");
14713
- const skillsRoot = options.skillsDir ? resolveCliPath(options.skillsDir) : path12.dirname(rolesDir);
15118
+ const skillsRoot = options.skillsDir ? resolveCliPath(options.skillsDir) : path14.dirname(rolesDir);
14714
15119
  const violations = [];
14715
15120
  const mapping = validateRoleMapping(rolesDir);
14716
15121
  printChecklist("roles validate (mapping)", mapping);
14717
15122
  violations.push(...mapping.violations);
14718
15123
  const skillTexts = {};
14719
- for (const entry of fs8.readdirSync(skillsRoot, { withFileTypes: true })) {
15124
+ for (const entry of fs9.readdirSync(skillsRoot, { withFileTypes: true })) {
14720
15125
  if (!entry.isDirectory() || !entry.name.startsWith("mstar-"))
14721
15126
  continue;
14722
- const skillFile = path12.join(skillsRoot, entry.name, "SKILL.md");
14723
- if (!fs8.existsSync(skillFile))
15127
+ const skillFile = path14.join(skillsRoot, entry.name, "SKILL.md");
15128
+ if (!fs9.existsSync(skillFile))
14724
15129
  continue;
14725
15130
  try {
14726
- skillTexts[entry.name] = fs8.readFileSync(skillFile, "utf8");
15131
+ skillTexts[entry.name] = fs9.readFileSync(skillFile, "utf8");
14727
15132
  } catch {}
14728
15133
  }
14729
15134
  const loadOrder = lintLoadOrder(skillTexts);
@@ -14765,11 +15170,11 @@ function parsePrReviewTarget(raw) {
14765
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) => {
14766
15171
  try {
14767
15172
  const findingsPath = resolveCliPath(options.findings);
14768
- if (!fs8.existsSync(findingsPath))
15173
+ if (!fs9.existsSync(findingsPath))
14769
15174
  throw new Error(`findings file not found: ${findingsPath}`);
14770
15175
  let parsed;
14771
15176
  try {
14772
- parsed = JSON.parse(fs8.readFileSync(findingsPath, "utf8"));
15177
+ parsed = JSON.parse(fs9.readFileSync(findingsPath, "utf8"));
14773
15178
  } catch (error) {
14774
15179
  throw new Error(`--findings is not valid JSON: ${error.message}`);
14775
15180
  }
@@ -14847,9 +15252,9 @@ prReviewCommand.command("report-path").description("Resolve the local-report (or
14847
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) => {
14848
15253
  try {
14849
15254
  const abs = resolveCliPath(reportFile);
14850
- if (!fs8.existsSync(abs))
15255
+ if (!fs9.existsSync(abs))
14851
15256
  throw new Error(`report file not found: ${abs}`);
14852
- const gate2 = validatePrReviewReport(fs8.readFileSync(abs, "utf8"));
15257
+ const gate2 = validatePrReviewReport(fs9.readFileSync(abs, "utf8"));
14853
15258
  printChecklist(abs, gate2);
14854
15259
  if (!gate2.ok)
14855
15260
  process.exitCode = 1;
@@ -14942,13 +15347,13 @@ function parseFindingEntry(entry, index) {
14942
15347
  const rec = entry;
14943
15348
  if (rec.path === undefined && rec.body === undefined && rec.line === undefined)
14944
15349
  return null;
14945
- const path13 = typeof rec.path === "string" ? rec.path : "";
15350
+ const path15 = typeof rec.path === "string" ? rec.path : "";
14946
15351
  const body = typeof rec.body === "string" ? rec.body : "";
14947
15352
  const line = typeof rec.line === "number" ? rec.line : Number.NaN;
14948
- if (!path13.trim() || !body.trim() || !Number.isInteger(line) || line < 1) {
15353
+ if (!path15.trim() || !body.trim() || !Number.isInteger(line) || line < 1) {
14949
15354
  throw new Error(`findings[${index}] must be an object {path: string, line: number >= 1, body: string} - got ${JSON.stringify(entry)}`);
14950
15355
  }
14951
- return { path: path13, line, side: "RIGHT", body };
15356
+ return { path: path15, line, side: "RIGHT", body };
14952
15357
  }
14953
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) => {
14954
15359
  try {
@@ -14957,17 +15362,17 @@ prReviewCommand.command("post").description("Build and POST the GitHub Review pe
14957
15362
  }
14958
15363
  const prNumber = Number(options.pr);
14959
15364
  const bodyPath = resolveCliPath(options.bodyFile);
14960
- if (!fs8.existsSync(bodyPath))
15365
+ if (!fs9.existsSync(bodyPath))
14961
15366
  throw new Error(`body file not found: ${bodyPath}`);
14962
- const body = fs8.readFileSync(bodyPath, "utf8");
15367
+ const body = fs9.readFileSync(bodyPath, "utf8");
14963
15368
  let comments = [];
14964
15369
  if (options.findings !== undefined) {
14965
15370
  const findingsPath = resolveCliPath(options.findings);
14966
- if (!fs8.existsSync(findingsPath))
15371
+ if (!fs9.existsSync(findingsPath))
14967
15372
  throw new Error(`findings file not found: ${findingsPath}`);
14968
15373
  let parsed;
14969
15374
  try {
14970
- parsed = JSON.parse(fs8.readFileSync(findingsPath, "utf8"));
15375
+ parsed = JSON.parse(fs9.readFileSync(findingsPath, "utf8"));
14971
15376
  } catch (error) {
14972
15377
  throw new Error(`--findings is not valid JSON: ${error.message}`);
14973
15378
  }
@@ -15071,7 +15476,7 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
15071
15476
  throw new SddScriptError("usage: pr-review worktree-setup \u2014 the five input modes are mutually exclusive", 2);
15072
15477
  }
15073
15478
  const startDir = process.cwd();
15074
- 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) === "") {
15075
15480
  throw new Error(`not a git repository: ${startDir}`);
15076
15481
  }
15077
15482
  const repoRoot = gitSync(["rev-parse", "--show-toplevel"], startDir);
@@ -15145,15 +15550,15 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
15145
15550
  const baseCandidate = mode === "pr" ? namePrNumber : Number(String(Math.abs([...headSpec].reduce((h, ch) => (h * 31 + ch.charCodeAt(0)) % 1000003, 7))));
15146
15551
  const reviewBranch = pickReviewBranchName(existing, baseCandidate === 0 ? 1 : baseCandidate, cliToday().replace(/-/g, ""));
15147
15552
  const branchSuffix = mode === "pr" ? "" : `-${headSpec.slice(0, 8)}`;
15148
- 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}`));
15149
15554
  if (options.path === undefined) {
15150
- fs8.mkdirSync(path12.join(repoRoot, ".worktrees"), { recursive: true });
15555
+ fs9.mkdirSync(path14.join(repoRoot, ".worktrees"), { recursive: true });
15151
15556
  if (gitIf(["check-ignore", ".worktrees/"], repoRoot) === "") {
15152
- const excludePath = path12.join(repoRoot, ".git", "info", "exclude");
15153
- 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") : "";
15154
15559
  if (!existing2.split(`
15155
15560
  `).some((line) => line.trim() === ".worktrees/")) {
15156
- fs8.appendFileSync(excludePath, `${existing2 === "" || existing2.endsWith(`
15561
+ fs9.appendFileSync(excludePath, `${existing2 === "" || existing2.endsWith(`
15157
15562
  `) ? "" : `
15158
15563
  `}.worktrees/
15159
15564
  `);
@@ -15181,7 +15586,7 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
15181
15586
  let sidecarFd;
15182
15587
  const cleanupOnFailure = (branchToDelete) => {
15183
15588
  try {
15184
- if (fs8.existsSync(worktreePath))
15589
+ if (fs9.existsSync(worktreePath))
15185
15590
  gitSync(["worktree", "remove", "--force", worktreePath], repoRoot);
15186
15591
  gitSync(["worktree", "prune"], repoRoot);
15187
15592
  if (branchToDelete !== "" && !existing.has(branchToDelete)) {
@@ -15272,7 +15677,7 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
15272
15677
  diffFileSha256: createHash("sha256").update(snapshot).digest("hex")
15273
15678
  };
15274
15679
  try {
15275
- sidecarFd = fs8.openSync(sidecarPath, "wx+");
15680
+ sidecarFd = fs9.openSync(sidecarPath, "wx+");
15276
15681
  } catch (error) {
15277
15682
  if (error.code !== "EEXIST" && error.code !== "EISDIR")
15278
15683
  throw error;
@@ -15281,21 +15686,21 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
15281
15686
  writeFdSync(sidecarFd, Buffer.from(JSON.stringify(sidecar2, null, 2), "utf8"));
15282
15687
  wroteSidecar = true;
15283
15688
  try {
15284
- fs8.writeFileSync(diffFile, snapshot, { flag: "wx" });
15689
+ fs9.writeFileSync(diffFile, snapshot, { flag: "wx" });
15285
15690
  } catch (error) {
15286
15691
  if (error.code !== "EEXIST" && error.code !== "EISDIR")
15287
15692
  throw error;
15288
15693
  throw new Error(`refusing to overwrite pre-existing non-snapshot path ${diffFile}`);
15289
15694
  }
15290
15695
  wroteSnapshot = true;
15291
- const snapshotStat = fs8.lstatSync(diffFile);
15696
+ const snapshotStat = fs9.lstatSync(diffFile);
15292
15697
  sidecar2.diffFileDev = snapshotStat.dev;
15293
15698
  sidecar2.diffFileIno = String(snapshotStat.ino);
15294
15699
  sidecar2.diffFileMtimeMs = snapshotStat.mtimeMs;
15295
15700
  pendingSidecar = sidecar2;
15296
- fs8.ftruncateSync(sidecarFd, 0);
15701
+ fs9.ftruncateSync(sidecarFd, 0);
15297
15702
  writeFdSync(sidecarFd, Buffer.from(JSON.stringify(sidecar2, null, 2), "utf8"));
15298
- fs8.closeSync(sidecarFd);
15703
+ fs9.closeSync(sidecarFd);
15299
15704
  sidecarFd = undefined;
15300
15705
  return sidecar2;
15301
15706
  };
@@ -15319,21 +15724,21 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
15319
15724
  }
15320
15725
  });
15321
15726
  function prReviewArtifactPathFor(worktreePath, suffix) {
15322
- const parent = path12.dirname(worktreePath);
15323
- const name = path12.basename(worktreePath);
15324
- const prefix = parent.endsWith(path12.sep) ? parent : parent + path12.sep;
15727
+ const parent = path14.dirname(worktreePath);
15728
+ const name = path14.basename(worktreePath);
15729
+ const prefix = parent.endsWith(path14.sep) ? parent : parent + path14.sep;
15325
15730
  return `${prefix}.${name}.prreview.${suffix}`;
15326
15731
  }
15327
15732
  function writeFdSync(fd, buf) {
15328
15733
  let written = 0;
15329
15734
  while (written < buf.length)
15330
- written += fs8.writeSync(fd, buf, written, buf.length - written, written);
15735
+ written += fs9.writeSync(fd, buf, written, buf.length - written, written);
15331
15736
  }
15332
15737
  function removeOwnedSnapshotFile(worktreePath, sidecar) {
15333
15738
  const snapshotPath = prReviewArtifactPathFor(worktreePath, "diff");
15334
15739
  let fd;
15335
15740
  try {
15336
- fd = fs8.openSync(snapshotPath, "r");
15741
+ fd = fs9.openSync(snapshotPath, "r");
15337
15742
  } catch (error) {
15338
15743
  if (error.code === "ENOENT")
15339
15744
  return;
@@ -15341,7 +15746,7 @@ function removeOwnedSnapshotFile(worktreePath, sidecar) {
15341
15746
  return;
15342
15747
  }
15343
15748
  try {
15344
- const st = fs8.fstatSync(fd);
15749
+ const st = fs9.fstatSync(fd);
15345
15750
  if (!st.isFile())
15346
15751
  return;
15347
15752
  const recordedIno = sidecar.diffFileIno;
@@ -15358,28 +15763,28 @@ function removeOwnedSnapshotFile(worktreePath, sidecar) {
15358
15763
  }
15359
15764
  const tmp = `${snapshotPath}.cleanup.${process.pid}.${randomUUID3()}`;
15360
15765
  try {
15361
- fs8.renameSync(snapshotPath, tmp);
15766
+ fs9.renameSync(snapshotPath, tmp);
15362
15767
  } catch (error) {
15363
15768
  console.error(import_picocolors2.default.yellow(`worktree-cleanup: snapshot at ${snapshotPath} left in place (cannot detach: ${error.message})`));
15364
15769
  return;
15365
15770
  }
15366
- const st2 = fs8.fstatSync(fd);
15771
+ const st2 = fs9.fstatSync(fd);
15367
15772
  let tmpStat;
15368
15773
  try {
15369
- tmpStat = fs8.lstatSync(tmp);
15774
+ tmpStat = fs9.lstatSync(tmp);
15370
15775
  } catch {
15371
15776
  tmpStat = undefined;
15372
15777
  }
15373
15778
  if (tmpStat !== undefined && tmpStat.ino === st2.ino && tmpStat.dev === st2.dev && st2.nlink === 1 && tmpStat.nlink === 1) {
15374
- fs8.unlinkSync(tmp);
15375
- const st3 = fs8.fstatSync(fd);
15779
+ fs9.unlinkSync(tmp);
15780
+ const st3 = fs9.fstatSync(fd);
15376
15781
  if (st3.nlink !== 0) {
15377
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`));
15378
15783
  }
15379
15784
  } else {
15380
15785
  try {
15381
- fs8.linkSync(tmp, snapshotPath);
15382
- fs8.unlinkSync(tmp);
15786
+ fs9.linkSync(tmp, snapshotPath);
15787
+ fs9.unlinkSync(tmp);
15383
15788
  } catch (error) {
15384
15789
  if (error.code === "EEXIST") {
15385
15790
  console.error(import_picocolors2.default.yellow(`worktree-cleanup: snapshot replacement left at ${tmp} (snapshot path was recreated concurrently)`));
@@ -15389,41 +15794,41 @@ function removeOwnedSnapshotFile(worktreePath, sidecar) {
15389
15794
  }
15390
15795
  }
15391
15796
  } finally {
15392
- fs8.closeSync(fd);
15797
+ fs9.closeSync(fd);
15393
15798
  }
15394
15799
  }
15395
15800
  function removeOwnedFreshSidecarFile(sidecarFd, worktreePath) {
15396
15801
  const sidecarPath = prReviewArtifactPathFor(worktreePath, "json");
15397
15802
  try {
15398
- const st = fs8.fstatSync(sidecarFd);
15803
+ const st = fs9.fstatSync(sidecarFd);
15399
15804
  if (!st.isFile() || st.nlink !== 1) {
15400
15805
  console.error(import_picocolors2.default.yellow(`worktree-setup rollback: sidecar at ${sidecarPath} left in place (identity no longer held)`));
15401
15806
  return;
15402
15807
  }
15403
15808
  const tmp = `${sidecarPath}.cleanup.${process.pid}.${randomUUID3()}`;
15404
15809
  try {
15405
- fs8.renameSync(sidecarPath, tmp);
15810
+ fs9.renameSync(sidecarPath, tmp);
15406
15811
  } catch (error) {
15407
15812
  console.error(import_picocolors2.default.yellow(`worktree-setup rollback: sidecar at ${sidecarPath} left in place (cannot detach: ${error.message})`));
15408
15813
  return;
15409
15814
  }
15410
- const st2 = fs8.fstatSync(sidecarFd);
15815
+ const st2 = fs9.fstatSync(sidecarFd);
15411
15816
  let tmpStat;
15412
15817
  try {
15413
- tmpStat = fs8.lstatSync(tmp);
15818
+ tmpStat = fs9.lstatSync(tmp);
15414
15819
  } catch {
15415
15820
  tmpStat = undefined;
15416
15821
  }
15417
15822
  if (tmpStat !== undefined && tmpStat.ino === st2.ino && tmpStat.dev === st2.dev) {
15418
- fs8.unlinkSync(tmp);
15419
- const st3 = fs8.fstatSync(sidecarFd);
15823
+ fs9.unlinkSync(tmp);
15824
+ const st3 = fs9.fstatSync(sidecarFd);
15420
15825
  if (st3.nlink !== 0) {
15421
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`));
15422
15827
  }
15423
15828
  } else {
15424
15829
  try {
15425
- fs8.linkSync(tmp, sidecarPath);
15426
- fs8.unlinkSync(tmp);
15830
+ fs9.linkSync(tmp, sidecarPath);
15831
+ fs9.unlinkSync(tmp);
15427
15832
  } catch (error) {
15428
15833
  if (error.code === "EEXIST") {
15429
15834
  console.error(import_picocolors2.default.yellow(`worktree-setup rollback: sidecar replacement left at ${tmp} (sidecar path was recreated concurrently)`));
@@ -15434,24 +15839,24 @@ function removeOwnedFreshSidecarFile(sidecarFd, worktreePath) {
15434
15839
  }
15435
15840
  } finally {
15436
15841
  try {
15437
- fs8.closeSync(sidecarFd);
15842
+ fs9.closeSync(sidecarFd);
15438
15843
  } catch {}
15439
15844
  }
15440
15845
  }
15441
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) => {
15442
15847
  try {
15443
- const worktreePath = path12.resolve(resolveCliPath(options.path));
15848
+ const worktreePath = path14.resolve(resolveCliPath(options.path));
15444
15849
  const sidecarPath = prReviewArtifactPathFor(worktreePath, "json");
15445
- if (!fs8.existsSync(sidecarPath)) {
15850
+ if (!fs9.existsSync(sidecarPath)) {
15446
15851
  throw new Error(`no setup sidecar found at ${sidecarPath} - run pr-review worktree-setup first (foreign worktrees are never cleaned here)`);
15447
15852
  }
15448
15853
  let sidecar;
15449
15854
  try {
15450
- sidecar = JSON.parse(fs8.readFileSync(sidecarPath, "utf8"));
15855
+ sidecar = JSON.parse(fs9.readFileSync(sidecarPath, "utf8"));
15451
15856
  } catch (error) {
15452
15857
  throw new Error(`setup sidecar at ${sidecarPath} is not valid JSON: ${error.message}`);
15453
15858
  }
15454
- 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);
15455
15860
  if (sidecar.reviewBranch === "") {
15456
15861
  if (options.branch !== "") {
15457
15862
  throw new Error(`this setup recorded no review branch (detached review) - refusing ${JSON.stringify(options.branch)} as a foreign branch`);
@@ -15463,7 +15868,7 @@ prReviewCommand.command("worktree-cleanup").description("Remove the review workt
15463
15868
  if (!savedOk) {
15464
15869
  throw new Error("refusing cleanup: the local report is not saved yet - save it first or pass --report-saved (\xA7 Local report archive)");
15465
15870
  }
15466
- if (fs8.existsSync(worktreePath)) {
15871
+ if (fs9.existsSync(worktreePath)) {
15467
15872
  gitSync(["worktree", "remove", worktreePath], gitRoot);
15468
15873
  }
15469
15874
  gitSync(["worktree", "prune"], gitRoot);
@@ -15474,7 +15879,7 @@ prReviewCommand.command("worktree-cleanup").description("Remove the review workt
15474
15879
  gitSync(["branch", "-D", sidecar.reviewBranch], gitRoot);
15475
15880
  }
15476
15881
  removeOwnedSnapshotFile(worktreePath, sidecar);
15477
- fs8.rmSync(sidecarPath, { force: true });
15882
+ fs9.rmSync(sidecarPath, { force: true });
15478
15883
  console.log(import_picocolors2.default.green(`worktree-cleanup: removed ${worktreePath}${sidecar.reviewBranch !== "" ? ` + deleted ${sidecar.reviewBranch}` : " (no local branch to delete)"}`));
15479
15884
  } catch (error) {
15480
15885
  failScript(error, "pr-review worktree-cleanup");
@@ -15532,17 +15937,17 @@ prReviewCommand.command("seat-prompt").description("Generate the read-only audit
15532
15937
  if (tier !== undefined && tier !== "quick" && tier !== "default" && tier !== "deep") {
15533
15938
  throw new SddScriptError(`usage: pr-review seat-prompt \u2014 --tier must be quick | default | deep, got ${JSON.stringify(tier)}`, 2);
15534
15939
  }
15535
- 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"));
15536
15941
  const prompt = prReviewSeatPrompt({
15537
15942
  stage: options.stage === "1" ? 1 : 2,
15538
15943
  domain: options.domain,
15539
15944
  seat: options.seat,
15540
15945
  skillRoot: auditSkillRoot,
15541
- worktreePath: path12.resolve(options.worktree),
15946
+ worktreePath: path14.resolve(options.worktree),
15542
15947
  reconFacts: options.recon ?? [],
15543
15948
  ...options.security === true ? { securitySeat: true } : {},
15544
15949
  ...tier !== undefined ? { tier } : {},
15545
- ...options.diffFile !== undefined && options.diffFile !== "" ? { diffFile: path12.resolve(resolveCliPath(options.diffFile)) } : {},
15950
+ ...options.diffFile !== undefined && options.diffFile !== "" ? { diffFile: path14.resolve(resolveCliPath(options.diffFile)) } : {},
15546
15951
  ...options.collectFolded === true ? { collectFolded: true } : {}
15547
15952
  });
15548
15953
  console.log(prompt);