@mstar-harness/cli 4.0.3 → 4.0.5

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 +1460 -453
  2. package/package.json +1 -1
@@ -361,6 +361,7 @@ __export(exports_engine, {
361
361
  resolveKnowledgeDir: () => resolveKnowledgeDir,
362
362
  resolveMstarcEnforcement: () => resolveMstarcEnforcement,
363
363
  resolvePlanDir: () => resolvePlanDir,
364
+ resolvePrReviewSettlement: () => resolvePrReviewSettlement,
364
365
  resolvePrReviewTier: () => resolvePrReviewTier,
365
366
  resolveProcessHarnessDir: () => resolveProcessHarnessDir,
366
367
  resolveProjectDir: () => resolveProjectDir,
@@ -14829,8 +14830,13 @@ function resolveReviewRunDir(opts) {
14829
14830
  const resolved = spec.kind === "codebase" ? { kind: "codebase", level: spec.level, round: spec.round ?? nextCodebaseRound(opts.reviewsDir, date, spec.level) } : spec;
14830
14831
  return join12(opts.reviewsDir, reviewRunDirName(date, resolved));
14831
14832
  }
14832
- function resolveScaffoldDirs(root) {
14833
+ function resolveScaffoldDirs(root, options = {}) {
14833
14834
  const start = resolve8(root);
14835
+ if (options.harnessDir !== undefined) {
14836
+ const harnessDir2 = options.harnessDir;
14837
+ const projectDir2 = mstarcDirOverride(harnessDir2, "projectDir") ?? join12(harnessDir2, "projects");
14838
+ return { harnessDir: harnessDir2, projectDir: projectDir2 };
14839
+ }
14834
14840
  const boundary = resolve8(start, defaultWorkspaceRoot(start));
14835
14841
  const rc = loadMstarc(start, boundary);
14836
14842
  const explicit = process.env.MSTAR_HARNESS_DIR;
@@ -14839,8 +14845,8 @@ function resolveScaffoldDirs(root) {
14839
14845
  const projectDir = declaredProjectDir !== null ? declaredProjectDir : join12(harnessDir, "projects");
14840
14846
  return { harnessDir, projectDir };
14841
14847
  }
14842
- async function scaffoldHarness(root) {
14843
- const { harnessDir, projectDir } = resolveScaffoldDirs(root);
14848
+ async function scaffoldHarness(root, options = {}) {
14849
+ const { harnessDir, projectDir } = resolveScaffoldDirs(root, options);
14844
14850
  for (const dir of SCAFFOLD_DIRS)
14845
14851
  mkdirSync4(join12(harnessDir, dir), { recursive: true });
14846
14852
  const defaultProjectDir = join12(projectDir, _DEFAULT_PROJECT);
@@ -15709,10 +15715,16 @@ function readCompletionEvidence(value, route = "integration") {
15709
15715
  const qaReport = value.qa.report;
15710
15716
  const extra = value.evidence_paths === undefined ? [] : value.evidence_paths;
15711
15717
  if (!Array.isArray(extra) || !extra.every(isNonEmptyString)) {
15712
- throw new CoordinationError("coordination.invalid-input", "Invalid evidence_paths: provide an array of absolute evidence paths. Inspect workflow state with mstar status validate.");
15713
- }
15714
- const paths = new Set([...qc.reports, qc.consolidated, ...extra]);
15715
- paths.add(qaReport);
15718
+ const entries = Array.isArray(extra) ? extra : [];
15719
+ const index2 = entries.findIndex((entry) => !isNonEmptyString(entry));
15720
+ throw new CoordinationError("coordination.invalid-input", index2 < 0 ? "Invalid evidence_paths: provide an array of absolute evidence paths. Inspect workflow state with mstar status validate." : `Invalid evidence_paths[${index2}]: every entry must be a non-empty evidence path.`, index2 < 0 ? {} : { field: `evidence_paths[${index2}]`, value: entries[index2] });
15721
+ }
15722
+ const evidenceRefs = [
15723
+ ...qc.reports.map((path2, index2) => ({ field: `qc.reports[${index2}]`, path: path2 })),
15724
+ { field: "qc.consolidated", path: qc.consolidated },
15725
+ { field: "qa.report", path: qaReport },
15726
+ ...extra.map((path2, index2) => ({ field: `evidence_paths[${index2}]`, path: path2 }))
15727
+ ];
15716
15728
  return {
15717
15729
  source_sha: sourceSha,
15718
15730
  review_base: reviewBase,
@@ -15723,7 +15735,7 @@ function readCompletionEvidence(value, route = "integration") {
15723
15735
  qa_gate: qaGate,
15724
15736
  qa_decision: "pass",
15725
15737
  qa_report: qaReport,
15726
- evidence_paths: [...paths]
15738
+ evidence_refs: evidenceRefs
15727
15739
  };
15728
15740
  }
15729
15741
  function assertCompletionReviewDecision(evidence, planId, qaGate) {
@@ -16755,6 +16767,9 @@ function resolveProcessHarnessDir(cwd = process.cwd(), harnessDir) {
16755
16767
  throw error;
16756
16768
  }
16757
16769
  if (linked) {
16770
+ const envRoot = process.env.MSTAR_HARNESS_DIR;
16771
+ if (typeof envRoot === "string" && envRoot.trim() !== "")
16772
+ return resolveHarnessDir(start);
16758
16773
  throw new CoordinationError("coordination.not-in-git", "The linked checkout's main worktree cannot be read. Run mstar status validate. Then inspect the main worktree at the control harness root.", { cwd: start, marker: join16(dir, ".git") });
16759
16774
  }
16760
16775
  const parent = dirname9(dir);
@@ -17124,17 +17139,19 @@ function planAreaRoots(harnessRoot, planId) {
17124
17139
  canonicalizeNearestExisting(resolveSddDir(harnessRoot, planId))
17125
17140
  ];
17126
17141
  }
17127
- function assertEvidenceInsidePlanArea(roots, paths) {
17128
- for (const path2 of paths) {
17142
+ function assertEvidenceInsidePlanArea(roots, refs) {
17143
+ const allowed = roots.join(" or ");
17144
+ for (const { field, path: path2 } of refs) {
17145
+ const details = { field, value: path2, allowed: roots };
17129
17146
  if (!isAbsolute8(path2)) {
17130
- throw invalidInput2("Evidence path must be absolute and inside the plan area. Inspect the plan scope with mstar plan show. Pass the plan id registered in the workflow row.", { path: path2 });
17147
+ throw invalidInput2(`Evidence value in ${field} is not an absolute path: ${JSON.stringify(path2)}; evidence must be an absolute path inside ${allowed}`, details);
17131
17148
  }
17132
17149
  const abs = canonicalizeNearestExisting(path2);
17133
17150
  if (!roots.some((root) => isWithin(root, abs))) {
17134
- throw new CoordinationError("coordination.path-mismatch", "Evidence path is outside the plan's plan/SDD area. Inspect the plan scope with mstar plan show. Pass the plan id registered in the workflow row.", { path: abs, allowed: roots });
17151
+ throw new CoordinationError("coordination.path-mismatch", `Evidence value in ${field} is outside the plan area: ${JSON.stringify(abs)}; evidence must be an absolute path inside ${allowed}`, { ...details, value: abs });
17135
17152
  }
17136
17153
  if (!existsSync13(abs)) {
17137
- throw new CoordinationError("coordination.invalid-input", "Evidence path does not exist inside the plan's plan/SDD area. Inspect the plan scope with mstar plan show. Pass the plan id registered in the workflow row.", { path: abs });
17154
+ throw new CoordinationError("coordination.invalid-input", `Evidence value in ${field} does not exist: ${JSON.stringify(abs)}; record the evidence inside ${allowed} first`, { ...details, value: abs });
17138
17155
  }
17139
17156
  }
17140
17157
  }
@@ -21794,7 +21811,7 @@ function detectHost(signals) {
21794
21811
  return "opencode";
21795
21812
  if (s.has("task_agent_batch") || s.has("ask") || s.has("hub"))
21796
21813
  return "omp";
21797
- if (s.has("subagent"))
21814
+ if (s.has("subagent") || s.has("spawn_teammate") || s.has("team_task_create"))
21798
21815
  return "dsh";
21799
21816
  if (s.has("AgentSwarm"))
21800
21817
  return "kimi";
@@ -22009,6 +22026,56 @@ function checkProvidedTallyShape(tally, violations) {
22009
22026
  violations.push(violation15("high", "review.incomplete-unexpected", `tally.incomplete is carried only by the "incomplete" tally verdict - tally.verdict is "${String(tally.verdict)}"`, "remove tally.incomplete, or set tally.verdict: incomplete"));
22010
22027
  }
22011
22028
  }
22029
+ function resolvePrReviewSettlement(facts) {
22030
+ if (facts === null || typeof facts !== "object") {
22031
+ throw new TypeError(`resolvePrReviewSettlement: run facts are required - got ${JSON.stringify(facts)}`);
22032
+ }
22033
+ if (facts.stopped !== undefined && !isSingleLineFact(facts.stopped)) {
22034
+ throw new TypeError(`resolvePrReviewSettlement: stopped must be a non-empty single-line string - got ${JSON.stringify(facts.stopped)}`);
22035
+ }
22036
+ const domainFields = [
22037
+ ["requiredDomains", facts.requiredDomains],
22038
+ ["openedDomains", facts.openedDomains]
22039
+ ];
22040
+ for (const [field, value] of domainFields) {
22041
+ if (!Array.isArray(value) || !value.every(isSingleLineFact)) {
22042
+ throw new TypeError(`resolvePrReviewSettlement: ${field} must be an array of non-empty single-line strings - got ${JSON.stringify(value)}`);
22043
+ }
22044
+ }
22045
+ if (facts.requiredDomains.length === 0) {
22046
+ throw new TypeError("resolvePrReviewSettlement: requiredDomains must be an array of non-empty single-line strings and must not be empty - got []");
22047
+ }
22048
+ if (typeof facts.diffBasisReadable !== "boolean") {
22049
+ throw new TypeError(`resolvePrReviewSettlement: diffBasisReadable must be a boolean - got ${JSON.stringify(facts.diffBasisReadable)}`);
22050
+ }
22051
+ if (facts.partialSeatScopes !== undefined && (!Array.isArray(facts.partialSeatScopes) || !facts.partialSeatScopes.every(isSingleLineFact))) {
22052
+ throw new TypeError(`resolvePrReviewSettlement: partialSeatScopes must be an array of non-empty single-line strings - got ${JSON.stringify(facts.partialSeatScopes)}`);
22053
+ }
22054
+ const unconsumed = [...facts.openedDomains];
22055
+ const missing = facts.requiredDomains.filter((domain2) => {
22056
+ const at = unconsumed.indexOf(domain2);
22057
+ if (at < 0)
22058
+ return true;
22059
+ unconsumed.splice(at, 1);
22060
+ return false;
22061
+ });
22062
+ const unreadableBasis = !facts.diffBasisReadable;
22063
+ const unscanned = [...new Set([
22064
+ ...missing,
22065
+ ...unreadableBasis ? ["the resolved diff basis"] : [],
22066
+ ...facts.partialSeatScopes ?? []
22067
+ ])];
22068
+ if (facts.stopped !== undefined) {
22069
+ return { settled: false, incomplete: { reason: `the run stopped before synthesis \u2014 ${facts.stopped}`, unscanned } };
22070
+ }
22071
+ if (missing.length > 0) {
22072
+ return { settled: false, incomplete: { reason: `required domain seat(s) never opened: ${missing.join(", ")}`, unscanned } };
22073
+ }
22074
+ if (unreadableBasis) {
22075
+ return { settled: false, incomplete: { reason: "the resolved diff basis could not be read", unscanned } };
22076
+ }
22077
+ return { settled: true };
22078
+ }
22012
22079
  function validateMstarReviewV1(doc) {
22013
22080
  const violations = [];
22014
22081
  if (!isPlainObject9(doc)) {
@@ -23172,8 +23239,8 @@ function readDshSessionBinding(context, sessionId, cwd) {
23172
23239
  return withExecutionReadGuard(context, (db) => {
23173
23240
  const row = db.prepare("select session_id, cwd, selected_workflow_id, execution_binding, excluded_before_seq, updated_at from dsh_session_bindings where session_id = ? and cwd = ?").get(sessionId, cwd);
23174
23241
  if (!row) {
23175
- const otherCwd = db.prepare("select 1 from dsh_session_bindings where session_id = ? limit 1").get(sessionId);
23176
- return otherCwd ? { kind: "unavailable", reason: "cwd-mismatch" } : { kind: "ok" };
23242
+ const otherCwd = db.prepare("select cwd from dsh_session_bindings where session_id = ? limit 1").get(sessionId);
23243
+ return otherCwd ? { kind: "unavailable", reason: "cwd-mismatch", recordedCwd: otherCwd.cwd } : { kind: "ok" };
23177
23244
  }
23178
23245
  return {
23179
23246
  kind: "ok",
@@ -26571,6 +26638,19 @@ function withExecutionPlanOperation(context, resolved, requestHash4, preflight,
26571
26638
  return { ...receipt, operationId: request.operationId, replayed: false, recovery };
26572
26639
  });
26573
26640
  }
26641
+ function branchOfClaim(value) {
26642
+ if (/[\r\n]/.test(value)) {
26643
+ throw invalidPlanInput('Invalid prepare workingBranch: the claim must be a single line \u2014 a branch name or "create <branch> from <base>"; retry through mstar plan prepare.', { field: "workingBranch", value });
26644
+ }
26645
+ const form = parseAssignmentBranchForms(`Working branch: ${value}`).createForm;
26646
+ if (form !== undefined) {
26647
+ if (form.name !== "" && form.base !== undefined && form.base !== "")
26648
+ return form.name;
26649
+ } else if (!/\s/.test(value)) {
26650
+ return value;
26651
+ }
26652
+ throw invalidPlanInput(`Invalid prepare workingBranch: record a branch name, or the Assignment's "create <branch> from <base>" form; retry through mstar plan prepare.`, { field: "workingBranch", value });
26653
+ }
26574
26654
  function readPrepareInputs(call) {
26575
26655
  const config = call.operation.config ?? {};
26576
26656
  assertExactKeys(config, ["worktreePath", "workingBranch", "qaGate", "findingsCleanup"], "prepare config");
@@ -26586,7 +26666,15 @@ function readPrepareInputs(call) {
26586
26666
  if (config.findingsCleanup !== undefined && !["zero-residual", "allow-residual"].includes(config.findingsCleanup)) {
26587
26667
  throw invalidPlanInput("Invalid prepare findingsCleanup: choose zero-residual or allow-residual; retry through mstar plan prepare.");
26588
26668
  }
26589
- return { config: { ...config, qaGate: config.qaGate ?? "mandatory", findingsCleanup: config.findingsCleanup ?? "allow-residual" } };
26669
+ const branch = config.workingBranch === undefined ? undefined : branchOfClaim(config.workingBranch);
26670
+ return {
26671
+ config: {
26672
+ ...config,
26673
+ ...branch === undefined ? {} : { workingBranch: branch },
26674
+ qaGate: config.qaGate ?? "mandatory",
26675
+ findingsCleanup: config.findingsCleanup ?? "allow-residual"
26676
+ }
26677
+ };
26590
26678
  }
26591
26679
  function assertWorkingBranchIsFeature(context, workingBranch) {
26592
26680
  if (workingBranch === undefined)
@@ -26736,7 +26824,7 @@ async function progressExecutionPlan(context, request) {
26736
26824
  plans: [plan, ...witness.siblings.map((sibling) => sibling.plan)]
26737
26825
  }, progress.track_branches);
26738
26826
  }
26739
- assertEvidenceInsidePlanArea(planAreas, progress.evidence_paths);
26827
+ assertEvidenceInsidePlanArea(planAreas, progress.evidence_paths.map((path2, index2) => ({ field: `progress.evidence_paths[${index2}]`, path: path2 })));
26740
26828
  const metadata = { ...isPlainObject(plan.metadata) ? plan.metadata : {} };
26741
26829
  const nextMetadata = progress.track_branches !== undefined ? { ...metadata, track_branches: [...progress.track_branches] } : metadata;
26742
26830
  const nextState = { ...state, status: progress.status };
@@ -26923,7 +27011,7 @@ async function readWorkflowSnapshot2(context, workflowId) {
26923
27011
  function assertReportOnlyCompletionEvidence(snapshot, planId) {
26924
27012
  const failure = consultDeliveryEvidence(snapshot).find((entry) => !entry.ok);
26925
27013
  if (failure !== undefined) {
26926
- throw new CoordinationError("coordination.invalid-transition", "The transition requires matching report-only completion evidence; inspect the workflow with mstar status validate.", {
27014
+ throw new CoordinationError("coordination.invalid-transition", "The report-only route completes only after its registered completion policy is RECORDED as fulfilled. Record that fulfilment with mstar workflow evidence --workflow <id> --file <absolute-json>, then retry plan complete.", {
26927
27015
  message: failure.message,
26928
27016
  plan_id: planId,
26929
27017
  code: failure.code
@@ -27083,7 +27171,7 @@ async function captureCompletionWitnesses(context, read, operation) {
27083
27171
  const prepared = effectivePrepareConfig(before.data);
27084
27172
  assertCompletionReviewDecision(evidence, read.planId, prepared.qa_gate);
27085
27173
  const planAreas = planAreaRoots(controlHarnessRoot(context), read.planId);
27086
- assertEvidenceInsidePlanArea(planAreas, evidence.evidence_paths);
27174
+ assertEvidenceInsidePlanArea(planAreas, evidence.evidence_refs);
27087
27175
  const evidenceRefs = completionEvidenceRefs(evidence);
27088
27176
  if (route === "report-only") {
27089
27177
  assertReportOnlyCompletionEvidence(snapshot, read.planId);
@@ -27125,7 +27213,7 @@ function completeInTransaction(witness, tx, at, read, operation, witnesses) {
27125
27213
  const evidence = readCompletionEvidence(operation.evidence, rowValidationRoute(snapshot, row));
27126
27214
  const prepared = effectivePrepareConfig(witness.view);
27127
27215
  assertCompletionReviewDecision(evidence, planId, prepared.qa_gate);
27128
- assertEvidenceInsidePlanArea(witnesses.planAreas, evidence.evidence_paths);
27216
+ assertEvidenceInsidePlanArea(witnesses.planAreas, evidence.evidence_refs);
27129
27217
  const refs = witnesses.evidenceRefs;
27130
27218
  const scope = route === "report-only" ? null : planScopeOf(witness.view, planId);
27131
27219
  const record = {
@@ -28193,7 +28281,7 @@ function recoverableIntegrationClaim(tx, input) {
28193
28281
  return claim;
28194
28282
  if (!input.required)
28195
28283
  return null;
28196
- throw invalidWorkflowTransition("The workflow cannot renew predecessor recovery; the current binding and claim are unchanged. A renewal requires a fresh operation id and complete stop evidence whose instant covers the named predecessor's claim and is not in the future. Inspect the claim and scope with mstar status validate; for an absent claim plan, inspect the backup with mstar store execution restore-preview before any restore.", {
28284
+ throw invalidWorkflowTransition("The workflow cannot renew predecessor recovery; the current binding and claim are unchanged. A renewal requires a fresh operation id and complete stop evidence whose instant covers the named predecessor's claim and is not in the future. Inspect the claim and scope with mstar status validate; for an absent claim plan, inspect the backup with mstar store execution restore-preview --harness=<abs> before any restore.", {
28197
28285
  workflow_id: workflowId,
28198
28286
  session_id: callerId,
28199
28287
  prior_session_id: priorSessionId,
@@ -35415,6 +35503,7 @@ var init_engine = __esm(() => {
35415
35503
  init_execution_store();
35416
35504
  init_issue();
35417
35505
  init_path();
35506
+ init_dispatch();
35418
35507
  init_execution_session();
35419
35508
  init_coordination_write();
35420
35509
  init_execution_store();
@@ -36116,7 +36205,7 @@ import fs23 from "node:fs";
36116
36205
  // package.json
36117
36206
  var package_default = {
36118
36207
  name: "@mstar-harness/cli",
36119
- version: "4.0.3",
36208
+ version: "4.0.5",
36120
36209
  description: "Morning Star harness CLI \u2014 installer bootstrap, canonical command adapter, and stdio MCP server.",
36121
36210
  repository: {
36122
36211
  type: "git",
@@ -36166,7 +36255,7 @@ var package_default = {
36166
36255
  // ../engine/package.json
36167
36256
  var package_default2 = {
36168
36257
  name: "@mstar-harness/engine",
36169
- version: "4.0.3",
36258
+ version: "4.0.5",
36170
36259
  description: "Morning Star Harness Workflow Engine \u2014 deterministic workflow enforcement library (path, status, lease, dispatch, sdd, iteration, lint gates).",
36171
36260
  license: "MIT",
36172
36261
  repository: {
@@ -56853,6 +56942,7 @@ init_engine();
56853
56942
  import { randomUUID as randomUUID32 } from "node:crypto";
56854
56943
  import { readFileSync as readFileSync26 } from "node:fs";
56855
56944
  import path3 from "node:path";
56945
+ init_engine();
56856
56946
  import { readFileSync as readFileSync32 } from "node:fs";
56857
56947
  import { constants as constants5 } from "node:os";
56858
56948
  import { isAbsolute as isAbsolute17 } from "node:path";
@@ -56885,8 +56975,8 @@ init_engine();
56885
56975
  import { readFileSync as readFileSync102 } from "node:fs";
56886
56976
  import path10 from "node:path";
56887
56977
  init_engine();
56888
- import { existsSync as existsSync42, readFileSync as readFileSync112, readdirSync as readdirSync22, statSync as statSync10 } from "node:fs";
56889
- import path222 from "node:path";
56978
+ import { existsSync as existsSync42, readFileSync as readFileSync112, readdirSync as readdirSync22, realpathSync as realpathSync22, statSync as statSync10 } from "node:fs";
56979
+ import path23 from "node:path";
56890
56980
  init_engine();
56891
56981
  init_engine();
56892
56982
  import fs from "node:fs";
@@ -56920,27 +57010,28 @@ import { execFileSync as execFileSync6, spawnSync } from "node:child_process";
56920
57010
  import fs12 from "node:fs";
56921
57011
  import { delimiter } from "node:path";
56922
57012
  import path21 from "node:path";
57013
+ import path222 from "node:path";
56923
57014
  import { execFileSync as execFileSync22 } from "node:child_process";
56924
57015
  import { existsSync as existsSync52, readFileSync as readFileSync122, statSync as statSync22 } from "node:fs";
56925
- import path23 from "node:path";
57016
+ import path24 from "node:path";
56926
57017
  init_engine();
56927
57018
  import { existsSync as existsSync62, readFileSync as readFileSync132, renameSync as renameSync3, unlinkSync as unlinkSync5, openSync as openSync7, fstatSync as fstatSync6, lstatSync as lstatSync5, closeSync as closeSync7, linkSync as linkSync2 } from "node:fs";
56928
- import path24 from "node:path";
57019
+ import path25 from "node:path";
56929
57020
  import { randomUUID as randomUUID72 } from "node:crypto";
56930
57021
  init_engine();
56931
- import fs13, { realpathSync as realpathSync22 } from "node:fs";
57022
+ import fs13, { realpathSync as realpathSync32 } from "node:fs";
56932
57023
  import { createHash as createHash22 } from "node:crypto";
56933
- import path25 from "node:path";
56934
- import { closeSync as closeSync22, constants as fsConstants2, fstatSync as fstatSync22, lstatSync as lstatSync22, openSync as openSync22, readFileSync as readFileSync142 } from "node:fs";
56935
57024
  import path26 from "node:path";
57025
+ import { closeSync as closeSync22, constants as fsConstants2, fstatSync as fstatSync22, lstatSync as lstatSync22, openSync as openSync22, readFileSync as readFileSync142 } from "node:fs";
57026
+ import path27 from "node:path";
56936
57027
  init_engine();
56937
57028
  init_engine();
56938
57029
  import { execFileSync as execFileSync32 } from "node:child_process";
56939
57030
  import fs15 from "node:fs";
56940
57031
  import os6 from "node:os";
56941
- import path28 from "node:path";
57032
+ import path29 from "node:path";
56942
57033
  import fs14 from "node:fs";
56943
- import path27 from "node:path";
57034
+ import path28 from "node:path";
56944
57035
  init_engine();
56945
57036
  import { constants as constants22 } from "node:os";
56946
57037
  import { spawn as nodeSpawn } from "node:child_process";
@@ -58149,12 +58240,12 @@ Recovery: ${recovery}`}`,
58149
58240
  details: envelopeDetails
58150
58241
  };
58151
58242
  }
58152
- function redactInputScalar(value) {
58243
+ function sanitizeInputScalar(value) {
58153
58244
  return redactSecrets2(value).text.replace(/\[REDACTED [^\]\r\n]+\]/g, "[REDACTED]").replace(/\bsk-[A-Za-z0-9-]+\b/g, "[REDACTED]");
58154
58245
  }
58155
58246
  function safeReceivedValue(value) {
58156
58247
  if (typeof value === "string")
58157
- return JSON.stringify(redactInputScalar(value));
58248
+ return JSON.stringify(sanitizeInputScalar(value));
58158
58249
  if (value === null)
58159
58250
  return "null";
58160
58251
  if (value === undefined)
@@ -58167,7 +58258,7 @@ function issueMessageSanitizer(input2) {
58167
58258
  const replacements = {};
58168
58259
  const visit2 = (value) => {
58169
58260
  if (typeof value === "string") {
58170
- const redacted = redactInputScalar(value);
58261
+ const redacted = sanitizeInputScalar(value);
58171
58262
  if (redacted !== value && replacements[value] === undefined)
58172
58263
  replacements[value] = redacted;
58173
58264
  } else if (Array.isArray(value)) {
@@ -58197,7 +58288,7 @@ function inputPath(issue2) {
58197
58288
  function rejectionFacts(issue2, input2) {
58198
58289
  const expected = issue2.code === "invalid_type" ? issue2.expected : issue2.code === "invalid_value" && ("values" in issue2) && Array.isArray(issue2.values) ? issue2.values.map(String).join(" | ") : issue2.code === "too_small" && ("minimum" in issue2) ? `${issue2.origin} ${issue2.inclusive ? ">=" : ">"} ${String(issue2.minimum)}` : issue2.code === "too_big" && ("maximum" in issue2) ? `${issue2.origin} ${issue2.inclusive ? "<=" : "<"} ${String(issue2.maximum)}` : issue2.code === "unrecognized_keys" ? "recognized keys" : "valid value";
58199
58290
  const value = inputValueAtPath(input2, issue2.path);
58200
- const received = value === undefined ? "undefined" : value === null ? "null" : typeof value === "object" ? Array.isArray(value) ? "array" : "object" : typeof value === "string" ? redactInputScalar(value) : String(value);
58291
+ const received = value === undefined ? "undefined" : value === null ? "null" : typeof value === "object" ? Array.isArray(value) ? "array" : "object" : typeof value === "string" ? sanitizeInputScalar(value) : String(value);
58201
58292
  return { expected, received };
58202
58293
  }
58203
58294
  function decodeInputDiagnostics(error62, input2) {
@@ -58216,7 +58307,7 @@ function decodeInputDiagnostics(error62, input2) {
58216
58307
  };
58217
58308
  });
58218
58309
  }
58219
- var IDENTITY_SUPPLIES = "CLI: pass --session-id or set MSTAR_HOST_SESSION_ID; MCP: the host must pass sessionId per call";
58310
+ var IDENTITY_SUPPLIES = "CLI: pass --session-id or set MSTAR_HOST_SESSION_ID; MCP: a shared connection accepts no caller-declared identity by default, so use the dsh native tool that covers the operation (plan bind, audit report validation and execution clear) or run the CLI command from the session's shell \u2014 plan prepare/progress/complete have no native tool yet";
58220
58311
  var TOKEN_SUPPLIES = {
58221
58312
  root: "the store's root execution token: read `mstar status validate` output field data.token",
58222
58313
  workflow: "the addressed workflow's execution token: read `mstar status validate` output data.workflows[].token for this workflow's id",
@@ -58681,10 +58772,12 @@ function payloadSchema(fields) {
58681
58772
  }));
58682
58773
  return exports_external.object(shape).passthrough();
58683
58774
  }
58775
+ var jsonKindContract = `${payloadContracts.json.reason} ${payloadContracts.json.alternative}`;
58684
58776
  var payloadSchemas = {
58685
58777
  review: { schema: payloadSchema(payloadContracts.review.schema), help: "mstar.review/v1 envelope; finding, tally and verdict invariants are validated by the engine." },
58686
- json: { schema: exports_external.unknown(), help: `${payloadContracts.json.reason} ${payloadContracts.json.alternative}` }
58778
+ json: { schema: exports_external.unknown().describe(jsonKindContract), help: jsonKindContract }
58687
58779
  };
58780
+ var documentHelp = `Document for the addressed kind: review is the typed mstar.review/v1 envelope the engine validates; json is an opaque escape \u2014 ${jsonKindContract}`;
58688
58781
  function ok32(command3, data) {
58689
58782
  return { version: 1, command: command3, status: "ok", code: "persist.ok", exitCode: 0, data };
58690
58783
  }
@@ -58769,8 +58862,8 @@ function getPersistCommandDefinitions() {
58769
58862
  arguments: [{ key: "kind", required: true, variadic: false, choices: kinds }],
58770
58863
  options: [
58771
58864
  { key: "key", flags: "--key <key>", required: true },
58772
- { key: "input", flags: "--input <json>", required: false },
58773
- { key: "file", flags: "--file <path>", required: false },
58865
+ { key: "input", flags: "--input <json>", required: false, help: documentHelp },
58866
+ { key: "file", flags: "--file <path>", required: false, help: documentHelp },
58774
58867
  { key: "store", flags: "--store <module>", required: false },
58775
58868
  { key: "schema", flags: "--schema <id>", required: false }
58776
58869
  ]
@@ -58910,24 +59003,55 @@ function getPersistCommandDefinitions() {
58910
59003
  })
58911
59004
  ];
58912
59005
  }
59006
+ function fieldSchema(field, condition) {
59007
+ let schema;
59008
+ if (field.type === "object") {
59009
+ schema = exports_external.object(Object.fromEntries(Object.entries(field.properties ?? {}).map(([name, child]) => [name, fieldSchema(child, condition)])));
59010
+ } else if (field.type === "string[]") {
59011
+ let array2 = exports_external.array(exports_external.string());
59012
+ if (field.minItems !== undefined)
59013
+ array2 = array2.min(field.minItems);
59014
+ if (field.itemsNonblank)
59015
+ array2 = array2.refine((items) => items.every((item) => item.trim() !== ""));
59016
+ schema = array2;
59017
+ } else if (field.type === "string" || field.type === "string | null") {
59018
+ if (field.values !== undefined) {
59019
+ schema = exports_external.enum(field.values);
59020
+ } else {
59021
+ let text7 = exports_external.string();
59022
+ if (field.nonblankWhenPresent)
59023
+ text7 = text7.refine((value) => value.trim() !== "", `${field.description ?? "field"} must be nonblank when present`);
59024
+ schema = text7;
59025
+ }
59026
+ } else {
59027
+ schema = exports_external.unknown();
59028
+ }
59029
+ if (field.nullable)
59030
+ schema = schema.nullable();
59031
+ return field.required || condition !== undefined && field.requiredWhen?.includes(condition) === true ? schema : schema.optional();
59032
+ }
59033
+ function payloadSchema2(typeName2, condition) {
59034
+ const fields = ISSUE_PAYLOAD_SCHEMAS[typeName2];
59035
+ return exports_external.object(Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, fieldSchema(field, condition)])));
59036
+ }
58913
59037
  var progressPayloadSchema = exports_external.record(exports_external.string(), exports_external.unknown());
58914
- var entryPayloadSchema = exports_external.record(exports_external.string(), exports_external.unknown());
58915
- var entriesPayloadSchema = exports_external.array(entryPayloadSchema);
59038
+ var entriesPayloadSchema = exports_external.array(payloadSchema2("CaptureInput").omit({ projectId: true }));
58916
59039
  var evidencePayloadSchema = exports_external.record(exports_external.string(), exports_external.unknown());
59040
+ var EVIDENCE_PATH_DESCRIPTION = "Absolute path to an existing evidence file inside the plan area ({PLAN_DIR} or {SDD_DIR}/<plan-id>); " + "a relative path, a missing file or a path outside the plan area is refused with the offending field. Inspect the plan scope with mstar plan show.";
58917
59041
  var completionEvidenceSchema = exports_external.object({
58918
59042
  source_sha: exports_external.string().min(1).optional(),
58919
59043
  review_base: exports_external.string().min(1).optional(),
58920
59044
  review_head: exports_external.string().min(1).optional(),
58921
- evidence_paths: exports_external.array(exports_external.string()).optional(),
59045
+ evidence_paths: exports_external.array(exports_external.string()).optional().describe(`Additional evidence files: ${EVIDENCE_PATH_DESCRIPTION}`),
58922
59046
  qc: exports_external.object({
58923
59047
  decision: exports_external.enum(["Approve", "Approve with residuals"]),
58924
- reports: exports_external.array(exports_external.string().min(1)).min(1),
58925
- consolidated: exports_external.string().min(1)
59048
+ reports: exports_external.array(exports_external.string().min(1)).min(1).describe(`QC seat reports: ${EVIDENCE_PATH_DESCRIPTION}`),
59049
+ consolidated: exports_external.string().min(1).describe(`The consolidated QC decision report: ${EVIDENCE_PATH_DESCRIPTION}`)
58926
59050
  }).passthrough(),
58927
59051
  qa: exports_external.object({
58928
59052
  gate: exports_external.enum(["mandatory", "pm-acceptance"]),
58929
59053
  decision: exports_external.literal("pass"),
58930
- report: exports_external.string().min(1)
59054
+ report: exports_external.string().min(1).describe(`The QA or PM acceptance report: ${EVIDENCE_PATH_DESCRIPTION}`)
58931
59055
  }).passthrough()
58932
59056
  }).passthrough();
58933
59057
  var inputSchema = exports_external.object({
@@ -58963,6 +59087,12 @@ class PlanInputError extends Error {
58963
59087
  function ok4(id, data) {
58964
59088
  return { version: 1, command: id, status: "ok", code: `${id}.ok`, exitCode: 0, data };
58965
59089
  }
59090
+ var EVIDENCE_PATH_FIELDS = { "qc.consolidated": true, "qa.report": true };
59091
+ function isEvidencePathField(field) {
59092
+ if (typeof field !== "string")
59093
+ return false;
59094
+ return EVIDENCE_PATH_FIELDS[field] === true || field.startsWith("qc.reports[") || field.startsWith("evidence_paths[") || field.startsWith("progress.evidence_paths[");
59095
+ }
58966
59096
  function failure2(id, error62) {
58967
59097
  if (error62 instanceof PlanInputError)
58968
59098
  return refusalEnvelope({ command: id, status: "usage", code: "command.invalid-input", exitCode: 2, message: error62.message });
@@ -58976,7 +59106,7 @@ function failure2(id, error62) {
58976
59106
  exitCode: 1,
58977
59107
  message,
58978
59108
  ...details === undefined ? {} : { details },
58979
- recovery: id === "plan.complete" && code2 === "coordination.scope-mismatch" ? details !== undefined && "expected" in details && "actual" in details ? "The recorded working branch does not match the workflow's registered delivery source. Correct the registered anchor with mstar workflow delivery-anchors, or re-record the row scope with mstar plan prepare." : "The plan records no worktree/branch scope. Record the plan worktree and feature branch with mstar plan prepare --workflow <workflow-id> --plan <plan-id> --worktree-path <absolute-path> --working-branch <branch>, then retry." : id === "plan.bind" ? "The registered workflow and current coordinator identity must match; a first bind needs the execution route and an existing binding is resumed through its active session reference. Run mstar plan bind --execution true --coordinator true --workflow <workflow-id>, or mstar plan bind --resume-ref <session-ref>." : id === "plan.show" ? "Select a registered workflow and plan id from the execution authority. Run mstar plan show --workflow <workflow-id> --plan <plan-id>." : id === "plan.prepare" ? "Correct the absolute feature-worktree path, feature branch, and Prepare gate values. Run mstar plan prepare --workflow <workflow-id> --plan <plan-id> --worktree-path <absolute-path> --working-branch <branch>." : id === "plan.progress" ? "The progress value must be the JSON progress object (status, summary, evidence_paths) and the plan revision must be current. Run mstar plan progress --workflow <workflow-id> --plan <plan-id> --progress <json-progress-object>." : id === "plan.issue-add" ? "Valid issue entries and the current revision for the addressed plan are required. Run mstar plan issue-add --workflow <workflow-id> --plan <plan-id> --entries <issues-file>." : id === "plan.issue-close" ? "The addressed plan issue needs its current revision and a supported disposition. Run mstar plan issue-close --workflow <workflow-id> --plan <plan-id> --issue <issue-id> --disposition <disposition>." : "Delivery-route evidence and QC/QA proof for this plan are required. Run mstar plan complete --workflow <workflow-id> --plan <plan-id> --file <absolute-evidence.json>."
59109
+ recovery: id === "plan.complete" && code2 === "coordination.invalid-transition" && details?.code === "PHASE6_DELIVERY_KIND_UNREGISTERED" ? "The workflow declares no delivery kind, and the kind is fixed at registration. Close it honestly with mstar workflow lifecycle --workflow <workflow-id> --status failed --reason <text>, then register a replacement workflow with the correct declared delivery kind." : id === "plan.complete" && code2 === "coordination.invalid-transition" && details?.code === "PHASE6_DELIVERY_EVIDENCE_INCOMPLETE" ? "Record the missing delivery evidence \u2014 for a report-only route the fulfilment of its registered completion policy \u2014 with mstar workflow evidence --workflow <workflow-id> --file <absolute-json>, then retry plan complete. Read the workflow's own state with mstar status validate." : id === "plan.complete" && code2 === "coordination.invalid-transition" && typeof details?.required === "string" ? "The submitted QA evidence does not match the plan's configured QA gate. Submit the matching QA or PM acceptance report, or re-record the configured gate with mstar plan prepare --qa-gate <gate>, then retry." : (id === "plan.complete" || id === "plan.progress") && isEvidencePathField(details?.field) ? "Correct the evidence values named by the refusal's field details: each must be an absolute path to an existing file inside the plan area. Read the plan's area with mstar plan show, then retry." : id === "plan.complete" && code2 === "coordination.scope-mismatch" ? details !== undefined && "expected" in details && "actual" in details ? "The recorded working branch does not match the workflow's registered delivery source. Correct the registered anchor with mstar workflow delivery-anchors, or re-record the row scope with mstar plan prepare." : "The plan records no worktree/branch scope. Record the plan worktree and feature branch with mstar plan prepare --workflow <workflow-id> --plan <plan-id> --worktree-path <absolute-path> --working-branch <branch>, then retry." : id === "plan.bind" ? "The registered workflow and current coordinator identity must match; a first bind needs the execution route and an existing binding is resumed through its active session reference. Run mstar plan bind --execution true --coordinator true --workflow <workflow-id>, or mstar plan bind --resume-ref <session-ref>." : id === "plan.show" ? "Select a registered workflow and plan id from the execution authority. Run mstar plan show --workflow <workflow-id> --plan <plan-id>." : id === "plan.prepare" ? "Correct the absolute feature-worktree path, feature branch, and Prepare gate values. Run mstar plan prepare --workflow <workflow-id> --plan <plan-id> --worktree-path <absolute-path> --working-branch <branch>." : id === "plan.progress" ? "The progress value must be the JSON progress object (status, summary, evidence_paths) and the plan revision must be current. Run mstar plan progress --workflow <workflow-id> --plan <plan-id> --progress <json-progress-object>." : id === "plan.issue-add" ? "Valid issue entries and the current revision for the addressed plan are required. Run mstar plan issue-add --workflow <workflow-id> --plan <plan-id> --entries <issues-file>." : id === "plan.issue-close" ? "The addressed plan issue needs its current revision and a supported disposition. Run mstar plan issue-close --workflow <workflow-id> --plan <plan-id> --issue <issue-id> --disposition <disposition>." : "Delivery-route evidence and QC/QA proof for this plan are required. Run mstar plan complete --workflow <workflow-id> --plan <plan-id> --file <absolute-evidence.json>."
58980
59110
  });
58981
59111
  }
58982
59112
  function command4(definition2) {
@@ -59210,6 +59340,20 @@ function optionHelpFor(verb) {
59210
59340
  expect: PLAN_EXPECT_HELP,
59211
59341
  sessionRef: `optional session transport: ${SESSION_REF_SUPPLIES}`
59212
59342
  };
59343
+ if (verb === "complete")
59344
+ return {
59345
+ evidence: `Completion evidence JSON object (--file <absolute-json> or inline). ${EVIDENCE_PATH_DESCRIPTION}`,
59346
+ file: `Completion evidence JSON file (absolute path); its qc.reports[], qc.consolidated, qa.report and evidence_paths[] values are evidence paths. ${EVIDENCE_PATH_DESCRIPTION}`,
59347
+ expect: PLAN_EXPECT_HELP,
59348
+ sessionRef: `optional session transport: ${SESSION_REF_SUPPLIES}`
59349
+ };
59350
+ if (verb === "issue-add")
59351
+ return {
59352
+ entries: "JSON array of plan-scoped capture entries, one object per finding; read the per-entry fields with mstar schema CaptureInput (projectId is derived from the addressed plan)",
59353
+ file: "Absolute path to a JSON file holding that entries array",
59354
+ expect: PLAN_EXPECT_HELP,
59355
+ sessionRef: `optional session transport: ${SESSION_REF_SUPPLIES}`
59356
+ };
59213
59357
  return { expect: PLAN_EXPECT_HELP, sessionRef: `optional session transport: ${SESSION_REF_SUPPLIES}` };
59214
59358
  }
59215
59359
  function getPlanCommandDefinitions() {
@@ -59576,15 +59720,17 @@ function parseWorkflowJson(text7, label, code2) {
59576
59720
  throw Object.assign(new Error(`${label} is not valid JSON (${diagnostic.cause}${diagnostic.location === undefined ? "" : ` at ${diagnostic.location}`})`), { code: code2, details: { parser: diagnostic } });
59577
59721
  }
59578
59722
  }
59723
+ var WORKFLOW_PLAN_PARALLELISM_VALUES = ["serial", "parallel"];
59579
59724
  var workflowExecutionPolicySchema = exports_external.object({
59580
- plan_parallelism: exports_external.unknown().optional(),
59581
- worktree_mode: exports_external.unknown().optional(),
59582
- push_policy: exports_external.unknown().optional()
59725
+ plan_parallelism: exports_external.enum(WORKFLOW_PLAN_PARALLELISM_VALUES).optional().describe("Concurrency contract: serial or parallel. Any other value is refused."),
59726
+ worktree_mode: exports_external.unknown().optional().describe("Accepted-but-opaque worktree mode value; copied into the policy block unchanged."),
59727
+ push_policy: exports_external.unknown().optional().describe("Accepted-but-opaque push policy value; copied into the policy block unchanged.")
59583
59728
  }).passthrough();
59584
59729
  function parseWorkflowExecutionPolicy(text7) {
59585
59730
  const parsed = workflowExecutionPolicySchema.safeParse(parseWorkflowJson(text7, "execution policy file", "workflow.execution-policy.file-malformed"));
59586
59731
  if (!parsed.success) {
59587
- throw new WorkflowInputError("an execution-policy operation needs a policy object");
59732
+ const problems = parsed.error.issues.map((issue2) => `${issue2.path.length === 0 ? "policy" : issue2.path.join(".")}: ${issue2.message}`).join("; ");
59733
+ throw new WorkflowInputError(`an execution-policy operation needs a policy object: ${problems}`);
59588
59734
  }
59589
59735
  return parsed.data;
59590
59736
  }
@@ -59752,14 +59898,13 @@ function makeDefinition(id, description, effect, keys, execute2, contextOptions
59752
59898
  ...keys.flatMap((key) => {
59753
59899
  if (key === "row")
59754
59900
  return [[key, { schema: exports_external.array(exports_external.unknown()) }]];
59755
- if (key === "input" || key === "policy")
59756
- return [[key, { schema: exports_external.record(exports_external.string(), exports_external.unknown()) }]];
59757
59901
  const override = payloadOverride[key];
59758
59902
  return override === undefined ? [] : [[key, { schema: override }]];
59759
59903
  }),
59760
59904
  ...Object.entries(payloadOverride).filter(([key]) => !keys.includes(key)).map(([key, schema2]) => [key, {
59761
59905
  schema: schema2,
59762
- ...key === "delivery" ? { help: "UTF-8 JSON object loaded from --file (pathname, never inline JSON); supply at least one complete member. development allows any subset of compound {outcome: created|updated|skipped, reason?: non-empty; required for skipped}, pr {repo,head,target: non-empty}, merge {provider,evidence: non-empty}; verification/report-only allows completion {policy,evidence: non-empty}. Omit untouched members; supplied member blocks are complete, not sub-field patches. Members outside registered delivery_kind are refused. A report-only completion.policy must match the registered completion_policy for lifecycle completion; a mismatched report may be recorded and corrected by another evidence update before close. A matching non-empty completion on a Done row is frozen; edit its referenced document in place, or use a separate workflow for a different completed intent. Done alone does not freeze other evidence. PR identity is immutable once recorded: keep its registered repo/head/target for that delivery, or use a separate workflow for a different PR. ACTIVE workflows use the DB-backed coordinator evidence operation; this --file route is pre-activation." } : {}
59906
+ ...key === "delivery" ? { help: "UTF-8 JSON object loaded from --file (pathname, never inline JSON); supply at least one complete member. development allows any subset of compound {outcome: created|updated|skipped, reason?: non-empty; required for skipped}, pr {repo,head,target: non-empty}, merge {provider,evidence: non-empty}; verification/report-only allows completion {policy,evidence: non-empty}. Omit untouched members; supplied member blocks are complete, not sub-field patches. Members outside registered delivery_kind are refused. A report-only completion.policy must match the registered completion_policy for lifecycle completion; a mismatched report may be recorded and corrected by another evidence update before close. A matching non-empty completion on a Done row is frozen; edit its referenced document in place, or use a separate workflow for a different completed intent. Done alone does not freeze other evidence. PR identity is immutable once recorded: keep its registered repo/head/target for that delivery, or use a separate workflow for a different PR. ACTIVE workflows use the DB-backed coordinator evidence operation; this --file route is pre-activation." } : {},
59907
+ ...key === "policy" ? { help: "Execution-policy object loaded from --file (pathname, never inline JSON): plan_parallelism, worktree_mode and push_policy, every member optional. The object REPLACES the recorded policy block \u2014 an omitted key is removed, never retained. plan_parallelism is the closed serial | parallel set; an unknown key is refused. Read the declared shape with mstar schema --command workflow.execution-policy." } : {}
59763
59908
  }])
59764
59909
  ]),
59765
59910
  output: commandEnvelopeSchema,
@@ -60009,8 +60154,11 @@ function getWorkflowCommandDefinitions() {
60009
60154
  }
60010
60155
  }, [{ key: "sessionId", context: "sessionId" }], {
60011
60156
  expect: `CAS expectation: ${TOKEN_SUPPLIES.workflow}`,
60012
- sessionRef: `session transport: ${SESSION_REF_SUPPLIES}`
60013
- }));
60157
+ sessionRef: `session transport: ${SESSION_REF_SUPPLIES}`,
60158
+ ...transition.name === "execution-policy" ? {
60159
+ file: "Absolute path to a UTF-8 JSON execution-policy object; read its fields with mstar schema --command workflow.execution-policy"
60160
+ } : {}
60161
+ }, transition.name === "execution-policy" ? { policy: workflowExecutionPolicySchema } : {}));
60014
60162
  }
60015
60163
  defs.push(makeDefinition("iteration.register", "Register a create-only iteration workflow with its branch anchors and Todo rows.", "write", ["workflow", "compassRef", "branchBase", "branchIntegration", "branchTargetIteration", "row", "project", "startedAt", "harness", "expect", "operation"], async (input2, context) => {
60016
60164
  try {
@@ -60362,13 +60510,29 @@ function readJson2(value, flag) {
60362
60510
  throw new SddScriptError(`${flag} must contain a JSON object`, 2);
60363
60511
  return parsed;
60364
60512
  }
60365
- function executionContext(input2, invocation, verb) {
60366
- const harness = absolute2(input2.harness, "--harness");
60367
- const root = resolveProcessHarnessDir(invocation.cwd, harness);
60368
- if (root === null)
60369
- throw new SddScriptError(`${verb}: no target harness was resolved; pass --harness <absolute-path>`, 2);
60370
- if (invocation.controlRoot !== null && path6.resolve(root) === path6.resolve(invocation.controlRoot)) {
60371
- throw new SddScriptError(`${verb}: the resolved target ${path6.resolve(root)} is this invocation's control root, and a control root is not an admitted execution target. ` + "Pass --harness <absolute-path> naming a harness other than this control root, or invoke from a checkout where no control root is discovered. " + "To back up or move a control root's own store, use mstar store backup.", 2);
60513
+ function targetRefusal(id, supplied) {
60514
+ const relative4 = supplied !== "";
60515
+ return refusalEnvelope({
60516
+ command: id,
60517
+ status: "usage",
60518
+ code: "command.invalid-input",
60519
+ exitCode: 2,
60520
+ message: relative4 ? `${id}: the operation target must be an absolute path; a relative "harness" would resolve against the invocation directory instead of naming the store this call reads or restores` : `${id} needs the operation's target: it names the store this call reads or restores, and this action never discovers one from the invocation directory`,
60521
+ helpRoute: `mstar schema --command ${id}`,
60522
+ recovery: "mstar store execution export --harness=<abs>, and the same --harness flag names the target on restore and restore-preview. A pinned MCP connection still takes the target from that field, never from its control root.",
60523
+ diagnostics: [{
60524
+ path: "harness",
60525
+ code: relative4 ? "invalid_type" : "required",
60526
+ message: relative4 ? "harness must be an absolute path" : "harness is required: the operation target is never discovered from the invocation directory",
60527
+ expected: "absolute path",
60528
+ received: relative4 ? "relative path" : "undefined"
60529
+ }]
60530
+ });
60531
+ }
60532
+ function executionContext(target, invocation, verb) {
60533
+ const root = path6.resolve(target);
60534
+ if (invocation.controlRoot !== null && root === path6.resolve(invocation.controlRoot)) {
60535
+ throw new SddScriptError(`${verb}: the resolved target ${root} is this invocation's control root, and a control root is not an admitted execution target. ` + "Pass --harness <absolute-path> naming a harness other than this control root, or invoke from a checkout where no control root is discovered. " + "To back up or move a control root's own store, use mstar store backup.", 2);
60372
60536
  }
60373
60537
  return { harnessDir: root };
60374
60538
  }
@@ -60376,9 +60540,12 @@ function document3(value, flag) {
60376
60540
  return readJson2(value, flag);
60377
60541
  }
60378
60542
  async function execute3(id, input2, invocation) {
60543
+ const verb = id.slice("store.execution.".length);
60544
+ const target = typeof input2.harness === "string" ? input2.harness.trim() : "";
60545
+ if (target === "" || !path6.isAbsolute(target))
60546
+ return targetRefusal(id, target);
60379
60547
  try {
60380
- const verb = id.slice("store.execution.".length);
60381
- const context = executionContext(input2, invocation, `store execution ${verb}`);
60548
+ const context = executionContext(target, invocation, `store execution ${verb}`);
60382
60549
  if (verb === "restore-preview") {
60383
60550
  const backupPath = absolute2(required22(input2.backup, "--backup"), "--backup");
60384
60551
  const preview = await previewExecutionRestore(context, backupPath);
@@ -60415,7 +60582,7 @@ async function execute3(id, input2, invocation) {
60415
60582
  const message = error62 instanceof Error ? error62.message : String(error62);
60416
60583
  const code2 = error62 !== null && typeof error62 === "object" && "code" in error62 && typeof error62.code === "string" ? error62.code : `${id}.internal-error`;
60417
60584
  const details = error62 !== null && typeof error62 === "object" && "details" in error62 && error62.details !== null && typeof error62.details === "object" && !Array.isArray(error62.details) ? error62.details : undefined;
60418
- return error62 instanceof SddScriptError ? refusalEnvelope({ command: id, status: "usage", code: "usage", exitCode: 2, message, ...details === undefined ? {} : { details } }) : refusalEnvelope({ command: id, status: "refused", code: code2, exitCode: 1, message, ...details === undefined ? {} : { details }, recovery: id === "store.execution.restore-preview" ? "Select a readable execution backup and writable preview destination. Run mstar store execution restore-preview --backup <backup> --out <preview>." : id === "store.execution.restore" ? "The backup preview or operator authorization does not match the diagnostic. Regenerate a current preview with mstar store execution restore-preview --backup <backup> --out <preview>, then retry restore with the same operator and authorization." : "Choose a writable export destination or omit --out for stdout. Run mstar store execution export." });
60585
+ return error62 instanceof SddScriptError ? refusalEnvelope({ command: id, status: "usage", code: "usage", exitCode: 2, message, ...details === undefined ? {} : { details } }) : refusalEnvelope({ command: id, status: "refused", code: code2, exitCode: 1, message, ...details === undefined ? {} : { details }, recovery: id === "store.execution.restore-preview" ? "Select a readable execution backup and writable preview destination. Run mstar store execution restore-preview --harness <path> --backup <backup> --out <preview>." : id === "store.execution.restore" ? "The backup preview or operator authorization does not match the diagnostic. Regenerate a current preview with mstar store execution restore-preview --harness <path> --backup <backup> --out <preview>, then retry restore with the same operator and authorization." : "Choose a writable export destination or omit --out for stdout. Run mstar store execution export --harness <path>." });
60419
60586
  }
60420
60587
  }
60421
60588
  function cliDefinition2(id) {
@@ -60435,11 +60602,12 @@ function cliDefinition2(id) {
60435
60602
  };
60436
60603
  const optionKeys2 = optionsByVerb[verb];
60437
60604
  const shape = Object.fromEntries(optionKeys2.map((key) => [key, true]));
60438
- const options = optionKeys2.map((key) => ({ key, flags: flags[key], required: false }));
60605
+ const options = optionKeys2.map((key) => ({ key, flags: flags[key], required: key === "harness" }));
60439
60606
  return {
60440
60607
  id,
60441
60608
  cli: { path: ["store", "execution", verb], aliases: [], arguments: [], options },
60442
60609
  input: inputSchema3.pick(shape),
60610
+ rootInputs: [],
60443
60611
  output: commandEnvelopeSchema,
60444
60612
  effects: writeVerbs[verb] === true ? ["read", "write"] : ["read"],
60445
60613
  description: verb === "export" ? "Export the current execution state as a canonical reporting artifact." : verb === "restore-preview" ? "Store execution restore-preview from a standalone store backup. Receipt retention is an expected source of backup-only `execution` " + "operation rows: a terminal close or adoption prunes that workflow's operation receipts (each listed in a preview of an older point with " + "`liveRevision: null`), the init-time purge beside the in-place epoch bump clears the superseded epoch's, and a restore preserves " + "prior-epoch receipt rows as history under its frozen bytes-plus-one-epoch contract, outside the current epoch's replay scope, so " + "restoring any of them is harmless and re-arms nothing. `result_json` payloads are write-time versioned: graph rows written " + "before the slimming change keep their full form, later rows carry the slim envelope, so inventory digests compare write-time " + "bytes per row and mixed forms never produce same-key content drift." : `Store execution ${verb} from a standalone store backup.`,
@@ -60602,37 +60770,6 @@ async function execute4(id, input2, invocation) {
60602
60770
  }
60603
60771
  var payloadType = Object.fromEntries(actions.flatMap(([verb, action]) => action.payload === null ? [] : [[verb, action.payload]]));
60604
60772
  var expectedRevisionVerbs = Object.fromEntries(actions.filter(([, action]) => action.cas).map(([verb]) => [verb, true]));
60605
- function fieldSchema(field, condition) {
60606
- let schema2;
60607
- if (field.type === "object") {
60608
- schema2 = exports_external.object(Object.fromEntries(Object.entries(field.properties ?? {}).map(([name, child]) => [name, fieldSchema(child, condition)])));
60609
- } else if (field.type === "string[]") {
60610
- let array2 = exports_external.array(exports_external.string());
60611
- if (field.minItems !== undefined)
60612
- array2 = array2.min(field.minItems);
60613
- if (field.itemsNonblank)
60614
- array2 = array2.refine((items) => items.every((item) => item.trim() !== ""));
60615
- schema2 = array2;
60616
- } else if (field.type === "string" || field.type === "string | null") {
60617
- if (field.values !== undefined) {
60618
- schema2 = exports_external.enum(field.values);
60619
- } else {
60620
- let text7 = exports_external.string();
60621
- if (field.nonblankWhenPresent)
60622
- text7 = text7.refine((value) => value.trim() !== "", `${field.description ?? "field"} must be nonblank when present`);
60623
- schema2 = text7;
60624
- }
60625
- } else {
60626
- schema2 = exports_external.unknown();
60627
- }
60628
- if (field.nullable)
60629
- schema2 = schema2.nullable();
60630
- return field.required || condition !== undefined && field.requiredWhen?.includes(condition) === true ? schema2 : schema2.optional();
60631
- }
60632
- function payloadSchema2(typeName2, condition) {
60633
- const fields = ISSUE_PAYLOAD_SCHEMAS[typeName2];
60634
- return exports_external.object(Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, fieldSchema(field, condition)])));
60635
- }
60636
60773
  function closureInputSchema(input2, defaultDisposition) {
60637
60774
  const fields = ISSUE_PAYLOAD_SCHEMAS.ClosureEvidence;
60638
60775
  const dispositions = [...new Set(Object.values(fields).flatMap((field) => field.requiredWhen ?? []))];
@@ -61544,7 +61681,12 @@ async function execute7(id, input2, invocation) {
61544
61681
  try {
61545
61682
  const verb = id.slice("sdd.".length);
61546
61683
  if (verb === "workspace") {
61547
- return ok10(id, { sddDir: sddWorkspace(required4(input2.planId, "PLAN_ID"), input2.controlRoot ? { controlRoot: input2.controlRoot } : {}) });
61684
+ const serverHarness = input2.controlRoot === undefined ? invocation.harnessPin : undefined;
61685
+ return ok10(id, { sddDir: sddWorkspace(required4(input2.planId, "PLAN_ID"), {
61686
+ cwd: invocation.cwd,
61687
+ ...input2.controlRoot === undefined ? {} : { controlRoot: input2.controlRoot },
61688
+ ...serverHarness === undefined ? {} : { harnessDir: serverHarness }
61689
+ }) });
61548
61690
  }
61549
61691
  if (verb === "task-brief") {
61550
61692
  const planFile = required4(input2.planFile, "PLAN_FILE");
@@ -61623,6 +61765,7 @@ function cliDefinition4(verb) {
61623
61765
  id,
61624
61766
  cli: { path: shape.path, aliases: [], arguments: shape.arguments, options: shape.options },
61625
61767
  input: inputSchemas[verb],
61768
+ ...verb === "workspace" ? { rootInputs: ["controlRoot"] } : {},
61626
61769
  ...payloads[verb] === undefined ? {} : { payloads: payloads[verb] },
61627
61770
  output: commandEnvelopeSchema,
61628
61771
  effects: shape.effects,
@@ -61726,22 +61869,25 @@ function findUpPackageRoot(startDir, predicate) {
61726
61869
  function declaresWorkspaces(manifest) {
61727
61870
  return Array.isArray(manifest.workspaces) || typeof manifest.workspaces === "string" || manifest.workspaces !== undefined && manifest.workspaces !== null && typeof manifest.workspaces === "object";
61728
61871
  }
61729
- function resolveCliProjectRoot() {
61730
- const override = process.env.MSTAR_CLI_PROJECT_ROOT;
61731
- if (override && override.trim())
61732
- return path12.resolve(override);
61733
- const monorepoRoot = findUpPackageRoot(process.cwd(), declaresWorkspaces);
61872
+ function projectRootFrom(startDir) {
61873
+ const monorepoRoot = findUpPackageRoot(startDir, declaresWorkspaces);
61734
61874
  if (monorepoRoot)
61735
61875
  return monorepoRoot;
61736
- const packageRoot = findUpPackageRoot(process.cwd(), () => true);
61876
+ const packageRoot = findUpPackageRoot(startDir, () => true);
61737
61877
  if (packageRoot)
61738
61878
  return packageRoot;
61739
- return process.cwd();
61879
+ return path12.resolve(startDir);
61880
+ }
61881
+ function resolveCliProjectRoot() {
61882
+ const override = process.env.MSTAR_CLI_PROJECT_ROOT;
61883
+ if (override && override.trim())
61884
+ return path12.resolve(override);
61885
+ return projectRootFrom(process.cwd());
61740
61886
  }
61741
- function resolveCliPath(userPath) {
61887
+ function resolveCliPath(userPath, base) {
61742
61888
  if (path12.isAbsolute(userPath))
61743
61889
  return userPath;
61744
- const root = resolveCliProjectRoot();
61890
+ const root = base === undefined ? resolveCliProjectRoot() : projectRootFrom(base);
61745
61891
  return root.endsWith(path12.sep) ? root + userPath : root + path12.sep + userPath;
61746
61892
  }
61747
61893
  function splitVersion(v) {
@@ -63268,8 +63414,54 @@ function diagnoseMcpTarget(target, configRoot, runtime = actualRuntime(), option
63268
63414
  notes: errors3.length === 0 ? [`MCP config aligned for ${target}.`] : []
63269
63415
  };
63270
63416
  }
63271
- var trackPrefix = (path232) => {
63272
- const index2 = path232.filter((part) => typeof part === "number").at(-1);
63417
+ var LAUNCH_DIRECTORY_RECOVERY = "Declare the connection's workspace with `mstar mcp --workspace <absolute path>`; or pin the harness root with `mstar mcp --harness <absolute path>` (or a non-blank MSTAR_HARNESS_DIR in the server environment), which anchors the workspace at the root's parent.";
63418
+ function launchDirectoryRefusal(command6, context2, target) {
63419
+ if (context2.launchDirectory !== true)
63420
+ return;
63421
+ const subjectCauses = target.fields === undefined ? [cause(target.subject, undefined)] : undefined;
63422
+ const offending = target.fields === undefined ? [] : unnamed(target.fields);
63423
+ if (subjectCauses === undefined && offending.length === 0)
63424
+ return;
63425
+ const causes = subjectCauses ?? offending.map((field) => cause(field.subject, field.value));
63426
+ return refusalEnvelope({
63427
+ command: command6,
63428
+ status: "usage",
63429
+ code: "command.invalid-input",
63430
+ exitCode: 2,
63431
+ message: `${command6}: ${causes.join("; ")}, and this connection declared no workspace: that directory is the MCP server's ` + "LAUNCH directory (the host's own), which says nothing about the caller's workspace",
63432
+ ...subjectCauses === undefined ? { diagnostics: offending.map(diagnostic) } : {},
63433
+ recovery: LAUNCH_DIRECTORY_RECOVERY
63434
+ });
63435
+ }
63436
+ function launchDirectoryDiagnostics(context2, target) {
63437
+ if (context2.launchDirectory !== true)
63438
+ return;
63439
+ const offending = unnamed(target.fields);
63440
+ return offending.length === 0 ? undefined : { diagnostics: offending.map(diagnostic), recovery: LAUNCH_DIRECTORY_RECOVERY };
63441
+ }
63442
+ function cause(subject, supplied) {
63443
+ return supplied === undefined ? `${subject} would come from this invocation's working directory` : `${subject} would resolve against this invocation's working directory`;
63444
+ }
63445
+ function diagnostic(field) {
63446
+ return field.value === undefined ? {
63447
+ path: field.field,
63448
+ code: "required",
63449
+ message: `${field.field} is required, as an absolute path: the LAUNCH directory is never used as ${field.subject}`,
63450
+ expected: "absolute path",
63451
+ received: "undefined"
63452
+ } : {
63453
+ path: field.field,
63454
+ code: "invalid_type",
63455
+ message: `${field.field} must be an absolute path: a relative one would resolve against the LAUNCH directory, so it cannot name ${field.subject}`,
63456
+ expected: "absolute path",
63457
+ received: "relative path"
63458
+ };
63459
+ }
63460
+ function unnamed(fields) {
63461
+ return fields.filter((field) => field.value === undefined ? field.optional !== true : !path222.isAbsolute(field.value));
63462
+ }
63463
+ var trackPrefix = (path242) => {
63464
+ const index2 = path242.filter((part) => typeof part === "number").at(-1);
63273
63465
  return typeof index2 === "number" ? `tracks[${index2}]` : "tracks";
63274
63466
  };
63275
63467
  var tracksSchema = exports_external.array(exports_external.object({
@@ -63349,40 +63541,82 @@ function activeGraphLifecycleBranches(graph) {
63349
63541
  }
63350
63542
  return [...branches.values()];
63351
63543
  }
63352
- function absolute4(_cwd, input2) {
63353
- return resolveCliPath(input2);
63544
+ function absolute4(cwd, input2) {
63545
+ return resolveCliPath(input2, cwd);
63546
+ }
63547
+ function canonicalPath2(target) {
63548
+ try {
63549
+ return realpathSync22(target);
63550
+ } catch {
63551
+ return path23.resolve(target);
63552
+ }
63553
+ }
63554
+ var pathInputs = {
63555
+ "dispatch.validate": [{ field: "assignmentFile", subject: "the assignment file" }],
63556
+ "worktree.check": [],
63557
+ "worktree.qc-alignment": [{ field: "files", subject: "the assignment file", each: true }],
63558
+ "review.seats": [{ field: "assignmentFile", subject: "the assignment file" }],
63559
+ lint: [{ field: "target", subject: "the lint target" }],
63560
+ "design-md.validate": [{ field: "dir", subject: "the design directory" }],
63561
+ "compound.validate": [],
63562
+ "skill.lint": [{ field: "skillDir", subject: "the skill directory" }],
63563
+ "roles.validate": [
63564
+ { field: "rolesDir", subject: "the role corpus directory" },
63565
+ { field: "skillsDir", subject: "the skills root", optional: true }
63566
+ ],
63567
+ "qc.validate-report": [{ field: "reportFile", subject: "the report file" }]
63568
+ };
63569
+ function launchDirectoryPaths(command6, input2, context2) {
63570
+ const fields = pathInputs[command6].flatMap((entry) => {
63571
+ const value = input2[entry.field];
63572
+ if (entry.each === true) {
63573
+ const paths2 = Array.isArray(value) ? value.filter((file2) => typeof file2 === "string") : [];
63574
+ return paths2.map((file2, index2) => ({
63575
+ field: `${entry.field}[${index2}]`,
63576
+ subject: paths2.length === 1 ? entry.subject : `${entry.subject} #${index2 + 1}`,
63577
+ value: file2
63578
+ }));
63579
+ }
63580
+ return [{
63581
+ field: entry.field,
63582
+ subject: entry.subject,
63583
+ value: typeof value === "string" ? value : undefined,
63584
+ ...entry.optional === true ? { optional: true } : {}
63585
+ }];
63586
+ });
63587
+ return fields.length === 0 ? undefined : launchDirectoryRefusal(command6, context2, { fields });
63354
63588
  }
63355
63589
  var codeExtensions = Object.fromEntries([".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".py", ".go", ".rs", ".sh", ".bash", ".zsh", ".rb", ".java", ".kt", ".swift"].map((ext) => [ext, true]));
63356
63590
  var provenanceExtensions = { ".md": true, ".ts": true };
63357
63591
  var skipDirs = { node_modules: true, ".git": true, dist: true, coverage: true, ".turbo": true };
63358
63592
  function lintType(file2) {
63359
- const base = path222.basename(file2);
63593
+ const base = path23.basename(file2);
63360
63594
  if (base === "STRATEGY.md")
63361
63595
  return "strategy";
63362
63596
  if (base === "SKILL.md")
63363
63597
  return "skill";
63364
63598
  if (/^task-\d+-report\.md$/i.test(base))
63365
63599
  return "report";
63366
- const dir = path222.dirname(file2);
63367
- if (dir.includes(`${path222.sep}plans${path222.sep}`) || dir.endsWith(`${path222.sep}plans`) || /^\d{8}-[a-z0-9.-]+\.md$/i.test(base))
63600
+ const dir = path23.dirname(file2);
63601
+ if (dir.includes(`${path23.sep}plans${path23.sep}`) || dir.endsWith(`${path23.sep}plans`) || /^\d{8}-[a-z0-9.-]+\.md$/i.test(base))
63368
63602
  return "plan";
63369
- return codeExtensions[path222.extname(base).toLowerCase()] ? "code" : null;
63603
+ return codeExtensions[path23.extname(base).toLowerCase()] ? "code" : null;
63370
63604
  }
63371
63605
  function collectTargets(dir, accept = (file2) => lintType(file2) !== null) {
63372
63606
  const targets = [];
63373
63607
  const visit2 = (current) => {
63374
63608
  for (const entry of readdirSync22(current, { withFileTypes: true })) {
63375
- if (entry.name.includes(path222.sep))
63609
+ if (entry.name.includes(path23.sep))
63376
63610
  continue;
63377
63611
  const child = current + entry.name;
63378
63612
  if (entry.isDirectory()) {
63379
63613
  if (!skipDirs[entry.name])
63380
- visit2(child + path222.sep);
63614
+ visit2(child + path23.sep);
63381
63615
  } else if (entry.isFile() && accept(child))
63382
63616
  targets.push(child);
63383
63617
  }
63384
63618
  };
63385
- visit2(dir.endsWith(path222.sep) ? dir : `${dir}${path222.sep}`);
63619
+ visit2(dir.endsWith(path23.sep) ? dir : `${dir}${path23.sep}`);
63386
63620
  return targets;
63387
63621
  }
63388
63622
  function parseHeaderField(text7, label) {
@@ -63430,12 +63664,15 @@ function lintOne(file2, type, prVariant = false) {
63430
63664
  violations.push({ ok: false, severity: "medium", code: `lint.provenance.${citation.kind}`, message: `provenance ${citation.kind} citation at line ${citation.line}: "${citation.match}" \u2014 tracked content must not disclose local plan/iteration ids or dated harness deep paths`, fix: `rewrite "${citation.match}" as a placeholder form (e.g. task-N-report, <plan-id>) or a synthetic example slug (any -example- segment)` });
63431
63665
  break;
63432
63666
  default:
63433
- throw new SddScriptError(`usage: lint <target> \u2014 unsupported file type "${path222.basename(file2)}" (lintable: plan files, SKILL.md, STRATEGY.md, task-N-report.md, code files)`, 2);
63667
+ throw new SddScriptError(`usage: lint <target> \u2014 unsupported file type "${path23.basename(file2)}" (lintable: plan files, SKILL.md, STRATEGY.md, task-N-report.md, code files)`, 2);
63434
63668
  }
63435
63669
  return { violations, markers };
63436
63670
  }
63437
63671
  async function execute8(id, input2, context2) {
63438
63672
  try {
63673
+ const unnamedPaths = launchDirectoryPaths(id, input2, context2);
63674
+ if (unnamedPaths !== undefined)
63675
+ return unnamedPaths;
63439
63676
  switch (id) {
63440
63677
  case "dispatch.validate": {
63441
63678
  const file2 = absolute4(context2.cwd, required5(input2.assignmentFile, "usage: dispatch validate <assignment-file> [--branch <branch>]"));
@@ -63525,7 +63762,7 @@ async function execute8(id, input2, context2) {
63525
63762
  const selectedIntegration = input2.integration ?? input2.control;
63526
63763
  const gate2 = l1PreDispatchCheck({
63527
63764
  workflowType: registered.state.type,
63528
- integrationWorktreePath: selectedIntegration !== undefined ? path222.resolve(selectedIntegration) : typeof registered.state.integration_worktree_path === "string" ? registered.state.integration_worktree_path : "",
63765
+ integrationWorktreePath: selectedIntegration !== undefined ? path23.resolve(selectedIntegration) : typeof registered.state.integration_worktree_path === "string" ? registered.state.integration_worktree_path : "",
63529
63766
  integrationBranch: String(branch.integration ?? ""),
63530
63767
  mainWorktree: { root: primary, branch: mainBranch.stdout.trim() },
63531
63768
  expectedMainBranch: input2.mainBranch ?? String(branch.base ?? ""),
@@ -63560,7 +63797,8 @@ async function execute8(id, input2, context2) {
63560
63797
  }]
63561
63798
  });
63562
63799
  }
63563
- const assignments = files.map((file2) => {
63800
+ const assignments = files.map((named) => {
63801
+ const file2 = absolute4(context2.cwd, named);
63564
63802
  if (!existsSync42(file2))
63565
63803
  throw new Error(`assignment file not found: ${file2}`);
63566
63804
  const text7 = readFileSync112(file2, "utf8");
@@ -63581,7 +63819,8 @@ async function execute8(id, input2, context2) {
63581
63819
  return gate2.ok ? ok11(id, { assignments, ...gateData(gate2) }) : rejected(id, gate2, "qc.alignment.mismatch");
63582
63820
  }
63583
63821
  case "review.seats": {
63584
- const file2 = required5(input2.assignmentFile, "usage: review seats <assignment-file> [--mode sdd|inline|targeted] [--reviewers <role1,role2,...>]");
63822
+ const named = required5(input2.assignmentFile, "usage: review seats <assignment-file> [--mode sdd|inline|targeted] [--reviewers <role1,role2,...>]");
63823
+ const file2 = absolute4(context2.cwd, named);
63585
63824
  if (!existsSync42(file2))
63586
63825
  throw new Error(`assignment file not found: ${file2}`);
63587
63826
  const text7 = readFileSync112(file2, "utf8");
@@ -63607,18 +63846,18 @@ async function execute8(id, input2, context2) {
63607
63846
  if (!existsSync42(abs))
63608
63847
  throw new Error(`lint target not found: ${abs}`);
63609
63848
  const isDir = statSync10(abs).isDirectory();
63610
- const targets = !isDir ? [abs] : forced === "provenance" ? collectTargets(abs, (file2) => provenanceExtensions[path222.extname(file2).toLowerCase()] === true) : collectTargets(abs);
63849
+ const targets = !isDir ? [abs] : forced === "provenance" ? collectTargets(abs, (file2) => provenanceExtensions[path23.extname(file2).toLowerCase()] === true) : collectTargets(abs);
63611
63850
  const results = targets.map((file2) => ({ file: file2, ...lintOne(file2, forced, input2.prVariant === true) }));
63612
63851
  return results.some((result) => result.violations.length) ? refusal(id, results.flatMap((r) => r.violations)[0]?.code ?? "lint.violations", "lint violations found", { results }, "Resolve each reported lint violation, then rerun mstar lint <target>.") : ok11(id, { results });
63613
63852
  }
63614
63853
  case "design-md.validate": {
63615
63854
  const dir = absolute4(context2.cwd, required5(input2.dir, "usage: design-md validate <dir>"));
63616
- const lightPath = path222.join(dir, "DESIGN.md");
63855
+ const lightPath = path23.join(dir, "DESIGN.md");
63617
63856
  if (!existsSync42(lightPath))
63618
63857
  throw new Error(`design file not found: ${lightPath}`);
63619
63858
  const light = readFileSync112(lightPath, "utf8");
63620
63859
  const violations = [...validateDesignTokenFrontmatter(light).violations];
63621
- const darkPath = path222.join(dir, "DESIGN.dark.md");
63860
+ const darkPath = path23.join(dir, "DESIGN.dark.md");
63622
63861
  if (existsSync42(darkPath))
63623
63862
  violations.push(...assertLightDarkParity(light, readFileSync112(darkPath, "utf8")).violations);
63624
63863
  const level = completenessLevel(light);
@@ -63632,19 +63871,55 @@ async function execute8(id, input2, context2) {
63632
63871
  const violations = [...validateSchemaYaml(readFileSync112(docPath, "utf8")).violations];
63633
63872
  if (input2.knowledgeDir !== undefined) {
63634
63873
  const knowledgeDir = absolute4(context2.cwd, input2.knowledgeDir);
63635
- violations.push(...assertIndexRows(knowledgeDir).violations, ...scopeGuard(docPath, [knowledgeDir]).violations);
63874
+ const harnessDir2 = context2.controlRoot ?? resolveProcessHarnessDir(context2.cwd);
63875
+ if (harnessDir2 === null) {
63876
+ violations.push({
63877
+ ok: false,
63878
+ severity: "high",
63879
+ code: "compound.catalog.unresolved-harness",
63880
+ message: `no {HARNESS_DIR} resolves for this invocation, so the knowledge catalog completeness of ${knowledgeDir} cannot be asserted`,
63881
+ fix: "run this command from a workspace that declares a harness root (.mstar / .agents, MSTAR_HARNESS_DIR), or mount the MCP server with --harness <harness-dir>; catalog completeness is a store.db query"
63882
+ });
63883
+ } else {
63884
+ const configuredRoot = catalogRootDir({ harnessDir: harnessDir2 }, "knowledge");
63885
+ const named = canonicalPath2(knowledgeDir);
63886
+ const root = canonicalPath2(configuredRoot);
63887
+ if (named !== root) {
63888
+ violations.push({
63889
+ ok: false,
63890
+ severity: "high",
63891
+ code: "compound.catalog.knowledge-dir-mismatch",
63892
+ message: `${knowledgeDir} is not the configured knowledge root ${configuredRoot}, so its catalog completeness cannot be asserted \u2014 ` + "completeness is a store.db query that reports the configured root's verdict (the documents registered relative to it), which is never a verdict about a subdirectory of that root or about another directory as a knowledge store",
63893
+ fix: `pass --knowledge-dir ${configuredRoot} to validate the configured root (omitting the flag validates only the document schema, with no catalog completeness check); or move/declare those documents under ${configuredRoot} and register them there; or point the project's knowledge root at that directory (\`.mstarc\` \`[config] knowledge_dir\`) and validate that root`
63894
+ });
63895
+ } else {
63896
+ try {
63897
+ violations.push(...(await assertKnowledgeCatalogCompleteness({ harnessDir: harnessDir2 })).violations);
63898
+ } catch (error62) {
63899
+ const code2 = error62?.code;
63900
+ violations.push({
63901
+ ok: false,
63902
+ severity: "high",
63903
+ code: "compound.catalog.unavailable",
63904
+ message: `the knowledge catalog completeness cannot be evaluated: ${typeof code2 === "string" && code2 !== "" ? `[${code2}] ` : ""}${error62 instanceof Error ? error62.message : String(error62)}`,
63905
+ fix: "restore the issue/catalog authority (`mstar store init|upgrade|migrate`) \u2014 unavailable catalog data is never read as complete"
63906
+ });
63907
+ }
63908
+ }
63909
+ }
63910
+ violations.push(...scopeGuard(docPath, [knowledgeDir]).violations);
63636
63911
  }
63637
63912
  const gate2 = { ok: violations.length === 0, violations };
63638
63913
  return gate2.ok ? ok11(id, gateData(gate2)) : rejected(id, gate2, "compound.invalid");
63639
63914
  }
63640
63915
  case "skill.lint": {
63641
63916
  const dir = absolute4(context2.cwd, required5(input2.skillDir, "usage: skill lint <skill-dir>"));
63642
- const skillFile = path222.join(dir, "SKILL.md");
63917
+ const skillFile = path23.join(dir, "SKILL.md");
63643
63918
  if (!existsSync42(skillFile))
63644
63919
  throw new Error(`SKILL.md not found: ${skillFile}`);
63645
63920
  const text7 = readFileSync112(skillFile, "utf8");
63646
63921
  const violations = [...lintSkillFrontmatter(text7).violations];
63647
- const profile = classifySkillLint(path222.basename(dir));
63922
+ const profile = classifySkillLint(path23.basename(dir));
63648
63923
  if (profile.mode !== null)
63649
63924
  violations.push(...lintFiveQuestion(stripFrontmatter(text7), profile.mode).violations);
63650
63925
  violations.push(...findEphemeralCitations(text7).map((citation) => ({ ok: false, severity: "medium", code: `skill.ephemeral.${citation.kind}`, message: `ephemeral ${citation.kind} citation at line ${citation.line}: "${citation.match}" \u2014 task artifacts and SDD deeplinks survive nothing; durable skill text cites in-repo artifacts only (knowledge conventions \u00a73)`, fix: `rewrite "${citation.match}" as a placeholder form (e.g. task-N-report, <plan-id>, {SDD_DIR}/task-N-report.md) or cite a stable in-repo artifact instead` })));
@@ -63653,13 +63928,13 @@ async function execute8(id, input2, context2) {
63653
63928
  }
63654
63929
  case "roles.validate": {
63655
63930
  const rolesDir = absolute4(context2.cwd, input2.rolesDir ?? "skills/mstar-roles");
63656
- const skillsRoot = absolute4(context2.cwd, input2.skillsDir ?? path222.dirname(rolesDir));
63931
+ const skillsRoot = absolute4(context2.cwd, input2.skillsDir ?? path23.dirname(rolesDir));
63657
63932
  const violations = [...validateRoleMapping(rolesDir).violations];
63658
63933
  const skillTexts = {};
63659
63934
  for (const entry of readdirSync22(skillsRoot, { withFileTypes: true })) {
63660
63935
  if (!entry.isDirectory() || !entry.name.startsWith("mstar-"))
63661
63936
  continue;
63662
- const file2 = path222.join(skillsRoot, entry.name, "SKILL.md");
63937
+ const file2 = path23.join(skillsRoot, entry.name, "SKILL.md");
63663
63938
  if (!existsSync42(file2))
63664
63939
  continue;
63665
63940
  try {
@@ -63783,7 +64058,7 @@ function required6(value, label) {
63783
64058
  return value;
63784
64059
  }
63785
64060
  function resolvePath(cwd, value) {
63786
- return path23.isAbsolute(value) ? value : path23.resolve(cwd, value);
64061
+ return path24.isAbsolute(value) ? value : path24.resolve(cwd, value);
63787
64062
  }
63788
64063
  function parseFindings(text7) {
63789
64064
  let data;
@@ -63918,7 +64193,7 @@ async function execute9(verb, input2, context2) {
63918
64193
  throw new SddScriptError(`--level must be one of ${auditLevels.join(" | ")}`, 2);
63919
64194
  if (derived2 && input2.round !== undefined && !/^[1-9]\d*$/.test(input2.round))
63920
64195
  throw new SddScriptError("--round must be an integer >= 1", 2);
63921
- const reviewsDir = input2.reviewsDir !== undefined ? resolvePath(context2.cwd, input2.reviewsDir) : derived2 ? resolveReviewDir(context2.cwd) : path23.dirname(dirOverride);
64196
+ const reviewsDir = input2.reviewsDir !== undefined ? resolvePath(context2.cwd, input2.reviewsDir) : derived2 ? resolveReviewDir(context2.cwd) : path24.dirname(dirOverride);
63922
64197
  const payload2 = parseFindings(readFileSync122(findingsFile, "utf8"));
63923
64198
  let sha = input2.sha;
63924
64199
  if (sha === undefined) {
@@ -63949,6 +64224,11 @@ async function execute9(verb, input2, context2) {
63949
64224
  }
63950
64225
  return ok12(id, result2);
63951
64226
  }
64227
+ const unnamedRepository = launchDirectoryRefusal(id, context2, {
64228
+ fields: [{ field: "path", subject: verb === "secret-scan" ? "the repository to scan" : "the repository to check", value: input2.path }]
64229
+ });
64230
+ if (unnamedRepository !== undefined)
64231
+ return unnamedRepository;
63952
64232
  const root = resolvePath(context2.cwd, input2.path ?? ".");
63953
64233
  if (!existsSync52(root) || !statSync22(root).isDirectory())
63954
64234
  throw new SddScriptError(`not a directory: ${root}`, 2);
@@ -63959,7 +64239,7 @@ async function execute9(verb, input2, context2) {
63959
64239
  const listed = await process2({ argv: ["git", "ls-files", "-z", "--", "."], cwd: root, env: {}, signal: context2.signal });
63960
64240
  if (listed.exitCode !== 0 || listed.signal !== null)
63961
64241
  throw new SddScriptError("not a git repository or git unavailable \u2014 refusing to report an empty scan as clean", 2);
63962
- const files = listed.stdout.split("\x00").filter(Boolean).map((file2) => path23.join(root, file2));
64242
+ const files = listed.stdout.split("\x00").filter(Boolean).map((file2) => path24.join(root, file2));
63963
64243
  const result2 = scanSecrets(files);
63964
64244
  return result2.unreadableFiles > 0 || result2.findings.length > 0 ? refusalEnvelope({ command: id, status: "refused", code: result2.unreadableFiles > 0 ? "audit.secret-scan.incomplete" : "audit.secret-scan.findings", exitCode: 1, message: result2.unreadableFiles > 0 ? `failed to read ${result2.unreadableFiles} tracked files; refusing to report clean` : `${result2.findings.length} secret findings`, details: { findings: result2.findings, unreadableFiles: result2.unreadableFiles }, recovery: result2.unreadableFiles > 0 && result2.findings.length > 0 ? "Restore access to each unreadable tracked file and rotate or revoke every reported credential before purging it from tracked content. Run mstar audit secret-scan." : result2.unreadableFiles > 0 ? "Restore read access to every unreadable tracked file. Run mstar audit secret-scan." : "Rotate or revoke every reported credential and purge it from tracked content. Run mstar audit secret-scan." }) : ok12(id, { findings: [], unreadableFiles: 0, filesScanned: files.length });
63965
64245
  }
@@ -64018,8 +64298,11 @@ var inputSchema8 = exports_external.object({
64018
64298
  unverified: exports_external.string().optional(),
64019
64299
  unmetAcUnsafe: exports_external.string().optional(),
64020
64300
  unmetAcSafe: exports_external.string().optional(),
64021
- incompleteReason: exports_external.string().optional(),
64022
- unscanned: exports_external.string().optional(),
64301
+ stopped: exports_external.string().optional(),
64302
+ requiredDomains: exports_external.string().optional(),
64303
+ openedDomains: exports_external.string().optional(),
64304
+ diffBasis: exports_external.string().optional(),
64305
+ partialScope: exports_external.array(exports_external.string()).optional(),
64023
64306
  reviewsDir: exports_external.string().optional(),
64024
64307
  target: exports_external.string().optional(),
64025
64308
  stage: exports_external.string().optional(),
@@ -64047,7 +64330,7 @@ var inputSchema8 = exports_external.object({
64047
64330
  remainingMinutes: exports_external.string().optional()
64048
64331
  });
64049
64332
  var contracts2 = {
64050
- tally: { args: [], options: [{ key: "findings", flags: "--findings <file.json>", required: true }, { key: "unverified", flags: "--unverified <n>", required: false, defaultValue: "0" }, { key: "unmetAcUnsafe", flags: "--unmet-ac-unsafe <n>", required: false, defaultValue: "0" }, { key: "unmetAcSafe", flags: "--unmet-ac-safe <n>", required: false, defaultValue: "0" }, { key: "incompleteReason", flags: "--incomplete-reason <text>", required: false, help: "Declares the run incomplete with this cause; requires --unscanned." }, { key: "unscanned", flags: "--unscanned <csv>", required: false, help: "Comma-separated scope the run never scanned; a lone none (case-insensitive) declares nothing left unscanned; requires --incomplete-reason." }], effects: ["read", "validate"], description: "Compute PR-review tally from a JSON array of {mergeClass: must-fix|should-fix|nit}; all counts default to zero and are limited to 0\u201350." },
64333
+ tally: { args: [], options: [{ key: "findings", flags: "--findings <file.json>", required: true, help: "Required; path to a JSON array of {mergeClass: must-fix | should-fix | nit}." }, { key: "unverified", flags: "--unverified <n>", required: false, defaultValue: "0", help: "Optional; non-negative integer no greater than 50; defaults to 0." }, { key: "unmetAcUnsafe", flags: "--unmet-ac-unsafe <n>", required: false, defaultValue: "0", help: "Optional; non-negative integer no greater than 50; defaults to 0." }, { key: "unmetAcSafe", flags: "--unmet-ac-safe <n>", required: false, defaultValue: "0", help: "Optional; non-negative integer no greater than 50; defaults to 0." }, { key: "stopped", flags: "--stopped <text>", required: false, help: "Optional; non-blank single line naming why the run stopped before synthesis; presence derives the incomplete verdict." }, { key: "requiredDomains", flags: "--required-domains <d,d,...>", required: false, help: "Required; comma-separated single-line domain names, one entry per required seat (a domain with two seats appears twice); at least one; omitted is refused, never inferred." }, { key: "openedDomains", flags: "--opened-domains <d,d,...>", required: false, help: "Required; comma-separated single-line domain names, one entry per seat that returned evidence (a domain with two seats needs two matching entries when both returned); an explicitly empty value means none, omission is refused." }, { key: "diffBasis", flags: "--diff-basis <readable|unreadable>", required: false, help: "Required; one of readable | unreadable; omitted is refused, never defaulted." }, { key: "partialScope", flags: "--partial-scope <scope...>", required: false, defaultValue: [], help: "Optional; repeat once per scope a seat declared as truncated coverage; when the run is unsettled these join the derived unscanned list, and when it settles they are echoed as declaredScopes." }], effects: ["read", "validate"], description: "Compute PR-review tally from a JSON array of {mergeClass: must-fix|should-fix|nit}; the incomplete verdict is derived from the run facts (--stopped, --required-domains/--opened-domains as one entry per seat, --diff-basis, and --partial-scope for scopes seats declared as truncated), never elapsed time; the three coverage/basis facts are required, so a run that does not report its coverage is refused; the count options default to zero and are limited to 0\u201350." },
64051
64334
  "report-path": { args: [], options: [{ key: "reviewsDir", flags: "--reviews-dir <dir>", required: false, help: "Review root; defaults to {REVIEW_DIR} under the harness dir." }, { key: "target", flags: "--target <spec>", required: true }, { key: "stage", flags: "--stage <1|2>", required: false, help: "Optional, but if supplied it requires --slug; stage must be 1 or 2." }, { key: "slug", flags: "--slug <domain-seat>", required: false, help: "Optional, but if supplied it requires --stage." }, { key: "date", flags: "--date <YYYY-MM-DD>", required: false, help: "Defaults to the local calendar date; no report file is written or reserved." }], effects: ["read"], description: "Compute the report path inside the target's run directory under {REVIEW_DIR} from the PR/branch/diff target, optional paired stage/slug, and local-date default. This command does not write the report, inspect collision state, or add a revision suffix." },
64052
64335
  "validate-report": { args: [{ key: "reportFile", required: true, variadic: false }], options: [], effects: ["read", "validate"], description: "Validate a saved PR-review report and return its structured violations." },
64053
64336
  post: { args: [], options: [{ key: "pr", flags: "--pr <n>", required: true }, { key: "bodyFile", flags: "--body-file <path>", required: true }, { key: "findings", flags: "--findings <file.json>", required: false }], effects: ["read", "validate", "process", "service"], description: "Post a body and optional parsed inline findings to the requested PR's resolved current head. If GitHub returns 422 for inline comments, retry once with those comments folded into the review body. A failed final response has unknown outcome: inspect the PR before retrying." },
@@ -64061,7 +64344,7 @@ var ok13 = (id, data) => ({ version: 1, command: id, status: "ok", code: `${id}.
64061
64344
  var failure6 = (id, error62) => {
64062
64345
  const message = error62 instanceof Error ? error62.message : String(error62);
64063
64346
  if (error62 instanceof UsageError3)
64064
- return refusalEnvelope({ command: id, status: "usage", code: "command.invalid-input", exitCode: 2, message, ...error62.diagnostics === undefined ? {} : { diagnostics: error62.diagnostics } });
64347
+ return refusalEnvelope({ command: id, status: "usage", code: "command.invalid-input", exitCode: 2, message, ...error62.diagnostics === undefined ? {} : { diagnostics: error62.diagnostics }, ...error62.recovery === undefined ? {} : { recovery: error62.recovery } });
64065
64348
  const { code: code2, details, recovery } = engineErrorFacts(error62);
64066
64349
  if (code2 === undefined)
64067
64350
  return { version: 1, command: id, status: "error", code: `${id}.failed`, exitCode: 1, message };
@@ -64078,12 +64361,14 @@ var failure6 = (id, error62) => {
64078
64361
 
64079
64362
  class UsageError3 extends Error {
64080
64363
  diagnostics;
64081
- constructor(message, diagnostics) {
64364
+ recovery;
64365
+ constructor(message, diagnostics, recovery) {
64082
64366
  super(message);
64083
64367
  this.diagnostics = diagnostics;
64368
+ this.recovery = recovery;
64084
64369
  }
64085
64370
  }
64086
- var abs = (cwd, file2) => path24.isAbsolute(file2) ? file2 : path24.resolve(cwd, file2);
64371
+ var abs = (cwd, file2) => path25.isAbsolute(file2) ? file2 : path25.resolve(cwd, file2);
64087
64372
  var need = (value, name) => {
64088
64373
  if (value === undefined || value === "")
64089
64374
  throw new UsageError3(`${name} is required`);
@@ -64136,11 +64421,17 @@ async function execute10(verb, input2, context2) {
64136
64421
  const id = idFor2(verb);
64137
64422
  try {
64138
64423
  if (verb === "tally") {
64139
- const file2 = abs(context2.cwd, need(input2.findings, "--findings"));
64140
- const diagnostics = [];
64424
+ const unnamedFindings = launchDirectoryDiagnostics(context2, {
64425
+ fields: [{ field: "findings", subject: "the findings file", value: input2.findings }]
64426
+ });
64427
+ const diagnostics = [...unnamedFindings?.diagnostics ?? []];
64141
64428
  const allowed = ["must-fix", "should-fix", "nit"];
64142
64429
  let findings = [];
64143
- if (!existsSync62(file2)) {
64430
+ const file2 = input2.findings === undefined || input2.findings === "" ? undefined : abs(context2.cwd, input2.findings);
64431
+ if (file2 === undefined || unnamedFindings !== undefined) {
64432
+ if (file2 === undefined && unnamedFindings === undefined)
64433
+ diagnostics.push({ path: "findings", code: "required", message: "--findings is required", expected: "present", received: "undefined" });
64434
+ } else if (!existsSync62(file2)) {
64144
64435
  diagnostics.push({ path: "findings", code: "invalid", message: `findings file not found: ${file2}` });
64145
64436
  } else {
64146
64437
  let parsed;
@@ -64164,45 +64455,71 @@ async function execute10(verb, input2, context2) {
64164
64455
  });
64165
64456
  }
64166
64457
  }
64167
- if (input2.incompleteReason === undefined !== (input2.unscanned === undefined)) {
64168
- diagnostics.push({
64169
- path: input2.incompleteReason === undefined ? "incompleteReason" : "unscanned",
64170
- code: "required",
64171
- message: "--incomplete-reason and --unscanned go together"
64172
- });
64458
+ if (input2.stopped !== undefined && (input2.stopped.trim() === "" || /[\r\n]/.test(input2.stopped))) {
64459
+ diagnostics.push({ path: "stopped", code: "invalid", message: "--stopped must be a single line of non-blank text" });
64173
64460
  }
64174
- if (input2.incompleteReason !== undefined && (input2.incompleteReason.trim() === "" || /[\r\n]/.test(input2.incompleteReason))) {
64175
- diagnostics.push({ path: "incompleteReason", code: "invalid", message: "--incomplete-reason must be a single line of non-blank text" });
64461
+ const missing = (flag, path262) => {
64462
+ diagnostics.push({ path: path262, code: "required", message: `${flag} is required`, expected: "present", received: "undefined" });
64463
+ };
64464
+ const domains = (raw, path262, flag) => {
64465
+ if (raw === undefined) {
64466
+ missing(flag, path262);
64467
+ return [];
64468
+ }
64469
+ if (raw.trim() === "")
64470
+ return [];
64471
+ const entries = raw.split(",").map((entry) => entry.trim());
64472
+ if (entries.some((entry) => entry === "" || /[\r\n]/.test(entry))) {
64473
+ diagnostics.push({ path: path262, code: "invalid", message: `${flag} must be a comma-separated list of single-line non-blank entries` });
64474
+ return [];
64475
+ }
64476
+ return entries;
64477
+ };
64478
+ const requiredDomains = domains(input2.requiredDomains, "requiredDomains", "--required-domains");
64479
+ if (input2.requiredDomains !== undefined && input2.requiredDomains.trim() === "") {
64480
+ diagnostics.push({ path: "requiredDomains", code: "invalid", message: "--required-domains must name at least one domain" });
64176
64481
  }
64177
- if (input2.unscanned !== undefined && input2.unscanned.split(",").some((entry) => entry.trim() === "" || /[\r\n]/.test(entry))) {
64178
- diagnostics.push({ path: "unscanned", code: "invalid", message: "--unscanned must be a comma-separated list of single-line non-blank entries" });
64482
+ const openedDomains = domains(input2.openedDomains, "openedDomains", "--opened-domains");
64483
+ if (input2.diffBasis === undefined)
64484
+ missing("--diff-basis", "diffBasis");
64485
+ else if (input2.diffBasis !== "readable" && input2.diffBasis !== "unreadable") {
64486
+ diagnostics.push({ path: "diffBasis", code: "invalid", message: "--diff-basis must be readable or unreadable" });
64179
64487
  }
64180
- const count = (raw, label, path252) => {
64488
+ const count = (raw, label, path262) => {
64181
64489
  if (raw === undefined)
64182
64490
  return 0;
64183
64491
  if (!/^\d+$/.test(raw) || Number(raw) > 50) {
64184
- diagnostics.push({ path: path252, code: "invalid", message: `${label} must be a non-negative integer no greater than 50` });
64492
+ diagnostics.push({ path: path262, code: "invalid", message: `${label} must be a non-negative integer no greater than 50` });
64185
64493
  return 0;
64186
64494
  }
64187
64495
  return Number(raw);
64188
64496
  };
64189
64497
  const unverifiedCount = count(input2.unverified, "--unverified", "unverified");
64498
+ const partialScope = (input2.partialScope ?? []).flatMap((entry) => {
64499
+ if (entry.trim() === "" || /[\r\n]/.test(entry)) {
64500
+ diagnostics.push({ path: "partialScope", code: "invalid", message: "--partial-scope entries must be single lines of non-blank text" });
64501
+ return [];
64502
+ }
64503
+ return [entry];
64504
+ });
64190
64505
  const unmetAcUnsafe = count(input2.unmetAcUnsafe, "--unmet-ac-unsafe", "unmetAcUnsafe");
64191
64506
  const unmetAcSafe = count(input2.unmetAcSafe, "--unmet-ac-safe", "unmetAcSafe");
64192
64507
  if (diagnostics.length > 0)
64193
- throw new UsageError3(diagnostics[0].message, diagnostics);
64194
- const rawScope = input2.unscanned ?? "";
64195
- const incomplete = input2.incompleteReason === undefined ? undefined : {
64196
- reason: need(input2.incompleteReason, "--incomplete-reason"),
64197
- unscanned: /^none$/i.test(rawScope.trim()) ? [] : rawScope.split(",").map((entry) => entry.trim()).filter((entry) => entry !== "")
64198
- };
64508
+ throw new UsageError3(diagnostics[0].message, diagnostics, unnamedFindings?.recovery);
64509
+ const settlement = resolvePrReviewSettlement({
64510
+ ...input2.stopped === undefined ? {} : { stopped: input2.stopped },
64511
+ requiredDomains,
64512
+ openedDomains,
64513
+ diffBasisReadable: input2.diffBasis === "readable",
64514
+ ...partialScope.length === 0 ? {} : { partialSeatScopes: partialScope }
64515
+ });
64199
64516
  const result = computePrTally({
64200
64517
  findings,
64201
64518
  unverifiedCount,
64202
64519
  unmetAc: [...Array.from({ length: unmetAcUnsafe }, () => ({ unsafeToShip: true })), ...Array.from({ length: unmetAcSafe }, () => ({ unsafeToShip: false }))],
64203
- ...incomplete === undefined ? {} : { incomplete }
64520
+ ...settlement.settled ? {} : { incomplete: settlement.incomplete }
64204
64521
  });
64205
- return ok13(id, result);
64522
+ return ok13(id, settlement.settled && partialScope.length > 0 ? { ...result, declaredScopes: [...new Set(partialScope)] } : result);
64206
64523
  }
64207
64524
  if (verb === "report-path") {
64208
64525
  const stage = input2.stage === undefined ? undefined : input2.stage === "1" ? 1 : input2.stage === "2" ? 2 : (() => {
@@ -64216,6 +64533,11 @@ async function execute10(verb, input2, context2) {
64216
64533
  return ok13(id, { path: prReviewReportPath({ reviewsDir, target: parseTarget(need(input2.target, "--target")), ...stage ? { stage } : {}, ...input2.slug ? { slug: input2.slug } : {}, ...input2.date ? { date: input2.date } : {} }) });
64217
64534
  }
64218
64535
  if (verb === "validate-report") {
64536
+ const unnamedReport = launchDirectoryRefusal(id, context2, {
64537
+ fields: [{ field: "reportFile", subject: "the report file", value: input2.reportFile }]
64538
+ });
64539
+ if (unnamedReport !== undefined)
64540
+ return unnamedReport;
64219
64541
  const file2 = abs(context2.cwd, need(input2.reportFile, "report file"));
64220
64542
  if (!existsSync62(file2))
64221
64543
  throw new Error(`report file not found: ${file2}`);
@@ -64223,6 +64545,9 @@ async function execute10(verb, input2, context2) {
64223
64545
  return result.ok ? ok13(id, result) : refusalEnvelope({ command: id, status: "refused", code: `${id}.invalid`, exitCode: 1, message: "PR-review report validation failed", details: { violations: result.violations }, recovery: "Correct each listed violation in the saved report. Run mstar pr-review validate-report <report-file>." });
64224
64546
  }
64225
64547
  if (verb === "post") {
64548
+ const unnamedRepository = launchDirectoryRefusal(id, context2, { subject: "the repository this review is posted to" });
64549
+ if (unnamedRepository !== undefined)
64550
+ return unnamedRepository;
64226
64551
  if (!/^\d+$/.test(need(input2.pr, "--pr")) || Number(input2.pr) < 1)
64227
64552
  throw new UsageError3("--pr requires a positive integer");
64228
64553
  const bodyFile = abs(context2.cwd, need(input2.bodyFile, "--body-file"));
@@ -64277,8 +64602,13 @@ ${response.stdout}`) && plan.inlineComments.length)
64277
64602
  return ok13(id, { posted: true, comments: "posted", review_url: reviewUrl || "(gh response)" });
64278
64603
  }
64279
64604
  if (verb === "worktree-cleanup") {
64280
- const worktreePath = path24.resolve(abs(context2.cwd, need(input2.worktreePath, "--path")));
64281
- const sidecarPath = path24.join(path24.dirname(worktreePath), `.${path24.basename(worktreePath)}.prreview.json`);
64605
+ const unnamedWorktree = launchDirectoryRefusal(id, context2, {
64606
+ fields: [{ field: "worktreePath", subject: "the review worktree to remove", value: input2.worktreePath }]
64607
+ });
64608
+ if (unnamedWorktree !== undefined)
64609
+ return unnamedWorktree;
64610
+ const worktreePath = path25.resolve(abs(context2.cwd, need(input2.worktreePath, "--path")));
64611
+ const sidecarPath = path25.join(path25.dirname(worktreePath), `.${path25.basename(worktreePath)}.prreview.json`);
64282
64612
  if (!existsSync62(sidecarPath))
64283
64613
  throw new Error(`no setup sidecar found at ${sidecarPath} - run pr-review worktree-setup first`);
64284
64614
  const sidecar = JSON.parse(readFileSync132(sidecarPath, "utf8"));
@@ -64287,7 +64617,7 @@ ${response.stdout}`) && plan.inlineComments.length)
64287
64617
  throw new Error(`--branch does not match the recorded review branch ${JSON.stringify(branch)} - refusing to delete a foreign branch`);
64288
64618
  if (input2.reportSaved !== true && sidecar.reportSaved !== true)
64289
64619
  throw new Error("refusing cleanup: the local report is not saved yet - save it first or pass --report-saved");
64290
- const gitRoot = typeof sidecar.repoRoot === "string" && sidecar.repoRoot !== "" ? sidecar.repoRoot : path24.dirname(worktreePath);
64620
+ const gitRoot = typeof sidecar.repoRoot === "string" && sidecar.repoRoot !== "" ? sidecar.repoRoot : path25.dirname(worktreePath);
64291
64621
  if (existsSync62(worktreePath)) {
64292
64622
  const removed = await spawn2(context2, ["git", "worktree", "remove", worktreePath], gitRoot);
64293
64623
  if (removed.exitCode !== 0 || removed.signal !== null)
@@ -64304,7 +64634,7 @@ ${response.stdout}`) && plan.inlineComments.length)
64304
64634
  if (deleted.exitCode !== 0 || deleted.signal !== null)
64305
64635
  throw new Error(deleted.stderr || `failed to delete ${branch}`);
64306
64636
  }
64307
- const diffPath = path24.join(path24.dirname(worktreePath), `.${path24.basename(worktreePath)}.prreview.diff`);
64637
+ const diffPath = path25.join(path25.dirname(worktreePath), `.${path25.basename(worktreePath)}.prreview.diff`);
64308
64638
  try {
64309
64639
  const fd = openSync7(diffPath, "r");
64310
64640
  try {
@@ -64329,6 +64659,9 @@ ${response.stdout}`) && plan.inlineComments.length)
64329
64659
  return ok13(id, { removed: worktreePath, branch: branch || null });
64330
64660
  }
64331
64661
  if (verb === "size") {
64662
+ const unnamedRepository = launchDirectoryRefusal(id, context2, { subject: "the repository this size classifies" });
64663
+ if (unnamedRepository !== undefined)
64664
+ return unnamedRepository;
64332
64665
  const base = need(input2.base, "--base");
64333
64666
  const head = need(input2.head, "--head");
64334
64667
  const rootResult = await spawn2(context2, ["git", "rev-parse", "--show-toplevel"]);
@@ -64369,8 +64702,17 @@ ${response.stdout}`) && plan.inlineComments.length)
64369
64702
  throw new UsageError3("--tier must be quick | default | deep");
64370
64703
  if (input2.remainingMinutes !== undefined && !/^-?\d+(?:\.\d+)?$/.test(input2.remainingMinutes))
64371
64704
  throw new UsageError3("--remaining-minutes must be a number of minutes");
64705
+ const unnamedSeatPaths = launchDirectoryRefusal(id, context2, {
64706
+ fields: [
64707
+ { field: "worktree", subject: "the review worktree", value: input2.worktree },
64708
+ { field: "skillRoot", subject: "the audit skill root", value: input2.skillRoot },
64709
+ { field: "diffFile", subject: "the review diff file", value: input2.diffFile, optional: true }
64710
+ ]
64711
+ });
64712
+ if (unnamedSeatPaths !== undefined)
64713
+ return unnamedSeatPaths;
64372
64714
  const skillRoot = abs(context2.cwd, input2.skillRoot ?? "skills/mstar-audit");
64373
- return ok13(id, { prompt: prReviewSeatPrompt({ stage: input2.stage === "1" ? 1 : 2, domain: need(input2.domain, "--domain"), seat: need(input2.seat, "--seat"), skillRoot, worktreePath: path24.resolve(input2.worktree ?? context2.cwd), reconFacts: input2.recon ?? [], ...input2.security ? { securitySeat: true } : {}, ...input2.tier ? { tier: input2.tier } : {}, ...input2.diffFile ? { diffFile: abs(context2.cwd, input2.diffFile) } : {}, ...input2.collectFolded ? { collectFolded: true } : {}, ...input2.remainingMinutes !== undefined ? { budgetRemainingMinutes: Number(input2.remainingMinutes) } : {} }) });
64715
+ return ok13(id, { prompt: prReviewSeatPrompt({ stage: input2.stage === "1" ? 1 : 2, domain: need(input2.domain, "--domain"), seat: need(input2.seat, "--seat"), skillRoot, worktreePath: path25.resolve(input2.worktree ?? context2.cwd), reconFacts: input2.recon ?? [], ...input2.security ? { securitySeat: true } : {}, ...input2.tier ? { tier: input2.tier } : {}, ...input2.diffFile ? { diffFile: abs(context2.cwd, input2.diffFile) } : {}, ...input2.collectFolded ? { collectFolded: true } : {}, ...input2.remainingMinutes !== undefined ? { budgetRemainingMinutes: Number(input2.remainingMinutes) } : {} }) });
64374
64716
  }
64375
64717
  return ok13(id, { budgets: PR_REVIEW_TIER_BUDGETS, nudgeCadence: PR_REVIEW_NUDGE_CADENCE });
64376
64718
  } catch (error62) {
@@ -64386,8 +64728,11 @@ function getPrReviewCommandDefinitions() {
64386
64728
  ...contract3.args.filter(({ required: required7 }) => required7).map(({ key }) => ({ name: key, ownership: "caller", route, required: true })),
64387
64729
  ...contract3.options.filter(({ required: required7 }) => required7).map(({ key }) => ({ name: key, ownership: "caller", route, required: true })),
64388
64730
  ...verb === "tally" ? [
64389
- { name: "incompleteReason", ownership: "caller", route, required: true, condition: { field: "unscanned", present: true }, constraint: "incompleteReason and unscanned must be supplied together" },
64390
- { name: "unscanned", ownership: "caller", route, required: true, condition: { field: "incompleteReason", present: true }, constraint: "incompleteReason and unscanned must be supplied together" }
64731
+ { name: "stopped", ownership: "caller", route, required: false, constraint: "non-blank single line; presence derives the incomplete verdict" },
64732
+ { name: "requiredDomains", ownership: "caller", route, required: false, constraint: "required at execution; comma-separated non-empty domain names, one entry per required seat - a domain with two seats appears twice; never inferred - an omission is refused beside the other field diagnostics" },
64733
+ { name: "openedDomains", ownership: "caller", route, required: false, constraint: "required at execution; comma-separated domain names, one entry per seat that returned evidence - a domain with two seats appears twice, and both entries are needed when both returned; an empty list is legal, an omission is refused beside the other field diagnostics" },
64734
+ { name: "diffBasis", ownership: "caller", route, required: false, constraint: "required at execution; one of readable | unreadable - an omission or an unaccepted value is refused beside the other field diagnostics" },
64735
+ { name: "partialScope", ownership: "caller", route, required: false, constraint: "optional; repeat once per scope a seat declared as truncated coverage; each entry is a single line of non-blank text; the entries join the derived unscanned list when the run is unsettled and are echoed as declaredScopes when it settles" }
64391
64736
  ] : [],
64392
64737
  ...verb === "report-path" ? [
64393
64738
  { name: "reviewsDir", ownership: "derivable", route, required: false, constraint: "defaults to {REVIEW_DIR} under the harness dir" },
@@ -64473,7 +64818,7 @@ function definitions() {
64473
64818
  return [
64474
64819
  make("sdd.exec", execInput, [{ key: "argv", required: true, variadic: true }], [{ key: "context", flags: "--context <path>", required: false }], ["read", "validate", "process"], "Run an admitted literal argv child in the SDD feature worktree.", async (input2, invocation) => {
64475
64820
  try {
64476
- if (!input2.context || !path25.isAbsolute(input2.context))
64821
+ if (!input2.context || !path26.isAbsolute(input2.context))
64477
64822
  throw new SddScriptError("usage: sdd exec --context <absolute.json> -- <executable> [args...]", 2);
64478
64823
  if (!input2.argv?.length)
64479
64824
  throw new SddScriptError("argv after -- must include the child executable", 2);
@@ -64578,9 +64923,9 @@ async function setupReviewWorktree(input2, invocation) {
64578
64923
  const existing = new Set((await git(invocation, ["for-each-ref", "--format=%(refname:short)", "refs/heads"], repoRoot)).split(/\r?\n/).filter(Boolean));
64579
64924
  const seed = mode === "pr" ? prNumber : Math.abs([...headSpec].reduce((hash3, char) => (hash3 * 31 + char.charCodeAt(0)) % 1000003, 7)) || 1;
64580
64925
  const reviewBranch = pickReviewBranchName(existing, seed, new Date().toISOString().slice(0, 10).replace(/-/g, ""));
64581
- const repoReal = realpathSync22(repoRoot);
64582
- const defaultRoot = path25.join(path25.dirname(repoReal), `${path25.basename(repoReal)}.worktrees`);
64583
- const worktreePath = path25.resolve(input2.targetPath ?? path25.join(defaultRoot, `review-${reviewBranch}${mode === "pr" ? "" : `-${headSpec.slice(0, 8)}`}`));
64926
+ const repoReal = realpathSync32(repoRoot);
64927
+ const defaultRoot = path26.join(path26.dirname(repoReal), `${path26.basename(repoReal)}.worktrees`);
64928
+ const worktreePath = path26.resolve(input2.targetPath ?? path26.join(defaultRoot, `review-${reviewBranch}${mode === "pr" ? "" : `-${headSpec.slice(0, 8)}`}`));
64584
64929
  if (input2.targetPath === undefined)
64585
64930
  fs13.mkdirSync(defaultRoot, { recursive: true });
64586
64931
  const origin = await gitProbe(invocation, ["remote", "get-url", "origin"], repoRoot);
@@ -64638,8 +64983,8 @@ async function setupReviewWorktree(input2, invocation) {
64638
64983
  ## Diff
64639
64984
  `, await git(invocation, ["diff", "-U10", range], worktreePath)];
64640
64985
  const diffText = parts.join("");
64641
- const diffFile = path25.join(path25.dirname(worktreePath), `.${path25.basename(worktreePath)}.prreview.diff`);
64642
- const sidecarFile = path25.join(path25.dirname(worktreePath), `.${path25.basename(worktreePath)}.prreview.json`);
64986
+ const diffFile = path26.join(path26.dirname(worktreePath), `.${path26.basename(worktreePath)}.prreview.diff`);
64987
+ const sidecarFile = path26.join(path26.dirname(worktreePath), `.${path26.basename(worktreePath)}.prreview.json`);
64643
64988
  let diffFd;
64644
64989
  let sidecarFd;
64645
64990
  let snapshotStat;
@@ -64708,7 +65053,7 @@ function cleanupClaims(snapshot, field, value) {
64708
65053
  try {
64709
65054
  return fs13.realpathSync(candidate);
64710
65055
  } catch {
64711
- return path25.resolve(candidate);
65056
+ return path26.resolve(candidate);
64712
65057
  }
64713
65058
  };
64714
65059
  if (field === "branch" && snapshot.branch?.integration === value)
@@ -64773,7 +65118,7 @@ async function cleanupWorktrees(input2, invocation, retainedOwnerKeys) {
64773
65118
  try {
64774
65119
  return fs13.realpathSync(value);
64775
65120
  } catch {
64776
- return path25.resolve(value);
65121
+ return path26.resolve(value);
64777
65122
  }
64778
65123
  };
64779
65124
  const assertedPaths = new Set((input2.worktree ?? []).map(pathKey));
@@ -64938,14 +65283,14 @@ function engineRefusal3(id, error62) {
64938
65283
  recovery: supportedRecovery
64939
65284
  });
64940
65285
  }
64941
- function usage22(id, message, path272) {
65286
+ function usage22(id, message, path282) {
64942
65287
  return refusalEnvelope({
64943
65288
  command: id,
64944
65289
  status: "usage",
64945
65290
  code: "command.invalid-input",
64946
65291
  exitCode: 2,
64947
65292
  message,
64948
- ...path272 === undefined ? {} : { diagnostics: [{ path: path272, code: "required", message }] }
65293
+ ...path282 === undefined ? {} : { diagnostics: [{ path: path282, code: "required", message }] }
64949
65294
  });
64950
65295
  }
64951
65296
  function decodeUsage(id, error62, input2) {
@@ -65034,12 +65379,12 @@ function getExecutionLedgerCommandDefinitions() {
65034
65379
  { name: "ts", ownership: "caller", route: "cli", required: false, constraint: "defaults to current time when omitted" },
65035
65380
  { name: "ts", ownership: "caller", route: "mcp", required: false, constraint: "defaults to current time when omitted" },
65036
65381
  { name: "sessionId", ownership: "caller", route: "cli", required: true, constraint: "acquired coordinator identity via flag or MSTAR_HOST_SESSION_ID" },
65037
- { name: "sessionId", ownership: "caller", route: "mcp", required: true, constraint: "host-supplied acquired coordinator identity per call" }
65382
+ { name: "sessionId", ownership: "caller", route: "mcp", required: true, constraint: "host-proven acquired coordinator identity: the dsh native tool or the CLI; a shared MCP connection accepts none by default" }
65038
65383
  ],
65039
65384
  description: "Append one note to the addressed workflow's retained notes ledger. Requires acquired coordinator identity and a matching active coordinator session reference; the engine proves the bound session is current immediately before the fsynced append, so a stale, revoked or foreign session refuses and no byte is written. The ledger is a plain append log, so a repeated id is a new record, not a replay.",
65040
65385
  async execute(raw, context2) {
65041
65386
  if (context2.sessionId === undefined || context2.sessionId.trim() === "") {
65042
- return usage22(APPEND_ID, "appending a workflow note requires an acquired coordinator identity (CLI: pass --session-id or set MSTAR_HOST_SESSION_ID; MCP: the host must pass sessionId per call).", "sessionId");
65387
+ return usage22(APPEND_ID, "appending a workflow note requires an acquired coordinator identity (CLI: pass --session-id or set MSTAR_HOST_SESSION_ID; MCP: no caller-declared identity is accepted by default \u2014 run this command from the session's shell).", "sessionId");
65043
65388
  }
65044
65389
  const parsed = appendInput.safeParse(raw);
65045
65390
  if (!parsed.success)
@@ -65104,7 +65449,7 @@ function getExecutionLedgerCommandDefinitions() {
65104
65449
  const root = resolveProcessHarnessDir(context2.cwd, input2.harness);
65105
65450
  if (root === null)
65106
65451
  return usage22(COVERAGE_ID, "no control harness resolved; supply an absolute harness", "harness");
65107
- if (input2.file !== undefined && !path26.isAbsolute(input2.file)) {
65452
+ if (input2.file !== undefined && !path27.isAbsolute(input2.file)) {
65108
65453
  return usage22(COVERAGE_ID, "file must be an absolute path", "file");
65109
65454
  }
65110
65455
  const file2 = input2.file ?? workflowNotesLedgerPath({ harnessDir: root }, input2.workflow);
@@ -65311,7 +65656,7 @@ function getOpencodeDoctorWarningsV2(config2, allRoles) {
65311
65656
  function diagnoseOpencodeV2Host(root, allRoles, opts) {
65312
65657
  const resolved = opts.resolved;
65313
65658
  const explicitSelection = opts.explicitSelection === true;
65314
- const location = path27.join(root, "opencode.json");
65659
+ const location = path28.join(root, "opencode.json");
65315
65660
  let config2;
65316
65661
  try {
65317
65662
  const parsed = JSON.parse(fs14.readFileSync(location, "utf8"));
@@ -65371,8 +65716,8 @@ function classifyOpencodeProbeError(error62) {
65371
65716
  }
65372
65717
  function opencodeProbeFailureMessage(mode, detail) {
65373
65718
  const suffix = detail ? ` (${detail})` : "";
65374
- const cause = mode === "binary-missing" ? "the opencode binary was not found" : mode === "timeout" ? "`opencode --version` timed out" : mode === "unparseable" ? "`opencode --version` output was not in the expected `opencode vMAJOR.MINOR.PATCH` form" : "`opencode --version` failed to run";
65375
- return `Could not probe the opencode generation (${mode}): ${cause}${suffix}. Install the OpenCode CLI (https://opencode.ai) or ${OPENCODE_GENERATION_RECOVERY}.`;
65719
+ const cause2 = mode === "binary-missing" ? "the opencode binary was not found" : mode === "timeout" ? "`opencode --version` timed out" : mode === "unparseable" ? "`opencode --version` output was not in the expected `opencode vMAJOR.MINOR.PATCH` form" : "`opencode --version` failed to run";
65720
+ return `Could not probe the opencode generation (${mode}): ${cause2}${suffix}. Install the OpenCode CLI (https://opencode.ai) or ${OPENCODE_GENERATION_RECOVERY}.`;
65376
65721
  }
65377
65722
  var doctorTargets = ["opencode", "cursor", "codex", "zcode", "omp", "dsh", "kimi"];
65378
65723
  var hostSignals = [
@@ -65382,6 +65727,9 @@ var hostSignals = [
65382
65727
  "task_agent_batch",
65383
65728
  "ask",
65384
65729
  "hub",
65730
+ "subagent",
65731
+ "spawn_teammate",
65732
+ "team_task_create",
65385
65733
  "Agent",
65386
65734
  "AgentSwarm",
65387
65735
  "AskUserQuestion",
@@ -65393,7 +65741,7 @@ var hostSignals = [
65393
65741
  "tool_search"
65394
65742
  ];
65395
65743
  var hostIds = ["opencode", "omp", "pi", "dsh", "cursor", "codex", "kimi", "zcode"];
65396
- var harnessRepoPath = path28.join(os6.homedir(), ".mstar", "harness");
65744
+ var harnessRepoPath = path29.join(os6.homedir(), ".mstar", "harness");
65397
65745
  var harnessMarkers = [".codex-plugin/plugin.json", ".zcode-plugin/plugin.json", ".omp-plugin/plugin.json"];
65398
65746
  var agentsTemplate = `# AGENTS.md \u2014 .mstar/ (harness layer)
65399
65747
 
@@ -65425,7 +65773,7 @@ function runBin(bin) {
65425
65773
  function localHarnessErrors() {
65426
65774
  if (!fs15.existsSync(harnessRepoPath))
65427
65775
  return [`Missing local harness repo: ${harnessRepoPath}`];
65428
- const marker = harnessMarkers.map((entry) => path28.join(harnessRepoPath, entry)).find((entry) => fs15.existsSync(entry));
65776
+ const marker = harnessMarkers.map((entry) => path29.join(harnessRepoPath, entry)).find((entry) => fs15.existsSync(entry));
65429
65777
  return marker === undefined ? [`Local harness repo is missing a plugin marker (expected one of: ${harnessMarkers.join(", ")}).`] : [];
65430
65778
  }
65431
65779
  function gitWorkspaceRoot(startDir) {
@@ -65440,19 +65788,22 @@ function gitWorkspaceRoot(startDir) {
65440
65788
  let boundary = startDir;
65441
65789
  for (const segment of cdup.split(/[\\/]/)) {
65442
65790
  if (segment && segment !== ".")
65443
- boundary = path28.dirname(boundary);
65791
+ boundary = path29.dirname(boundary);
65444
65792
  }
65445
65793
  return boundary;
65446
65794
  } catch {
65447
65795
  return startDir;
65448
65796
  }
65449
65797
  }
65450
- function pluginRoot(explicit) {
65798
+ function projectRootAt(workspace) {
65799
+ return resolveProjectRoot(workspace);
65800
+ }
65801
+ function pluginRoot(explicit, workspace) {
65451
65802
  if (explicit !== undefined)
65452
- return path28.resolve(explicit);
65453
- let candidate = resolveProjectRoot2();
65454
- while (!fs15.existsSync(path28.join(candidate, "plugin.json"))) {
65455
- const parent = path28.dirname(candidate);
65803
+ return path29.resolve(workspace, explicit);
65804
+ let candidate = projectRootAt(workspace);
65805
+ while (!fs15.existsSync(path29.join(candidate, "plugin.json"))) {
65806
+ const parent = path29.dirname(candidate);
65456
65807
  if (parent === candidate)
65457
65808
  break;
65458
65809
  candidate = parent;
@@ -65492,29 +65843,29 @@ function diagnoseOpencodeTarget(root, generation) {
65492
65843
  return { location: result.location, errors: result.errors, notes: result.warnings, generations: result.generations, generationSource: result.generationSource };
65493
65844
  } catch (error62) {
65494
65845
  return {
65495
- location: path28.join(root, "opencode.json"),
65846
+ location: path29.join(root, "opencode.json"),
65496
65847
  errors: [error62 instanceof Error ? error62.message : String(error62)],
65497
65848
  notes: []
65498
65849
  };
65499
65850
  }
65500
65851
  }
65501
- async function diagnose(target, scope, generation) {
65852
+ async function diagnose(target, scope, generation, projectRoot) {
65502
65853
  if (target === "opencode") {
65503
- const root = scope === "global" ? path28.join(os6.homedir(), ".config", "opencode") : resolveProjectRoot2();
65854
+ const root = scope === "global" ? path29.join(os6.homedir(), ".config", "opencode") : projectRoot;
65504
65855
  return diagnoseOpencodeTarget(root, generation);
65505
65856
  }
65506
65857
  if (target === "cursor") {
65507
- const result2 = diagnoseCursorHost(scope);
65858
+ const result2 = diagnoseCursorHost(scope, { project: projectInstallPath(projectRoot) });
65508
65859
  return { location: result2.location, errors: result2.errors, notes: [] };
65509
65860
  }
65510
65861
  if (target === "kimi")
65511
65862
  return diagnoseKimiHost();
65512
65863
  if (target === "zcode") {
65513
- const result2 = diagnoseZcodeHost(scope, { projectRoot: resolveProjectRoot2(), harnessRepoPath });
65864
+ const result2 = diagnoseZcodeHost(scope, { projectRoot, harnessRepoPath });
65514
65865
  return { location: result2.location, errors: result2.errors, notes: [] };
65515
65866
  }
65516
65867
  if (target === "codex") {
65517
- const result2 = diagnoseCodexHost(runBin("codex"), path28.join(os6.homedir(), ".agents", "plugins", "marketplace.json"));
65868
+ const result2 = diagnoseCodexHost(runBin("codex"), path29.join(os6.homedir(), ".agents", "plugins", "marketplace.json"));
65518
65869
  return { location: result2.location, errors: [...localHarnessErrors(), ...result2.errors], notes: result2.notes };
65519
65870
  }
65520
65871
  if (target === "dsh")
@@ -65554,17 +65905,24 @@ function getLocalCommandDefinitions() {
65554
65905
  input: exports_external.object({ path: exports_external.string().min(1).optional() }),
65555
65906
  effects: ["write"],
65556
65907
  description: "Create the harness directories and default project; then run mstar store init to activate execution authority.",
65557
- async execute(input2) {
65558
- const root = input2.path === undefined ? process.cwd() : path28.resolve(input2.path);
65559
- setArtifactStore(createFsStore(resolveScaffoldDirs(root).harnessDir));
65560
- const harnessDir2 = await scaffoldHarness(root);
65908
+ async execute(input2, context2) {
65909
+ const unnamedRoot = launchDirectoryRefusal("harness.scaffold", context2, {
65910
+ fields: [{ field: "path", subject: "the scaffold root", value: input2.path }]
65911
+ });
65912
+ if (unnamedRoot !== undefined)
65913
+ return unnamedRoot;
65914
+ const root = input2.path === undefined ? context2.cwd : path29.resolve(context2.cwd, input2.path);
65915
+ const harnessPin = input2.path === undefined ? context2.harnessPin : undefined;
65916
+ const scaffoldOptions = harnessPin === undefined ? {} : { harnessDir: harnessPin };
65917
+ setArtifactStore(createFsStore(resolveScaffoldDirs(root, scaffoldOptions).harnessDir));
65918
+ const harnessDir2 = await scaffoldHarness(root, scaffoldOptions);
65561
65919
  const projectDir = resolveProjectDir(root, { harnessDir: harnessDir2 });
65562
65920
  const created = [];
65563
65921
  const skipped = [];
65564
65922
  const workspaceRoot = gitWorkspaceRoot(root);
65565
- const defaultHarness = path28.join(workspaceRoot, ".mstar");
65566
- if (detectHarnessKind(harnessDir2) === "mstar" && path28.resolve(harnessDir2) === defaultHarness) {
65567
- const gitignorePath = path28.join(workspaceRoot, ".gitignore");
65923
+ const defaultHarness = path29.join(workspaceRoot, ".mstar");
65924
+ if (detectHarnessKind(harnessDir2) === "mstar" && path29.resolve(harnessDir2) === defaultHarness) {
65925
+ const gitignorePath = path29.join(workspaceRoot, ".gitignore");
65568
65926
  const current = fs15.existsSync(gitignorePath) ? fs15.readFileSync(gitignorePath, "utf8") : "";
65569
65927
  if (hasHarnessRootDeclaration(current))
65570
65928
  skipped.push(".gitignore (author-owned harness-root declaration)");
@@ -65586,12 +65944,12 @@ function getLocalCommandDefinitions() {
65586
65944
  }
65587
65945
  } else
65588
65946
  skipped.push(".gitignore (canonical harness snippet) \u2014 custom harness layout manages its own ignore rules");
65589
- const agentsPath = path28.join(harnessDir2, "AGENTS.md");
65947
+ const agentsPath = path29.join(harnessDir2, "AGENTS.md");
65590
65948
  if (!fs15.existsSync(agentsPath)) {
65591
65949
  fs15.writeFileSync(agentsPath, agentsTemplate, "utf8");
65592
- created.push(`${path28.basename(harnessDir2)}/AGENTS.md`);
65950
+ created.push(`${path29.basename(harnessDir2)}/AGENTS.md`);
65593
65951
  } else
65594
- skipped.push(`${path28.basename(harnessDir2)}/AGENTS.md (already present)`);
65952
+ skipped.push(`${path29.basename(harnessDir2)}/AGENTS.md (already present)`);
65595
65953
  return ok16("harness.scaffold", { harnessDir: harnessDir2, projectDir, created, skipped });
65596
65954
  }
65597
65955
  }),
@@ -65616,8 +65974,12 @@ function getLocalCommandDefinitions() {
65616
65974
  effects: ["read"],
65617
65975
  description: "Validate Morning Star setup for one supported host target.",
65618
65976
  async execute(input2, context2) {
65619
- const result = await diagnose(input2.target, input2.scope, input2.generation);
65620
- const projectOpencodeMcpPath = input2.target === "opencode" && input2.scope === "project" ? path28.join(resolveProjectRoot2(), "opencode.json") : undefined;
65977
+ const unnamedProject = input2.scope === "project" ? launchDirectoryRefusal("doctor", context2, { subject: "the project root this diagnosis reads" }) : undefined;
65978
+ if (unnamedProject !== undefined)
65979
+ return unnamedProject;
65980
+ const projectRoot = projectRootAt(context2.cwd);
65981
+ const result = await diagnose(input2.target, input2.scope, input2.generation, projectRoot);
65982
+ const projectOpencodeMcpPath = input2.target === "opencode" && input2.scope === "project" ? path29.join(projectRoot, "opencode.json") : undefined;
65621
65983
  const resolvedGenerations = result.generations ?? [];
65622
65984
  const resolvedGeneration = input2.generation ?? (resolvedGenerations.length === 1 ? resolvedGenerations[0] : undefined);
65623
65985
  const v2AmongResolved = resolvedGenerations.includes("v2") || input2.generation === "v2";
@@ -65666,8 +66028,13 @@ function getLocalCommandDefinitions() {
65666
66028
  input: exports_external.object({ root: exports_external.string().optional() }),
65667
66029
  effects: ["validate"],
65668
66030
  description: "Validate a plugin package against Agent Plugins v1.0.0.",
65669
- async execute(input2) {
65670
- const root = pluginRoot(input2.root);
66031
+ async execute(input2, context2) {
66032
+ const unnamedRoot = launchDirectoryRefusal("plugin.validate", context2, {
66033
+ fields: [{ field: "root", subject: "the plugin package", value: input2.root }]
66034
+ });
66035
+ if (unnamedRoot !== undefined)
66036
+ return unnamedRoot;
66037
+ const root = pluginRoot(input2.root, context2.cwd);
65671
66038
  const result = validateAgentPlugin(root);
65672
66039
  return result.ok ? ok16("plugin.validate", { root, ...result }) : refusalEnvelope({ command: "plugin.validate", status: "refused", code: "plugin.invalid", exitCode: 1, message: result.errors.join(`
65673
66040
  `), details: { root, ...result }, recovery: "Correct the plugin package errors listed in the validation report. Run mstar plugin validate." });
@@ -65679,7 +66046,12 @@ function getLocalCommandDefinitions() {
65679
66046
  effects: ["read"],
65680
66047
  description: "Resolve harness, specs, workflow, project, and review directories from a start directory.",
65681
66048
  async execute(input2, context2) {
65682
- const startDir = input2.path === undefined ? context2.cwd : path28.resolve(context2.cwd, input2.path);
66049
+ const unnamedStart = launchDirectoryRefusal("path.resolve", context2, {
66050
+ fields: [{ field: "path", subject: "the start directory", value: input2.path }]
66051
+ });
66052
+ if (unnamedStart !== undefined)
66053
+ return unnamedStart;
66054
+ const startDir = input2.path === undefined ? context2.cwd : path29.resolve(context2.cwd, input2.path);
65683
66055
  const harnessDir2 = resolveHarnessDir(startDir);
65684
66056
  if (harnessDir2 === null) {
65685
66057
  return refusalEnvelope({ command: "path.resolve", status: "refused", code: "path.harness-not-found", exitCode: 1, message: `no harness dir found from ${startDir}`, details: {
@@ -66033,7 +66405,7 @@ function commandRequirements(definition22) {
66033
66405
  requirements.push({ name: sessionOption2.key, ownership: "caller", route: "cli" });
66034
66406
  }
66035
66407
  if (!overridden.has(`mcp:${sessionOption2.key}`)) {
66036
- requirements.push({ name: sessionOption2.key, ownership: "caller", route: "mcp", help: "when the selected route requires session identity, it must be supplied by the caller (host per call); legacy pre-activation routes do not require it, and legacy `plan bind --resume` refuses declared identity while ignoring ambient environment identity" });
66408
+ requirements.push({ name: sessionOption2.key, ownership: "caller", route: "mcp", help: "MCP: published only on a server launched with --trust-caller-session-id (off by default); a shared connection carries no host-proven caller identity, so use the dsh native tool that covers the operation or run the CLI command from the session's shell" });
66037
66409
  }
66038
66410
  }
66039
66411
  return requirements;
@@ -66296,6 +66668,7 @@ async function runAdmitted(bindings, context2) {
66296
66668
  function admittedCommand(bindings) {
66297
66669
  return Object.freeze({
66298
66670
  ...bindings.sessionId === undefined ? {} : { sessionId: bindings.sessionId },
66671
+ ...bindings.harness === undefined ? {} : { harness: bindings.harness },
66299
66672
  ...bindings.stdinText === undefined ? {} : { stdinText: bindings.stdinText },
66300
66673
  execute(context2) {
66301
66674
  return runAdmitted(bindings, context2);
@@ -66409,6 +66782,7 @@ function admitCommandInput(definition22, input2, contract3, schema3 = definition
66409
66782
  }
66410
66783
  const parsedRecord = parsed.data !== null && typeof parsed.data === "object" ? parsed.data : {};
66411
66784
  const stdinText = definition22.effects.includes("stdin") && typeof parsedRecord.input === "string" ? parsedRecord.input : undefined;
66785
+ const callHarness = parsedRecord.harness;
66412
66786
  return {
66413
66787
  success: true,
66414
66788
  ...admittedCommand({
@@ -66417,6 +66791,7 @@ function admitCommandInput(definition22, input2, contract3, schema3 = definition
66417
66791
  data: shape(parsed.data),
66418
66792
  required: required7,
66419
66793
  ...typeof selectorValue === "string" ? { sessionId: selectorValue } : {},
66794
+ ...typeof callHarness === "string" && callHarness.trim() !== "" ? { harness: callHarness } : {},
66420
66795
  ...stdinText === undefined ? {} : { stdinText }
66421
66796
  })
66422
66797
  };
@@ -66432,6 +66807,49 @@ async function executeCommand(id2, input2, context2) {
66432
66807
  return admitted.envelope;
66433
66808
  return admitted.execute(context2);
66434
66809
  }
66810
+ var SEAT_FAMILIES = ["workflow"];
66811
+ var SEAT_ACTIONS = {
66812
+ plan: ["bind", "complete"],
66813
+ session: ["recover", "run"],
66814
+ status: ["workflow-close"],
66815
+ "workflow-note": ["append"],
66816
+ iteration: ["register"]
66817
+ };
66818
+ function foldedFamilyToolName(family) {
66819
+ return `mstar_${family.replace(/[.-]/g, "_")}`;
66820
+ }
66821
+ function familyOf(definition22) {
66822
+ return definition22.cli.path[0] ?? definition22.id.split(".")[0];
66823
+ }
66824
+ function actionOf(commandId) {
66825
+ const dot = commandId.indexOf(".");
66826
+ return dot === -1 ? commandId : commandId.slice(dot + 1);
66827
+ }
66828
+ function isSeatDefinition(definition22) {
66829
+ const family = familyOf(definition22);
66830
+ return SEAT_FAMILIES.includes(family) || (SEAT_ACTIONS[family] ?? []).includes(actionOf(definition22.id));
66831
+ }
66832
+ var seatIndexCache;
66833
+ function seatIndex() {
66834
+ if (seatIndexCache !== undefined)
66835
+ return seatIndexCache;
66836
+ const ids = new Set;
66837
+ const actions2 = new Map;
66838
+ for (const definition22 of getCommandDefinitions()) {
66839
+ if (!isSeatDefinition(definition22))
66840
+ continue;
66841
+ ids.add(definition22.id);
66842
+ const tool = foldedFamilyToolName(familyOf(definition22));
66843
+ const byAction = actions2.get(tool) ?? new Map;
66844
+ byAction.set(actionOf(definition22.id), definition22.id);
66845
+ actions2.set(tool, byAction);
66846
+ }
66847
+ seatIndexCache = { ids, actions: actions2 };
66848
+ return seatIndexCache;
66849
+ }
66850
+ function isCoordinatorSeatCommand(commandId) {
66851
+ return seatIndex().ids.has(commandId);
66852
+ }
66435
66853
  function normalizeNotFound(error62, executable) {
66436
66854
  if (error62 !== null && typeof error62 === "object" && error62.code === "ENOENT") {
66437
66855
  return Object.assign(new Error(`executable not found in $PATH: ${executable}`), { code: "process.not-found", exitCode: 127 });
@@ -68375,10 +68793,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
68375
68793
  this._name = path19.basename(filename, path19.extname(filename));
68376
68794
  return this;
68377
68795
  }
68378
- executableDir(path29) {
68379
- if (path29 === undefined)
68796
+ executableDir(path30) {
68797
+ if (path30 === undefined)
68380
68798
  return this._executableDir;
68381
- this._executableDir = path29;
68799
+ this._executableDir = path30;
68382
68800
  return this;
68383
68801
  }
68384
68802
  helpInformation(contextOptions) {
@@ -68553,15 +68971,15 @@ var program = new Command;
68553
68971
 
68554
68972
  // src/index.ts
68555
68973
  var import_picocolors = __toESM(require_picocolors(), 1);
68556
- import path38 from "node:path";
68974
+ import path39 from "node:path";
68557
68975
 
68558
68976
  // src/adapters/codex.ts
68559
68977
  import os9 from "node:os";
68560
- import path32 from "node:path";
68978
+ import path33 from "node:path";
68561
68979
 
68562
68980
  // src/adapters/codex-agent-files.ts
68563
68981
  import fs16 from "node:fs";
68564
- import path29 from "node:path";
68982
+ import path30 from "node:path";
68565
68983
  import { randomUUID as randomUUID8 } from "node:crypto";
68566
68984
  function statIfPresent(target) {
68567
68985
  try {
@@ -68573,7 +68991,7 @@ function statIfPresent(target) {
68573
68991
  }
68574
68992
  }
68575
68993
  function checkParent(target) {
68576
- const parent = path29.dirname(target);
68994
+ const parent = path30.dirname(target);
68577
68995
  const stat = statIfPresent(parent);
68578
68996
  if (stat && !stat.isDirectory())
68579
68997
  throw new Error(`Agent directory must be a real directory: ${parent}`);
@@ -68583,10 +69001,10 @@ var BACKUP_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
68583
69001
  var MAX_RETAINED_BACKUPS = 3;
68584
69002
  function pruneBackups(target, keep) {
68585
69003
  try {
68586
- const dir = path29.dirname(target);
68587
- const prefix = `${path29.basename(target)}.`;
69004
+ const dir = path30.dirname(target);
69005
+ const prefix = `${path30.basename(target)}.`;
68588
69006
  const stale = fs16.readdirSync(dir).flatMap((name) => {
68589
- const full = path29.join(dir, name);
69007
+ const full = path30.join(dir, name);
68590
69008
  if (full === keep || !name.startsWith(prefix) || !name.endsWith(BACKUP_SUFFIX))
68591
69009
  return [];
68592
69010
  if (!BACKUP_UUID.test(name.slice(prefix.length, -BACKUP_SUFFIX.length)))
@@ -68602,8 +69020,8 @@ function ensureCodexAgentFile(source, target, dryRun) {
68602
69020
  checkParent(target);
68603
69021
  const stat = statIfPresent(target);
68604
69022
  if (stat?.isSymbolicLink()) {
68605
- const linked = path29.resolve(path29.dirname(target), fs16.readlinkSync(target));
68606
- const matches = linked === path29.resolve(source) || fs16.existsSync(linked) && fs16.existsSync(source) && fs16.realpathSync(linked) === fs16.realpathSync(source);
69023
+ const linked = path30.resolve(path30.dirname(target), fs16.readlinkSync(target));
69024
+ const matches = linked === path30.resolve(source) || fs16.existsSync(linked) && fs16.existsSync(source) && fs16.realpathSync(linked) === fs16.realpathSync(source);
68607
69025
  if (!matches)
68608
69026
  throw new Error(`Refusing unrelated agent symlink: ${target} -> ${linked}`);
68609
69027
  } else if (stat && !stat.isFile()) {
@@ -68628,7 +69046,7 @@ function ensureCodexAgentFile(source, target, dryRun) {
68628
69046
  ...previous3 ? [`Would back up differing agent file: ${target}`] : [],
68629
69047
  `Would ${stat?.isSymbolicLink() ? "replace legacy symlink with" : "install"} regular agent file: ${target}`
68630
69048
  ];
68631
- fs16.mkdirSync(path29.dirname(target), { recursive: true });
69049
+ fs16.mkdirSync(path30.dirname(target), { recursive: true });
68632
69050
  const notes = [];
68633
69051
  if (previous3) {
68634
69052
  const backup = `${target}.${randomUUID8()}${BACKUP_SUFFIX}`;
@@ -68700,10 +69118,10 @@ function runCliCommand(command7, opts = {}) {
68700
69118
  // src/adapters/shared-install.ts
68701
69119
  import fs18 from "node:fs";
68702
69120
  import os7 from "node:os";
68703
- import path31 from "node:path";
69121
+ import path32 from "node:path";
68704
69122
  var REPO_URL = "https://github.com/btspoony/mstar-harness.git";
68705
69123
  var PLUGIN_NAME5 = "morning-star-harness";
68706
- var HARNESS_REPO_PATH = path31.join(os7.homedir(), ".mstar", "harness");
69124
+ var HARNESS_REPO_PATH = path32.join(os7.homedir(), ".mstar", "harness");
68707
69125
  var HARNESS_MARKERS2 = [
68708
69126
  ".codex-plugin/plugin.json",
68709
69127
  ".zcode-plugin/plugin.json",
@@ -68711,11 +69129,11 @@ var HARNESS_MARKERS2 = [
68711
69129
  ];
68712
69130
  function harnessMarkerPath() {
68713
69131
  for (const marker of HARNESS_MARKERS2) {
68714
- const candidate = path31.join(HARNESS_REPO_PATH, marker);
69132
+ const candidate = path32.join(HARNESS_REPO_PATH, marker);
68715
69133
  if (fs18.existsSync(candidate))
68716
69134
  return candidate;
68717
69135
  }
68718
- return path31.join(HARNESS_REPO_PATH, HARNESS_MARKERS2[0]);
69136
+ return path32.join(HARNESS_REPO_PATH, HARNESS_MARKERS2[0]);
68719
69137
  }
68720
69138
  function pathOrSymlinkExists(filePath) {
68721
69139
  try {
@@ -68754,9 +69172,9 @@ function ensureLocalHarnessRepo(dryRun) {
68754
69172
  Could not move broken checkout aside: ${String(error62)}. Recover by moving ${HARNESS_REPO_PATH} aside manually, then rerun the installer.`);
68755
69173
  }
68756
69174
  notes.push(`Moved invalid checkout to ${brokenPath} for diagnosis`);
68757
- ensureDir(path31.dirname(HARNESS_REPO_PATH), false);
69175
+ ensureDir(path32.dirname(HARNESS_REPO_PATH), false);
68758
69176
  try {
68759
- runCommand(["git", "clone", REPO_URL, HARNESS_REPO_PATH], path31.dirname(HARNESS_REPO_PATH), false);
69177
+ runCommand(["git", "clone", REPO_URL, HARNESS_REPO_PATH], path32.dirname(HARNESS_REPO_PATH), false);
68760
69178
  } catch (error62) {
68761
69179
  throw new Error(`Existing checkout validation failed:
68762
69180
  ${errors3.join(`
@@ -68775,8 +69193,8 @@ ${cloneErrors.join(`
68775
69193
  notes.push(`Cloned ${REPO_URL} to ${HARNESS_REPO_PATH}`);
68776
69194
  return notes;
68777
69195
  }
68778
- ensureDir(path31.dirname(HARNESS_REPO_PATH), dryRun);
68779
- runCommand(["git", "clone", REPO_URL, HARNESS_REPO_PATH], path31.dirname(HARNESS_REPO_PATH), dryRun);
69196
+ ensureDir(path32.dirname(HARNESS_REPO_PATH), dryRun);
69197
+ runCommand(["git", "clone", REPO_URL, HARNESS_REPO_PATH], path32.dirname(HARNESS_REPO_PATH), dryRun);
68780
69198
  if (!dryRun) {
68781
69199
  const errors3 = validateLocalHarnessRepo2();
68782
69200
  if (errors3.length)
@@ -68794,7 +69212,7 @@ function validateLocalHarnessRepo2(dryRun = false) {
68794
69212
  return errors3;
68795
69213
  }
68796
69214
  const marker = harnessMarkerPath();
68797
- if (!fs18.existsSync(path31.join(HARNESS_REPO_PATH, ".git"))) {
69215
+ if (!fs18.existsSync(path32.join(HARNESS_REPO_PATH, ".git"))) {
68798
69216
  errors3.push(`Local harness repo is missing .git: ${HARNESS_REPO_PATH}`);
68799
69217
  } else {
68800
69218
  if (!dryRun) {
@@ -68812,7 +69230,7 @@ function validateLocalHarnessRepo2(dryRun = false) {
68812
69230
  }
68813
69231
  function ensureGitCheckout(repoUrl, checkoutPath, dryRun) {
68814
69232
  const notes = [];
68815
- const parentDir = path31.dirname(checkoutPath);
69233
+ const parentDir = path32.dirname(checkoutPath);
68816
69234
  if (pathOrSymlinkExists(checkoutPath)) {
68817
69235
  const stat = fs18.lstatSync(checkoutPath);
68818
69236
  if (stat.isSymbolicLink()) {
@@ -68820,7 +69238,7 @@ function ensureGitCheckout(repoUrl, checkoutPath, dryRun) {
68820
69238
  if (dryRun)
68821
69239
  return notes;
68822
69240
  fs18.unlinkSync(checkoutPath);
68823
- } else if (fs18.existsSync(path31.join(checkoutPath, ".git"))) {
69241
+ } else if (fs18.existsSync(path32.join(checkoutPath, ".git"))) {
68824
69242
  if (!dryRun) {
68825
69243
  runCommand(["git", "-C", checkoutPath, "pull", "--ff-only"], checkoutPath, dryRun);
68826
69244
  }
@@ -68853,7 +69271,7 @@ function ensureSymlink(target, linkPath, dryRun) {
68853
69271
  }
68854
69272
  return `Symlink already exists: ${linkPath} -> ${target}`;
68855
69273
  }
68856
- ensureDir(path31.dirname(linkPath), dryRun);
69274
+ ensureDir(path32.dirname(linkPath), dryRun);
68857
69275
  if (!dryRun)
68858
69276
  fs18.symlinkSync(target, linkPath);
68859
69277
  return `Linked ${linkPath} -> ${target}`;
@@ -68930,13 +69348,13 @@ function detectCodexPluginVersion2() {
68930
69348
  return detectCodexPluginVersion((args) => runCodex(args, false, CODEX_LOCAL_TIMEOUT_MS));
68931
69349
  }
68932
69350
  function agentSourcePath(agentName) {
68933
- return path32.join(HARNESS_REPO_PATH, "codex", "agents", `${agentName}.toml`);
69351
+ return path33.join(HARNESS_REPO_PATH, "codex", "agents", `${agentName}.toml`);
68934
69352
  }
68935
69353
  function globalAgentFilePath(agentName) {
68936
- return path32.join(os9.homedir(), ".codex", "agents", `${agentName}.toml`);
69354
+ return path33.join(os9.homedir(), ".codex", "agents", `${agentName}.toml`);
68937
69355
  }
68938
69356
  function projectAgentFilePath(agentName) {
68939
- return path32.join(resolveProjectRoot2(), ".codex", "agents", `${agentName}.toml`);
69357
+ return path33.join(resolveProjectRoot2(), ".codex", "agents", `${agentName}.toml`);
68940
69358
  }
68941
69359
  function ensureAgentFiles(scope, dryRun) {
68942
69360
  const notes = [];
@@ -68957,10 +69375,10 @@ function validateAgentFiles(scope) {
68957
69375
  return errors3;
68958
69376
  }
68959
69377
  function iterationCommandSourcePath(skillName) {
68960
- return path32.join(HARNESS_REPO_PATH, "commands", `${skillName}.md`);
69378
+ return path33.join(HARNESS_REPO_PATH, "commands", `${skillName}.md`);
68961
69379
  }
68962
69380
  function projectIterationSkillLinkPath(skillName) {
68963
- return path32.join(resolveProjectRoot2(), ".agents", "skills", skillName, "SKILL.md");
69381
+ return path33.join(resolveProjectRoot2(), ".agents", "skills", skillName, "SKILL.md");
68964
69382
  }
68965
69383
  function ensureIterationSkillLinks(dryRun) {
68966
69384
  const notes = [];
@@ -69017,13 +69435,13 @@ function runInit(scope, dryRun) {
69017
69435
  };
69018
69436
  }
69019
69437
  function runDoctor(scope) {
69020
- const diagnostic = diagnoseCodexHost((args) => runCodex(args, false, CODEX_LOCAL_TIMEOUT_MS), path32.join(os9.homedir(), ".agents", "plugins", "marketplace.json"));
69021
- const errors3 = [...validateLocalHarnessRepo2(), ...validateAgentFiles(scope), ...diagnostic.errors];
69022
- const notes = [...diagnostic.notes];
69438
+ const diagnostic2 = diagnoseCodexHost((args) => runCodex(args, false, CODEX_LOCAL_TIMEOUT_MS), path33.join(os9.homedir(), ".agents", "plugins", "marketplace.json"));
69439
+ const errors3 = [...validateLocalHarnessRepo2(), ...validateAgentFiles(scope), ...diagnostic2.errors];
69440
+ const notes = [...diagnostic2.notes];
69023
69441
  if (scope === "project") {
69024
69442
  errors3.push(...validateIterationSkillLinks());
69025
69443
  }
69026
- return { location: diagnostic.location, errors: errors3, notes };
69444
+ return { location: diagnostic2.location, errors: errors3, notes };
69027
69445
  }
69028
69446
  var codexAdapter = {
69029
69447
  target: "codex",
@@ -69041,13 +69459,13 @@ function withProbeAbort(pending, timeoutMs) {
69041
69459
  const abortable = pending;
69042
69460
  const timeout = Promise.withResolvers();
69043
69461
  timer = setTimeout(() => {
69044
- let cause;
69462
+ let cause2;
69045
69463
  try {
69046
69464
  abortable.abort?.();
69047
69465
  } catch (error62) {
69048
- cause = error62;
69466
+ cause2 = error62;
69049
69467
  }
69050
- const failure11 = Object.assign(new Error(`Probe timed out after ${timeoutMs}ms`), { code: "ETIMEDOUT", cause });
69468
+ const failure11 = Object.assign(new Error(`Probe timed out after ${timeoutMs}ms`), { code: "ETIMEDOUT", cause: cause2 });
69051
69469
  timeout.reject(failure11);
69052
69470
  }, timeoutMs);
69053
69471
  timeout.promise.catch(() => {});
@@ -69132,12 +69550,12 @@ function projectInit(dryRun) {
69132
69550
  return { location, notes };
69133
69551
  }
69134
69552
  function globalDoctor() {
69135
- const diagnostic = diagnoseCursorHost("global");
69136
- return { ...diagnostic, errors: [...validateLocalHarnessRepo2(), ...diagnostic.errors] };
69553
+ const diagnostic2 = diagnoseCursorHost("global");
69554
+ return { ...diagnostic2, errors: [...validateLocalHarnessRepo2(), ...diagnostic2.errors] };
69137
69555
  }
69138
69556
  function projectDoctor() {
69139
- const diagnostic = diagnoseCursorHost("project");
69140
- return { ...diagnostic, errors: [...validateLocalHarnessRepo2(), ...diagnostic.errors] };
69557
+ const diagnostic2 = diagnoseCursorHost("project");
69558
+ return { ...diagnostic2, errors: [...validateLocalHarnessRepo2(), ...diagnostic2.errors] };
69141
69559
  }
69142
69560
  var cursorAdapter = {
69143
69561
  target: "cursor",
@@ -69294,9 +69712,9 @@ var kimiAdapter = {
69294
69712
  // src/adapters/omp.ts
69295
69713
  import fs19 from "node:fs";
69296
69714
  import { homedir } from "node:os";
69297
- import path33 from "node:path";
69715
+ import path34 from "node:path";
69298
69716
  import { execFileSync as execFileSync9 } from "node:child_process";
69299
- var OMP_PACKAGE_REL = path33.join("packages", "omp");
69717
+ var OMP_PACKAGE_REL = path34.join("packages", "omp");
69300
69718
  var OMP_PLUGIN_NAME = "@mstar-harness/omp";
69301
69719
  function ompAvailable() {
69302
69720
  try {
@@ -69318,23 +69736,23 @@ function ompEntryRoots(scope, projectRoot) {
69318
69736
  if (derived2 !== null)
69319
69737
  roots.push(derived2);
69320
69738
  }
69321
- roots.push(scope === "project" ? path33.join(projectRoot, ".omp", "plugins") : ompPluginsRoot());
69739
+ roots.push(scope === "project" ? path34.join(projectRoot, ".omp", "plugins") : ompPluginsRoot());
69322
69740
  return [...new Set(roots)];
69323
69741
  }
69324
69742
  function ompRootOfEntryPath(entryPath) {
69325
- const suffix = path33.join("node_modules", OMP_PLUGIN_NAME);
69326
- const normalized = path33.normalize(entryPath);
69743
+ const suffix = path34.join("node_modules", OMP_PLUGIN_NAME);
69744
+ const normalized = path34.normalize(entryPath);
69327
69745
  if (!normalized.endsWith(suffix))
69328
69746
  return null;
69329
69747
  const root = normalized.slice(0, normalized.length - suffix.length);
69330
- return root.endsWith(path33.sep) ? root.slice(0, -1) : root;
69748
+ return root.endsWith(path34.sep) ? root.slice(0, -1) : root;
69331
69749
  }
69332
69750
  function ompPluginsRoot() {
69333
69751
  const dataHome = process.env["XDG_DATA_HOME"];
69334
- return dataHome !== undefined && dataHome !== "" ? path33.join(dataHome, "omp", "plugins") : path33.join(homedir(), ".omp", "plugins");
69752
+ return dataHome !== undefined && dataHome !== "" ? path34.join(dataHome, "omp", "plugins") : path34.join(homedir(), ".omp", "plugins");
69335
69753
  }
69336
69754
  function declaredByPluginManager(root) {
69337
- const manifest = path33.join(root, "package.json");
69755
+ const manifest = path34.join(root, "package.json");
69338
69756
  if (!fs19.existsSync(manifest))
69339
69757
  return false;
69340
69758
  try {
@@ -69357,7 +69775,7 @@ Recovery: ${recovery}`);
69357
69775
  }
69358
69776
  function clearOmpEntry(root, ompPackagePath, notes, scope = "global") {
69359
69777
  const scopeFlag = scopeFlagText(scope);
69360
- const entry = path33.join(root, "node_modules", OMP_PLUGIN_NAME);
69778
+ const entry = path34.join(root, "node_modules", OMP_PLUGIN_NAME);
69361
69779
  try {
69362
69780
  fs19.lstatSync(entry);
69363
69781
  } catch {
@@ -69440,7 +69858,7 @@ function installedPluginEntry(entries) {
69440
69858
  }
69441
69859
  return null;
69442
69860
  };
69443
- return entries.find((entry) => nameOf(entry) === OMP_PLUGIN_NAME) ?? entries.find((entry) => typeof entry["path"] === "string" && entry["path"].endsWith(path33.join("node_modules", OMP_PLUGIN_NAME)));
69861
+ return entries.find((entry) => nameOf(entry) === OMP_PLUGIN_NAME) ?? entries.find((entry) => typeof entry["path"] === "string" && entry["path"].endsWith(path34.join("node_modules", OMP_PLUGIN_NAME)));
69444
69862
  }
69445
69863
  async function runInit4(scope, dryRun, initFlags) {
69446
69864
  const notes = [];
@@ -69452,7 +69870,7 @@ async function runInit4(scope, dryRun, initFlags) {
69452
69870
  if (!dryRun)
69453
69871
  await ensureHostPresent("omp");
69454
69872
  notes.push(...ensureLocalHarnessRepo(dryRun));
69455
- if (fs19.existsSync(path33.join(HARNESS_REPO_PATH, ".git"))) {
69873
+ if (fs19.existsSync(path34.join(HARNESS_REPO_PATH, ".git"))) {
69456
69874
  if (dryRun) {
69457
69875
  notes.push(`Would update local harness repo: git -C ${HARNESS_REPO_PATH} pull --ff-only`);
69458
69876
  } else {
@@ -69469,12 +69887,12 @@ async function runInit4(scope, dryRun, initFlags) {
69469
69887
  }
69470
69888
  }
69471
69889
  if (dryRun) {
69472
- const ompPackagePath = path33.join(HARNESS_REPO_PATH, OMP_PACKAGE_REL);
69890
+ const ompPackagePath = path34.join(HARNESS_REPO_PATH, OMP_PACKAGE_REL);
69473
69891
  const scopeFlag = scopeFlagText(scope);
69474
69892
  const linkArgs = ["plugin", "link", ompPackagePath];
69475
69893
  notes.push("omp CLI presence is unchecked under --dry-run (would-run preview); install Oh My Pi (`omp`) before executing init.", `Would run: omp ${linkArgs.join(" ")}`);
69476
69894
  } else {
69477
- const ompPackagePath = path33.join(HARNESS_REPO_PATH, OMP_PACKAGE_REL);
69895
+ const ompPackagePath = path34.join(HARNESS_REPO_PATH, OMP_PACKAGE_REL);
69478
69896
  const scopeFlag = scopeFlagText(scope);
69479
69897
  const expectedVersion = initFlags?.pluginVersion ?? readHarnessVersion();
69480
69898
  const installSpec = `${OMP_PLUGIN_NAME}@${expectedVersion}`;
@@ -69487,7 +69905,7 @@ async function runInit4(scope, dryRun, initFlags) {
69487
69905
  throw ompRefusal(`omp plugin install ${installSpec} failed`, message, `run \`omp plugin install ${installSpec}\` yourself and read its output`);
69488
69906
  }
69489
69907
  };
69490
- if (!fs19.existsSync(path33.join(ompPackagePath, "plugin.json"))) {
69908
+ if (!fs19.existsSync(path34.join(ompPackagePath, "plugin.json"))) {
69491
69909
  try {
69492
69910
  runCliCommand(["bun", "install"], { cwd: HARNESS_REPO_PATH, dryRun });
69493
69911
  runCliCommand(["bun", "run", "engine:build"], { cwd: HARNESS_REPO_PATH, dryRun });
@@ -69567,7 +69985,7 @@ var ompAdapter = {
69567
69985
 
69568
69986
  // src/adapters/opencode.ts
69569
69987
  import os10 from "node:os";
69570
- import path34 from "node:path";
69988
+ import path35 from "node:path";
69571
69989
 
69572
69990
  // src/constants.ts
69573
69991
  var ALL_ROLES = [
@@ -69659,20 +70077,20 @@ var MORNING_STAR_MCP_SERVER = { type: "local", command: ["npx", "@mstar-harness/
69659
70077
  function resolveOpencodeConfigPath(scope, outputPath2) {
69660
70078
  if (outputPath2 && outputPath2.trim()) {
69661
70079
  const raw = outputPath2.trim();
69662
- if (path34.isAbsolute(raw))
70080
+ if (path35.isAbsolute(raw))
69663
70081
  return raw;
69664
70082
  if (raw.split(/[\\/]/).includes("..")) {
69665
70083
  throw new Error(`--output must not contain ".." segments: ${raw}`);
69666
70084
  }
69667
70085
  const root2 = resolveProjectRoot2();
69668
- return root2.endsWith(path34.sep) ? root2 + raw : root2 + path34.sep + raw;
70086
+ return root2.endsWith(path35.sep) ? root2 + raw : root2 + path35.sep + raw;
69669
70087
  }
69670
70088
  if (scope === "global") {
69671
70089
  const home = os10.homedir();
69672
- return `${home}${path34.sep}.config${path34.sep}opencode${path34.sep}opencode.json`;
70090
+ return `${home}${path35.sep}.config${path35.sep}opencode${path35.sep}opencode.json`;
69673
70091
  }
69674
70092
  const root = resolveProjectRoot2();
69675
- return root.endsWith(path34.sep) ? `${root}opencode.json` : `${root}${path34.sep}opencode.json`;
70093
+ return root.endsWith(path35.sep) ? `${root}opencode.json` : `${root}${path35.sep}opencode.json`;
69676
70094
  }
69677
70095
  function ensureConfigSchema(config2) {
69678
70096
  const next = ensureObject2(config2);
@@ -69863,7 +70281,7 @@ function printV2Summary(tag) {
69863
70281
  // src/adapters/zcode.ts
69864
70282
  import fs20 from "node:fs";
69865
70283
  import os11 from "node:os";
69866
- import path35 from "node:path";
70284
+ import path36 from "node:path";
69867
70285
  function writeMarketplaceFiles(marketplacePath, knownPath, marketplace, known, write2 = writeJson) {
69868
70286
  const previous3 = [marketplacePath, knownPath].map((filePath) => {
69869
70287
  try {
@@ -69902,10 +70320,10 @@ var PLUGIN_ICON_URL = "https://raw.githubusercontent.com/btspoony/mstar-harness/
69902
70320
  var GITHUB_REPO2 = "btspoony/mstar-harness";
69903
70321
  var GITHUB_REF = "main";
69904
70322
  var ZCODE_PLUGIN_CHECKOUT_PROJECT2 = ".zcode/plugin-checkout";
69905
- var ZCODE_PLUGINS_ROOT = path35.join(os11.homedir(), ".zcode", "cli", "plugins");
69906
- var KNOWN_MARKETPLACES_PATH = path35.join(ZCODE_PLUGINS_ROOT, "known_marketplaces.json");
69907
- var MARKETPLACE_DIR = path35.join(ZCODE_PLUGINS_ROOT, "marketplaces", MARKETPLACE_ID2);
69908
- var MARKETPLACE_JSON_PATH = path35.join(MARKETPLACE_DIR, "marketplace.json");
70323
+ var ZCODE_PLUGINS_ROOT = path36.join(os11.homedir(), ".zcode", "cli", "plugins");
70324
+ var KNOWN_MARKETPLACES_PATH = path36.join(ZCODE_PLUGINS_ROOT, "known_marketplaces.json");
70325
+ var MARKETPLACE_DIR = path36.join(ZCODE_PLUGINS_ROOT, "marketplaces", MARKETPLACE_ID2);
70326
+ var MARKETPLACE_JSON_PATH = path36.join(MARKETPLACE_DIR, "marketplace.json");
69909
70327
  var GITHUB_SOURCE = { source: "github", repo: GITHUB_REPO2, ref: GITHUB_REF };
69910
70328
  function nowIso() {
69911
70329
  return new Date().toISOString();
@@ -69960,7 +70378,7 @@ function runInit5(scope, dryRun) {
69960
70378
  const notes = ensureLocalHarnessRepo(dryRun);
69961
70379
  const projectRoot = resolveProjectRoot2();
69962
70380
  if (scope === "project") {
69963
- const checkoutPath = path35.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT2);
70381
+ const checkoutPath = path36.join(projectRoot, ZCODE_PLUGIN_CHECKOUT_PROJECT2);
69964
70382
  notes.push(...ensureGitCheckout(REPO_URL, checkoutPath, dryRun));
69965
70383
  notes.push(`Materialized local ZCode plugin checkout at ${ZCODE_PLUGIN_CHECKOUT_PROJECT2} for smoke checks (the registered marketplace still points at the github repo).`);
69966
70384
  }
@@ -70042,6 +70460,41 @@ import { spawn as spawn4 } from "node:child_process";
70042
70460
  import { constants as constants7 } from "node:os";
70043
70461
  init_engine();
70044
70462
 
70463
+ // src/schema-branches.ts
70464
+ function unionBranchSchemas(root) {
70465
+ const branches = [];
70466
+ const pending = [root];
70467
+ while (pending.length > 0) {
70468
+ const candidate = pending.pop();
70469
+ if (candidate === null || typeof candidate !== "object")
70470
+ continue;
70471
+ const schema3 = candidate;
70472
+ branches.push(schema3);
70473
+ for (const keyword of ["anyOf", "oneOf"]) {
70474
+ const alternatives = schema3[keyword];
70475
+ if (Array.isArray(alternatives))
70476
+ pending.push(...alternatives);
70477
+ }
70478
+ }
70479
+ return branches;
70480
+ }
70481
+ function inputFields(root) {
70482
+ const fields = new Map;
70483
+ for (const branch of unionBranchSchemas(root)) {
70484
+ const properties = branch.properties;
70485
+ if (properties === null || typeof properties !== "object")
70486
+ continue;
70487
+ for (const [key, property] of Object.entries(properties)) {
70488
+ if (fields.has(key))
70489
+ continue;
70490
+ if (property === null || typeof property !== "object")
70491
+ continue;
70492
+ fields.set(key, property);
70493
+ }
70494
+ }
70495
+ return fields;
70496
+ }
70497
+
70045
70498
  // src/sdd-evidence.ts
70046
70499
  init_engine();
70047
70500
  import { execFileSync as execFileSync10, spawn as spawn3 } from "node:child_process";
@@ -71380,11 +71833,11 @@ async function verifySddEvidence2(invocation) {
71380
71833
 
71381
71834
  // src/plugin-version-alignment.ts
71382
71835
  import os13 from "node:os";
71383
- import path36 from "node:path";
71836
+ import path37 from "node:path";
71384
71837
  function ompEntriesInScope(plugins, scope, projectRoot) {
71385
71838
  if (projectRoot === undefined)
71386
71839
  return plugins;
71387
- const projectPluginsPrefix = path36.join(path36.resolve(projectRoot), ".omp", "plugins") + path36.sep;
71840
+ const projectPluginsPrefix = path37.join(path37.resolve(projectRoot), ".omp", "plugins") + path37.sep;
71388
71841
  const inScope = [];
71389
71842
  const unscoped = [];
71390
71843
  for (const entry of plugins) {
@@ -71393,7 +71846,7 @@ function ompEntriesInScope(plugins, scope, projectRoot) {
71393
71846
  unscoped.push(entry);
71394
71847
  continue;
71395
71848
  }
71396
- const inProject = path36.resolve(entryPath).startsWith(projectPluginsPrefix);
71849
+ const inProject = path37.resolve(entryPath).startsWith(projectPluginsPrefix);
71397
71850
  if (scope === "project" ? inProject : !inProject)
71398
71851
  inScope.push(entry);
71399
71852
  }
@@ -71428,7 +71881,7 @@ function detectInstalledPluginVersion(target, scope = "project") {
71428
71881
  discovered = detectOmpPluginVersion(scope);
71429
71882
  break;
71430
71883
  case "dsh":
71431
- discovered = detectDshPluginVersion(process.env[DSH_HOME_ENV] ?? path36.join(os13.homedir(), DSH_HOME_SUBDIR));
71884
+ discovered = detectDshPluginVersion(process.env[DSH_HOME_ENV] ?? path37.join(os13.homedir(), DSH_HOME_SUBDIR));
71432
71885
  break;
71433
71886
  case "kimi":
71434
71887
  discovered = detectKimiPluginVersion();
@@ -71467,8 +71920,8 @@ function usageEnvelope(command7, message, details) {
71467
71920
  const diagnostics = Array.isArray(details?.diagnostics) ? details.diagnostics : [];
71468
71921
  const rootCommand = command7 === "mstar";
71469
71922
  const route = diagnostics.find((entry) => entry.helpRoute !== undefined)?.helpRoute ?? (rootCommand ? "mstar --help" : `mstar ${command7.replaceAll(".", " ")} --help`);
71470
- const diagnostic = diagnostics.find((entry) => entry.usage !== undefined);
71471
- const recoveryUsage = typeof diagnostic?.usage === "string" ? ` Correct usage: ${diagnostic.usage}.` : "";
71923
+ const diagnostic2 = diagnostics.find((entry) => entry.usage !== undefined);
71924
+ const recoveryUsage = typeof diagnostic2?.usage === "string" ? ` Correct usage: ${diagnostic2.usage}.` : "";
71472
71925
  const rejected2 = diagnostics.find((entry) => entry.path !== undefined && entry.expected !== undefined && entry.received !== undefined);
71473
71926
  return refusalEnvelope({
71474
71927
  command: command7,
@@ -71514,9 +71967,9 @@ function parserDiagnostic(error62, argv) {
71514
71967
  const unknown2 = error62.code === "commander.unknownOption";
71515
71968
  const excess = error62.code === "commander.excessArguments";
71516
71969
  const rejectedIndex = definition3 === undefined ? undefined : excess ? excessArgumentIndex(argv, definition3) : !unknown2 && !missingValue || quoted === undefined ? undefined : rejectedOptionIndex(argv, definition3, quoted, missingValue ? option : undefined);
71517
- const path30 = field ?? (excess && rejectedIndex !== undefined ? `argv[${rejectedIndex}]` : undefined);
71970
+ const path31 = field ?? (excess && rejectedIndex !== undefined ? `argv[${rejectedIndex}]` : undefined);
71518
71971
  return {
71519
- ...path30 === undefined ? {} : { path: path30 },
71972
+ ...path31 === undefined ? {} : { path: path31 },
71520
71973
  ...unknown2 ? { expected: "recognized option", received: quoted ?? "unknown option" } : {},
71521
71974
  ...missingValue && option !== undefined ? { expected: "option value", received: "missing value" } : {},
71522
71975
  ...option === undefined ? {} : { flag: option.flags },
@@ -71626,20 +72079,13 @@ function optionKey(flags2) {
71626
72079
  }
71627
72080
  function optionJsonSchema(definition3, key) {
71628
72081
  const schemas4 = [];
71629
- const pending = [definition3.input.toJSONSchema()];
71630
- while (pending.length > 0) {
71631
- const schema3 = pending.pop();
71632
- if (schema3 === null || typeof schema3 !== "object")
72082
+ for (const branch of unionBranchSchemas(definition3.input.toJSONSchema())) {
72083
+ const properties = branch.properties;
72084
+ if (properties === null || typeof properties !== "object")
71633
72085
  continue;
71634
- if ("properties" in schema3 && schema3.properties !== null && typeof schema3.properties === "object") {
71635
- const property = schema3.properties[key];
71636
- if (property !== undefined && typeof property === "object" && property !== null)
71637
- schemas4.push(property);
71638
- }
71639
- if ("anyOf" in schema3 && Array.isArray(schema3.anyOf))
71640
- pending.push(...schema3.anyOf);
71641
- if ("oneOf" in schema3 && Array.isArray(schema3.oneOf))
71642
- pending.push(...schema3.oneOf);
72086
+ const property = properties[key];
72087
+ if (property !== undefined && typeof property === "object" && property !== null)
72088
+ schemas4.push(property);
71643
72089
  }
71644
72090
  if (schemas4.length === 0)
71645
72091
  return {};
@@ -71666,11 +72112,6 @@ function renderCommandContract(definition3, route, descriptor = getCommandSchema
71666
72112
  if (route === "cli" && definition3.cli.options.some((option) => option.context === "sessionId")) {
71667
72113
  lines.push("Session identity resolves --session-id first, then the launched session's minted MSTAR_EXECUTION_IDENTITY, then DSH_SESSION_ID, then the ambient MSTAR_HOST_SESSION_ID (empty/whitespace ignored), else unset. For token-authorized writes it is transport-resolved attribution, not authorization: the acquired coordinator session/binding authorizes the write, and an explicit session reference is a checked constraint.");
71668
72114
  }
71669
- if (route === "mcp") {
71670
- const argumentTokens = descriptor.cli.arguments.map((argument) => argument.required ? ` <${argument.key}${argument.variadic ? "..." : ""}>` : ` [${argument.key}${argument.variadic ? "..." : ""}]`).join("");
71671
- const optionTokens = descriptor.cli.options.map((option) => ` ${option.flags}`).join("");
71672
- lines.push(`CLI: mstar ${descriptor.cli.path.join(" ")}${argumentTokens}${optionTokens}`);
71673
- }
71674
72115
  const sessionSelector = definition3.cli.options.find((option) => option.context === "sessionId")?.key;
71675
72116
  const requiredInputs = route === "mcp" && sessionSelector !== undefined ? descriptor.required.filter((field) => field !== sessionSelector) : descriptor.required;
71676
72117
  const requiredLine = requiredInputs.length === 0 ? undefined : `Required inputs: ${requiredInputs.join(", ")}`;
@@ -71710,17 +72151,12 @@ function renderCommandContract(definition3, route, descriptor = getCommandSchema
71710
72151
  lines.push(`${route.toUpperCase()} input alternatives: ${cardinality} of ${members2.join(" | ")}${condition === undefined ? "" : ` when ${condition.field}${condition.equals !== undefined ? `=${JSON.stringify(condition.equals)}` : condition.present === false ? " is absent" : " is present"}`}`);
71711
72152
  }
71712
72153
  const inputProperties = new Set;
71713
- const schemas4 = [descriptor.input];
71714
- while (schemas4.length > 0) {
71715
- const schema3 = schemas4.pop();
71716
- if (schema3 === null || typeof schema3 !== "object")
72154
+ for (const branch of unionBranchSchemas(descriptor.input)) {
72155
+ const properties = branch.properties;
72156
+ if (properties === null || typeof properties !== "object")
71717
72157
  continue;
71718
- if ("properties" in schema3 && schema3.properties !== null && typeof schema3.properties === "object") {
71719
- for (const key of Object.keys(schema3.properties))
71720
- inputProperties.add(key);
71721
- }
71722
- if ("anyOf" in schema3 && Array.isArray(schema3.anyOf))
71723
- schemas4.push(...schema3.anyOf);
72158
+ for (const key of Object.keys(properties))
72159
+ inputProperties.add(key);
71724
72160
  }
71725
72161
  const payloadKeys = Object.keys(descriptor.payloadSchemas);
71726
72162
  const payloadFields = payloadKeys.filter((key) => inputProperties.has(key));
@@ -72109,7 +72545,7 @@ function registerCliCommands(program2, definitions2, baseContext) {
72109
72545
  for (const field of Object.keys(definition3.payloads ?? {}))
72110
72546
  delete independentInput[field];
72111
72547
  const admission = admitCommandInput(definition3, independentInput, getCommandSchemas([definition3])[0]);
72112
- const admissionDiagnostics = admission.success ? [] : (admission.envelope.details?.diagnostics ?? []).filter((diagnostic) => typeof diagnostic.path !== "string" || !Object.keys(definition3.payloads ?? {}).some((field) => diagnostic.path === field || diagnostic.path?.startsWith(`${field}.`)));
72548
+ const admissionDiagnostics = admission.success ? [] : (admission.envelope.details?.diagnostics ?? []).filter((diagnostic2) => typeof diagnostic2.path !== "string" || !Object.keys(definition3.payloads ?? {}).some((field) => diagnostic2.path === field || diagnostic2.path?.startsWith(`${field}.`)));
72113
72549
  writeEnvelope(usageEnvelope(definition3.id, "Invalid command payload.", {
72114
72550
  diagnostics: [...payload2.diagnostics, ...admissionDiagnostics]
72115
72551
  }));
@@ -72164,7 +72600,7 @@ function registerCliCommands(program2, definitions2, baseContext) {
72164
72600
  import fs22 from "node:fs";
72165
72601
  import { execFileSync as execFileSync11 } from "node:child_process";
72166
72602
  import { tmpdir as tmpdir2 } from "node:os";
72167
- import path37 from "node:path";
72603
+ import path38 from "node:path";
72168
72604
  var CLI_NAME = "mstar-harness";
72169
72605
  var CLI_PACKAGE = "@mstar-harness/cli";
72170
72606
  var LATEST_PROBE_TIMEOUT_MS = 2000;
@@ -72190,11 +72626,11 @@ function resolveTrustedNpm() {
72190
72626
  let checkout = null;
72191
72627
  let dir = process.cwd();
72192
72628
  for (;; ) {
72193
- if (fs22.existsSync(path37.join(dir, ".git"))) {
72629
+ if (fs22.existsSync(path38.join(dir, ".git"))) {
72194
72630
  checkout = dir;
72195
72631
  break;
72196
72632
  }
72197
- const parent = path37.dirname(dir);
72633
+ const parent = path38.dirname(dir);
72198
72634
  if (parent === dir)
72199
72635
  break;
72200
72636
  dir = parent;
@@ -72209,7 +72645,7 @@ function resolveTrustedNpm() {
72209
72645
  }
72210
72646
  })();
72211
72647
  const insideCheckout = (candidate) => {
72212
- if (candidate.split(path37.sep).join("/").includes("node_modules/.bin"))
72648
+ if (candidate.split(path38.sep).join("/").includes("node_modules/.bin"))
72213
72649
  return true;
72214
72650
  if (resolvedCheckout === null)
72215
72651
  return false;
@@ -72217,15 +72653,15 @@ function resolveTrustedNpm() {
72217
72653
  try {
72218
72654
  resolved = fs22.realpathSync(candidate);
72219
72655
  } catch {}
72220
- return resolved === resolvedCheckout || resolved.startsWith(resolvedCheckout + path37.sep);
72656
+ return resolved === resolvedCheckout || resolved.startsWith(resolvedCheckout + path38.sep);
72221
72657
  };
72222
- for (const entry of (process.env["PATH"] ?? "").split(path37.delimiter)) {
72658
+ for (const entry of (process.env["PATH"] ?? "").split(path38.delimiter)) {
72223
72659
  if (entry === "")
72224
72660
  continue;
72225
- const candidateDir = path37.resolve(entry);
72661
+ const candidateDir = path38.resolve(entry);
72226
72662
  if (insideCheckout(candidateDir))
72227
72663
  continue;
72228
- const candidate = path37.join(candidateDir, executable);
72664
+ const candidate = path38.join(candidateDir, executable);
72229
72665
  if (fs22.existsSync(candidate))
72230
72666
  return candidate;
72231
72667
  }
@@ -72235,9 +72671,9 @@ function resolveTrustedNpm() {
72235
72671
  function neutralNpmConfigs() {
72236
72672
  if (neutralConfigs !== null)
72237
72673
  return neutralConfigs;
72238
- const dir = fs22.mkdtempSync(path37.join(tmpdir2(), "mstar-npm-config-"));
72239
- const user = path37.join(dir, "user-npmrc");
72240
- const global = path37.join(dir, "global-npmrc");
72674
+ const dir = fs22.mkdtempSync(path38.join(tmpdir2(), "mstar-npm-config-"));
72675
+ const user = path38.join(dir, "user-npmrc");
72676
+ const global = path38.join(dir, "global-npmrc");
72241
72677
  fs22.writeFileSync(user, "");
72242
72678
  fs22.writeFileSync(global, "");
72243
72679
  neutralConfigs = { user, global };
@@ -72318,8 +72754,7 @@ function ensureGlobalCli(opts) {
72318
72754
  import { isAbsolute as isAbsolute21 } from "node:path";
72319
72755
 
72320
72756
  // src/mcp/stdio.ts
72321
- init_engine();
72322
- import { dirname as dirname24 } from "node:path";
72757
+ import { dirname as dirname24, resolve as resolve25 } from "node:path";
72323
72758
 
72324
72759
  // ../../node_modules/.bun/@modelcontextprotocol+server@2.1.0/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
72325
72760
  var __create2 = Object.create;
@@ -75968,9 +76403,9 @@ var rev2026Codec = {
75968
76403
  const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3);
75969
76404
  if (!parsed.success)
75970
76405
  for (const issue2 of parsed.error.issues) {
75971
- const path30 = issue2.path.map(String);
75972
- const key = path30.length > 0 ? path30.join(".") : "_meta";
75973
- if (path30.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing"))
76406
+ const path31 = issue2.path.map(String);
76407
+ const key = path31.length > 0 ? path31.join(".") : "_meta";
76408
+ if (path31.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing"))
75974
76409
  continue;
75975
76410
  issues.push({
75976
76411
  key,
@@ -76305,28 +76740,28 @@ var PERMITTED_X_MCP_HEADER_TYPES = new Set([
76305
76740
  function scanXMcpHeaderDeclarations(inputSchema10) {
76306
76741
  const declarations = [];
76307
76742
  const seenLower = /* @__PURE__ */ new Map;
76308
- const visit2 = (node3, path30, reachable) => {
76743
+ const visit2 = (node3, path31, reachable) => {
76309
76744
  if (node3 === null || typeof node3 !== "object")
76310
76745
  return;
76311
76746
  const schema3 = node3;
76312
76747
  if (X_MCP_HEADER_KEY in schema3) {
76313
- if (!reachable || path30.length === 0)
76314
- return `${pathName(path30)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
76748
+ if (!reachable || path31.length === 0)
76749
+ return `${pathName(path31)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
76315
76750
  const raw = schema3[X_MCP_HEADER_KEY];
76316
76751
  if (typeof raw !== "string" || raw.length === 0)
76317
- return `${pathName(path30)}: x-mcp-header MUST be a non-empty string`;
76752
+ return `${pathName(path31)}: x-mcp-header MUST be a non-empty string`;
76318
76753
  if (!RFC9110_TOKEN.test(raw))
76319
- return `${pathName(path30)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
76754
+ return `${pathName(path31)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
76320
76755
  const type = typeof schema3.type === "string" ? schema3.type : undefined;
76321
76756
  if (type === undefined || !PERMITTED_X_MCP_HEADER_TYPES.has(type))
76322
- return `${pathName(path30)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
76757
+ return `${pathName(path31)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
76323
76758
  const lower = raw.toLowerCase();
76324
76759
  const prior = seenLower.get(lower);
76325
76760
  if (prior !== undefined)
76326
76761
  return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
76327
76762
  seenLower.set(lower, raw);
76328
76763
  declarations.push({
76329
- path: path30,
76764
+ path: path31,
76330
76765
  headerName: raw,
76331
76766
  type
76332
76767
  });
@@ -76334,7 +76769,7 @@ function scanXMcpHeaderDeclarations(inputSchema10) {
76334
76769
  const properties = schema3.properties;
76335
76770
  if (properties !== null && typeof properties === "object")
76336
76771
  for (const [key, child] of Object.entries(properties)) {
76337
- const fault$1 = visit2(child, [...path30, key], reachable);
76772
+ const fault$1 = visit2(child, [...path31, key], reachable);
76338
76773
  if (fault$1 !== undefined)
76339
76774
  return fault$1;
76340
76775
  }
@@ -76344,7 +76779,7 @@ function scanXMcpHeaderDeclarations(inputSchema10) {
76344
76779
  continue;
76345
76780
  const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
76346
76781
  for (const branch of branches) {
76347
- const fault$1 = visit2(branch, [...path30, `<${k}>`], false);
76782
+ const fault$1 = visit2(branch, [...path31, `<${k}>`], false);
76348
76783
  if (fault$1 !== undefined)
76349
76784
  return fault$1;
76350
76785
  }
@@ -76385,8 +76820,8 @@ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([
76385
76820
  "$defs",
76386
76821
  "definitions"
76387
76822
  ]);
76388
- function pathName(path30) {
76389
- return path30.length === 0 ? "<root>" : path30.join(".");
76823
+ function pathName(path31) {
76824
+ return path31.length === 0 ? "<root>" : path31.join(".");
76390
76825
  }
76391
76826
  var HEADER_MISMATCH_ERROR_CODE = -32020;
76392
76827
  var INBOUND_VALIDATION_LADDER = [
@@ -76691,7 +77126,7 @@ var PROPERTY_KEYS_BY_TYPE = {
76691
77126
  array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])
76692
77127
  };
76693
77128
  var SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options);
76694
- function walkProperty(node3, path30, vendor, unsupported) {
77129
+ function walkProperty(node3, path31, vendor, unsupported) {
76695
77130
  if (!isJsonObject(node3))
76696
77131
  return node3;
76697
77132
  const allowedKeys = typeof node3.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node3.type) ? PROPERTY_KEYS_BY_TYPE[node3.type] : undefined;
@@ -76705,9 +77140,9 @@ function walkProperty(node3, path30, vendor, unsupported) {
76705
77140
  if (!SUPPORTED_STRING_FORMATS.has(node3.format))
76706
77141
  pruned[key] = value;
76707
77142
  else if (typeof value !== "string" || !isLibraryFormatPattern(node3.format, value, vendor))
76708
- unsupported.push(`${path30}.${key}`);
77143
+ unsupported.push(`${path31}.${key}`);
76709
77144
  } else
76710
- unsupported.push(`${path30}.${key}`);
77145
+ unsupported.push(`${path31}.${key}`);
76711
77146
  return pruned;
76712
77147
  }
76713
77148
  function walkRequestedSchema(converted, vendor) {
@@ -76730,13 +77165,13 @@ function describeUnsupportedProperties(pruned, fallback) {
76730
77165
  const offenders = Object.entries(pruned.properties).filter(([, node3]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node3).success).map(([name]) => `properties.${name}`);
76731
77166
  return offenders.length > 0 ? offenders.join(", ") : fallback;
76732
77167
  }
76733
- function findDroppedConstraintPaths(original, parsed, path30 = "") {
77168
+ function findDroppedConstraintPaths(original, parsed, path31 = "") {
76734
77169
  if (Array.isArray(original) && Array.isArray(parsed))
76735
- return original.flatMap((item, index2) => findDroppedConstraintPaths(item, parsed[index2], `${path30}[${index2}]`));
77170
+ return original.flatMap((item, index2) => findDroppedConstraintPaths(item, parsed[index2], `${path31}[${index2}]`));
76736
77171
  if (!isJsonObject(original) || !isJsonObject(parsed))
76737
77172
  return [];
76738
77173
  return Object.entries(original).flatMap(([key, value]) => {
76739
- const childPath = path30 ? `${path30}.${key}` : key;
77174
+ const childPath = path31 ? `${path31}.${key}` : key;
76740
77175
  if (!Object.prototype.hasOwnProperty.call(parsed, key))
76741
77176
  return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];
76742
77177
  return findDroppedConstraintPaths(value, parsed[key], childPath);
@@ -81027,8 +81462,8 @@ var require_utils = /* @__PURE__ */ __commonJSMin((exports, module) => {
81027
81462
  ind++;
81028
81463
  return ind;
81029
81464
  }
81030
- function removeDotSegments(path30) {
81031
- let input2 = path30;
81465
+ function removeDotSegments(path31) {
81466
+ let input2 = path31;
81032
81467
  const output2 = [];
81033
81468
  let nextSlash = -1;
81034
81469
  let len = 0;
@@ -81202,8 +81637,8 @@ var require_schemes = /* @__PURE__ */ __commonJSMin((exports, module) => {
81202
81637
  wsComponent.secure = undefined;
81203
81638
  }
81204
81639
  if (wsComponent.resourceName) {
81205
- const [path30, query] = wsComponent.resourceName.split("?");
81206
- wsComponent.path = path30 && path30 !== "/" ? path30 : undefined;
81640
+ const [path31, query] = wsComponent.resourceName.split("?");
81641
+ wsComponent.path = path31 && path31 !== "/" ? path31 : undefined;
81207
81642
  wsComponent.query = query;
81208
81643
  wsComponent.resourceName = undefined;
81209
81644
  }
@@ -87557,6 +87992,9 @@ function withToolCorrection(transport, catalog) {
87557
87992
  // ../../node_modules/.bun/@modelcontextprotocol+server@2.1.0/node_modules/@modelcontextprotocol/server/dist/index.mjs
87558
87993
  var DEFAULT_MAX_REQUEST_BODY_SIZE = 4 * 1024 * 1024;
87559
87994
 
87995
+ // src/mcp/register.ts
87996
+ import { resolve as resolve23 } from "node:path";
87997
+
87560
87998
  // src/mcp/effects.ts
87561
87999
  init_engine();
87562
88000
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
@@ -87702,9 +88140,9 @@ function writeRecordAtomic2(sddDir, runDir, record3) {
87702
88140
  const rel = relative11(sddDir, recordPath);
87703
88141
  if (rel === "" || rel.startsWith("..") || isAbsolute20(rel))
87704
88142
  throw new Error("evidence record path escaped the SDD directory");
87705
- for (const path30 of [sddDir, dirname23(runDir), runDir]) {
87706
- if (!lstatSync14(path30).isDirectory())
87707
- throw new Error(`evidence path is not a real directory: ${path30}`);
88143
+ for (const path31 of [sddDir, dirname23(runDir), runDir]) {
88144
+ if (!lstatSync14(path31).isDirectory())
88145
+ throw new Error(`evidence path is not a real directory: ${path31}`);
87708
88146
  }
87709
88147
  const fd = openSync9(tempPath, "wx", 384);
87710
88148
  try {
@@ -87714,9 +88152,9 @@ function writeRecordAtomic2(sddDir, runDir, record3) {
87714
88152
  closeSync9(fd);
87715
88153
  }
87716
88154
  try {
87717
- for (const path30 of [sddDir, dirname23(runDir), runDir]) {
87718
- if (!lstatSync14(path30).isDirectory())
87719
- throw new Error(`evidence path changed before record commit: ${path30}`);
88155
+ for (const path31 of [sddDir, dirname23(runDir), runDir]) {
88156
+ if (!lstatSync14(path31).isDirectory())
88157
+ throw new Error(`evidence path changed before record commit: ${path31}`);
87720
88158
  }
87721
88159
  try {
87722
88160
  if (!lstatSync14(recordPath).isFile())
@@ -87734,24 +88172,24 @@ function writeRecordAtomic2(sddDir, runDir, record3) {
87734
88172
  function hash3(bytes) {
87735
88173
  return createHash24("sha256").update(bytes).digest("hex");
87736
88174
  }
87737
- function writeExclusiveFile(path30, bytes) {
87738
- const fd = openSync9(path30, "wx", 384);
88175
+ function writeExclusiveFile(path31, bytes) {
88176
+ const fd = openSync9(path31, "wx", 384);
87739
88177
  try {
87740
88178
  writeFileSync8(fd, bytes);
87741
88179
  } finally {
87742
88180
  closeSync9(fd);
87743
88181
  }
87744
88182
  }
87745
- function replaceFileAtomically(path30, bytes) {
87746
- const parent = dirname23(path30);
88183
+ function replaceFileAtomically(path31, bytes) {
88184
+ const parent = dirname23(path31);
87747
88185
  if (!lstatSync14(parent).isDirectory())
87748
88186
  throw new Error(`artifact parent is not a real directory: ${parent}`);
87749
- const temporary = join35(parent, `.${basename17(path30)}-${randomUUID11()}.tmp`);
88187
+ const temporary = join35(parent, `.${basename17(path31)}-${randomUUID11()}.tmp`);
87750
88188
  writeExclusiveFile(temporary, bytes);
87751
88189
  try {
87752
88190
  if (!lstatSync14(parent).isDirectory())
87753
88191
  throw new Error(`artifact parent changed before commit: ${parent}`);
87754
- renameSync5(temporary, path30);
88192
+ renameSync5(temporary, path31);
87755
88193
  } catch (error62) {
87756
88194
  rmSync3(temporary, { force: true });
87757
88195
  throw error62;
@@ -87880,19 +88318,19 @@ async function captureEvidence(requestPath, argv, invocation) {
87880
88318
  throw error62;
87881
88319
  }
87882
88320
  }
87883
- function artifactFact2(path30) {
88321
+ function artifactFact2(path31) {
87884
88322
  try {
87885
- const stat = lstatSync14(path30);
88323
+ const stat = lstatSync14(path31);
87886
88324
  if (stat.isSymbolicLink())
87887
- return { path: basename17(path30), state: "symlink", bytes: null, sha256: null };
88325
+ return { path: basename17(path31), state: "symlink", bytes: null, sha256: null };
87888
88326
  if (!stat.isFile())
87889
- return { path: basename17(path30), state: "other", bytes: null, sha256: null };
88327
+ return { path: basename17(path31), state: "other", bytes: null, sha256: null };
87890
88328
  if (stat.size > MAX_CAPTURE_LOG_BYTES)
87891
- return { path: basename17(path30), state: "regular", bytes: stat.size, sha256: null };
87892
- const bytes = readFileSync27(path30);
87893
- return { path: basename17(path30), state: "regular", bytes: bytes.byteLength, sha256: hash3(bytes) };
88329
+ return { path: basename17(path31), state: "regular", bytes: stat.size, sha256: null };
88330
+ const bytes = readFileSync27(path31);
88331
+ return { path: basename17(path31), state: "regular", bytes: bytes.byteLength, sha256: hash3(bytes) };
87894
88332
  } catch (error62) {
87895
- return error62.code === "ENOENT" ? { path: basename17(path30), state: "missing", bytes: null, sha256: null } : { path: basename17(path30), state: "unreadable", bytes: null, sha256: null };
88333
+ return error62.code === "ENOENT" ? { path: basename17(path31), state: "missing", bytes: null, sha256: null } : { path: basename17(path31), state: "unreadable", bytes: null, sha256: null };
87896
88334
  }
87897
88335
  }
87898
88336
  function readTargetRequest(pathValue) {
@@ -88072,6 +88510,180 @@ function spawnBounded(request, allowTruncation = false, maxStreamBytes = MAX_STR
88072
88510
  });
88073
88511
  }
88074
88512
 
88513
+ // src/mcp/fold.ts
88514
+ function familyOf2(definition3) {
88515
+ const segment = definition3.cli.path[0];
88516
+ if (segment !== undefined)
88517
+ return segment;
88518
+ const dot = definition3.id.indexOf(".");
88519
+ return dot === -1 ? definition3.id : definition3.id.slice(0, dot);
88520
+ }
88521
+ function actionOf2(commandId) {
88522
+ const dot = commandId.indexOf(".");
88523
+ return dot === -1 ? commandId : commandId.slice(dot + 1);
88524
+ }
88525
+ function familyToolName(family) {
88526
+ return `mstar_${family.replace(/[.-]/g, "_")}`;
88527
+ }
88528
+ var FAMILY_PURPOSE = {
88529
+ status: "Lifecycle, findings and tech-debt status reads, closes and retirements.",
88530
+ persist: "Read and replace persisted review or JSON documents.",
88531
+ migrate: "Retired legacy-plan migration; refuses without mutating.",
88532
+ iteration: "Iteration phase gates, push cadence and registration.",
88533
+ plan: "Coordinator plan rows: bind, progress, complete and issue links. bind writes the engine row only; a dsh-coordinating session that needs dsh-local ledger attribution uses the native mstar_plan_bind.",
88534
+ session: "Launch or recover a coordinator session identity.",
88535
+ workflow: "Workflow lifecycle: register, evidence, phase, policy and branch anchors.",
88536
+ issue: "Issue store: capture, triage, closure and links.",
88537
+ milestone: "Project milestones: add, update, assign issues and read rollups.",
88538
+ catalog: "Catalog rows: discover, import, register, link, reconcile and purge.",
88539
+ roadmap: "Project roadmap: reviewed Markdown import, export and replace.",
88540
+ store: "Execution store: init, upgrade, migrate, backup, restore and export.",
88541
+ "workflow-note": "Workflow note ledger: append notes and read coverage facts.",
88542
+ sdd: "SDD task evidence: workspace, task briefs, review packages, context and exec.",
88543
+ audit: "Codebase audit: scaffold a review report, secret-scan and supply-chain checks.",
88544
+ dispatch: "Validate an Assignment's fields and branch protection.",
88545
+ worktree: "Worktree isolation: entry/plan checks, QC alignment and guarded cleanup.",
88546
+ review: "Map an execution mode to QC seats and assert tri identity.",
88547
+ lint: "Lint harness artifacts by content type.",
88548
+ "design-md": "Validate DESIGN.md tokens, light/dark parity and completeness.",
88549
+ compound: "Validate a knowledge document and its index scope.",
88550
+ skill: "Lint a skill directory.",
88551
+ roles: "Validate the role mapping and load-order corpus.",
88552
+ qc: "Validate a saved QC seat report.",
88553
+ "pr-review": "PR review: size, seat prompt, tally, report path, worktree and post.",
88554
+ harness: "Scaffold harness directories and the default project.",
88555
+ doctor: "Validate the host setup for one supported target.",
88556
+ plugin: "Validate a plugin package against Agent Plugins v1.0.0.",
88557
+ path: "Resolve harness, specs, workflow, project and review directories.",
88558
+ host: "Host detection and skill-root resolution.",
88559
+ dashboard: "Start the read-only Morning Star dashboard on 127.0.0.1.",
88560
+ schema: "Bounded command-contract discovery: one leaf command, a family list or a payload schema.",
88561
+ report: "Create an offline, redacted issue-report draft."
88562
+ };
88563
+ function publishedFields(input2) {
88564
+ return Object.fromEntries(inputFields(input2));
88565
+ }
88566
+ function requiredFields(input2) {
88567
+ return Array.isArray(input2.required) ? input2.required.filter((field) => typeof field === "string") : [];
88568
+ }
88569
+ function selectorAlternatives(input2) {
88570
+ if (requiredFields(input2).length > 0)
88571
+ return [];
88572
+ const branches = ["anyOf", "oneOf"].flatMap((keyword) => Array.isArray(input2[keyword]) ? input2[keyword] : []).map((branch) => requiredFields(branch !== null && typeof branch === "object" ? branch : {})).filter((fields) => fields.length > 0);
88573
+ return branches.length >= 2 ? branches.flat() : [];
88574
+ }
88575
+ function conflictingDeclarations(first, other) {
88576
+ const same = (key) => JSON.stringify(first[key]) === JSON.stringify(other[key]);
88577
+ if (!same("type") || !same("enum") || !same("const"))
88578
+ return true;
88579
+ return Object.hasOwn(first, "properties") !== Object.hasOwn(other, "properties") || Object.hasOwn(first, "required") !== Object.hasOwn(other, "required");
88580
+ }
88581
+ function familyDescription(family, members2, actions2, perAction) {
88582
+ const lines = [FAMILY_PURPOSE[family] ?? `${family} commands.`];
88583
+ members2.forEach((member, index2) => {
88584
+ const required7 = requiredFields(member.input);
88585
+ const alternatives = selectorAlternatives(member.input);
88586
+ const payload2 = Object.keys(member.definition.payloads ?? {}).length === 0 ? "" : "; payload via mstar_schema";
88587
+ const requirement = alternatives.length > 0 ? `exactly one of ${alternatives.join(", ")}` : required7.length === 0 ? "no required fields" : required7.join(", ");
88588
+ lines.push(`- ${actions2[index2]}: ${requirement}${payload2}`);
88589
+ });
88590
+ if (perAction.length > 0)
88591
+ lines.push(`Varies by action: ${perAction.join(", ")} (mstar_schema).`);
88592
+ const example = members2[0].definition.id;
88593
+ lines.push(actions2[0] === family ? `Fields: mstar_schema {"action":"schema","command":"${example}"}.` : `Fields: mstar_schema {"action":"schema","command":"<family>.<action>"} (e.g. "${example}").`);
88594
+ return lines.join(`
88595
+ `);
88596
+ }
88597
+ function foldFamilyTools(members2) {
88598
+ const groups = new Map;
88599
+ for (const member of members2) {
88600
+ const family = familyOf2(member.definition);
88601
+ const group = groups.get(family);
88602
+ if (group === undefined)
88603
+ groups.set(family, [member]);
88604
+ else
88605
+ group.push(member);
88606
+ }
88607
+ const owners = new Map;
88608
+ const tools = [];
88609
+ for (const [family, group] of groups) {
88610
+ const toolName = familyToolName(family);
88611
+ const owner = owners.get(toolName);
88612
+ if (owner !== undefined) {
88613
+ throw new Error(`MCP tool name collision: ${toolName} (families ${owner} and ${family})`);
88614
+ }
88615
+ owners.set(toolName, family);
88616
+ const actions2 = group.map((member) => actionOf2(member.definition.id));
88617
+ const duplicate = actions2.find((action, index2) => actions2.indexOf(action) !== index2);
88618
+ if (duplicate !== undefined)
88619
+ throw new Error(`${family}: duplicate action ${JSON.stringify(duplicate)}`);
88620
+ const properties = { action: { type: "string", enum: actions2 } };
88621
+ const selectors = new Map;
88622
+ const acceptedFields = new Map;
88623
+ const perAction = new Set;
88624
+ const requirements = [{
88625
+ name: "action",
88626
+ ownership: "caller",
88627
+ route: "mcp",
88628
+ help: "the family action to run; every other field belongs to that action"
88629
+ }];
88630
+ for (const [index2, member] of group.entries()) {
88631
+ const fields = publishedFields(member.input);
88632
+ acceptedFields.set(actions2[index2], Object.keys(fields));
88633
+ for (const [key, property] of Object.entries(fields)) {
88634
+ if (key === "action") {
88635
+ throw new Error(`${family}: ${member.definition.id} declares an "action" input, which the family selector owns`);
88636
+ }
88637
+ const published = properties[key];
88638
+ if (published === undefined)
88639
+ properties[key] = property;
88640
+ else if (conflictingDeclarations(published, property)) {
88641
+ perAction.add(key);
88642
+ }
88643
+ }
88644
+ const selector = member.selector;
88645
+ if (selector === undefined)
88646
+ continue;
88647
+ const accepting = selectors.get(selector.key) ?? [];
88648
+ accepting.push(actionOf2(member.definition.id));
88649
+ selectors.set(selector.key, accepting);
88650
+ if (properties[selector.key] === undefined)
88651
+ properties[selector.key] = { type: "string" };
88652
+ if (!requirements.some((entry) => entry.name === selector.key)) {
88653
+ requirements.push({
88654
+ name: selector.key,
88655
+ ownership: "caller",
88656
+ route: "mcp",
88657
+ help: "per-call session identity"
88658
+ });
88659
+ }
88660
+ }
88661
+ for (const key of perAction)
88662
+ delete properties[key];
88663
+ const familySelectors = [...selectors].map(([key, accepting]) => ({ key, actions: accepting }));
88664
+ tools.push({
88665
+ family,
88666
+ toolName,
88667
+ actions: actions2,
88668
+ definitions: group.map((member) => member.definition),
88669
+ selectors: familySelectors,
88670
+ acceptedFields,
88671
+ descriptorView: {
88672
+ type: "object",
88673
+ properties,
88674
+ required: ["action"],
88675
+ "x-mstar-requirements": requirements,
88676
+ ...familySelectors.length === 0 ? {} : { "x-mstar-selectors": familySelectors }
88677
+ },
88678
+ description: familyDescription(family, group, actions2, [...perAction])
88679
+ });
88680
+ }
88681
+ return tools;
88682
+ }
88683
+ function definitionForAction(family, action) {
88684
+ return family.definitions.find((definition3) => actionOf2(definition3.id) === action);
88685
+ }
88686
+
88075
88687
  // src/mcp/outcome.ts
88076
88688
  function validateCommandOutcome(definition3, envelope3) {
88077
88689
  const result = envelope3 !== null && typeof envelope3 === "object" ? envelope3 : null;
@@ -88117,14 +88729,19 @@ Recovery: ${recovery}`}`;
88117
88729
  }
88118
88730
 
88119
88731
  // src/mcp/register.ts
88120
- function mcpToolName(commandId) {
88121
- return `mstar_${commandId.replace(/[.-]/g, "_")}`;
88122
- }
88123
- function mcpInputContract(definition3, descriptor) {
88732
+ function mcpInputContract(definition3, descriptor, options2) {
88124
88733
  const input2 = definition3.input;
88125
88734
  const jsonSchema = descriptor.input;
88126
- if (!(input2 instanceof exports_external.ZodObject))
88127
- return { schema: input2, jsonSchema };
88735
+ const selector = definition3.cli.options.find((option) => option.context === "sessionId");
88736
+ const requiredRoots = options2.unpinnedRootRequired ? options2.rootInputs : [];
88737
+ if (!(input2 instanceof exports_external.ZodObject)) {
88738
+ const gatedRoots = requiredRoots.filter((field) => inputFields(jsonSchema).has(field));
88739
+ return {
88740
+ schema: input2,
88741
+ jsonSchema: gatedRoots.length === 0 ? jsonSchema : { ...jsonSchema, required: [...descriptor.required, ...gatedRoots] },
88742
+ unpinnedRootGate: gatedRoots
88743
+ };
88744
+ }
88128
88745
  const properties = { ...jsonSchema.properties };
88129
88746
  const composed = {};
88130
88747
  for (const [field, payload2] of Object.entries(definition3.payloads ?? {})) {
@@ -88134,9 +88751,12 @@ function mcpInputContract(definition3, descriptor) {
88134
88751
  properties[field] = descriptor.payloadSchemas[field];
88135
88752
  }
88136
88753
  const extended2 = Object.keys(composed).length === 0 ? input2 : input2.safeExtend(composed);
88137
- const selector = definition3.cli.options.find((option) => option.context === "sessionId");
88754
+ const requiredFields2 = new Set(descriptor.required);
88755
+ for (const field of requiredRoots)
88756
+ if (Object.hasOwn(properties, field))
88757
+ requiredFields2.add(field);
88138
88758
  const requiredShape = {};
88139
- for (const field of descriptor.required) {
88759
+ for (const field of requiredFields2) {
88140
88760
  if (field === selector?.key)
88141
88761
  continue;
88142
88762
  const declared = extended2.shape[field];
@@ -88144,7 +88764,7 @@ function mcpInputContract(definition3, descriptor) {
88144
88764
  requiredShape[field] = declared.unwrap();
88145
88765
  }
88146
88766
  let schema3 = Object.keys(requiredShape).length === 0 ? extended2 : extended2.safeExtend(requiredShape);
88147
- if (selector !== undefined) {
88767
+ if (selector !== undefined && options2.publishSelector) {
88148
88768
  schema3 = schema3.safeExtend({ [selector.key]: exports_external.string().optional() });
88149
88769
  properties[selector.key] = { type: "string" };
88150
88770
  }
@@ -88152,8 +88772,8 @@ function mcpInputContract(definition3, descriptor) {
88152
88772
  if (properties[field] !== undefined)
88153
88773
  properties[field] = { ...properties[field], default: value };
88154
88774
  }
88155
- const required7 = selector === undefined ? descriptor.required : descriptor.required.filter((field) => field !== selector.key);
88156
- const requirements = descriptor.requirements.filter((entry) => entry.route === "mcp");
88775
+ const required7 = selector === undefined ? [...requiredFields2] : [...requiredFields2].filter((field) => field !== selector.key);
88776
+ const requirements = descriptor.requirements.filter((entry) => entry.route === "mcp" && (options2.publishSelector || entry.name !== selector?.key));
88157
88777
  return {
88158
88778
  schema: schema3,
88159
88779
  jsonSchema: {
@@ -88161,14 +88781,16 @@ function mcpInputContract(definition3, descriptor) {
88161
88781
  required: required7,
88162
88782
  properties,
88163
88783
  "x-mstar-requirements": requirements
88164
- }
88784
+ },
88785
+ unpinnedRootGate: []
88165
88786
  };
88166
88787
  }
88167
- function declaresHarness(contract3) {
88168
- const properties = contract3.jsonSchema.properties;
88169
- return properties !== null && typeof properties === "object" && Object.hasOwn(properties, "harness");
88788
+ function rootInputsOf(definition3, descriptor) {
88789
+ if (definition3.rootInputs !== undefined)
88790
+ return definition3.rootInputs;
88791
+ return inputFields(descriptor.input).has("harness") ? ["harness"] : [];
88170
88792
  }
88171
- function handlerInput(definition3, input2, defaultHarness) {
88793
+ function handlerInput(definition3, input2, defaultHarness, harnessIsRoot) {
88172
88794
  if (input2 === null || typeof input2 !== "object")
88173
88795
  return input2;
88174
88796
  const record3 = input2;
@@ -88176,53 +88798,343 @@ function handlerInput(definition3, input2, defaultHarness) {
88176
88798
  const normalized = { ...record3 };
88177
88799
  for (const key of contextKeys)
88178
88800
  delete normalized[key];
88179
- const explicit = typeof normalized.harness === "string" && normalized.harness.trim() !== "";
88180
- if (defaultHarness !== undefined && !explicit)
88801
+ if (defaultHarness !== undefined && harnessIsRoot)
88181
88802
  normalized.harness = defaultHarness;
88182
88803
  return normalized;
88183
88804
  }
88184
- function normalizedBlankHarness(input2, defaultHarness) {
88185
- if (defaultHarness === undefined || input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88805
+ function normalizedRootInputs(rootInputs, input2, defaultHarness) {
88806
+ if (input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88186
88807
  return input2;
88187
88808
  const record3 = input2;
88188
- if (typeof record3.harness !== "string" || record3.harness.trim() !== "")
88809
+ const named = rootInputs.filter((field) => Object.hasOwn(record3, field));
88810
+ if (named.length === 0)
88189
88811
  return input2;
88190
- return { ...record3, harness: defaultHarness };
88812
+ const normalized = { ...record3 };
88813
+ for (const field of named) {
88814
+ if (defaultHarness !== undefined) {
88815
+ if (field === "harness")
88816
+ normalized[field] = defaultHarness;
88817
+ else
88818
+ delete normalized[field];
88819
+ continue;
88820
+ }
88821
+ const value = normalized[field];
88822
+ if (typeof value === "string" && value.trim() !== "")
88823
+ normalized[field] = resolve23(value);
88824
+ }
88825
+ return normalized;
88191
88826
  }
88192
- function registerMcpCommands(server, definitions2, resolveContext, services = [], onToolsRegistered) {
88193
- const connectionEffects = createMcpEffects(services);
88194
- const tools = definitions2.map((definition3) => ({ definition: definition3, name: mcpToolName(definition3.id) }));
88195
- const names = new Set;
88196
- for (const { definition: definition3, name } of tools) {
88197
- if (names.has(name)) {
88198
- throw new Error(`MCP tool name collision: ${name} (from command ${definition3.id})`);
88827
+ function callRootOf(rootInputs, input2) {
88828
+ if (input2 === null || typeof input2 !== "object")
88829
+ return;
88830
+ const record3 = input2;
88831
+ for (const field of rootInputs) {
88832
+ const value = record3[field];
88833
+ if (typeof value === "string" && value.trim() !== "")
88834
+ return value;
88835
+ }
88836
+ return;
88837
+ }
88838
+ function namedRoot(field, input2) {
88839
+ if (input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88840
+ return false;
88841
+ const value = input2[field];
88842
+ return typeof value === "string" && value.trim() !== "";
88843
+ }
88844
+ function unpinnedRootFacts(definition3, field) {
88845
+ return {
88846
+ message: `${definition3.id} needs the call's "${field}" selector: this MCP connection declared no control root, and the command resolves its root from that field`,
88847
+ recovery: `pass \`${field}\` naming this call's root directory (an absolute path, or one relative to the server's launch directory), or declare the root for the whole connection \u2014 \`mstar mcp --harness <absolute path>\`, or a non-blank MSTAR_HARNESS_DIR in the server environment \u2014 and no call needs the selector`,
88848
+ diagnostic: {
88849
+ path: field,
88850
+ code: "required",
88851
+ message: `${field} is required: this connection declared no control root`,
88852
+ expected: "present",
88853
+ received: "undefined"
88854
+ }
88855
+ };
88856
+ }
88857
+ function unpinnedRootRefusal(definition3, field, admission) {
88858
+ const facts = unpinnedRootFacts(definition3, field);
88859
+ const admissionDiagnostics = admission?.envelope.details?.diagnostics ?? [];
88860
+ return refusalEnvelope({
88861
+ command: definition3.id,
88862
+ status: "usage",
88863
+ code: "command.invalid-input",
88864
+ exitCode: 2,
88865
+ message: facts.message,
88866
+ helpRoute: `mstar schema --command ${definition3.id}`,
88867
+ recovery: facts.recovery,
88868
+ diagnostics: [facts.diagnostic, ...admissionDiagnostics]
88869
+ });
88870
+ }
88871
+ function callerIdentityFacts(definition3, selectors) {
88872
+ const cli = `mstar ${definition3.cli.path.join(" ")}`;
88873
+ const native = definition3.id === "plan.bind" ? "the dsh native tool `mstar_plan_bind` (its identity is the carrying session's `exec.agent.id`)" : undefined;
88874
+ const planGap = ["plan.prepare", "plan.progress", "plan.complete"].includes(definition3.id);
88875
+ return {
88876
+ message: `${definition3.id} cannot run on this MCP connection: a caller-declared session identity was supplied, and this server was not launched with --trust-caller-session-id. ` + "An MCP child process has no host-proven caller identity, so a sessionId on the wire cannot become a coordinator identity.",
88877
+ recovery: [
88878
+ "Drop `sessionId` on this connection; it is not a published field unless the launcher opts in.",
88879
+ ...native === undefined ? [] : [`The host-proven route for this operation is ${native}.`],
88880
+ `Otherwise run \`${cli}\` from the session's shell, which takes --session-id or MSTAR_HOST_SESSION_ID.`,
88881
+ ...planGap ? ["No dsh native tool covers plan prepare/progress/complete yet; the CLI is the only route for them."] : []
88882
+ ].join(" "),
88883
+ diagnostics: selectors.map((key) => ({
88884
+ path: key,
88885
+ code: "not_allowed",
88886
+ message: `${key} is not an input of this connection: it carries no host-proven caller identity`,
88887
+ expected: "omitted",
88888
+ received: "supplied"
88889
+ }))
88890
+ };
88891
+ }
88892
+ function suppliedSelectors(family, input2) {
88893
+ if (input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88894
+ return [];
88895
+ const record3 = input2;
88896
+ const declared = new Set;
88897
+ for (const member of family.definitions) {
88898
+ for (const option of member.cli.options) {
88899
+ if (option.context === "sessionId")
88900
+ declared.add(option.key);
88199
88901
  }
88200
- names.add(name);
88201
88902
  }
88202
- onToolsRegistered?.([...names]);
88203
- for (const { definition: definition3, name } of tools) {
88903
+ return [...declared].filter((key) => record3[key] !== undefined);
88904
+ }
88905
+ function strippedActionInput(input2) {
88906
+ if (input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88907
+ return input2;
88908
+ const { action: _action, ...rest } = input2;
88909
+ return rest;
88910
+ }
88911
+ function withoutFields(input2, fields) {
88912
+ if (fields.length === 0)
88913
+ return input2;
88914
+ if (input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88915
+ return input2;
88916
+ const rest = { ...input2 };
88917
+ for (const field of fields)
88918
+ delete rest[field];
88919
+ return rest;
88920
+ }
88921
+ function unknownActionRefusal(family, action, rejected2) {
88922
+ const listed = family.actions.map((entry) => JSON.stringify(entry)).join(" | ");
88923
+ const received = typeof action === "string" ? "supplied" : action === undefined ? "undefined" : typeof action;
88924
+ const keys = rejected2.map(sanitizeInputScalar);
88925
+ const dropped = keys.map((key) => JSON.stringify(key)).join(", ");
88926
+ const accepted = cappedFieldList(familyAcceptedFields(family));
88927
+ return refusalEnvelope({
88928
+ command: family.toolName,
88929
+ status: "usage",
88930
+ code: "command.invalid-input",
88931
+ exitCode: 2,
88932
+ message: `unknown action for ${family.toolName}; available actions: ${family.actions.join(", ")}` + (keys.length === 0 ? "" : `; no action of this family accepts the field${keys.length === 1 ? "" : "s"} ${dropped}`),
88933
+ helpRoute: `mstar schema --family ${family.family}`,
88934
+ recovery: `call ${family.toolName} with "action" set to one of the available actions; for one action's fields call mstar_schema {"action":"schema","family":"${family.family}"} and then {"action":"schema","command":"${family.definitions[0].id}"}` + (keys.length === 0 ? "" : `; drop ${dropped}`),
88935
+ diagnostics: [
88936
+ { path: "action", code: "not_allowed", message: `action must be one of ${listed}`, expected: listed, received },
88937
+ ...keys.map((key) => ({
88938
+ path: key,
88939
+ code: "not_allowed",
88940
+ message: `${key} is not an input of ${family.toolName}; no action of this family accepts it`,
88941
+ expected: accepted,
88942
+ received: "supplied"
88943
+ }))
88944
+ ],
88945
+ details: {
88946
+ actions: family.actions,
88947
+ ...keys.length === 0 ? {} : { fields: keys }
88948
+ }
88949
+ });
88950
+ }
88951
+ function undeclaredSelectors(family, definition3, input2) {
88952
+ if (input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88953
+ return [];
88954
+ const record3 = input2;
88955
+ const declared = new Set(definition3.cli.options.filter((option) => option.context === "sessionId").map((option) => option.key));
88956
+ return family.selectors.filter((selector) => !declared.has(selector.key) && record3[selector.key] !== undefined).map((selector) => ({ key: selector.key, acceptingActions: selector.actions }));
88957
+ }
88958
+ var ACCEPTED_FIELD_LIST_CAP = 12;
88959
+ function cappedFieldList(fields) {
88960
+ if (fields.length === 0)
88961
+ return "no fields";
88962
+ return fields.length <= ACCEPTED_FIELD_LIST_CAP ? fields.join(", ") : `${fields.slice(0, ACCEPTED_FIELD_LIST_CAP).join(", ")}, ...`;
88963
+ }
88964
+ function undeclaredFields(family, definition3, input2, callerIdentity) {
88965
+ if (input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88966
+ return [];
88967
+ const record3 = input2;
88968
+ const accepted = family.acceptedFields.get(actionOf2(definition3.id)) ?? [];
88969
+ const declared = new Set([...accepted, ...transportFields(family, callerIdentity)]);
88970
+ return Object.keys(record3).filter((key) => record3[key] !== undefined && !declared.has(key));
88971
+ }
88972
+ function transportFields(family, callerIdentity) {
88973
+ const keys = new Set(["action"]);
88974
+ if (!callerIdentity)
88975
+ return keys;
88976
+ for (const member of family.definitions) {
88977
+ for (const option of member.cli.options) {
88978
+ if (option.context === "sessionId")
88979
+ keys.add(option.key);
88980
+ }
88981
+ }
88982
+ return keys;
88983
+ }
88984
+ function familyAcceptedFields(family) {
88985
+ const accepted = new Set;
88986
+ for (const fields of family.acceptedFields.values())
88987
+ for (const field of fields)
88988
+ accepted.add(field);
88989
+ return [...accepted];
88990
+ }
88991
+ function familyWideInvalidFields(family, input2, callerIdentity) {
88992
+ if (input2 === null || typeof input2 !== "object" || Array.isArray(input2))
88993
+ return [];
88994
+ const record3 = input2;
88995
+ const declared = new Set([...familyAcceptedFields(family), ...transportFields(family, callerIdentity)]);
88996
+ return Object.keys(record3).filter((key) => record3[key] !== undefined && !declared.has(key));
88997
+ }
88998
+ function undeclaredInputRefusal(family, definition3, selectors, rejected2, admission, unpublished = [], missingRoot) {
88999
+ const action = actionOf2(definition3.id);
89000
+ const accepted = family.acceptedFields.get(action) ?? [];
89001
+ const acceptedList = cappedFieldList(accepted);
89002
+ const keys = rejected2.map(sanitizeInputScalar);
89003
+ const dropped = keys.map((key) => JSON.stringify(key)).join(", ");
89004
+ const root = missingRoot === undefined ? undefined : unpinnedRootFacts(definition3, missingRoot);
89005
+ const identity = unpublished.length === 0 ? undefined : callerIdentityFacts(definition3, unpublished);
89006
+ const selectorClauses = selectors.map((selector) => {
89007
+ const key = sanitizeInputScalar(selector.key);
89008
+ return `${JSON.stringify(key)} (accepted by: ${selector.acceptingActions.join(", ")})`;
89009
+ });
89010
+ const selectorNames = selectors.map((selector) => JSON.stringify(sanitizeInputScalar(selector.key))).join(", ");
89011
+ const selectorActions = [...new Set(selectors.flatMap((selector) => selector.acceptingActions))];
89012
+ const acceptingActions = [...family.acceptedFields].filter(([sibling, fields]) => sibling !== action && fields.some((field) => rejected2.includes(field))).map(([sibling]) => sibling);
89013
+ const admissionDiagnostics = admission?.envelope.details?.diagnostics ?? [];
89014
+ const payloadNote = rejected2.includes("payload") ? "; nested payload contents belong to the action's own payload schema, not to this field index" : "";
89015
+ const message = [
89016
+ ...root === undefined ? [] : [root.message],
89017
+ ...identity === undefined ? [] : [identity.message],
89018
+ selectors.length === 0 ? "" : `action ${JSON.stringify(action)} of ${family.toolName} does not declare the selector${selectors.length === 1 ? "" : "s"} ${selectorClauses.join(", ")}`,
89019
+ rejected2.length === 0 ? "" : `it does not accept the field${keys.length === 1 ? "" : "s"} ${dropped}; it accepts: ${acceptedList}${payloadNote}`
89020
+ ].filter(Boolean).join("; ");
89021
+ const recovery = [
89022
+ ...root === undefined ? [] : [root.recovery],
89023
+ ...identity === undefined ? [] : [identity.recovery],
89024
+ selectors.length === 0 ? "" : `drop ${selectorNames} to run ${definition3.id} under the connection identity, or call ${family.toolName} with "action" set to one of: ${selectorActions.join(", ")}`,
89025
+ rejected2.length === 0 ? "" : `drop ${dropped}${acceptingActions.length === 0 ? "" : ` (the action(s) that accept it: ${acceptingActions.join(", ")})`}, or call mstar_schema {"action":"schema","command":${JSON.stringify(definition3.id)}} for this action's real input shape`
89026
+ ].filter(Boolean).join("; ");
89027
+ const diagnostics = [
89028
+ ...root === undefined ? [] : [root.diagnostic],
89029
+ ...identity?.diagnostics ?? [],
89030
+ ...selectors.map((selector) => {
89031
+ const key = sanitizeInputScalar(selector.key);
89032
+ return {
89033
+ path: key,
89034
+ code: "not_allowed",
89035
+ message: `${key} is not an input of ${definition3.id}; the actions that accept it: ${selector.acceptingActions.join(", ")}`,
89036
+ expected: selector.acceptingActions.map((entry) => JSON.stringify(entry)).join(" | "),
89037
+ received: "supplied"
89038
+ };
89039
+ }),
89040
+ ...keys.map((key) => ({
89041
+ path: key,
89042
+ code: "not_allowed",
89043
+ message: `${key} is not an input of ${definition3.id}; the fields it accepts: ${acceptedList}`,
89044
+ expected: acceptedList,
89045
+ received: "supplied"
89046
+ })),
89047
+ ...admissionDiagnostics
89048
+ ];
89049
+ const details = {
89050
+ action: definition3.id,
89051
+ ...identity === undefined ? {} : { identity: { selectors: unpublished, trust: "off" } },
89052
+ ...selectors.length === 0 ? {} : {
89053
+ selectors: selectors.map((selector) => ({ key: sanitizeInputScalar(selector.key), acceptingActions: selector.acceptingActions }))
89054
+ },
89055
+ ...rejected2.length === 0 ? {} : { fields: keys, acceptedFields: accepted },
89056
+ ...acceptingActions.length === 0 ? {} : { acceptingActions }
89057
+ };
89058
+ return identity === undefined ? refusalEnvelope({
89059
+ command: definition3.id,
89060
+ status: "usage",
89061
+ code: "command.invalid-input",
89062
+ exitCode: 2,
89063
+ message,
89064
+ helpRoute: `mstar schema --family ${family.family}`,
89065
+ recovery,
89066
+ diagnostics,
89067
+ details
89068
+ }) : refusalEnvelope({
89069
+ command: definition3.id,
89070
+ status: "refused",
89071
+ code: "mcp.caller-identity-unavailable",
89072
+ exitCode: 1,
89073
+ message,
89074
+ helpRoute: `mstar schema --command ${definition3.id}`,
89075
+ recovery,
89076
+ diagnostics,
89077
+ details
89078
+ });
89079
+ }
89080
+ function registerMcpCommands(server, definitions2, resolveContext, services = [], onToolsRegistered) {
89081
+ const connectionEffects = createMcpEffects(services);
89082
+ const unpinnedRootRequired = resolveContext.defaultHarness === undefined;
89083
+ const callerIdentity = resolveContext.callerIdentity === true;
89084
+ const prepared = new Map;
89085
+ const members2 = definitions2.map((definition3) => {
88204
89086
  const descriptor = getCommandSchemas([definition3])[0];
88205
- const contract3 = mcpInputContract(definition3, descriptor);
88206
- const harnessDefault = declaresHarness(contract3);
89087
+ const selector = definition3.cli.options.find((option) => option.context === "sessionId");
89088
+ const rootInputs = rootInputsOf(definition3, descriptor);
89089
+ const harnessIsRoot = rootInputs.includes("harness");
89090
+ const contract3 = mcpInputContract(definition3, descriptor, { unpinnedRootRequired, rootInputs, publishSelector: callerIdentity });
89091
+ prepared.set(definition3.id, { definition: definition3, descriptor, contract: contract3, harnessDefault: harnessIsRoot, rootInputs });
89092
+ return {
89093
+ definition: definition3,
89094
+ input: { ...descriptor.input, required: contract3.jsonSchema.required },
89095
+ ...selector === undefined || !callerIdentity ? {} : { selector: { key: selector.key } }
89096
+ };
89097
+ });
89098
+ const families = foldFamilyTools(members2);
89099
+ onToolsRegistered?.(families.map((family) => family.toolName));
89100
+ for (const family of families) {
88207
89101
  const inputSchema10 = {
88208
89102
  "~standard": {
88209
89103
  version: 1,
88210
89104
  vendor: "mstar-harness",
88211
- jsonSchema: { input: () => contract3.jsonSchema, output: () => contract3.jsonSchema },
89105
+ jsonSchema: { input: () => family.descriptorView, output: () => family.descriptorView },
88212
89106
  validate(input2) {
88213
- const defaultSessionId = resolveContext.defaultSessionId;
88214
- const defaultHarness = harnessDefault ? resolveContext.defaultHarness : undefined;
88215
- const admitted = admitCommandInput(definition3, normalizedBlankHarness(input2, defaultHarness), descriptor, contract3.schema, (data) => handlerInput(definition3, data, defaultHarness), defaultSessionId === undefined ? undefined : { sessionId: defaultSessionId });
88216
- return admitted.success ? { value: admitted } : { issues: [{ message: JSON.stringify(admitted.envelope) }] };
89107
+ const record3 = input2 !== null && typeof input2 === "object" && !Array.isArray(input2) ? input2 : undefined;
89108
+ const action = record3?.action;
89109
+ const definition3 = typeof action === "string" ? definitionForAction(family, action) : undefined;
89110
+ if (definition3 === undefined) {
89111
+ return { issues: [{ message: JSON.stringify(unknownActionRefusal(family, action, familyWideInvalidFields(family, input2, callerIdentity))) }] };
89112
+ }
89113
+ const unpublishedSelectors = callerIdentity ? [] : suppliedSelectors(family, input2);
89114
+ const declaredInput = withoutFields(input2, unpublishedSelectors);
89115
+ const refusedSelectors = undeclaredSelectors(family, definition3, declaredInput);
89116
+ const rejected2 = undeclaredFields(family, definition3, declaredInput, callerIdentity);
89117
+ const entry = prepared.get(definition3.id);
89118
+ const defaultHarness = resolveContext.defaultHarness;
89119
+ const rootInput = normalizedRootInputs(entry.rootInputs, strippedActionInput(withoutFields(declaredInput, [...refusedSelectors.map((selector) => selector.key), ...rejected2])), defaultHarness);
89120
+ const admitted = admitCommandInput(definition3, rootInput, entry.descriptor, entry.contract.schema, (data) => handlerInput(definition3, data, defaultHarness, entry.harnessDefault));
89121
+ const missingRoot = entry.contract.unpinnedRootGate.find((field) => !namedRoot(field, input2));
89122
+ if (unpublishedSelectors.length > 0 || refusedSelectors.length > 0 || rejected2.length > 0) {
89123
+ return { issues: [{ message: JSON.stringify(undeclaredInputRefusal(family, definition3, refusedSelectors, rejected2, admitted.success ? undefined : admitted, unpublishedSelectors, missingRoot)) }] };
89124
+ }
89125
+ if (missingRoot !== undefined) {
89126
+ return { issues: [{ message: JSON.stringify(unpinnedRootRefusal(definition3, missingRoot, admitted.success ? undefined : admitted)) }] };
89127
+ }
89128
+ return admitted.success ? { value: { ...admitted, definition: definition3, callRoot: callRootOf(entry.rootInputs, rootInput) } } : { issues: [{ message: JSON.stringify(admitted.envelope) }] };
88217
89129
  }
88218
89130
  }
88219
89131
  };
88220
- server.registerTool(name, {
88221
- description: renderCommandContract(definition3, "mcp", descriptor),
88222
- inputSchema: inputSchema10,
88223
- outputSchema: definition3.output
89132
+ server.registerTool(family.toolName, {
89133
+ description: family.description,
89134
+ inputSchema: inputSchema10
88224
89135
  }, async (admitted, extra) => {
88225
- const resolved = await resolveContext(definition3, admitted.sessionId, extra.mcpReq.signal, services, connectionEffects);
89136
+ const { definition: definition3, callRoot } = admitted;
89137
+ const resolved = await resolveContext(definition3, admitted.sessionId, extra.mcpReq.signal, services, connectionEffects, { harness: callRoot });
88226
89138
  const sessionId = admitted.sessionId ?? resolved.sessionId;
88227
89139
  const requestContext = Object.freeze({
88228
89140
  ...resolved,
@@ -88246,7 +89158,22 @@ function registerMcpCommands(server, definitions2, resolveContext, services = []
88246
89158
  }
88247
89159
 
88248
89160
  // src/mcp/server.ts
88249
- function createMcpServer(resolveContext, definitions2 = getCommandDefinitions(), onToolsRegistered) {
89161
+ function leafSeatRefusal(command7) {
89162
+ return refusalEnvelope({
89163
+ command: command7,
89164
+ status: "refused",
89165
+ code: `${command7}.leaf-seat`,
89166
+ exitCode: 1,
89167
+ message: "known leaf sessions cannot hold a workflow coordinator seat: they cannot bind or complete a plan, recover a session, " + "launch a child under a minted coordinator identity, or write workflow delivery, lifecycle, adoption or ledger state",
89168
+ recovery: 'This connection was launched with --seat leaf (the calling session header carries origin "subagent" or delegationDepth > 0). ' + "Coordinator-seat operations belong to the non-leaf coordinating session: run the operation there, or continue with the commands this seat may use (issue.add / issue.close / plan.prepare / plan.progress and every read)."
89169
+ });
89170
+ }
89171
+ function seatDefinitions(definitions2, seat) {
89172
+ if (seat !== "leaf")
89173
+ return definitions2;
89174
+ return definitions2.map((definition3) => isCoordinatorSeatCommand(definition3.id) ? { ...definition3, execute: async () => leafSeatRefusal(definition3.id) } : definition3);
89175
+ }
89176
+ function createMcpServer(resolveContext, definitions2 = getCommandDefinitions(), onToolsRegistered, seat) {
88250
89177
  const server = new McpServer({ name: "mstar-harness", version: package_default.version });
88251
89178
  const services = [];
88252
89179
  const closeServices = async () => {
@@ -88261,8 +89188,8 @@ function createMcpServer(resolveContext, definitions2 = getCommandDefinitions(),
88261
89188
  server.server.onclose = () => {
88262
89189
  closeServices();
88263
89190
  };
88264
- const createRequestContext = async (definition3, sessionId, signal, requestServices, effects) => {
88265
- const context2 = await resolveContext(definition3, sessionId, signal, requestServices, effects);
89191
+ const createRequestContext = async (definition3, sessionId, signal, requestServices, effects, call) => {
89192
+ const context2 = await resolveContext(definition3, sessionId, signal, requestServices, effects, call);
88266
89193
  const requestContext = Object.freeze({
88267
89194
  ...context2,
88268
89195
  versions: Object.freeze({ ...context2.versions }),
@@ -88271,43 +89198,102 @@ function createMcpServer(resolveContext, definitions2 = getCommandDefinitions(),
88271
89198
  });
88272
89199
  return requestContext;
88273
89200
  };
88274
- Object.defineProperty(createRequestContext, "defaultSessionId", {
88275
- get: () => resolveContext.defaultSessionId,
88276
- enumerable: true
88277
- });
88278
89201
  Object.defineProperty(createRequestContext, "defaultHarness", {
88279
89202
  get: () => resolveContext.defaultHarness,
88280
89203
  enumerable: true
88281
89204
  });
88282
- registerMcpCommands(server, definitions2, createRequestContext, services, onToolsRegistered);
89205
+ Object.defineProperty(createRequestContext, "callerIdentity", {
89206
+ get: () => resolveContext.callerIdentity === true,
89207
+ enumerable: true
89208
+ });
89209
+ registerMcpCommands(server, seatDefinitions(definitions2, seat), createRequestContext, services, onToolsRegistered);
88283
89210
  return server;
88284
89211
  }
88285
89212
 
88286
89213
  // src/mcp/stdio.ts
88287
- function declaredSessionId(identityEnv) {
88288
- if (identityEnv === undefined)
88289
- return;
88290
- const value = process.env[identityEnv];
88291
- return typeof value === "string" && value.trim() !== "" ? value : undefined;
89214
+ var NULL_ROOT_BOOTSTRAP_COMMANDS = new Set(["harness.scaffold"]);
89215
+ var ROOT_FREE_COMMANDS = new Set([
89216
+ "schema",
89217
+ "path.resolve",
89218
+ "host.detect",
89219
+ "host.skill-root",
89220
+ "doctor",
89221
+ "plugin.validate",
89222
+ "report",
89223
+ "lint",
89224
+ "design-md.validate",
89225
+ "skill.lint",
89226
+ "roles.validate",
89227
+ "qc.validate-report",
89228
+ "review.seats",
89229
+ "dispatch.validate",
89230
+ "worktree.qc-alignment",
89231
+ "iteration.push-cadence",
89232
+ "audit.secret-scan",
89233
+ "audit.supply-chain",
89234
+ "pr-review.tally",
89235
+ "pr-review.budget",
89236
+ "pr-review.validate-report",
89237
+ "pr-review.size",
89238
+ "pr-review.seat-prompt",
89239
+ "pr-review.post",
89240
+ "pr-review.worktree-cleanup",
89241
+ "store.execution.export",
89242
+ "store.execution.restore-preview",
89243
+ "store.execution.restore"
89244
+ ]);
89245
+
89246
+ class McpControlRootError extends Error {
89247
+ details;
89248
+ code = "mcp.control-root-unresolved";
89249
+ constructor(message, details) {
89250
+ super(message);
89251
+ this.details = details;
89252
+ this.name = "McpControlRootError";
89253
+ }
89254
+ }
89255
+ function unresolvedControlRootMessage(cwd) {
89256
+ return `[mcp.control-root-unresolved] No control root was DECLARED for this MCP connection. ` + `The launch cwd (${cwd}) is the HOST's directory and is never used as one: it says nothing about which workspace a caller belongs to, so adopting it would root writes on an unrelated project. ` + "Recovery \u2014 the two launcher recoveries work for EVERY command: " + "launch the server with `mstar mcp --harness <absolute path>`; " + "set MSTAR_HARNESS_DIR in the server environment to the harness directory. " + "The per-call recovery is tool-dependent: only a command that publishes a `harness` input accepts one, so pass the call's `harness` selector naming the workspace's harness \u2014 or use `mstar_schema` to pick a command that does not need a root at all.";
89257
+ }
89258
+ function declaredRoot(options2) {
89259
+ if (options2.harnessRoot !== undefined)
89260
+ return resolve25(options2.harnessRoot);
89261
+ const fromEnv = process.env.MSTAR_HARNESS_DIR;
89262
+ return typeof fromEnv === "string" && fromEnv.trim() !== "" ? resolve25(fromEnv) : undefined;
88292
89263
  }
88293
89264
  function createContextResolver(options2 = {}) {
88294
- const resolver2 = (_definition, _sessionId, signal, _services, effects) => {
88295
- const sessionId = declaredSessionId(options2.identityEnv);
89265
+ const pinned = declaredRoot(options2);
89266
+ const resolver2 = (definition3, _sessionId, signal, _services, effects, call) => {
89267
+ const callHarness = typeof call?.harness === "string" && call.harness.trim() !== "" ? resolve25(call.harness) : undefined;
89268
+ let controlRoot;
89269
+ if (pinned !== undefined)
89270
+ controlRoot = pinned;
89271
+ else if (callHarness !== undefined)
89272
+ controlRoot = callHarness;
89273
+ else if (NULL_ROOT_BOOTSTRAP_COMMANDS.has(definition3.id))
89274
+ controlRoot = null;
89275
+ else if (ROOT_FREE_COMMANDS.has(definition3.id))
89276
+ controlRoot = null;
89277
+ else {
89278
+ const cwd = process.cwd();
89279
+ throw new McpControlRootError(unresolvedControlRootMessage(cwd), { cwd });
89280
+ }
88296
89281
  return {
88297
- cwd: options2.harnessRoot === undefined ? process.cwd() : dirname24(options2.harnessRoot),
88298
- controlRoot: options2.harnessRoot ?? resolveProcessHarnessDir(process.cwd()),
88299
- ...sessionId === undefined ? {} : { sessionId },
89282
+ cwd: options2.workspace ?? (controlRoot === null ? process.cwd() : dirname24(controlRoot)),
89283
+ controlRoot,
89284
+ ...options2.workspace === undefined && controlRoot === null ? { launchDirectory: true } : {},
89285
+ ...pinned === undefined ? {} : { harnessPin: pinned },
88300
89286
  versions: { engine: null, cli: null, plugin: null, host: null, platform: null },
88301
89287
  signal,
88302
89288
  effects
88303
89289
  };
88304
89290
  };
88305
- Object.defineProperty(resolver2, "defaultSessionId", {
88306
- get: () => declaredSessionId(options2.identityEnv),
89291
+ Object.defineProperty(resolver2, "defaultHarness", {
89292
+ get: () => pinned,
88307
89293
  enumerable: true
88308
89294
  });
88309
- Object.defineProperty(resolver2, "defaultHarness", {
88310
- get: () => options2.harnessRoot,
89295
+ Object.defineProperty(resolver2, "callerIdentity", {
89296
+ value: options2.trustCallerSessionId === true,
88311
89297
  enumerable: true
88312
89298
  });
88313
89299
  return resolver2;
@@ -88322,20 +89308,33 @@ function serveMcpStdioOver(transport, options2 = {}) {
88322
89308
  return serveStdio(() => createMcpServer(createContextResolver(options2), undefined, (names) => {
88323
89309
  for (const name of names)
88324
89310
  catalog.add(name);
88325
- }), { legacy: "serve", transport: corrected });
89311
+ }, options2.seat), { legacy: "serve", transport: corrected });
88326
89312
  }
88327
89313
  if (false) {}
88328
89314
 
88329
89315
  // src/mcp/command.ts
88330
- function absoluteHarness(value) {
88331
- if (!isAbsolute21(value)) {
88332
- throw new CommanderError(2, "commander.invalidArgument", `--harness must be an absolute path; got ${JSON.stringify(value)}`);
89316
+ function absolutePath2(flag) {
89317
+ return (value) => {
89318
+ if (!isAbsolute21(value)) {
89319
+ throw new CommanderError(2, "commander.invalidArgument", `${flag} must be an absolute path; got ${JSON.stringify(value)}`);
89320
+ }
89321
+ return value;
89322
+ };
89323
+ }
89324
+ function seatValue(value) {
89325
+ if (value !== "leaf") {
89326
+ throw new CommanderError(2, "commander.invalidArgument", `--seat must be "leaf"; got ${JSON.stringify(value)}`);
88333
89327
  }
88334
89328
  return value;
88335
89329
  }
88336
89330
  function registerMcpCommand(program2) {
88337
- program2.command("mcp").description("Run the Morning Star MCP server over stdio").option("--identity-env <NAME>", "read the default session id from environment variable NAME; without it no ambient identity is read, and a per-call sessionId always wins. The declared default applies to the whole connection, so per-caller identity needs an explicit sessionId or its own scoped mount.").option("--harness <path>", "absolute harness root for every call; it also anchors the invocation workspace at its parent, so cwd-derived paths land under the pinned harness. Without it the server probes process.cwd() for one", absoluteHarness).action(async (options2) => {
88338
- await serveMcpStdio({ identityEnv: options2.identityEnv, harnessRoot: options2.harness });
89331
+ program2.command("mcp").description("Run the Morning Star MCP server over stdio").option("--harness <path>", "absolute harness root that PINS this connection: every call resolves its control root here, and the invocation workspace is anchored at its parent, so cwd-derived paths land under the pinned harness. Without it a non-blank MSTAR_HARNESS_DIR in the server environment pins the same way (resolved against the server's launch directory, because an environment value has no CLI boundary to refuse a relative path). Without either, a call to a command that needs a root must name its own through the published `harness` selector, and a call that names none is refused; commands that need no root (schema, path.resolve, host.*, the read-only validators) run either way. The launch cwd is never used as a control root, and a root-free command may not default a path input from it either: with no declared workspace the input becomes required (harness.scaffold's path, roles.validate's rolesDir, audit.secret-scan's path, ...), and the report/scan actions whose subject IS the checkout (pr-review.post, pr-review.size) are refused", absolutePath2("--harness")).option("--workspace <path>", "absolute session workspace every call runs from (the invocation cwd), for a mounting host whose caller works outside the harness root's parent. Without it the workspace is the declared control root's parent directory; a connection that declares no root instead runs from its own launch directory, which a root-free command may not read or write by default, so declaring this flag is also how a mounting host names the directory harness.scaffold may bootstrap", absolutePath2("--workspace")).option("--seat <seat>", 'declare the connection\'s seat: "leaf" refuses the coordinator-seat commands for this connection before execution, with the named cause and recovery. Those commands are the two classes that need a coordinator seat: those that establish or replace one (bind or complete a plan, recover a session, launch a child under a minted coordinator identity) and the workflow-scope writes (delivery evidence, lifecycle, close, adoption, coordinator notes, iteration registration). The set is derived from the command layer (`coordinator-seat.ts` in @mstar-harness/commands), which both this connection and the dsh host guard read, so it is not restated here. The remaining commands are not additionally restricted by this seat filter; each keeps its own input and authorization requirements', seatValue).option("--trust-caller-session-id", "DANGEROUS, default OFF: trust a caller-declared `sessionId` as an execution identity on this connection. An MCP server is a child process with no host-proven caller identity, so the default connection publishes no session selector and refuses a supplied one; enabling this lets any caller that knows a live coordinator session id act as it. Enable it only for a deployment whose callers are already authenticated by a channel this server owns. The host-proven routes stay available either way: the dsh native tools (plan bind, audit report validation, execution clear) and the CLI").action(async (options2) => {
89332
+ await serveMcpStdio({
89333
+ harnessRoot: options2.harness,
89334
+ workspace: options2.workspace,
89335
+ ...options2.seat === undefined ? {} : { seat: options2.seat },
89336
+ ...options2.trustCallerSessionId === true ? { trustCallerSessionId: true } : {}
89337
+ });
88339
89338
  });
88340
89339
  }
88341
89340
 
@@ -88411,10 +89410,18 @@ async function runInit6(options2) {
88411
89410
  const installedPluginVersion = installResult.pluginVersion;
88412
89411
  console.log(adapter.installsPlugin === true ? `Plugin version: ${installedPluginVersion ?? "unconfirmed (the existing row was skipped and its manifest is unreadable)"}; global CLI: ${globalState}.` : `Global CLI: ${globalState}.`);
88413
89412
  const pluginMismatched = installedPluginVersion !== undefined && installedPluginVersion !== chosenCli2;
88414
- const globalFailed = globalResult2.action === "failed" && (installedPluginVersion ?? packageVersion) !== packageVersion;
89413
+ const globalFailed = globalResult2.action === "failed" && chosenCli2 !== packageVersion;
88415
89414
  if (pluginMismatched || globalFailed) {
88416
- throw new Error(`The host plugin is at ${installedPluginVersion ?? "an unconfirmed version"}, while this run targets ${chosenCli2}` + `${globalResult2.action === "failed" ? ` and the global CLI could not be updated (${globalResult2.spec}), so the CLI on PATH stays at ${packageVersion}` : ""}.
88417
- ` + `Recovery: realign the plugin (\`git -C ~/.mstar/harness pull --ff-only\` then re-run init, or install the published plugin at ${chosenCli2}), ` + `or re-run with --no-global-cli to stay on the running version ${packageVersion}.`);
89415
+ const causes = [
89416
+ ...pluginMismatched ? [`The host plugin is at ${installedPluginVersion}, while this run targets ${chosenCli2}.`] : [],
89417
+ ...globalFailed ? [`The global install of ${globalResult2.spec} failed, so the CLI on PATH stays at ${packageVersion}.`] : []
89418
+ ];
89419
+ const recoveries = [
89420
+ ...pluginMismatched ? [`realign the plugin (\`git -C ~/.mstar/harness pull --ff-only\` then re-run init, or install the published plugin at ${chosenCli2})`] : [],
89421
+ ...globalFailed ? [`fix the global install (\`npm i -g @mstar-harness/cli@${chosenCli2}\`)`] : []
89422
+ ];
89423
+ throw new Error(`${causes.join(" ")}
89424
+ ` + `Recovery: ${recoveries.join(", or ")}, or re-run with --no-global-cli to stay on the running version ${packageVersion}.`);
88418
89425
  }
88419
89426
  console.log(`Next: npx @mstar-harness/cli doctor --target ${target}${scope === "project" ? "" : " --scope global"}`);
88420
89427
  return;
@@ -88479,7 +89486,7 @@ program2.name("mstar-harness").description("Morning Star harness CLI for target-
88479
89486
  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, or the target's single supported scope)").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").addOption(new Option("--opencode-generation <generation>", "OpenCode config generation: v1|v2 (default: probe the installed opencode version on real installs; config markers under --dry-run)").choices(["v1", "v2"])).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 (options2) => {
88480
89487
  await runInit6({ ...options2, noFallbacks: options2.fallbacks === false, noGlobalCli: options2.globalCli === false });
88481
89488
  });
88482
- var invocationCwd = process.env.MSTAR_CLI_PROJECT_ROOT === undefined || process.env.MSTAR_CLI_PROJECT_ROOT === "" ? process.cwd() : path38.resolve(process.env.MSTAR_CLI_PROJECT_ROOT);
89489
+ var invocationCwd = process.env.MSTAR_CLI_PROJECT_ROOT === undefined || process.env.MSTAR_CLI_PROJECT_ROOT === "" ? process.cwd() : path39.resolve(process.env.MSTAR_CLI_PROJECT_ROOT);
88483
89490
  registerCliCommands(program2, getCommandDefinitions(), {
88484
89491
  cwd: invocationCwd,
88485
89492
  controlRoot: resolveProcessHarnessDir(invocationCwd),