@mstar-harness/cli 3.6.3 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/mstar-harness.js +734 -103
  2. package/package.json +1 -1
@@ -4106,14 +4106,15 @@ import { dirname as dirname4, join as join7, resolve as resolve5, sep } from "no
4106
4106
  import { execFileSync as execFileSync2 } from "node:child_process";
4107
4107
  import { existsSync as existsSync7 } from "node:fs";
4108
4108
  import { isAbsolute as isAbsolute5, resolve as resolve8 } from "node:path";
4109
- import { execFileSync as execFileSync3 } from "node:child_process";
4109
+ import { execFileSync as execFileSync3, spawn } from "node:child_process";
4110
4110
  import { mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as readFileSync7, realpathSync as realpathSync3, statSync as statSync4, writeFileSync as writeFileSync4 } from "node:fs";
4111
- import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute6, join as join10, resolve as resolve9 } from "node:path";
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
4113
  import { execFileSync as execFileSync4 } from "node:child_process";
4113
4114
  import { existsSync as existsSync8, mkdirSync as mkdirSync8, readdirSync as readdirSync8, readFileSync as readFileSync9, rmdirSync as rmdirSync2, rmSync, writeFileSync as writeFileSync6 } from "node:fs";
4114
4115
  import { basename as basename5, join as join12, resolve as resolve11, sep as sep3 } from "node:path";
4115
4116
  import { existsSync as existsSync9, readdirSync as readdirSync9, readFileSync as readFileSync10 } from "node:fs";
4116
- import { basename as basename6, isAbsolute as isAbsolute8, join as join13, relative as relative4, resolve as resolve12, sep as sep4 } from "node:path";
4117
+ import { basename as basename6, isAbsolute as isAbsolute8, join as join13, relative as relative5, resolve as resolve12, sep as sep4 } from "node:path";
4117
4118
  import { existsSync as existsSync10 } from "node:fs";
4118
4119
  import { join as join14 } from "node:path";
4119
4120
  import { readdirSync as readdirSync10 } from "node:fs";
@@ -4590,6 +4591,32 @@ function validateIntegrationMergeLease(lease) {
4590
4591
  }
4591
4592
  return { ok: violations.length === 0, violations };
4592
4593
  }
4594
+ function planExecutionLeaseLocations(row) {
4595
+ return { row: row.execution_lease };
4596
+ }
4597
+ function verifyPlanExecutionLease(row, planId) {
4598
+ const { row: rowLease } = planExecutionLeaseLocations(row);
4599
+ const lease = rowLease;
4600
+ if (lease === undefined) {
4601
+ if (row.status === "InProgress") {
4602
+ return {
4603
+ ok: false,
4604
+ violations: [
4605
+ violation2("high", "lease.verify.orphan", "plan is InProgress without an execution_lease \u2014 orphan: STOP, no writable dispatch until recovery (status-and-residuals.md \u00a7 Orphan recovery)")
4606
+ ]
4607
+ };
4608
+ }
4609
+ return {
4610
+ ok: false,
4611
+ violations: [
4612
+ violation2("high", "lease.verify.missing", `plan ${planId} has no execution_lease at the SSOT location plans[].execution_lease`)
4613
+ ]
4614
+ };
4615
+ }
4616
+ const violations = [];
4617
+ violations.push(...validateExecutionLease(lease).violations);
4618
+ return { ok: violations.length === 0, violations, lease };
4619
+ }
4593
4620
  var STATUS_WRITE_LOCKDIR = ".status-write.lockdir";
4594
4621
  var LOCKDIR_HOLDER_PID = "holder.pid";
4595
4622
  var heldLockDirs = new AsyncLocalStorage2;
@@ -5664,11 +5691,40 @@ function resolveSpecsDir(harnessDir, opts = {}) {
5664
5691
  mkdirSync5(fallback, { recursive: true });
5665
5692
  return fallback;
5666
5693
  }
5694
+ function resolvePlanDir(harnessDir) {
5695
+ const declared = mstarcDirOverride(harnessDir, "planDir");
5696
+ if (declared !== null)
5697
+ return declared;
5698
+ const dir = resolve7(harnessDir);
5699
+ const name = basename3(dir);
5700
+ if (name === ".plans" || name === "plans")
5701
+ return dir;
5702
+ return join9(dir, "plans");
5703
+ }
5667
5704
  function assertSafePathComponent(value, what) {
5668
5705
  if (value === "" || value === "." || value === ".." || !/^[A-Za-z0-9._-]+$/.test(value)) {
5669
5706
  throw new Error(`${what} must be a single safe path component ([A-Za-z0-9._-]+; not "", ".", "..", or containing "/" or "\\") \u2014 got ${JSON.stringify(value)}`);
5670
5707
  }
5671
5708
  }
5709
+ function canonicalizeNearestExisting(path2) {
5710
+ const abs = resolve7(path2);
5711
+ let dir = abs;
5712
+ const tail = [];
5713
+ for (;; ) {
5714
+ if (existsSync6(dir)) {
5715
+ try {
5716
+ return join9(realpathSync2(dir), ...tail);
5717
+ } catch {
5718
+ return abs;
5719
+ }
5720
+ }
5721
+ const parent = dirname5(dir);
5722
+ if (parent === dir)
5723
+ return abs;
5724
+ tail.unshift(basename3(dir));
5725
+ dir = parent;
5726
+ }
5727
+ }
5672
5728
  function resolveSddDir(harnessDir, planId) {
5673
5729
  assertSafePathComponent(planId, "planId");
5674
5730
  const base = resolve7(harnessDir);
@@ -5783,6 +5839,53 @@ function detectHarnessKind(harnessDir) {
5783
5839
  return "agents";
5784
5840
  return null;
5785
5841
  }
5842
+ function assertPlanWritingPath(planPath, harnessDir) {
5843
+ const planAbs = resolve7(planPath);
5844
+ if (!harnessDir) {
5845
+ return {
5846
+ ok: false,
5847
+ severity: "high",
5848
+ code: "plan-path.no-harness",
5849
+ message: `persistent plan tracking is not enabled \u2014 cannot place plan ${planAbs} under {PLAN_DIR}`,
5850
+ fix: "initialize the harness (scaffoldHarness) so plans land in {PLAN_DIR}"
5851
+ };
5852
+ }
5853
+ const planDir = resolvePlanDir(harnessDir);
5854
+ const rel = relative2(planDir, planAbs);
5855
+ const inside = rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
5856
+ if (!inside) {
5857
+ return {
5858
+ ok: false,
5859
+ severity: "high",
5860
+ code: "plan-path.outside-plan-dir",
5861
+ message: `plan file ${planAbs} is outside {PLAN_DIR} (${planDir})`,
5862
+ fix: `write the plan under ${planDir}`
5863
+ };
5864
+ }
5865
+ if (existsSync6(planAbs)) {
5866
+ try {
5867
+ const canonicalPlan = realpathSync2(planAbs);
5868
+ const canonicalPlanDir = existsSync6(planDir) ? realpathSync2(planDir) : resolve7(planDir);
5869
+ const canonicalRel = relative2(canonicalPlanDir, canonicalPlan);
5870
+ const canonicalInside = canonicalRel === "" || !canonicalRel.startsWith("..") && !isAbsolute4(canonicalRel);
5871
+ if (!canonicalInside) {
5872
+ return {
5873
+ ok: false,
5874
+ severity: "high",
5875
+ code: "plan-path.symlink-escape",
5876
+ message: `plan file ${planAbs} resolves to ${canonicalPlan}, outside {PLAN_DIR} (${canonicalPlanDir})`,
5877
+ fix: `write the plan under ${planDir}`
5878
+ };
5879
+ }
5880
+ } catch {}
5881
+ }
5882
+ return {
5883
+ ok: true,
5884
+ severity: "low",
5885
+ code: "plan-path.ok",
5886
+ message: `plan file ${planAbs} lives under {PLAN_DIR} (${planDir})`
5887
+ };
5888
+ }
5786
5889
  function isDirectory(dir) {
5787
5890
  try {
5788
5891
  return statSync3(dir).isDirectory();
@@ -5905,6 +6008,16 @@ function l2PreDispatchCheck(input, opts = {}) {
5905
6008
  });
5906
6009
  return gate(violations);
5907
6010
  }
6011
+ function assertBranchAlignment(worktreePath, expectedBranch, opts = {}) {
6012
+ const violations = [];
6013
+ const probe = probeBranch(worktreePath, opts);
6014
+ if ("error" in probe) {
6015
+ violations.push(violation7("high", "worktree.branch-probe-failed", `cannot probe branch at "${worktreePath}": ${probe.error}`, "verify the path is a git worktree checkout on the expected branch (not detached)"));
6016
+ } else if (probe.branch !== expectedBranch) {
6017
+ violations.push(violation7("high", "worktree.branch-mismatch", `worktree "${worktreePath}" is on branch "${probe.branch}", expected "${expectedBranch}" (Assignment Working branch)`, `checkout ${expectedBranch} in that worktree`));
6018
+ }
6019
+ return gate(violations);
6020
+ }
5908
6021
  var QC_ALIGNMENT_FIELDS = [
5909
6022
  { key: "planId", label: "plan_id" },
5910
6023
  { key: "reviewRange", label: "Review range" },
@@ -6058,6 +6171,16 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
6058
6171
  if (!planFile || !Number.isInteger(taskN) || taskN < 1) {
6059
6172
  throw new SddScriptError("usage: mstar sdd task-brief PLAN_FILE TASK_NUMBER [OUTFILE]", 2);
6060
6173
  }
6174
+ const bound = opts.context;
6175
+ const observedCwd = opts.cwd ?? process.cwd();
6176
+ if (bound) {
6177
+ const inputPlan = canonicalizeNearestExisting(resolve9(observedCwd, planFile));
6178
+ if (inputPlan !== canonicalizeNearestExisting(bound.planFile)) {
6179
+ throwGateFail([
6180
+ contextViolation("high", "sdd.context.plan-file-mismatch", `plan file "${planFile}" does not match the bound context plan file "${bound.planFile}" \u2014 ` + "bound mode extracts only the resolved context's plan; refused before any read or write")
6181
+ ]);
6182
+ }
6183
+ }
6061
6184
  let content;
6062
6185
  try {
6063
6186
  content = readFileSync7(planFile, "utf8");
@@ -6065,8 +6188,12 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
6065
6188
  throw new SddScriptError(`no such plan file: ${planFile}`, 2);
6066
6189
  }
6067
6190
  let out;
6191
+ let mkdirAfterGate = null;
6068
6192
  if (outFile) {
6069
- out = outFile;
6193
+ out = bound ? resolve9(observedCwd, outFile) : outFile;
6194
+ } else if (bound) {
6195
+ out = join10(bound.sddDir, `task-${taskN}-brief.md`);
6196
+ mkdirAfterGate = bound.sddDir;
6070
6197
  } else {
6071
6198
  const sddDir = opts.sddDir ?? process.env.SDD_DIR;
6072
6199
  if (!sddDir) {
@@ -6075,6 +6202,13 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
6075
6202
  mkdirSync6(sddDir, { recursive: true });
6076
6203
  out = join10(sddDir, `task-${taskN}-brief.md`);
6077
6204
  }
6205
+ if (bound) {
6206
+ const gate2 = checkSddAction(bound, { kind: "artifact", cwd: observedCwd, target: out });
6207
+ if (!gate2.ok)
6208
+ throwGateFail(gate2.violations);
6209
+ if (mkdirAfterGate !== null)
6210
+ mkdirSync6(mkdirAfterGate, { recursive: true });
6211
+ }
6078
6212
  const records = content.endsWith(`
6079
6213
  `) ? content.split(`
6080
6214
  `).slice(0, -1) : content.split(`
@@ -6099,13 +6233,15 @@ function taskBrief(planFile, taskN, outFile, opts = {}) {
6099
6233
  if (printed.length === 0) {
6100
6234
  throw new SddScriptError(`task ${taskN} not found in ${planFile} (no heading matching Task ${taskN})`, 3);
6101
6235
  }
6102
- return out;
6236
+ return bound ? resolve9(observedCwd, out) : out;
6103
6237
  }
6104
6238
  function reviewPackage(base, head, outFile, opts = {}) {
6105
6239
  if (!base || !head) {
6106
6240
  throw new SddScriptError("usage: mstar sdd review-package BASE HEAD [OUTFILE]", 2);
6107
6241
  }
6108
- const cwd = opts.cwd ?? process.cwd();
6242
+ const bound = opts.context;
6243
+ const cwd = bound && opts.cwd === undefined ? bound.featureCwd : opts.cwd ?? process.cwd();
6244
+ const observedCwd = opts.cwd ?? process.cwd();
6109
6245
  const verifyRef = (ref, what) => {
6110
6246
  try {
6111
6247
  execFileSync3("git", ["rev-parse", "--verify", "--quiet", ref], { cwd, stdio: ["ignore", "pipe", "pipe"] });
@@ -6116,8 +6252,14 @@ function reviewPackage(base, head, outFile, opts = {}) {
6116
6252
  verifyRef(base, "BASE");
6117
6253
  verifyRef(head, "HEAD");
6118
6254
  let out;
6255
+ let mkdirAfterGate = null;
6119
6256
  if (outFile) {
6120
- out = outFile;
6257
+ out = bound ? resolve9(observedCwd, outFile) : outFile;
6258
+ } else if (bound) {
6259
+ const shortBase = gitOut(cwd, ["rev-parse", "--short", base]) ?? base;
6260
+ const shortHead = gitOut(cwd, ["rev-parse", "--short", head]) ?? head;
6261
+ out = join10(bound.sddDir, `review-${shortBase}..${shortHead}.diff`);
6262
+ mkdirAfterGate = bound.sddDir;
6121
6263
  } else {
6122
6264
  const sddDir = opts.sddDir ?? process.env.SDD_DIR;
6123
6265
  if (!sddDir) {
@@ -6128,6 +6270,13 @@ function reviewPackage(base, head, outFile, opts = {}) {
6128
6270
  const shortHead = gitOut(cwd, ["rev-parse", "--short", head]) ?? head;
6129
6271
  out = join10(sddDir, `review-${shortBase}..${shortHead}.diff`);
6130
6272
  }
6273
+ if (bound) {
6274
+ const gate2 = checkSddAction(bound, { kind: "artifact", cwd: observedCwd, target: out });
6275
+ if (!gate2.ok)
6276
+ throwGateFail(gate2.violations);
6277
+ if (mkdirAfterGate !== null)
6278
+ mkdirSync6(mkdirAfterGate, { recursive: true });
6279
+ }
6131
6280
  const run = (args) => execFileSync3("git", args, { cwd, maxBuffer: GIT_CAPTURE_MAX_BYTES });
6132
6281
  const parts = [
6133
6282
  Buffer.from(`# Review package: ${base}..${head}
@@ -6145,7 +6294,354 @@ function reviewPackage(base, head, outFile, opts = {}) {
6145
6294
  run(["diff", "-U10", `${base}..${head}`])
6146
6295
  ];
6147
6296
  writeFileSync4(out, Buffer.concat(parts));
6148
- return out;
6297
+ return bound ? resolve9(observedCwd, out) : out;
6298
+ }
6299
+ function isPlainObject6(value) {
6300
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6301
+ }
6302
+ function isInside(child, ancestor) {
6303
+ const rel = relative3(ancestor, child);
6304
+ return rel === "" || !rel.startsWith("..") && !isAbsolute6(rel);
6305
+ }
6306
+ function canonicalDir(path2) {
6307
+ try {
6308
+ return statSync4(path2).isDirectory() ? realpathSync3(path2) : null;
6309
+ } catch {
6310
+ return null;
6311
+ }
6312
+ }
6313
+ function contextViolation(severity, code, message, fix) {
6314
+ return { ok: false, severity, code, message, fix };
6315
+ }
6316
+ function throwGateFail(violations) {
6317
+ const detail = violations.map((v) => `${v.code}: ${v.message}${v.fix ? ` (fix: ${v.fix})` : ""}`).join(`
6318
+ `);
6319
+ throw new SddScriptError(`SDD execution context rejected:
6320
+ ${detail}`, 1);
6321
+ }
6322
+ function throwUsage(message) {
6323
+ throw new SddScriptError(message, 2);
6324
+ }
6325
+ function readActiveWorkflowIds(controlHarnessRoot) {
6326
+ const statusPath = join10(controlHarnessRoot, "status.json");
6327
+ if (!isFile2(statusPath))
6328
+ return null;
6329
+ let doc;
6330
+ try {
6331
+ doc = readJson(statusPath);
6332
+ } catch {
6333
+ return null;
6334
+ }
6335
+ if (!isPlainObject6(doc) || doc.version !== 2 || !Array.isArray(doc.workflows))
6336
+ return null;
6337
+ const ids = new Set;
6338
+ for (const entry of doc.workflows) {
6339
+ if (isPlainObject6(entry) && typeof entry.id === "string")
6340
+ ids.add(entry.id);
6341
+ }
6342
+ return ids;
6343
+ }
6344
+ function findWorkflowPlanRow(controlHarnessRoot, planId) {
6345
+ let workflowsDir;
6346
+ try {
6347
+ workflowsDir = resolveWorkflowDir(controlHarnessRoot, { harnessDir: controlHarnessRoot });
6348
+ } catch {
6349
+ return { kind: "none" };
6350
+ }
6351
+ if (!isDirectory2(workflowsDir))
6352
+ return { kind: "none" };
6353
+ let workflowIds;
6354
+ try {
6355
+ workflowIds = readdirSync6(workflowsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
6356
+ } catch {
6357
+ return { kind: "none" };
6358
+ }
6359
+ const matches = [];
6360
+ for (const id of workflowIds) {
6361
+ const snapshotPath = join10(workflowsDir, id, WORKFLOW_SNAPSHOT_FILE);
6362
+ if (!isFile2(snapshotPath))
6363
+ continue;
6364
+ let doc;
6365
+ try {
6366
+ doc = readJson(snapshotPath);
6367
+ } catch {
6368
+ continue;
6369
+ }
6370
+ const plans = doc.plans;
6371
+ if (!Array.isArray(plans))
6372
+ continue;
6373
+ for (const row of plans) {
6374
+ if (isPlainObject6(row) && (row.id === planId || row.plan_id === planId)) {
6375
+ matches.push({ workflowId: id, row });
6376
+ break;
6377
+ }
6378
+ }
6379
+ }
6380
+ if (matches.length === 0)
6381
+ return { kind: "none" };
6382
+ const registeredActive = readActiveWorkflowIds(controlHarnessRoot);
6383
+ if (registeredActive === null) {
6384
+ return { kind: "row", workflowId: matches[0].workflowId, row: matches[0].row };
6385
+ }
6386
+ const active = matches.filter((m) => registeredActive.has(m.workflowId));
6387
+ if (active.length === 0)
6388
+ return { kind: "none" };
6389
+ if (active.length > 1) {
6390
+ return { kind: "ambiguous", workflowIds: active.map((m) => m.workflowId) };
6391
+ }
6392
+ return { kind: "row", workflowId: active[0].workflowId, row: active[0].row };
6393
+ }
6394
+ function resolveSddExecutionContext(input) {
6395
+ const { planId, workingBranch } = input;
6396
+ if (typeof planId !== "string" || planId.trim() === "") {
6397
+ throwUsage("SddExecutionContext.planId must be a non-empty string");
6398
+ }
6399
+ if (typeof workingBranch !== "string" || workingBranch.trim() === "") {
6400
+ throwUsage("SddExecutionContext.workingBranch must be a non-empty string");
6401
+ }
6402
+ for (const field of ["controlHarnessRoot", "featureCwd", "planFile", "sddDir"]) {
6403
+ const value = input[field];
6404
+ if (typeof value !== "string" || value.trim() === "") {
6405
+ throwUsage(`SddExecutionContext.${field} must be a non-empty string`);
6406
+ }
6407
+ if (!isAbsolute6(value)) {
6408
+ throwUsage(`SddExecutionContext.${field} must be an absolute path (A3: all paths normalized absolute); got ${JSON.stringify(value)}`);
6409
+ }
6410
+ }
6411
+ try {
6412
+ assertSafePathComponent(planId, "SddExecutionContext.planId");
6413
+ } catch (err) {
6414
+ throwUsage(`SddExecutionContext rejected: ${err.message}`);
6415
+ }
6416
+ const canonicalControlHarnessRoot = canonicalDir(input.controlHarnessRoot);
6417
+ if (canonicalControlHarnessRoot === null) {
6418
+ throwGateFail([
6419
+ contextViolation("high", "sdd.context.control-root-missing", `controlHarnessRoot "${input.controlHarnessRoot}" does not exist or is not a directory \u2014 a declared control root is authoritative and is never re-inferred from the feature cwd (A3)`)
6420
+ ]);
6421
+ }
6422
+ const stem = basename4(input.planFile).replace(/\.md$/, "");
6423
+ if (stem !== planId) {
6424
+ throwUsage(`SddExecutionContext.planFile "${input.planFile}" does not match plan "${planId}" \u2014 the plan file must be {PLAN_DIR}/<plan-id>.md under the declared control harness`);
6425
+ }
6426
+ if (!isFile2(input.planFile)) {
6427
+ throwUsage(`no such plan file: ${input.planFile}`);
6428
+ }
6429
+ const planGate = assertPlanWritingPath(input.planFile, input.controlHarnessRoot);
6430
+ if (!planGate.ok) {
6431
+ if (planGate.code === "plan-path.symlink-escape") {
6432
+ throwGateFail([planGate]);
6433
+ }
6434
+ throwUsage(`SddExecutionContext.planFile rejected: ${planGate.code}: ${planGate.message}`);
6435
+ }
6436
+ const composedSddDir = resolveSddDir(canonicalControlHarnessRoot, planId);
6437
+ const canonicalComposedSddDir = canonicalizeNearestExisting(composedSddDir);
6438
+ const canonicalSddDir = canonicalizeNearestExisting(input.sddDir);
6439
+ if (canonicalSddDir !== canonicalComposedSddDir) {
6440
+ if (!isInside(canonicalSddDir, canonicalControlHarnessRoot)) {
6441
+ throwGateFail([
6442
+ contextViolation("high", "sdd.context.sdd-dir-escape", `sddDir "${input.sddDir}" canonicalizes to "${canonicalSddDir}", outside the control harness "${canonicalControlHarnessRoot}" \u2014 symlink escape refused (environmental gate failure)`)
6443
+ ]);
6444
+ }
6445
+ throwUsage(`SddExecutionContext.sddDir "${input.sddDir}" does not match plan "${planId}" \u2014 expected the {SDD_DIR} composition ${composedSddDir}`);
6446
+ }
6447
+ const canonicalFeatureCwd = canonicalDir(input.featureCwd);
6448
+ if (canonicalFeatureCwd === null) {
6449
+ throwGateFail([
6450
+ 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
+ ]);
6452
+ }
6453
+ const controlCheckout = dirname6(canonicalControlHarnessRoot);
6454
+ if (isInside(canonicalFeatureCwd, controlCheckout)) {
6455
+ 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")
6457
+ ]);
6458
+ }
6459
+ if (isInside(canonicalControlHarnessRoot, canonicalFeatureCwd)) {
6460
+ 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`)
6462
+ ]);
6463
+ }
6464
+ const match = findWorkflowPlanRow(canonicalControlHarnessRoot, planId);
6465
+ if (match.kind === "ambiguous") {
6466
+ throwGateFail([
6467
+ contextViolation("high", "sdd.context.workflow-plan-ambiguous", `plan "${planId}" appears in multiple registered active workflows (${match.workflowIds.join(", ")}) \u2014 ` + "the governing execution_lease is undecidable; resolve the duplicate registration before dispatch")
6468
+ ]);
6469
+ }
6470
+ const row = match.kind === "row" ? match.row : null;
6471
+ if (row !== null && row.execution_lease !== undefined) {
6472
+ const leaseVerify = verifyPlanExecutionLease(row, planId);
6473
+ if (!leaseVerify.ok)
6474
+ throwGateFail(leaseVerify.violations);
6475
+ const lease = leaseVerify.lease;
6476
+ const l1 = l1PreDispatchCheck({
6477
+ controlWorktreePath: controlCheckout,
6478
+ leaseWorktreePath: lease.worktree_path,
6479
+ leaseWorkingBranch: lease.working_branch,
6480
+ planId
6481
+ });
6482
+ if (!l1.ok)
6483
+ throwGateFail(l1.violations);
6484
+ if (canonicalizeNearestExisting(lease.worktree_path) !== canonicalFeatureCwd) {
6485
+ throwGateFail([
6486
+ contextViolation("high", "sdd.context.lease-worktree-mismatch", `SddExecutionContext.featureCwd "${canonicalFeatureCwd}" does not match the verified execution_lease.worktree_path "${String(lease.worktree_path)}" \u2014 the context must match the verified lease (A3)`)
6487
+ ]);
6488
+ }
6489
+ if (workingBranch !== lease.working_branch) {
6490
+ throwGateFail([
6491
+ contextViolation("high", "sdd.context.lease-branch-mismatch", `SddExecutionContext.workingBranch "${workingBranch}" does not match the verified execution_lease.working_branch "${String(lease.working_branch)}" (plan "${planId}")`)
6492
+ ]);
6493
+ }
6494
+ } else if (row !== null && row.status === "InProgress") {
6495
+ throwGateFail(verifyPlanExecutionLease(row, planId).violations);
6496
+ } else {
6497
+ const branchGate = assertBranchAlignment(canonicalFeatureCwd, workingBranch);
6498
+ if (!branchGate.ok)
6499
+ throwGateFail(branchGate.violations);
6500
+ }
6501
+ return {
6502
+ planId,
6503
+ controlHarnessRoot: canonicalControlHarnessRoot,
6504
+ featureCwd: canonicalFeatureCwd,
6505
+ workingBranch,
6506
+ planFile: realpathSync3(input.planFile),
6507
+ sddDir: canonicalSddDir
6508
+ };
6509
+ }
6510
+ function checkSddAction(context, action) {
6511
+ const violations = [];
6512
+ const add = (code, message, fix) => {
6513
+ violations.push(contextViolation("high", code, message, fix));
6514
+ };
6515
+ if (action.kind !== "source" && action.kind !== "artifact" && action.kind !== "launch") {
6516
+ add("sdd.context.kind-unknown", `unknown action kind ${JSON.stringify(action.kind)} \u2014 expected "source" | "artifact" | "launch"`);
6517
+ return { ok: false, violations };
6518
+ }
6519
+ if (typeof action.cwd !== "string" || action.cwd.trim() === "") {
6520
+ add("sdd.context.cwd-missing", "action.cwd (the observed invocation cwd) is required \u2014 never an Assignment echo");
6521
+ return { ok: false, violations };
6522
+ }
6523
+ const featureReal = canonicalDir(context.featureCwd);
6524
+ const canonicalSddDir = canonicalizeNearestExisting(context.sddDir);
6525
+ const canonicalPlanFile = canonicalizeNearestExisting(context.planFile);
6526
+ const cwdResolved = resolve9(action.cwd);
6527
+ const checkTarget = (baseDir, target, kind) => {
6528
+ if (featureReal === null)
6529
+ return;
6530
+ const targetAbs = resolve9(baseDir, target);
6531
+ const canonical = canonicalizeNearestExisting(targetAbs);
6532
+ if (!isInside(canonical, featureReal)) {
6533
+ const declaredPrefix = targetAbs === featureReal || targetAbs.startsWith(`${featureReal}/`);
6534
+ if (declaredPrefix) {
6535
+ add("sdd.context.target-symlink-escape", `${kind} target "${target}" canonicalizes to "${canonical}", outside the feature worktree \u2014 symlink escape refused before mutation`);
6536
+ } else {
6537
+ add(`sdd.context.${kind}-target-outside-feature`, `${kind} target "${target}" resolves to "${targetAbs}", outside the feature worktree "${featureReal}" \u2014 refused before mutation`);
6538
+ }
6539
+ }
6540
+ };
6541
+ if (action.kind === "source") {
6542
+ const cwdReal = canonicalDir(cwdResolved);
6543
+ if (cwdReal === null) {
6544
+ add("sdd.context.cwd-missing", `observed source cwd "${action.cwd}" does not exist or is not a directory`);
6545
+ return { ok: false, violations };
6546
+ }
6547
+ if (featureReal === null || !isInside(cwdReal, featureReal)) {
6548
+ add("sdd.context.source-cwd-outside-feature", `observed source cwd "${cwdReal}" is outside the feature worktree "${context.featureCwd}" \u2014 a declared-correct context does not make a wrong-checkout write safe (A3)`, `run the source action from inside ${context.featureCwd}`);
6549
+ return { ok: false, violations };
6550
+ }
6551
+ if (action.target !== undefined)
6552
+ checkTarget(cwdReal, action.target, "source");
6553
+ } else if (action.kind === "artifact") {
6554
+ if (typeof action.target !== "string" || action.target.trim() === "") {
6555
+ add("sdd.context.target-missing", "artifact checks require the destination target");
6556
+ return { ok: false, violations };
6557
+ }
6558
+ const targetAbs = resolve9(cwdResolved, action.target);
6559
+ const canonical = canonicalizeNearestExisting(targetAbs);
6560
+ if (!isInside(canonical, canonicalSddDir) && canonical !== canonicalPlanFile) {
6561
+ const rawSddDir = resolve9(context.sddDir);
6562
+ const declaredPrefix = targetAbs === rawSddDir || targetAbs.startsWith(`${rawSddDir}/`) || targetAbs === canonicalSddDir || targetAbs.startsWith(`${canonicalSddDir}/`) || targetAbs === canonicalPlanFile;
6563
+ if (declaredPrefix) {
6564
+ add("sdd.context.artifact-symlink-escape", `artifact target "${targetAbs}" canonicalizes to "${canonical}", outside the plan's control sddDir \u2014 symlink escape refused before write`);
6565
+ } else {
6566
+ add("sdd.context.artifact-outside-plan", `artifact target "${targetAbs}" is outside the plan's control sddDir "${context.sddDir}" and is not the declared planFile "${context.planFile}" \u2014 legitimate control artifact edits stay inside the plan's artifacts; arbitrary control source edits are not allowed (A3)`);
6567
+ }
6568
+ }
6569
+ } else {
6570
+ if (featureReal === null) {
6571
+ add("sdd.context.launch-cwd-missing", `feature worktree "${context.featureCwd}" does not exist or is not a directory \u2014 cannot bind the child's starting cwd`);
6572
+ } else {
6573
+ violations.push(...assertBranchAlignment(featureReal, context.workingBranch).violations);
6574
+ }
6575
+ if (action.target !== undefined && action.target.trim() !== "" && featureReal !== null) {
6576
+ checkTarget(featureReal, action.target, "launch");
6577
+ }
6578
+ }
6579
+ return { ok: violations.length === 0, violations };
6580
+ }
6581
+ function signalExitNumber(signal) {
6582
+ return osConstants.signals[signal] ?? 0;
6583
+ }
6584
+ async function runInSddContext(context, argv) {
6585
+ if (!Array.isArray(argv) || argv.length === 0 || typeof argv[0] !== "string" || argv[0].trim() === "") {
6586
+ throwUsage("runInSddContext: argv must be [executable, ...args] with a non-empty executable \u2014 the array is passed to the child literally (no shell)");
6587
+ }
6588
+ const resolved = resolveSddExecutionContext(context);
6589
+ const gate2 = checkSddAction(resolved, { kind: "launch", cwd: process.cwd() });
6590
+ if (!gate2.ok)
6591
+ throwGateFail(gate2.violations);
6592
+ return await new Promise((settle, reject) => {
6593
+ let child;
6594
+ try {
6595
+ child = spawn(argv[0], argv.slice(1), {
6596
+ cwd: resolved.featureCwd,
6597
+ shell: false,
6598
+ stdio: "inherit"
6599
+ });
6600
+ } catch (err) {
6601
+ if (err.code === "ENOENT") {
6602
+ settle(127);
6603
+ return;
6604
+ }
6605
+ throw err;
6606
+ }
6607
+ let done = false;
6608
+ let spawnError = null;
6609
+ const forward = (signal) => {
6610
+ if (!done && child.exitCode === null && child.signalCode === null)
6611
+ child.kill(signal);
6612
+ };
6613
+ const cleanup = () => {
6614
+ process.removeListener("SIGINT", forward);
6615
+ process.removeListener("SIGTERM", forward);
6616
+ };
6617
+ process.on("SIGINT", forward);
6618
+ process.on("SIGTERM", forward);
6619
+ child.on("error", (err) => {
6620
+ spawnError = err;
6621
+ if (err.code !== "ENOENT" && !done) {
6622
+ done = true;
6623
+ cleanup();
6624
+ reject(err);
6625
+ }
6626
+ });
6627
+ child.on("close", (code, signal) => {
6628
+ if (done)
6629
+ return;
6630
+ done = true;
6631
+ cleanup();
6632
+ if (spawnError !== null) {
6633
+ if (spawnError.code === "ENOENT")
6634
+ settle(127);
6635
+ else
6636
+ reject(spawnError);
6637
+ return;
6638
+ }
6639
+ if (signal !== null)
6640
+ settle(128 + signalExitNumber(signal));
6641
+ else
6642
+ settle(code ?? 0);
6643
+ });
6644
+ });
6149
6645
  }
6150
6646
  function violation8(severity, code, message, fix) {
6151
6647
  return { ok: false, severity, code, message, fix };
@@ -7518,7 +8014,7 @@ function collectKnowledgeDocs(dir) {
7518
8014
  if (entry.isDirectory()) {
7519
8015
  stack.push(full);
7520
8016
  } else if (entry.name.endsWith(".md") && entry.name !== "README.md" && entry.name !== "index.md") {
7521
- docs.push(relative4(dir, full).split(sep4).join("/"));
8017
+ docs.push(relative5(dir, full).split(sep4).join("/"));
7522
8018
  }
7523
8019
  }
7524
8020
  }
@@ -7622,7 +8118,7 @@ function findTemporaryMarkers(fileText) {
7622
8118
  }
7623
8119
  markers.push({ line: i + 1, text, removalPath });
7624
8120
  if (removalPath === null) {
7625
- violations.push(violation11("medium", "lint.temporary.no-removal-path", `temporary marker at line ${i + 1} records no removal path (plan/status artifact reference) \u2014 record one before claiming the task complete (mstar-coding-behavior \u00a7 Simplification markers)`, 'add a plan/status reference to the marker, e.g. "removal tracked in status.json" or "plan 20260808-slice2 removes this"'));
8121
+ violations.push(violation11("medium", "lint.temporary.no-removal-path", `temporary marker at line ${i + 1} records no removal path (plan/status artifact reference) \u2014 record one before claiming the task complete (mstar-coding-behavior \u00a7 Simplification markers)`, 'add a plan/status reference to the marker, e.g. "removal tracked in status.json" or "plan 20991231-example-plan removes this"'));
7626
8122
  }
7627
8123
  }
7628
8124
  return { ok: violations.length === 0, violations, markers };
@@ -7918,6 +8414,14 @@ function validateRoleMapping(rolesDir, options = {}) {
7918
8414
  return { ok: violations.length === 0, violations };
7919
8415
  }
7920
8416
  var LOAD_ORDER_HEADING_RE = /^#{1,6}\s+[^\r\n]*\b(?:load[\s-]*order|first\s+action)\b[^\r\n]*$/i;
8417
+ var HUB_BOOTSTRAP_ASSERTIONS = [
8418
+ { marker: "identity-first", why: "identity boundary before any skill list" },
8419
+ { marker: "skill presets", why: "Assignment Skill presets decision field" },
8420
+ { marker: "none", why: "explicit none => identity only, no optional topic preset" },
8421
+ { marker: "standard", why: "omitted on a substantive round => standard preset" },
8422
+ { marker: "role-owned", why: "role-owned methods / evidence obligations load regardless of preset" },
8423
+ { marker: "unknown preset", why: "unknown preset / missing identity => Needs Context / Blocked, never infer PM" }
8424
+ ];
7921
8425
  function extractLoadOrderSection(text) {
7922
8426
  const lines = text.split(/\r?\n/);
7923
8427
  let start = -1;
@@ -7951,11 +8455,22 @@ function lintLoadOrder(skillTexts) {
7951
8455
  continue;
7952
8456
  const section = extractLoadOrderSection(text);
7953
8457
  if (section === null) {
7954
- violations.push(violation12("medium", "roles.loadorder.section.missing", `skill "${name}" has no Load Order / First action section \u2014 every mstar-* topic skill must declare its first read (mstar-harness-core \u00a7 \u52a0\u8f7d\u7ea6\u5b9a; mstar-roles \u00a7 Load Order (Required))`, `add a "## Load Order" section naming mstar-harness-core as the first read`));
8458
+ violations.push(violation12("medium", "roles.loadorder.section.missing", `skill "${name}" has no Load Order / First action section \u2014 every mstar-* topic skill must declare its first read (mstar-harness-core \u00a7 \u52a0\u8f7d\u5951\u7ea6; mstar-roles \u00a7 Load Order = single load-selection authority)`, `add a "## Load Order" section: topics name mstar-harness-core first; mstar-roles declares the Skill presets decision matrix`));
8459
+ continue;
8460
+ }
8461
+ if (name === "mstar-roles") {
8462
+ const lower = section.toLowerCase();
8463
+ const missing = HUB_BOOTSTRAP_ASSERTIONS.filter((a) => !lower.includes(a.marker.toLowerCase()));
8464
+ if (missing.length > 0) {
8465
+ violations.push(violation12("medium", "roles.loadorder.hub.bootstrap.missing", `skill "${name}" Load Order section is missing the hub bootstrap decision matrix: ${missing.map((m) => `"${m.marker}" (${m.why})`).join("; ")} (mstar-roles \u00a7 Load Order = single load-selection authority)`, "declare identity-first, the Skill presets none/standard decision, role-owned methods, and the unknown-preset / missing-identity refusal in the Load Order section"));
8466
+ }
8467
+ if (!section.includes("mstar-harness-core")) {
8468
+ violations.push(violation12("medium", "roles.loadorder.core.missing", `skill "${name}" Load Order section does not point at mstar-harness-core \u2014 the hub bootstrap is exempt from core-first, but core remains the lifecycle/authorization conflict authority and global entry whenever loaded`, "keep the conditional mstar-harness-core pointer (global entry / conflict authority) in the Load Order section"));
8469
+ }
7955
8470
  continue;
7956
8471
  }
7957
8472
  if (!section.includes("mstar-harness-core")) {
7958
- violations.push(violation12("medium", "roles.loadorder.core.missing", `skill "${name}" Load Order section does not declare mstar-harness-core as its first dependency (mstar-harness-core \u00a7 \u52a0\u8f7d\u7ea6\u5b9a: \u51e1 mstar-*\uff08name \u2260 mstar-harness-core\uff09\u5047\u5b9a\u8bfb\u8005\u5df2 Read \u672c skill)`, "name mstar-harness-core first in the Load Order section"));
8473
+ violations.push(violation12("medium", "roles.loadorder.core.missing", `skill "${name}" Load Order section does not declare mstar-harness-core as its first dependency (mstar-harness-core \u00a7 \u52a0\u8f7d\u5951\u7ea6: directly-invoked topics keep core as first dependency; the mstar-roles hub bootstrap is the only exception)`, "name mstar-harness-core first in the Load Order section"));
7959
8474
  }
7960
8475
  }
7961
8476
  return { ok: violations.length === 0, violations };
@@ -8035,6 +8550,16 @@ function collectHeadings(bodyText) {
8035
8550
  }
8036
8551
  return headings;
8037
8552
  }
8553
+ function classifySkillLint(skillId) {
8554
+ const id = skillId ?? "";
8555
+ if (id === "mstar-harness-core")
8556
+ return { kind: "core", mode: null };
8557
+ if (id === "mstar-skill-authoring")
8558
+ return { kind: "authoring", mode: "authoring" };
8559
+ if (id.startsWith("mstar-"))
8560
+ return { kind: "runtime", mode: "runtime" };
8561
+ return { kind: "authoring", mode: "authoring" };
8562
+ }
8038
8563
  var RUNTIME_HEADING_ALIASES = {
8039
8564
  workflow: ["process", "playbook"],
8040
8565
  "decision-rules": [
@@ -8098,7 +8623,7 @@ must-fix=${mustFix} should-fix=${shouldFix} nit=${nit} unverified=${unverified}`
8098
8623
  var REVIEW_SCHEMA_ID = "mstar.review/v1";
8099
8624
  var INSPECTOR_VERDICTS = ["comment", "request_changes", "approve"];
8100
8625
  var INSPECTOR_SEVERITIES = ["critical", "warning", "suggestion", "info"];
8101
- function isPlainObject7(value) {
8626
+ function isPlainObject8(value) {
8102
8627
  return typeof value === "object" && value !== null && !Array.isArray(value);
8103
8628
  }
8104
8629
  var TALLY_COUNT_KEYS = ["mustFix", "shouldFix", "nit", "unverified"];
@@ -8109,7 +8634,7 @@ function checkProvidedTallyShape(tally, violations) {
8109
8634
  if (typeof tally.scorePct !== "number" || !Number.isInteger(tally.scorePct) || tally.scorePct < 0 || tally.scorePct > 100) {
8110
8635
  violations.push(violation14("high", "review.tally-malformed", `tally.scorePct must be an integer in [0, 100] - got ${String(tally.scorePct)}`));
8111
8636
  }
8112
- if (!isPlainObject7(tally.tally)) {
8637
+ if (!isPlainObject8(tally.tally)) {
8113
8638
  violations.push(violation14("high", "review.tally-malformed", "tally.tally must be an object carrying the four class counts"));
8114
8639
  } else {
8115
8640
  for (const key of TALLY_COUNT_KEYS) {
@@ -8125,7 +8650,7 @@ function checkProvidedTallyShape(tally, violations) {
8125
8650
  }
8126
8651
  function validateMstarReviewV1(doc) {
8127
8652
  const violations = [];
8128
- if (!isPlainObject7(doc)) {
8653
+ if (!isPlainObject8(doc)) {
8129
8654
  return {
8130
8655
  ok: false,
8131
8656
  violations: [violation14("high", "review.not-object", "review document must be a JSON object")]
@@ -8152,7 +8677,7 @@ function validateMstarReviewV1(doc) {
8152
8677
  violations.push(violation14("high", "review.findings-not-array", "findings must be an array"));
8153
8678
  } else {
8154
8679
  doc.findings.forEach((finding, index) => {
8155
- if (!isPlainObject7(finding)) {
8680
+ if (!isPlainObject8(finding)) {
8156
8681
  violations.push(violation14("high", "review.invalid-finding", `findings[${index}] must be an object`));
8157
8682
  return;
8158
8683
  }
@@ -8192,7 +8717,7 @@ function validateMstarReviewV1(doc) {
8192
8717
  });
8193
8718
  }
8194
8719
  if (doc.tally !== undefined) {
8195
- if (!isPlainObject7(doc.tally)) {
8720
+ if (!isPlainObject8(doc.tally)) {
8196
8721
  violations.push(violation14("high", "review.invalid-tally", "tally must be a PrTallyResult object"));
8197
8722
  } else {
8198
8723
  checkProvidedTallyShape(doc.tally, violations);
@@ -8202,7 +8727,7 @@ function validateMstarReviewV1(doc) {
8202
8727
  }
8203
8728
  }
8204
8729
  if (doc.target !== undefined) {
8205
- if (!isPlainObject7(doc.target)) {
8730
+ if (!isPlainObject8(doc.target)) {
8206
8731
  violations.push(violation14("high", "review.invalid-target", "target must be an object"));
8207
8732
  } else {
8208
8733
  if (doc.target.owner !== undefined && typeof doc.target.owner !== "string") {
@@ -8799,7 +9324,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
8799
9324
  import { basename as basename7, dirname as dirname7, join as join3, resolve as resolve10 } from "node:path";
8800
9325
  import { fileURLToPath } from "node:url";
8801
9326
  import { readFileSync as readFileSync22, statSync as statSync5 } from "node:fs";
8802
- import { dirname as dirname22, isAbsolute as isAbsolute7, join as join22, relative as relative3, resolve as resolve22 } from "node:path";
9327
+ import { dirname as dirname22, isAbsolute as isAbsolute7, join as join22, relative as relative4, resolve as resolve22 } from "node:path";
8803
9328
  import { existsSync as existsSync62, mkdirSync as mkdirSync52, readdirSync as readdirSync52, readFileSync as readFileSync62, realpathSync as realpathSync22, statSync as statSync32, writeFileSync as writeFileSync32 } from "node:fs";
8804
9329
  import { execFileSync as execFileSync5 } from "node:child_process";
8805
9330
  import { basename as basename32, dirname as dirname52, isAbsolute as isAbsolute42, join as join92, relative as relative22, resolve as resolve72 } from "node:path";
@@ -8814,7 +9339,7 @@ import { dirname as dirname42, join as join72, resolve as resolve52, sep as sep2
8814
9339
  import { mkdirSync as mkdirSync32 } from "node:fs";
8815
9340
  import { join as join6 } from "node:path";
8816
9341
  import { copyFileSync, mkdirSync as mkdirSync7, readFileSync as readFileSync82, readdirSync as readdirSync7, writeFileSync as writeFileSync52 } from "node:fs";
8817
- import { dirname as dirname72, isAbsolute as isAbsolute72, join as join11, relative as relative32, resolve as resolve102, sep as sep22 } from "node:path";
9342
+ import { dirname as dirname72, isAbsolute as isAbsolute72, join as join11, relative as relative42, resolve as resolve102, sep as sep22 } from "node:path";
8818
9343
  var SEVERITY_ORDER2 = ["critical", "high", "medium", "low", "nit"];
8819
9344
  function readJson2(filePath) {
8820
9345
  if (!existsSync11(filePath))
@@ -8972,7 +9497,7 @@ function loadMstarc2(startDir, boundary) {
8972
9497
  return { file, dir: dirname22(file), config: parseMstarc2(readFileSync22(file, "utf8")) };
8973
9498
  }
8974
9499
  function isAtOrBelow3(dir, root) {
8975
- const rel = relative3(root, dir);
9500
+ const rel = relative4(root, dir);
8976
9501
  return rel === "" || !rel.startsWith("..") && !isAbsolute7(rel);
8977
9502
  }
8978
9503
  function parseCompassFrontmatterText2(content, filePath) {
@@ -9108,11 +9633,11 @@ function validateIntegrationMergeLease2(lease) {
9108
9633
  }
9109
9634
  return { ok: violations.length === 0, violations };
9110
9635
  }
9111
- function planExecutionLeaseLocations(row) {
9636
+ function planExecutionLeaseLocations2(row) {
9112
9637
  return { row: row.execution_lease };
9113
9638
  }
9114
- function verifyPlanExecutionLease(row, planId) {
9115
- const { row: rowLease } = planExecutionLeaseLocations(row);
9639
+ function verifyPlanExecutionLease2(row, planId) {
9640
+ const { row: rowLease } = planExecutionLeaseLocations2(row);
9116
9641
  const lease = rowLease;
9117
9642
  if (lease === undefined) {
9118
9643
  if (row.status === "InProgress") {
@@ -9866,7 +10391,7 @@ var ROOT_METADATA_LIFT_KEYS = {
9866
10391
  program_roadmap: true,
9867
10392
  updated_at: true
9868
10393
  };
9869
- function isPlainObject6(value) {
10394
+ function isPlainObject7(value) {
9870
10395
  return typeof value === "object" && value !== null && !Array.isArray(value);
9871
10396
  }
9872
10397
  function dateString(value) {
@@ -10046,10 +10571,10 @@ function applyRootMetadataLift(snapshot, metadata, migrationNotes, activeIterati
10046
10571
  if (typeof metadata.control_worktree_path === "string" && metadata.control_worktree_path !== "") {
10047
10572
  data.control_worktree_path = metadata.control_worktree_path;
10048
10573
  }
10049
- if (isPlainObject6(metadata.integration_merge_lease)) {
10574
+ if (isPlainObject7(metadata.integration_merge_lease)) {
10050
10575
  data.integration_merge_lease = metadata.integration_merge_lease;
10051
10576
  }
10052
- const legacyMetadata = isPlainObject6(data.legacy_metadata) ? { ...data.legacy_metadata } : {};
10577
+ const legacyMetadata = isPlainObject7(data.legacy_metadata) ? { ...data.legacy_metadata } : {};
10053
10578
  for (const [key, value] of Object.entries(metadata)) {
10054
10579
  if (key === "harness_root")
10055
10580
  continue;
@@ -10105,7 +10630,7 @@ function buildRegister(residualFindings, byPlan, projectId, migratedAt) {
10105
10630
  const raw = residualFindings[planId];
10106
10631
  if (!Array.isArray(raw))
10107
10632
  continue;
10108
- const open = raw.filter((entry) => isPlainObject6(entry) && isOpenResidual2(entry)).sort((a, b) => {
10633
+ const open = raw.filter((entry) => isPlainObject7(entry) && isOpenResidual2(entry)).sort((a, b) => {
10109
10634
  const aId = typeof a.id === "string" ? a.id : "";
10110
10635
  const bId = typeof b.id === "string" ? b.id : "";
10111
10636
  return compareIds(aId, bId);
@@ -10194,12 +10719,12 @@ function migrateHarnessTree(root, opts = {}) {
10194
10719
  if (legacy.version === undefined) {
10195
10720
  throw new Error(`refusing to migrate: no v1 status.json found at ${statusPath} (nothing to migrate)`);
10196
10721
  }
10197
- const rows = Array.isArray(legacy.plans) ? legacy.plans.filter(isPlainObject6) : [];
10722
+ const rows = Array.isArray(legacy.plans) ? legacy.plans.filter(isPlainObject7) : [];
10198
10723
  if (Array.isArray(legacy.plans)) {
10199
10724
  const unLiftable = [];
10200
10725
  const idCounts = new Map;
10201
10726
  for (const row of legacy.plans) {
10202
- if (!isPlainObject6(row) || rowIdOf(row) === null) {
10727
+ if (!isPlainObject7(row) || rowIdOf(row) === null) {
10203
10728
  unLiftable.push(row);
10204
10729
  continue;
10205
10730
  }
@@ -10215,7 +10740,7 @@ function migrateHarnessTree(root, opts = {}) {
10215
10740
  throw new Error(`refusing to migrate: ${duplicates.length} duplicate plan id(s) (${duplicates.join(", ")}) \u2014 every v1 row must land in exactly one snapshot`);
10216
10741
  }
10217
10742
  }
10218
- const metadata = isPlainObject6(legacy.metadata) ? legacy.metadata : {};
10743
+ const metadata = isPlainObject7(legacy.metadata) ? legacy.metadata : {};
10219
10744
  const rootUpdatedAt = dateString(legacy.updated_at) ?? dateString(metadata.updated_at) ?? todayString3();
10220
10745
  const migratedAt = dateString(metadata.updated_at) ?? rootUpdatedAt;
10221
10746
  const migrationNotes = [];
@@ -10252,9 +10777,9 @@ function migrateHarnessTree(root, opts = {}) {
10252
10777
  migrationNotes.push("no active iteration snapshot found \u2014 root metadata execution-policy/branch keys have no lift home and stay unmapped (visible here, not silently dropped)");
10253
10778
  }
10254
10779
  const notesFiles = collectNotesFiles(snapshots);
10255
- const residualFindings = isPlainObject6(legacy.residual_findings) ? legacy.residual_findings : {};
10780
+ const residualFindings = isPlainObject7(legacy.residual_findings) ? legacy.residual_findings : {};
10256
10781
  const register = buildRegister(residualFindings, byPlan, projectId, migratedAt);
10257
- const programRoadmap = isPlainObject6(metadata.program_roadmap) ? metadata.program_roadmap : null;
10782
+ const programRoadmap = isPlainObject7(metadata.program_roadmap) ? metadata.program_roadmap : null;
10258
10783
  let roadmap = null;
10259
10784
  if (programRoadmap) {
10260
10785
  const rawTitle = typeof programRoadmap.title === "string" && programRoadmap.title !== "" ? programRoadmap.title : "Program roadmap";
@@ -10323,8 +10848,8 @@ async function applyMigratePlan(plan) {
10323
10848
  if (!isAbsolute72(plan.workflowDir) || !isAbsolute72(plan.projectDir)) {
10324
10849
  throw new Error(`refusing to apply migration: plan workflowDir/projectDir must be absolute (got ${JSON.stringify(plan.workflowDir)} / ${JSON.stringify(plan.projectDir)})`);
10325
10850
  }
10326
- const workflowTargetOf = (canonicalFile) => join11(workflowRoot, relative32("workflows", canonicalFile));
10327
- const projectTargetOf = (canonicalFile) => join11(projectRoot, relative32("projects", canonicalFile));
10851
+ const workflowTargetOf = (canonicalFile) => join11(workflowRoot, relative42("workflows", canonicalFile));
10852
+ const projectTargetOf = (canonicalFile) => join11(projectRoot, relative42("projects", canonicalFile));
10328
10853
  const allDestinations = [
10329
10854
  plan.archive.file,
10330
10855
  ...plan.snapshots.map((snapshot) => snapshot.file),
@@ -10514,7 +11039,7 @@ async function runMigrateCommand(options) {
10514
11039
  }
10515
11040
 
10516
11041
  // src/agent-plugins.ts
10517
- import fs from "node:fs";
11042
+ import fs, { realpathSync as realpathSync6 } from "node:fs";
10518
11043
  import path3 from "node:path";
10519
11044
 
10520
11045
  // src/utils.ts
@@ -10579,7 +11104,7 @@ function describeType(value) {
10579
11104
  return "array";
10580
11105
  return typeof value;
10581
11106
  }
10582
- function isPlainObject8(value) {
11107
+ function isPlainObject9(value) {
10583
11108
  return typeof value === "object" && value !== null && !Array.isArray(value);
10584
11109
  }
10585
11110
  function parseScalar3(raw) {
@@ -10623,7 +11148,7 @@ function isValidMcpUrl(raw) {
10623
11148
  return true;
10624
11149
  }
10625
11150
  function validateManifest(manifest, errors2, warnings) {
10626
- if (!isPlainObject8(manifest)) {
11151
+ if (!isPlainObject9(manifest)) {
10627
11152
  errors2.push("plugin.json: manifest must be a JSON object");
10628
11153
  return;
10629
11154
  }
@@ -10659,7 +11184,7 @@ function validateManifest(manifest, errors2, warnings) {
10659
11184
  }
10660
11185
  }
10661
11186
  if (doc.author !== undefined) {
10662
- if (!isPlainObject8(doc.author)) {
11187
+ if (!isPlainObject9(doc.author)) {
10663
11188
  errors2.push('plugin.json: "author" must be an object with optional string fields name/email/url');
10664
11189
  } else {
10665
11190
  const author = doc.author;
@@ -10682,11 +11207,11 @@ function validateManifest(manifest, errors2, warnings) {
10682
11207
  }
10683
11208
  }
10684
11209
  if (doc.extensions !== undefined) {
10685
- if (!isPlainObject8(doc.extensions)) {
11210
+ if (!isPlainObject9(doc.extensions)) {
10686
11211
  warnings.push('plugin.json: "extensions" is not an object \u2014 ignored');
10687
11212
  } else {
10688
11213
  for (const [namespace, value] of Object.entries(doc.extensions)) {
10689
- if (!isPlainObject8(value)) {
11214
+ if (!isPlainObject9(value)) {
10690
11215
  warnings.push(`plugin.json: "extensions.${namespace}" is not an object \u2014 ignored`);
10691
11216
  }
10692
11217
  }
@@ -10695,7 +11220,7 @@ function validateManifest(manifest, errors2, warnings) {
10695
11220
  }
10696
11221
  function validateMcpServer(name, entry, errors2) {
10697
11222
  const prefix = `mcp.json: mcpServers.${name}`;
10698
- if (!isPlainObject8(entry)) {
11223
+ if (!isPlainObject9(entry)) {
10699
11224
  errors2.push(`${prefix} must be an object`);
10700
11225
  return;
10701
11226
  }
@@ -10729,7 +11254,7 @@ function validateMcpServer(name, entry, errors2) {
10729
11254
  }
10730
11255
  }
10731
11256
  if (server.env !== undefined) {
10732
- if (!isPlainObject8(server.env)) {
11257
+ if (!isPlainObject9(server.env)) {
10733
11258
  errors2.push(`${prefix}: "env" must be an object of strings`);
10734
11259
  } else {
10735
11260
  for (const [key, value] of Object.entries(server.env)) {
@@ -10768,7 +11293,7 @@ function validateMcpServer(name, entry, errors2) {
10768
11293
  errors2.push(`${prefix}: "url" must be an absolute http(s) URL without user info or fragment; non-loopback endpoints must use https`);
10769
11294
  }
10770
11295
  if (server.headers !== undefined) {
10771
- if (!isPlainObject8(server.headers)) {
11296
+ if (!isPlainObject9(server.headers)) {
10772
11297
  errors2.push(`${prefix}: "headers" must be an object of strings`);
10773
11298
  } else {
10774
11299
  const seen = new Set;
@@ -10795,7 +11320,7 @@ function validateMcpServer(name, entry, errors2) {
10795
11320
  }
10796
11321
  }
10797
11322
  function validateMcp(root, manifestSchema, errors2) {
10798
- const mcpPath = path3.join(root, "mcp.json");
11323
+ const mcpPath = `${root}${path3.sep}mcp.json`;
10799
11324
  if (!fs.existsSync(mcpPath))
10800
11325
  return;
10801
11326
  let parsed;
@@ -10805,7 +11330,7 @@ function validateMcp(root, manifestSchema, errors2) {
10805
11330
  errors2.push(`mcp.json: ${error.message}`);
10806
11331
  return;
10807
11332
  }
10808
- if (!isPlainObject8(parsed)) {
11333
+ if (!isPlainObject9(parsed)) {
10809
11334
  errors2.push("mcp.json: configuration must be a JSON object");
10810
11335
  return;
10811
11336
  }
@@ -10828,7 +11353,7 @@ function validateMcp(root, manifestSchema, errors2) {
10828
11353
  }
10829
11354
  }
10830
11355
  const servers = doc.mcpServers;
10831
- if (!isPlainObject8(servers)) {
11356
+ if (!isPlainObject9(servers)) {
10832
11357
  errors2.push('mcp.json: "mcpServers" is required and must be an object');
10833
11358
  return;
10834
11359
  }
@@ -10837,7 +11362,7 @@ function validateMcp(root, manifestSchema, errors2) {
10837
11362
  }
10838
11363
  }
10839
11364
  function validateSkills(root, errors2, warnings) {
10840
- const skillsPath = path3.join(root, "skills");
11365
+ const skillsPath = `${root}${path3.sep}skills`;
10841
11366
  try {
10842
11367
  if (!fs.existsSync(skillsPath))
10843
11368
  return;
@@ -10846,29 +11371,41 @@ function validateSkills(root, errors2, warnings) {
10846
11371
  return;
10847
11372
  }
10848
11373
  const entries = fs.readdirSync(skillsPath, { withFileTypes: true });
10849
- const realRoot = fs.realpathSync(root);
11374
+ const realRoot = realpathSync6(root);
10850
11375
  for (const entry of entries) {
10851
11376
  if (!entry.isDirectory() && !entry.isSymbolicLink())
10852
11377
  continue;
10853
11378
  const skillDir = entry.name;
10854
11379
  let realSkillPath;
10855
11380
  try {
10856
- realSkillPath = fs.realpathSync(path3.join(skillsPath, skillDir));
11381
+ realSkillPath = realpathSync6(`${skillsPath}${path3.sep}${skillDir}`);
10857
11382
  } catch (error) {
10858
11383
  warnings.push(`skills: ${skillDir}/ cannot be resolved (${error.message}; skill skipped)`);
10859
11384
  continue;
10860
11385
  }
10861
- const relative5 = path3.relative(realRoot, realSkillPath);
10862
- if (relative5 === ".." || relative5.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative5)) {
11386
+ const insideRoot = realSkillPath === realRoot || realSkillPath.startsWith(realRoot + path3.sep) || realRoot.endsWith(path3.sep) && realSkillPath.startsWith(realRoot);
11387
+ if (!insideRoot) {
10863
11388
  warnings.push(`skills: ${skillDir}/ resolves outside the plugin root (${realSkillPath}; skill skipped)`);
10864
11389
  continue;
10865
11390
  }
10866
- const skillMdPath = path3.join(skillsPath, skillDir, "SKILL.md");
11391
+ const skillMdPath = `${skillsPath}${path3.sep}${skillDir}${path3.sep}SKILL.md`;
10867
11392
  if (!fs.existsSync(skillMdPath) || !fs.statSync(skillMdPath).isFile()) {
10868
11393
  warnings.push(`skills: ${skillDir}/ has no SKILL.md (directory is not a skill; ignored)`);
10869
11394
  continue;
10870
11395
  }
10871
- const frontmatter = parseFrontmatter2(skillMdPath);
11396
+ let realSkillMdPath;
11397
+ try {
11398
+ realSkillMdPath = realpathSync6(skillMdPath);
11399
+ } catch (error) {
11400
+ warnings.push(`skills: ${skillDir}/SKILL.md cannot be resolved (${error.message}; skill skipped)`);
11401
+ continue;
11402
+ }
11403
+ const skillMdInsideRoot = realSkillMdPath.startsWith(realRoot + path3.sep) || realRoot.endsWith(path3.sep) && realSkillMdPath.startsWith(realRoot);
11404
+ if (!skillMdInsideRoot) {
11405
+ warnings.push(`skills: ${skillDir}/SKILL.md resolves outside the plugin root (${realSkillMdPath}; skill skipped)`);
11406
+ continue;
11407
+ }
11408
+ const frontmatter = parseFrontmatter2(realSkillMdPath);
10872
11409
  if (!frontmatter) {
10873
11410
  warnings.push(`skills: ${skillDir}/SKILL.md is missing YAML frontmatter (name and description are required; skill skipped)`);
10874
11411
  continue;
@@ -10900,7 +11437,11 @@ function validateSkills(root, errors2, warnings) {
10900
11437
  function validateAgentPlugin(root) {
10901
11438
  const errors2 = [];
10902
11439
  const warnings = [];
10903
- const manifestPath = path3.join(root, "plugin.json");
11440
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
11441
+ errors2.push(`plugin root: not a directory: ${root}`);
11442
+ return { ok: false, errors: errors2, warnings };
11443
+ }
11444
+ const manifestPath = `${root}${path3.sep}plugin.json`;
10904
11445
  if (!fs.existsSync(manifestPath)) {
10905
11446
  errors2.push(`plugin.json: manifest not found at ${manifestPath} (plugin root must contain plugin.json)`);
10906
11447
  return { ok: false, errors: errors2, warnings };
@@ -10913,7 +11454,7 @@ function validateAgentPlugin(root) {
10913
11454
  return { ok: false, errors: errors2, warnings };
10914
11455
  }
10915
11456
  validateManifest(manifest, errors2, warnings);
10916
- const manifestSchema = isPlainObject8(manifest) ? manifest["$schema"] : undefined;
11457
+ const manifestSchema = isPlainObject9(manifest) ? manifest["$schema"] : undefined;
10917
11458
  validateMcp(root, manifestSchema, errors2);
10918
11459
  validateSkills(root, errors2, warnings);
10919
11460
  return { ok: errors2.length === 0, errors: errors2, warnings };
@@ -11895,11 +12436,20 @@ function isAnyMstarHarnessOpencodeSlot(plugin) {
11895
12436
  function resolveOpencodeConfigPath(scope, outputPath) {
11896
12437
  if (outputPath && outputPath.trim()) {
11897
12438
  const raw = outputPath.trim();
11898
- return path9.isAbsolute(raw) ? raw : path9.join(resolveProjectRoot2(), raw);
12439
+ if (path9.isAbsolute(raw))
12440
+ return raw;
12441
+ if (raw.split(/[\\/]/).includes("..")) {
12442
+ throw new Error(`--output must not contain ".." segments: ${raw}`);
12443
+ }
12444
+ const root2 = resolveProjectRoot2();
12445
+ return root2.endsWith(path9.sep) ? root2 + raw : root2 + path9.sep + raw;
12446
+ }
12447
+ if (scope === "global") {
12448
+ const home = os5.homedir();
12449
+ return `${home}${path9.sep}.config${path9.sep}opencode${path9.sep}opencode.json`;
11899
12450
  }
11900
- if (scope === "global")
11901
- return path9.join(os5.homedir(), ".config", "opencode", "opencode.json");
11902
- return path9.join(resolveProjectRoot2(), "opencode.json");
12451
+ const root = resolveProjectRoot2();
12452
+ return root.endsWith(path9.sep) ? `${root}opencode.json` : `${root}${path9.sep}opencode.json`;
11903
12453
  }
11904
12454
  function ensureConfigSchema(config) {
11905
12455
  const next = ensureObject(config);
@@ -12000,6 +12550,8 @@ var MARKETPLACE_NAME2 = "mstar-local";
12000
12550
  var MARKETPLACE_DESCRIPTION = "Morning Star harness marketplace (GitHub source).";
12001
12551
  var PLUGIN_DESCRIPTION = "Multi-agent code harness framework with unified skills for OpenCode, Cursor, Codex, Kimi Code, and ZCode.";
12002
12552
  var PLUGIN_CATEGORY = "Productivity";
12553
+ var PLUGIN_DISPLAY_NAME = "Morning Star Harness";
12554
+ var PLUGIN_ICON_URL = "https://raw.githubusercontent.com/btspoony/mstar-harness/main/assets/icon.png";
12003
12555
  var GITHUB_REPO = "btspoony/mstar-harness";
12004
12556
  var GITHUB_REF = "main";
12005
12557
  var ZCODE_PLUGIN_MARKER = ".zcode-plugin/plugin.json";
@@ -12017,6 +12569,8 @@ function marketplacePluginEntry() {
12017
12569
  return {
12018
12570
  name: PLUGIN_NAME,
12019
12571
  source: { ...GITHUB_SOURCE },
12572
+ displayName: PLUGIN_DISPLAY_NAME,
12573
+ icon: PLUGIN_ICON_URL,
12020
12574
  description: PLUGIN_DESCRIPTION,
12021
12575
  category: PLUGIN_CATEGORY
12022
12576
  };
@@ -12287,11 +12841,20 @@ function resolveProjectRoot3() {
12287
12841
  return path11.resolve(candidate);
12288
12842
  return resolveProjectRoot();
12289
12843
  }
12844
+ 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);
12848
+ if (!withinRoot) {
12849
+ throw new Error(`path escapes ${base}: ${segments.join(path11.sep)}`);
12850
+ }
12851
+ return resolved;
12852
+ }
12290
12853
  function findUpPackageRoot(startDir, predicate) {
12291
12854
  let dir = path11.resolve(startDir);
12292
12855
  for (;; ) {
12293
12856
  try {
12294
- const manifest = JSON.parse(fs7.readFileSync(path11.join(dir, "package.json"), "utf8"));
12857
+ const manifest = JSON.parse(fs7.readFileSync(joinWithinRoot(dir, "package.json"), "utf8"));
12295
12858
  if (predicate(manifest))
12296
12859
  return dir;
12297
12860
  } catch {}
@@ -12319,7 +12882,8 @@ function resolveCliProjectRoot() {
12319
12882
  function resolveCliPath(userPath) {
12320
12883
  if (path11.isAbsolute(userPath))
12321
12884
  return userPath;
12322
- return path11.resolve(resolveCliProjectRoot(), userPath);
12885
+ const root = resolveCliProjectRoot();
12886
+ return root.endsWith(path11.sep) ? root + userPath : root + path11.sep + userPath;
12323
12887
  }
12324
12888
 
12325
12889
  // src/index.ts
@@ -12526,7 +13090,7 @@ function gitWorkspaceRoot(startDir) {
12526
13090
  if (segment && segment !== ".")
12527
13091
  boundary = path12.dirname(boundary);
12528
13092
  }
12529
- return path12.resolve(boundary);
13093
+ return boundary;
12530
13094
  } catch {}
12531
13095
  return startDir;
12532
13096
  }
@@ -12538,8 +13102,9 @@ function runScaffold(pathArg) {
12538
13102
  const skipped = [];
12539
13103
  const workspaceRoot = gitWorkspaceRoot(root);
12540
13104
  const harnessKind = detectHarnessKind(harnessDir);
12541
- if (harnessKind === "mstar" && path12.resolve(harnessDir) === path12.join(workspaceRoot, ".mstar")) {
12542
- const gitignorePath = path12.join(workspaceRoot, ".gitignore");
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`;
12543
13108
  const snippet = emitGitignoreSnippet("mstar");
12544
13109
  const current = fs8.existsSync(gitignorePath) ? fs8.readFileSync(gitignorePath, "utf8") : "";
12545
13110
  const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));
@@ -12984,11 +13549,11 @@ function readPersistPayload(options) {
12984
13549
  throw new SddScriptError("usage: persist --file <path> and --stdin are mutually exclusive", 2);
12985
13550
  }
12986
13551
  if (options.file !== undefined) {
12987
- const filePath = path12.resolve(options.file);
12988
- if (!fs8.existsSync(filePath)) {
12989
- throw new Error(`persist payload file not found: ${filePath}`);
13552
+ const requested = path12.isAbsolute(options.file) ? options.file : `${process.cwd()}${path12.sep}${options.file}`;
13553
+ if (!fs8.existsSync(requested)) {
13554
+ throw new Error(`persist payload file not found: ${requested}`);
12990
13555
  }
12991
- return fs8.readFileSync(filePath, "utf8");
13556
+ return fs8.readFileSync(requested, "utf8");
12992
13557
  }
12993
13558
  return fs8.readFileSync(0, "utf8");
12994
13559
  }
@@ -13127,7 +13692,7 @@ function solePlanRow(plans, label) {
13127
13692
  return { row: plans[0] };
13128
13693
  }
13129
13694
  function verifyLeaseRow(row, planId, snapshotPath) {
13130
- const result = verifyPlanExecutionLease(row, planId);
13695
+ const result = verifyPlanExecutionLease2(row, planId);
13131
13696
  if (result.ok) {
13132
13697
  const holder = String(result.lease.holder ?? "");
13133
13698
  console.log(import_picocolors2.default.green(`${snapshotPath}: OK plan ${planId} \u2014 execution_lease valid (holder ${holder})`));
@@ -13215,7 +13780,28 @@ function failScript(error, context) {
13215
13780
  console.error(import_picocolors2.default.red(`${context} failed: ${error.message}`));
13216
13781
  process.exitCode = 1;
13217
13782
  }
13218
- var sddCommand = program2.command("sdd").description("SDD workspace / task-brief / review-package helpers (engine-backed)");
13783
+ function loadSddContextFile(pathValue) {
13784
+ if (!pathValue || !path12.isAbsolute(pathValue)) {
13785
+ throw new SddScriptError(`--context must be an absolute path to a SddExecutionContext JSON file; got ${JSON.stringify(pathValue ?? "")}`, 2);
13786
+ }
13787
+ let raw;
13788
+ try {
13789
+ raw = fs8.readFileSync(pathValue, "utf8");
13790
+ } catch {
13791
+ throw new SddScriptError(`no such context file: ${pathValue}`, 2);
13792
+ }
13793
+ let doc;
13794
+ try {
13795
+ doc = JSON.parse(raw);
13796
+ } catch (error) {
13797
+ throw new SddScriptError(`context file is not valid JSON: ${pathValue} (${error.message})`, 2);
13798
+ }
13799
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) {
13800
+ throw new SddScriptError(`context file must contain a JSON object: ${pathValue}`, 2);
13801
+ }
13802
+ return doc;
13803
+ }
13804
+ var sddCommand = program2.command("sdd").description("SDD workspace / task-brief / review-package / check-context / exec helpers (engine-backed; " + "check-context + exec + --context are the spec-A3 bound execution surface)");
13219
13805
  sddCommand.command("workspace").description("Resolve and ensure {SDD_DIR} for a plan (exit 1 on resolution failures, 2 on usage errors)").argument("[plan-id]", "Plan id whose SDD dir is resolved/created").argument("[control-root]", "Control worktree root (default: MSTAR_CONTROL_ROOT or the cwd's git top-level)").action((planId, controlRoot) => {
13220
13806
  try {
13221
13807
  if (!planId) {
@@ -13228,28 +13814,68 @@ sddCommand.command("workspace").description("Resolve and ensure {SDD_DIR} for a
13228
13814
  failScript(error, "sdd workspace");
13229
13815
  }
13230
13816
  });
13231
- sddCommand.command("task-brief").description("Extract the `## Task N` section of a plan into a brief file (exit 3 when task N is missing)").argument("[plan-file]", "Plan markdown file").argument("[task-number]", "Task number whose brief is extracted").argument("[outfile]", "Output file (default: {SDD_DIR}/task-N-brief.md)").action((planFile, taskNumber, outfile) => {
13817
+ sddCommand.command("task-brief").description("Extract the `## Task N` section of a plan into a brief file (exit 3 when task N is missing). " + "With --context the artifact destination is gate-checked before mkdir/write and the emitted path is absolute").argument("[plan-file]", "Plan markdown file").argument("[task-number]", "Task number whose brief is extracted").argument("[outfile]", "Output file (default: {SDD_DIR}/task-N-brief.md)").option("--context <path>", "Absolute path to a SddExecutionContext JSON \u2014 binds the artifact write (spec A3)").action((planFile, taskNumber, outfile, options = {}) => {
13232
13818
  try {
13233
13819
  if (!planFile || !taskNumber) {
13234
- throw new SddScriptError("usage: mstar sdd task-brief PLAN_FILE TASK_NUMBER [OUTFILE]", 2);
13820
+ throw new SddScriptError("usage: mstar sdd task-brief PLAN_FILE TASK_NUMBER [OUTFILE] [--context <absolute.json>]", 2);
13235
13821
  }
13236
- const out = taskBrief(planFile, Number(taskNumber), outfile);
13822
+ const bound = options.context ? { context: resolveSddExecutionContext(loadSddContextFile(options.context)) } : undefined;
13823
+ const out = taskBrief(planFile, Number(taskNumber), outfile, bound);
13237
13824
  console.log(import_picocolors2.default.green(`task ${taskNumber} brief: ${out}`));
13238
13825
  } catch (error) {
13239
13826
  failScript(error, "sdd task-brief");
13240
13827
  }
13241
13828
  });
13242
- sddCommand.command("review-package").description("Write commits + stat + diff -U10 for BASE..HEAD into a review file (exit 2 on bad refs)").argument("[base]", "Base ref (commit SHA)").argument("[head]", "Head ref (commit SHA)").argument("[outfile]", "Output file (default: {SDD_DIR}/review-<short-base>..<short-head>.diff)").action((base, head, outfile) => {
13829
+ sddCommand.command("review-package").description("Write commits + stat + diff -U10 for BASE..HEAD into a review file (exit 2 on bad refs). " + "With --context the review range is probed in the feature worktree and the package is gate-checked into the plan's control artifacts").argument("[base]", "Base ref (commit SHA)").argument("[head]", "Head ref (commit SHA)").argument("[outfile]", "Output file (default: {SDD_DIR}/review-<short-base>..<short-head>.diff)").option("--context <path>", "Absolute path to a SddExecutionContext JSON \u2014 binds the artifact write (spec A3)").action((base, head, outfile, options = {}) => {
13243
13830
  try {
13244
13831
  if (!base || !head) {
13245
- throw new SddScriptError("usage: mstar sdd review-package BASE HEAD [OUTFILE]", 2);
13832
+ throw new SddScriptError("usage: mstar sdd review-package BASE HEAD [OUTFILE] [--context <absolute.json>]", 2);
13246
13833
  }
13247
- const out = reviewPackage(base, head, outfile);
13834
+ const bound = options.context ? { context: resolveSddExecutionContext(loadSddContextFile(options.context)) } : undefined;
13835
+ const out = reviewPackage(base, head, outfile, bound);
13248
13836
  console.log(import_picocolors2.default.green(`review package: ${out}`));
13249
13837
  } catch (error) {
13250
13838
  failScript(error, "sdd review-package");
13251
13839
  }
13252
13840
  });
13841
+ sddCommand.command("check-context").description("Gate one action seam against a resolved SDD execution context (spec A3): the observed cwd is this process's cwd. " + "Exit 0 pass, 1 gate fail, 2 usage; a refused action performs no write").option("--context <path>", "Absolute path to the SddExecutionContext JSON file").option("--kind <kind>", "Action seam kind: source | artifact | launch").option("--target <path>", "Path the action would touch (required for artifact; optional for source/launch)").action((options) => {
13842
+ try {
13843
+ if (!options.context) {
13844
+ throw new SddScriptError("usage: mstar sdd check-context --context <absolute.json> --kind source|artifact|launch [--target <path>]", 2);
13845
+ }
13846
+ if (!options.kind) {
13847
+ throw new SddScriptError("usage: mstar sdd check-context --context <absolute.json> --kind source|artifact|launch [--target <path>]", 2);
13848
+ }
13849
+ if (options.kind !== "source" && options.kind !== "artifact" && options.kind !== "launch") {
13850
+ throw new SddScriptError(`usage: --kind must be source|artifact|launch; got ${JSON.stringify(options.kind)}`, 2);
13851
+ }
13852
+ const resolved = resolveSddExecutionContext(loadSddContextFile(options.context));
13853
+ const gate2 = checkSddAction(resolved, { kind: options.kind, cwd: process.cwd(), target: options.target });
13854
+ if (!gate2.ok) {
13855
+ printChecklist("sdd check-context", gate2);
13856
+ process.exitCode = 1;
13857
+ return;
13858
+ }
13859
+ console.log(import_picocolors2.default.green(`check-context: OK \u2014 ${options.kind} action allowed under plan "${resolved.planId}"`));
13860
+ } catch (error) {
13861
+ failScript(error, "sdd check-context");
13862
+ }
13863
+ });
13864
+ sddCommand.command("exec").description("Run an argv child bound to a resolved SDD execution context (spec A3): spawn cwd = the context's feature worktree, " + "no shell (the argv after -- reaches the child literally), inherited env + stdio. " + "Gate failure exits 1, usage 2, spawn-not-found 127, child exit preserved, signal termination 128+signal (SIGINT/SIGTERM forwarded)").option("--context <path>", "Absolute path to the SddExecutionContext JSON file").argument("[argv...]", "Child executable + args placed after -- (passed through unchanged)").action(async (argv, options) => {
13865
+ try {
13866
+ if (!options.context) {
13867
+ throw new SddScriptError("usage: mstar sdd exec --context <absolute.json> -- <executable> [args...]", 2);
13868
+ }
13869
+ if (argv.length === 0) {
13870
+ throw new SddScriptError(`usage: mstar sdd exec --context <absolute.json> -- <executable> [args...]
13871
+ The argv after -- is passed to the child literally (no shell).`, 2);
13872
+ }
13873
+ const code = await runInSddContext(loadSddContextFile(options.context), argv);
13874
+ process.exitCode = code;
13875
+ } catch (error) {
13876
+ failScript(error, "sdd exec");
13877
+ }
13878
+ });
13253
13879
  var iterationCommand = program2.command("iteration").description("iteration phase-gate + push-cadence checks (engine-backed)");
13254
13880
  function printChecklist(label, gate2) {
13255
13881
  if (gate2.ok) {
@@ -13264,7 +13890,7 @@ function printChecklist(label, gate2) {
13264
13890
  console.error(` fix: ${violation15.fix}`);
13265
13891
  }
13266
13892
  }
13267
- iterationCommand.command("gate").description("Evaluate the phase-transition gate: prints the transition (phase-2-execute / phase-3-close / phase-4-pr-delivery) " + "plus the \xA73.1 entry and \xA73.5 exit checklists. Exit 1 when the gate verdict fails \u2014 during the Phase-3 window " + "(transition: phase-3-close) exit 1 is EXPECTED until the \xA73.4 close items (status: completed + end_date) are " + "written: the exit checklist gates Phase 4, not the Phase-3 entry (qc2 F-003)").requiredOption("--workflow <id>", "Workflow id whose snapshot is evaluated").requiredOption("--compass <path>", "delivery-compass.md path").option("--harness <path>", "Harness dir override (default: resolved {HARNESS_DIR})").option("--branch <branch>", "Current branch probe (exit \xA73.5 item 5)").option("--integration <branch>", "Spec integration branch probe (exit \xA73.5 item 5)").option("--target <branch>", "PR base branch probe (exit \xA73.5 item 6)").action((options) => {
13893
+ iterationCommand.command("gate").description("Evaluate the phase-transition gate: prints the transition (phase-2-execute / phase-3-close / phase-4-pr-delivery) " + "plus the \xA73.1 entry and \xA73.5 exit checklists. Exit 1 when the gate verdict fails \u2014 during the Phase-3 window " + "(transition: phase-3-close) exit 1 is EXPECTED until the \xA73.4 close items (status: completed + end_date) are " + "written: the exit checklist gates Phase 4, not the Phase-3 entry").requiredOption("--workflow <id>", "Workflow id whose snapshot is evaluated").requiredOption("--compass <path>", "delivery-compass.md path").option("--harness <path>", "Harness dir override (default: resolved {HARNESS_DIR})").option("--branch <branch>", "Current branch probe (exit \xA73.5 item 5)").option("--integration <branch>", "Spec integration branch probe (exit \xA73.5 item 5)").option("--target <branch>", "PR base branch probe (exit \xA73.5 item 6)").action((options) => {
13268
13894
  try {
13269
13895
  const snapshotPath = resolveSnapshotPath(options.workflow, options.harness);
13270
13896
  const compassPath = path12.resolve(options.compass);
@@ -13428,7 +14054,7 @@ worktreeCommand.command("qc-alignment").description("Assert the QC/QA alignment
13428
14054
  }
13429
14055
  const assignments = [];
13430
14056
  for (const fileArg of files) {
13431
- const file = path12.resolve(fileArg);
14057
+ const file = path12.isAbsolute(fileArg) ? fileArg : `${process.cwd()}${path12.sep}${fileArg}`;
13432
14058
  if (!fs8.existsSync(file)) {
13433
14059
  throw new Error(`assignment file not found: ${file}`);
13434
14060
  }
@@ -13474,7 +14100,7 @@ reviewCommand.command("seats").description("Map an Assignment's execution mode t
13474
14100
  if (!assignmentFile) {
13475
14101
  throw new SddScriptError("usage: review seats <assignment-file> [--mode sdd|inline|targeted] [--reviewers <role1,role2,...>]", 2);
13476
14102
  }
13477
- const file = path12.resolve(assignmentFile);
14103
+ const file = path12.isAbsolute(assignmentFile) ? assignmentFile : `${process.cwd()}${path12.sep}${assignmentFile}`;
13478
14104
  if (!fs8.existsSync(file)) {
13479
14105
  throw new Error(`assignment file not found: ${file}`);
13480
14106
  }
@@ -13553,25 +14179,31 @@ function lintTargetType(filePath) {
13553
14179
  }
13554
14180
  function collectLintTargets(dir) {
13555
14181
  const targets = [];
13556
- const walk = (current) => {
14182
+ const visit = (current) => {
13557
14183
  for (const entry of fs8.readdirSync(current, { withFileTypes: true })) {
14184
+ if (entry.name.includes(path12.sep))
14185
+ continue;
14186
+ const child = current + entry.name;
13558
14187
  if (entry.isDirectory()) {
13559
14188
  if (LINT_SKIP_DIRS[entry.name] !== true)
13560
- walk(path12.join(current, entry.name));
13561
- } else if (entry.isFile() && lintTargetType(path12.join(current, entry.name)) !== null) {
13562
- targets.push(path12.join(current, entry.name));
14189
+ visit(child + path12.sep);
14190
+ } else if (entry.isFile() && lintTargetType(child) !== null) {
14191
+ targets.push(child);
13563
14192
  }
13564
14193
  }
13565
14194
  };
13566
- walk(dir);
14195
+ const root = dir.endsWith(path12.sep) ? `${dir}` : `${dir}${path12.sep}`;
14196
+ visit(root);
13567
14197
  return targets;
13568
14198
  }
13569
- function lintOneFile(filePath, forcedType, prVariant) {
13570
- const abs = path12.resolve(filePath);
13571
- const text = fs8.readFileSync(abs, "utf8");
14199
+ var lintIo = {
14200
+ readText: async (resolvedPath) => fs8.promises.readFile(resolvedPath, "utf8")
14201
+ };
14202
+ async function lintOneFile(filePath, forcedType, prVariant) {
14203
+ const text = await lintIo.readText(filePath);
13572
14204
  const violations = [];
13573
14205
  const markers = [];
13574
- const effective = forcedType ?? lintTargetType(abs);
14206
+ const effective = forcedType ?? lintTargetType(filePath);
13575
14207
  switch (effective) {
13576
14208
  case "plan":
13577
14209
  violations.push(...planQualityBar(text).violations);
@@ -13601,12 +14233,12 @@ function lintOneFile(filePath, forcedType, prVariant) {
13601
14233
  violations.push(...validateFindingDoc(text, { ...prVariant ? { prVariant: true } : {} }).violations);
13602
14234
  break;
13603
14235
  default:
13604
- throw new SddScriptError(`usage: lint <target> \u2014 unsupported file type "${path12.basename(abs)}" (lintable: plan files, SKILL.md, STRATEGY.md, task-N-report.md, code files)`, 2);
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);
13605
14237
  }
13606
14238
  return { violations, markers };
13607
14239
  }
13608
14240
  var lintCommand = program2.command("lint").description("lint harness artifacts by content type (engine-backed): plan files \u2192 quality bar, SKILL.md \u2192 frontmatter, " + "STRATEGY.md \u2192 required sections, task-N-report.md \u2192 SDD TDD triple, code files \u2192 simplify:/temporary markers");
13609
- lintCommand.description("Lint <target> (file or dir) \u2014 exit 1 on violations, 2 on usage. --type forces one content type " + "(plan | skill | strategy | report | code | finding); finding docs are explicit-only").argument("[target]", "File or directory to lint").option("--type <type>", "Force the content type (plan | skill | strategy | report | code | finding)").option("--pr-variant", "With --type finding: enforce the PR-only Merge class contract (presence, enum, placement after Confidence)").action((target, options) => {
14241
+ lintCommand.description("Lint <target> (file or dir) \u2014 exit 1 on violations, 2 on usage. --type forces one content type " + "(plan | skill | strategy | report | code | finding); finding docs are explicit-only").argument("[target]", "File or directory to lint").option("--type <type>", "Force the content type (plan | skill | strategy | report | code | finding)").option("--pr-variant", "With --type finding: enforce the PR-only Merge class contract (presence, enum, placement after Confidence)").action(async (target, options) => {
13610
14242
  try {
13611
14243
  if (!target)
13612
14244
  throw new SddScriptError("usage: lint <target> (file or dir)", 2);
@@ -13632,7 +14264,7 @@ lintCommand.description("Lint <target> (file or dir) \u2014 exit 1 on violations
13632
14264
  const label = `lint ${file}`;
13633
14265
  let result;
13634
14266
  try {
13635
- result = lintOneFile(file, forcedType ?? undefined, options.prVariant === true);
14267
+ result = await lintOneFile(file, forcedType ?? undefined, options.prVariant === true);
13636
14268
  } catch (error) {
13637
14269
  if (error instanceof SddScriptError)
13638
14270
  throw error;
@@ -13667,7 +14299,7 @@ designMdCommand.command("validate").description("Validate DESIGN.md in <dir>: to
13667
14299
  if (!dir)
13668
14300
  throw new SddScriptError("usage: design-md validate <dir>", 2);
13669
14301
  const abs = resolveCliPath(dir);
13670
- const lightPath = path12.join(abs, "DESIGN.md");
14302
+ const lightPath = `${abs}${path12.sep}DESIGN.md`;
13671
14303
  if (!fs8.existsSync(lightPath))
13672
14304
  throw new Error(`design file not found: ${lightPath}`);
13673
14305
  const light = fs8.readFileSync(lightPath, "utf8");
@@ -13675,7 +14307,7 @@ designMdCommand.command("validate").description("Validate DESIGN.md in <dir>: to
13675
14307
  const tokens = validateDesignTokenFrontmatter(light);
13676
14308
  printChecklist("design-md validate (tokens)", tokens);
13677
14309
  violations.push(...tokens.violations);
13678
- const darkPath = path12.join(abs, "DESIGN.dark.md");
14310
+ const darkPath = `${abs}${path12.sep}DESIGN.dark.md`;
13679
14311
  if (fs8.existsSync(darkPath)) {
13680
14312
  const parity = assertLightDarkParity(light, fs8.readFileSync(darkPath, "utf8"));
13681
14313
  printChecklist("design-md validate (light/dark parity)", parity);
@@ -13888,7 +14520,7 @@ function listTrackedFiles(root) {
13888
14520
  } catch {
13889
14521
  throw new SddScriptError("not a git repository or git unavailable \u2014 refusing to report an empty scan as clean", 2);
13890
14522
  }
13891
- return out.split("\x00").filter((f) => f !== "").map((f) => path12.join(root, f));
14523
+ return out.split("\x00").filter((f) => f !== "").map((f) => root.endsWith(path12.sep) ? root + f : root + path12.sep + f);
13892
14524
  }
13893
14525
  auditCommand.command("secret-scan").description("Read-only credential-pattern scan over git-tracked files under [path] " + "(default cwd): prints {file, line, type} findings; never prints values. " + "Exit 1 on findings, 0 when clean, 2 when the tracked-file walk or reads fail").argument("[path]", "Directory to scan (default: cwd)").action((scanPath) => {
13894
14526
  try {
@@ -14047,13 +14679,11 @@ skillCommand.command("lint").description("Lint <skill-dir>/SKILL.md: frontmatter
14047
14679
  const frontmatter = lintSkillFrontmatter(text);
14048
14680
  printChecklist("skill lint (frontmatter)", frontmatter);
14049
14681
  violations.push(...frontmatter.violations);
14050
- const skillBase = path12.basename(path12.dirname(skillFile));
14051
- const isCore = skillBase === "mstar-harness-core";
14052
- const fiveQuestionMode = skillBase.startsWith("mstar-") && !isCore && skillBase !== "mstar-skill-authoring" ? "runtime" : "authoring";
14053
- if (isCore) {
14682
+ const profile = classifySkillLint(path12.basename(path12.dirname(skillFile)));
14683
+ if (profile.mode === null) {
14054
14684
  console.log(import_picocolors2.default.yellow("skill lint (five questions): EXEMPT \u2014 mstar-harness-core is exempt by design (hub headings)"));
14055
14685
  } else {
14056
- const fiveQuestion = lintFiveQuestion(stripFrontmatter(text), fiveQuestionMode);
14686
+ const fiveQuestion = lintFiveQuestion(stripFrontmatter(text), profile.mode);
14057
14687
  printChecklist("skill lint (five questions)", fiveQuestion);
14058
14688
  violations.push(...fiveQuestion.violations);
14059
14689
  }
@@ -14689,9 +15319,10 @@ prReviewCommand.command("worktree-setup").description("Create the isolated revie
14689
15319
  }
14690
15320
  });
14691
15321
  function prReviewArtifactPathFor(worktreePath, suffix) {
14692
- const parent = path12.dirname(path12.resolve(worktreePath));
14693
- const name = path12.basename(path12.resolve(worktreePath));
14694
- return path12.join(parent, `.${name}.prreview.${suffix}`);
15322
+ const parent = path12.dirname(worktreePath);
15323
+ const name = path12.basename(worktreePath);
15324
+ const prefix = parent.endsWith(path12.sep) ? parent : parent + path12.sep;
15325
+ return `${prefix}.${name}.prreview.${suffix}`;
14695
15326
  }
14696
15327
  function writeFdSync(fd, buf) {
14697
15328
  let written = 0;