pan-wizard 3.27.0 → 3.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +48 -48
  2. package/agents/pan-previewer.md +1 -1
  3. package/bin/install-lib.cjs +580 -18
  4. package/bin/install.js +25 -44
  5. package/commands/pan/army.md +1 -1
  6. package/commands/pan/cost.md +14 -2
  7. package/commands/pan/preview.md +2 -2
  8. package/hooks/dist/pan-check-update.js +4 -0
  9. package/hooks/dist/pan-cost-logger.js +322 -43
  10. package/hooks/dist/pan-trace-logger.js +275 -32
  11. package/package.json +8 -2
  12. package/pan-wizard-core/bin/lib/commands.cjs +3 -1
  13. package/pan-wizard-core/bin/lib/constants.cjs +39 -0
  14. package/pan-wizard-core/bin/lib/context-budget.cjs +80 -0
  15. package/pan-wizard-core/bin/lib/cost-rebuild.cjs +511 -0
  16. package/pan-wizard-core/bin/lib/cost.cjs +174 -18
  17. package/pan-wizard-core/bin/lib/foreign-planning.cjs +56 -0
  18. package/pan-wizard-core/bin/lib/git.cjs +5 -1
  19. package/pan-wizard-core/bin/lib/hud.cjs +5 -3
  20. package/pan-wizard-core/bin/lib/hygiene.cjs +52 -24
  21. package/pan-wizard-core/bin/lib/init.cjs +8 -0
  22. package/pan-wizard-core/bin/lib/memory.cjs +14 -8
  23. package/pan-wizard-core/bin/lib/optimize.cjs +78 -2
  24. package/pan-wizard-core/bin/lib/utils.cjs +22 -0
  25. package/pan-wizard-core/bin/lib/verify.cjs +46 -12
  26. package/pan-wizard-core/bin/pan-tools.cjs +8 -1
  27. package/pan-wizard-core/mcp/server.cjs +92 -8
  28. package/pan-wizard-core/mcp/tool-registry.cjs +50 -3
  29. package/pan-wizard-core/references/model-profiles.md +2 -2
  30. package/pan-wizard-core/workflows/health.md +2 -0
  31. package/pan-zcode/README.md +1 -1
  32. package/scripts/build-agent-plugin.js +220 -0
  33. package/scripts/build-plugin.js +48 -3
  34. package/scripts/coverage-gate.cjs +257 -0
  35. package/scripts/generate-skills-docs.py +1 -1
  36. package/scripts/install-git-hooks.js +5 -0
  37. package/scripts/mutation-probe.cjs +272 -0
  38. package/scripts/release-check.js +80 -13
  39. package/scripts/test-quality-lint.cjs +240 -0
  40. package/scripts/test-surface.cjs +335 -0
@@ -134,9 +134,82 @@ function getCurrentSessionId(cwd) {
134
134
  }
135
135
  }
136
136
 
137
+ /**
138
+ * Day-scoped auto-session id, the same shape the trace hook mints
139
+ * (`sess_auto_YYYYMMDD`) so a day's hook-written and agent-reported events share one
140
+ * session instead of splitting into two.
141
+ */
142
+ function autoSessionId(now = new Date()) {
143
+ const p = (n) => String(n).padStart(2, '0');
144
+ return `sess_auto_${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}`;
145
+ }
146
+
147
+ /**
148
+ * How long a `current-session` pointer is evidence of a live session. An explicit
149
+ * (non-auto) session used to stay "current" indefinitely — a July session was still
150
+ * current in September in a field project, so `readActiveSessionMeta` in the cost hook
151
+ * backfilled two-month-old command/phase onto today's ledger rows, and agent-reported
152
+ * events would have landed in a long-dead session's directory (field sweep 2026-09-17).
153
+ */
154
+ const SESSION_STALE_MS = 24 * 60 * 60 * 1000;
155
+
156
+ /**
157
+ * Last time anything was written to a session: its event log if it has one, else the
158
+ * moment it started. Null when the session cannot be read at all.
159
+ */
160
+ function sessionLastActivityMs(cwd, sid) {
161
+ const dir = path.join(getTracesDir(cwd), sid);
162
+ try {
163
+ return fs.statSync(path.join(dir, TRACE_EVENT_FILE)).mtimeMs;
164
+ } catch { /* no events yet */ }
165
+ try {
166
+ const meta = JSON.parse(fs.readFileSync(path.join(dir, OPT_SESSION_FILE), 'utf-8'));
167
+ const t = new Date(meta.started_at).getTime();
168
+ return Number.isFinite(t) ? t : null;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Is this session finished, or too old to still be the one running? Read-only —
176
+ * finalizing a stale session is the writing path's job (the trace hook's rollover).
177
+ */
178
+ function isSessionStale(cwd, sid, now = Date.now()) {
179
+ const dir = path.join(getTracesDir(cwd), sid);
180
+ try {
181
+ const meta = JSON.parse(fs.readFileSync(path.join(dir, OPT_SESSION_FILE), 'utf-8'));
182
+ if (meta && meta.ended_at) return true;
183
+ } catch { /* unreadable meta — fall through to the age test */ }
184
+ const last = sessionLastActivityMs(cwd, sid);
185
+ if (last === null) return true;
186
+ return now - last > SESSION_STALE_MS;
187
+ }
188
+
189
+ /**
190
+ * Append one trace event.
191
+ *
192
+ * Creates the day's auto-session when none is active. It used to return false instead,
193
+ * and the 16 `optimize trace log` call sites in the workflows are fire-and-forget
194
+ * (`2>/dev/null || true`), so on the phase pipeline — which never starts a trace
195
+ * session — every agent-reported event was silently discarded. Across fourteen field
196
+ * projects the instrument held 3,737 events, 99.7% of them the completion rows the hook
197
+ * writes, and not one error, gap or correction in its whole history (sweep 2026-09-17).
198
+ * An explicit `--session` is still honoured verbatim.
199
+ */
137
200
  function logTraceEvent(cwd, event, sessionId) {
138
- const sid = sessionId || getCurrentSessionId(cwd);
139
- if (!sid) return false;
201
+ // An explicit id is honoured verbatim. A POINTER, by contrast, is only evidence while
202
+ // the session it names is alive; a dead one is no session at all.
203
+ let sid = sessionId || null;
204
+ if (!sid) {
205
+ const current = getCurrentSessionId(cwd);
206
+ if (current && !isSessionStale(cwd, current)) sid = current;
207
+ }
208
+ if (!sid) {
209
+ const created = initTraceSession(cwd, { sessionId: autoSessionId(), description: 'auto-session (day-scoped)' });
210
+ if (!created || created.error) return false;
211
+ sid = created.session_id;
212
+ }
140
213
 
141
214
  try {
142
215
  const sessionDir = path.join(getTracesDir(cwd), sid);
@@ -1290,6 +1363,9 @@ module.exports = {
1290
1363
  TRACE_EVENT_FILE,
1291
1364
  OPT_SESSION_FILE,
1292
1365
  CURRENT_SESSION_FILE,
1366
+ autoSessionId,
1367
+ isSessionStale,
1368
+ SESSION_STALE_MS,
1293
1369
  EVENT_TYPES,
1294
1370
  IMPACT_LEVELS,
1295
1371
  VALID_SCOPES,
@@ -182,10 +182,32 @@ function hasBraveSearchKey() {
182
182
  return fileAccessible(path.join(os.homedir(), '.pan-wizard', 'brave_api_key'));
183
183
  }
184
184
 
185
+ /**
186
+ * Which workflow model a planning tree runs (PLANNING_MODEL_MARKERS). The phase model
187
+ * wins when its markers are present, since a phase project may also hold focus
188
+ * artifacts; `fragment` means entries exist but none of them mark a deliberate
189
+ * workflow, and `absent` that the directory could not be read.
190
+ *
191
+ * @param {string} planningDir - absolute path to the tree (e.g. planningPath(cwd))
192
+ * @returns {{model: 'phase'|'focus'|'campaign'|'fragment'|'empty'|'absent', evidence: string[], entries: number}}
193
+ */
194
+ function detectPlanningModel(planningDir) {
195
+ const { PLANNING_MODEL_MARKERS } = require('./constants.cjs');
196
+ let entries;
197
+ try { entries = fs.readdirSync(planningDir); } catch { return { model: 'absent', evidence: [], entries: 0 }; }
198
+ const lower = new Set(entries.map(e => String(e).toLowerCase()));
199
+ for (const model of ['phase', 'focus', 'campaign']) {
200
+ const evidence = PLANNING_MODEL_MARKERS[model].filter(m => lower.has(m));
201
+ if (evidence.length) return { model, evidence, entries: entries.length };
202
+ }
203
+ return { model: entries.length ? 'fragment' : 'empty', evidence: [], entries: entries.length };
204
+ }
205
+
185
206
  module.exports = {
186
207
  readJsonFile,
187
208
  removeQuotes,
188
209
  planningPath,
210
+ detectPlanningModel,
189
211
  planningRel,
190
212
  phasesPath,
191
213
  milestonesPath,
@@ -14,7 +14,8 @@ const {
14
14
  PLAN_SUFFIX, SUMMARY_SUFFIX, STANDARDS_FILE, STANDARDS_CATALOG, HEALTH_STATUS,
15
15
  BUILTIN_DRIFT_RULES, DRIFT_VERDICTS, BINARY_EXTENSIONS, DRIFT_MAX_FILES, DRIFT_MAX_FILE_SIZE, DRIFT_SEVERITY_WEIGHTS,
16
16
  } = require('./constants.cjs');
17
- const { planningPath, phasesPath, filterPlanFiles, filterSummaryFiles, fileAccessible } = require('./utils.cjs');
17
+ const { planningPath, phasesPath, filterPlanFiles, filterSummaryFiles, fileAccessible, detectPlanningModel } = require('./utils.cjs');
18
+ const { detectForeignPlanningTree } = require('./foreign-planning.cjs');
18
19
  // Drift detection lives in verify-drift.cjs; re-exported below so consumers of
19
20
  // verify.cjs are unaffected by the decomposition.
20
21
  const { runDriftCheck, parseConventionRules, checkFileConventions, calculateDriftScore, getChangedFiles, cmdDriftCheck } = require('./verify-drift.cjs');
@@ -1293,29 +1294,59 @@ function cmdValidateHealth(cwd, options, raw) {
1293
1294
 
1294
1295
  // Check 1: .planning/ exists (fatal if missing -- skip remaining checks)
1295
1296
  if (!checkPlanningDirExists(cwd, addIssue)) {
1297
+ // A verdict payload carries `errors[]`, which is OUTSIDE output()'s error family
1298
+ // (plural collections are detail, not a failure signal — see CLI-REFERENCE "Error
1299
+ // Shape"), so the exit code must be set explicitly here, as `reconcile` does.
1300
+ // `broken` → 1. Reality check RC2 (2026-09-10): this site exited 0 for a missing
1301
+ // .planning/, so an orchestrator gating on the exit code read it as healthy.
1296
1302
  output({
1297
1303
  status: HEALTH_STATUS.BROKEN,
1298
1304
  errors,
1299
1305
  warnings,
1300
1306
  info,
1301
1307
  repairable_count: 0,
1302
- }, raw);
1308
+ }, raw, undefined, 1);
1303
1309
  return;
1304
1310
  }
1305
1311
 
1312
+ // Check 1b: the tree exists but belongs to another tool (gsd-core shares the
1313
+ // directory name and PAN's legacy uppercase file names). Report that as its own
1314
+ // error and stop: E002-E005 would describe a foreign layout as a broken PAN one,
1315
+ // and --repair must never write into it. Reality check R15.
1316
+ const foreign = detectForeignPlanningTree(planningPath(cwd));
1317
+ if (foreign) {
1318
+ addIssue('error', 'E006', `planning tree belongs to ${foreign.tool}: ${foreign.evidence.join(', ')}`, 'Run PAN with --planning-dir <dir> to use a separate tree (ADR-0043)');
1319
+ output({ status: HEALTH_STATUS.BROKEN, errors, warnings, info, repairable_count: 0 }, raw, undefined, 1);
1320
+ return;
1321
+ }
1322
+
1323
+ // Check 1c: which workflow model is this tree running? Checks 2-8b below are the
1324
+ // PHASE model's — a focus-model project (`/pan:focus`, no project/roadmap/state by
1325
+ // design) and an orchestration campaign would each fail all of them and be called
1326
+ // broken, which is what eight of fourteen field projects hit (sweep 2026-09-17).
1327
+ // config.json is the one check every model shares.
1328
+ const shape = detectPlanningModel(planningPath(cwd));
1329
+ const phaseModel = shape.model === 'phase' || shape.model === 'fragment' || shape.model === 'empty';
1330
+
1306
1331
  // Checks 2-8: individual structure and consistency checks
1307
- checkProjectFile(cwd, addIssue);
1308
- checkRoadmapFile(cwd, addIssue);
1309
- checkStateFile(cwd, addIssue, repairs);
1332
+ if (phaseModel) {
1333
+ checkProjectFile(cwd, addIssue);
1334
+ checkRoadmapFile(cwd, addIssue);
1335
+ checkStateFile(cwd, addIssue, repairs);
1336
+ } else {
1337
+ addIssue('info', 'I003', `${shape.model}-model project (${shape.evidence.join(', ')}) — the phase-model checks (project.md, roadmap.md, state.md, phases/) do not apply`, null);
1338
+ }
1310
1339
  checkConfigFile(cwd, addIssue, repairs);
1311
- checkPhaseDirectories(cwd, addIssue);
1312
- checkPhaseContents(cwd, addIssue);
1340
+ if (phaseModel) {
1341
+ checkPhaseDirectories(cwd, addIssue);
1342
+ checkPhaseContents(cwd, addIssue);
1313
1343
 
1314
- // Check 8b: cross-document state consistency
1315
- checkStateConsistency(cwd, addIssue, repairs);
1344
+ // Check 8b: cross-document state consistency
1345
+ checkStateConsistency(cwd, addIssue, repairs);
1316
1346
 
1317
- // Check 8c: verification gate (phases with verifier enabled need verification.md)
1318
- checkVerificationGate(cwd, addIssue);
1347
+ // Check 8c: verification gate (phases with verifier enabled need verification.md)
1348
+ checkVerificationGate(cwd, addIssue);
1349
+ }
1319
1350
 
1320
1351
  // Check 9 (optional): standards compliance
1321
1352
  if (options.standards) {
@@ -1418,7 +1449,10 @@ function cmdValidateHealth(cwd, options, raw) {
1418
1449
  result.link_graph = linkGraphResult;
1419
1450
  }
1420
1451
 
1421
- output(result, raw);
1452
+ // Explicit verdict exit: `broken` → 1; `degraded` and `healthy` → 0 (warnings are
1453
+ // not failures). Computed AFTER --repair ran, so the code reflects the post-repair
1454
+ // state the JSON reports. See the note at the early-return site above.
1455
+ output(result, raw, undefined, status === HEALTH_STATUS.BROKEN ? 1 : 0);
1422
1456
  }
1423
1457
 
1424
1458
  /**
@@ -203,6 +203,7 @@ const codebase = require('./lib/codebase.cjs');
203
203
  const memory = require('./lib/memory.cjs');
204
204
  const bus = require('./lib/bus.cjs');
205
205
  const cost = require('./lib/cost.cjs');
206
+ const costRebuild = require('./lib/cost-rebuild.cjs');
206
207
  const preview = require('./lib/preview.cjs');
207
208
  const reviewDeep = require('./lib/review-deep.cjs');
208
209
  const knowledge = require('./lib/knowledge.cjs');
@@ -1207,8 +1208,14 @@ async function main() {
1207
1208
  cost.cmdCostAppend(cwd, rec, raw);
1208
1209
  } else if (subcommand === 'clear') {
1209
1210
  cost.cmdCostClear(cwd, raw);
1211
+ } else if (subcommand === 'rebuild') {
1212
+ costRebuild.cmdCostRebuild(cwd, {
1213
+ apply: args.includes('--apply'),
1214
+ mainThread: !args.includes('--no-main-thread'),
1215
+ claudeDir: getArgValue(args, '--claude-dir'),
1216
+ }, raw);
1210
1217
  } else {
1211
- error('Unknown cost subcommand. Available: report, append, clear');
1218
+ error('Unknown cost subcommand. Available: report, append, clear, rebuild');
1212
1219
  }
1213
1220
  break;
1214
1221
  }
@@ -50,7 +50,36 @@ const META_SERVER_INFO_KEY = 'io.modelcontextprotocol/serverInfo';
50
50
  // claim to speak a version we don't. Newest first (the `server/discover` order).
51
51
  const SUPPORTED_VERSIONS_LIST = [MODERN_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05'];
52
52
  const SUPPORTED_PROTOCOL_VERSIONS = new Set(SUPPORTED_VERSIONS_LIST);
53
- const SERVER_INFO = { name: 'pan-mcp', version: '0.1.0' };
53
+ /**
54
+ * The version the server reports in `initialize` / `server/discover`. Read from the
55
+ * package.json two levels up: the repository root in the source tree, the runtime
56
+ * directory in an install (the installer writes package.json beside pan-wizard-core/).
57
+ * The plugin bundles carry no package.json there, so fall back to the plugin manifest
58
+ * and finally to a marker that is visibly not a release. Never throws: a missing
59
+ * file must not stop the server from answering. Reality check R9: this was a literal
60
+ * '0.1.0' while the package shipped 3.x.
61
+ */
62
+ function readPackageVersion(baseDir = path.join(__dirname, '..', '..')) {
63
+ // Order: the repo/runtime package.json when it carries a version; the install
64
+ // manifest every runtime writes (the runtime directory's package.json is a bare
65
+ // `{"type":"commonjs"}` marker with no version — measured on a fresh install,
66
+ // 2026-09-10, where the first version of this reader answered 0.0.0-unknown); the
67
+ // Claude plugin manifest; an Agent Plugins manifest.
68
+ const candidates = [
69
+ path.join(baseDir, 'package.json'),
70
+ path.join(baseDir, 'pan-file-manifest.json'),
71
+ path.join(baseDir, '.claude-plugin', 'plugin.json'),
72
+ path.join(baseDir, 'plugin.json'),
73
+ ];
74
+ for (const file of candidates) {
75
+ try {
76
+ const v = JSON.parse(fs.readFileSync(file, 'utf8')).version;
77
+ if (typeof v === 'string' && v.trim()) return v.trim();
78
+ } catch { /* try the next candidate */ }
79
+ }
80
+ return '0.0.0-unknown';
81
+ }
82
+ const SERVER_INFO = { name: 'pan-mcp', version: readPackageVersion() };
54
83
 
55
84
  /**
56
85
  * Default engine location: `bin/` is a sibling of this `mcp/` directory inside
@@ -75,6 +104,25 @@ function defaultPanToolsPath() {
75
104
  return path.join(__dirname, '..', 'bin', 'pan-tools.cjs');
76
105
  }
77
106
 
107
+ /**
108
+ * A verdict payload: a JSON object with no error-family key. The family is `error`
109
+ * and any key ending in `_error` — the same definition core.cjs's reportsFailure()
110
+ * uses for the CLI exit code, mirrored here because the server stays engine-agnostic
111
+ * (it never requires the engine's modules; it spawns them). Plural collections such
112
+ * as `errors[]` are verdict DETAIL, not a failure signal. Returns the parsed object,
113
+ * or null when the text is not such a payload.
114
+ */
115
+ function parseVerdict(text) {
116
+ if (typeof text !== 'string' || !text.trim()) return null;
117
+ let parsed;
118
+ try { parsed = JSON.parse(text); } catch { return null; }
119
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
120
+ for (const k of Object.keys(parsed)) {
121
+ if (k === 'error' || k.endsWith('_error')) { if (parsed[k]) return null; }
122
+ }
123
+ return parsed;
124
+ }
125
+
78
126
  /** Real spawn: shell-less execFile of `node <argv...>`. */
79
127
  function defaultSpawn(nodeArgs) {
80
128
  try {
@@ -154,7 +202,7 @@ function createServer(opts = {}) {
154
202
  const gitImpl = opts.gitImpl || makeDefaultGit(cwd);
155
203
  const env = opts.env || process.env;
156
204
 
157
- function runVerb(verb, extraArgs) {
205
+ function runVerb(verb, extraArgs, verbCwd = cwd) {
158
206
  // Defense in depth: the verb always comes from the registry, but re-check the
159
207
  // forbidden pattern here so no future caller can smuggle a force/reset op past it.
160
208
  if (reg.FORBIDDEN_VERB.test(verb)) {
@@ -163,22 +211,46 @@ function createServer(opts = {}) {
163
211
  // No --raw: pan-tools' default output is structured JSON (which is what the MCP
164
212
  // client wants); --raw would instead emit a bare human scalar. Large results
165
213
  // arrive via the @file: overflow protocol, resolved here.
166
- const r = spawn([panToolsPath, verb, ...extraArgs, '--cwd', cwd]);
214
+ const r = spawn([panToolsPath, verb, ...extraArgs, '--cwd', verbCwd]);
167
215
  if (r && r.ok) r.stdout = resolveOverflow(r.stdout);
168
216
  return r;
169
217
  }
170
218
 
219
+ /**
220
+ * Per-call project root (ADR-0045 D6). Every TOOL accepts an optional `cwd`;
221
+ * it must be an absolute path to an existing directory. Returns
222
+ * { cwd, input } with the field removed from the input handed to the tool, or
223
+ * { error } shaped for a -32602 — a bad root is a bad REQUEST, and nothing is
224
+ * spawned. Resources never come through here: their argv is static.
225
+ */
226
+ function resolveCallCwd(input) {
227
+ const src = input || {};
228
+ if (src.cwd === undefined) return { cwd, input: src };
229
+ let candidate;
230
+ try { candidate = reg.validateProjectCwd(src.cwd); }
231
+ catch (e) { return { error: { code: -32602, message: String((e && e.message) || e) } }; }
232
+ let isDir = false;
233
+ try { isDir = fs.statSync(candidate).isDirectory(); } catch { /* absent → not a directory */ }
234
+ if (!isDir) return { error: { code: -32602, message: `Invalid "cwd": not an existing directory: ${candidate}` } };
235
+ const { cwd: _omit, ...rest } = src;
236
+ return { cwd: path.resolve(candidate), input: rest };
237
+ }
238
+
171
239
  // Returns { error:{code,message} } for JSON-RPC protocol errors (unknown tool /
172
240
  // invalid arguments — a bad *request*), or { result:{content,isError} } where
173
241
  // isError:true signals a genuine tool *execution* failure (the verb ran and failed).
174
242
  function callTool(name, input) {
175
243
  const tool = reg.byToolName[name];
176
244
  if (!tool) return { error: { code: -32602, message: `Unknown tool: ${name}` } };
245
+ const call = resolveCallCwd(input);
246
+ if (call.error) return { error: call.error };
177
247
  // Native, in-process tools (orchestrator / merge gate) run a handler; a thrown
178
248
  // Error means bad params (-32602), matching the spawn-tool validation path.
249
+ // The git executor follows the per-call root unless a test injected one.
179
250
  if (typeof tool.handler === 'function') {
180
251
  try {
181
- const out = tool.handler({ cwd, input: input || {}, env, gitImpl });
252
+ const gitForCall = opts.gitImpl ? gitImpl : (call.cwd === cwd ? gitImpl : makeDefaultGit(call.cwd));
253
+ const out = tool.handler({ cwd: call.cwd, input: call.input, env, gitImpl: gitForCall });
182
254
  const text = (out && out.text != null) ? out.text : JSON.stringify(out && out.json);
183
255
  return { result: { content: [{ type: 'text', text }], isError: !!(out && out.isError) } };
184
256
  } catch (e) {
@@ -186,9 +258,9 @@ function createServer(opts = {}) {
186
258
  }
187
259
  }
188
260
  let extra;
189
- try { extra = tool.args ? tool.args(input || {}) : []; }
261
+ try { extra = tool.args ? tool.args(call.input) : []; }
190
262
  catch (e) { return { error: { code: -32602, message: String((e && e.message) || e) } }; }
191
- const r = runVerb(tool.verb, extra);
263
+ const r = runVerb(tool.verb, extra, call.cwd);
192
264
  return { result: { content: [{ type: 'text', text: r.ok ? r.stdout : (r.stderr || 'error') }], isError: !r.ok } };
193
265
  }
194
266
 
@@ -206,7 +278,19 @@ function createServer(opts = {}) {
206
278
  // non-array into the spawn.
207
279
  const tail = Array.isArray(res.args) ? res.args : [];
208
280
  const r = runVerb(res.verb, tail);
209
- if (!r.ok) return { error: { code: -32603, message: r.stderr || 'resource read failed' } };
281
+ if (!r.ok) {
282
+ // A VERDICT is data, not a failed read. `validate health` (pan://health) exits
283
+ // non-zero when its verdict is `broken` — CLI-REFERENCE: verdict commands set
284
+ // their exit code explicitly, for shell gating — while still printing the full
285
+ // JSON report. Over MCP the report IS the resource, so accept stdout when it is
286
+ // a JSON object carrying no error-family key. Anything else (no JSON, or an
287
+ // `error`/`*_error` key) is a genuine read failure → JSON-RPC error.
288
+ const text = resolveOverflow(r.stdout);
289
+ if (parseVerdict(text) !== null) {
290
+ return { result: { contents: [{ uri, mimeType: 'application/json', text }] } };
291
+ }
292
+ return { error: { code: -32603, message: r.stderr || 'resource read failed' } };
293
+ }
210
294
  return { result: { contents: [{ uri, mimeType: 'application/json', text: r.stdout }] } };
211
295
  }
212
296
 
@@ -315,6 +399,6 @@ function main() {
315
399
  if (require.main === module) main();
316
400
 
317
401
  module.exports = {
318
- createServer, defaultPanToolsPath, defaultSpawn, SERVER_INFO, toMcpTool, toMcpResource,
402
+ createServer, defaultPanToolsPath, defaultSpawn, parseVerdict, readPackageVersion, SERVER_INFO, toMcpTool, toMcpResource,
319
403
  PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION, SUPPORTED_VERSIONS_LIST, META_PROTOCOL_VERSION_KEY,
320
404
  };
@@ -39,7 +39,9 @@ const QUERY_RE = /^[\w .,:/&()-]{1,120}$/; // find-phase query fragment
39
39
  *
40
40
  * THE RULE FOR ADDING ONE — a resource must be readable on ANY project, including
41
41
  * a bare directory with no `.planning/`. If "no data yet" is reported as an error
42
- * (non-zero exit / an error-family key), it is a TOOL, not a resource: a client
42
+ * (an error-family key in the JSON it prints, or no JSON at all — a non-zero exit BY
43
+ * ITSELF is a verdict signal for shell gating, and the reader accepts the JSON as data;
44
+ * see server.cjs readResource), it is a TOOL, not a resource: a client
43
45
  * that lists resources and reads them should not collect failures for a young
44
46
  * project. `preview` is the worked example — `preview phases` exits non-zero
45
47
  * without a roadmap, so it is exposed as a tool below rather than as a resource.
@@ -62,7 +64,7 @@ const RESOURCES = [
62
64
  description: 'Phase inventory: the phase directories present, with a count.' },
63
65
  { uri: 'pan://progress', name: 'Progress', verb: 'progress', description: 'Requirement and plan completion progress.' },
64
66
  { uri: 'pan://health', name: 'Project health', verb: 'validate', args: ['health'],
65
- description: 'Health check over .planning/: issue codes with severities. Reports an unhealthy project as DATA (exit 0), so it is readable even on a broken or empty one.' },
67
+ description: 'Health check over .planning/: issue codes with severities. Reports an unhealthy project as DATA: the JSON verdict is the resource even when the CLI exits non-zero for shell gating, so it is readable on a broken or empty project.' },
66
68
  { uri: 'pan://links', name: 'Doc-code links', verb: 'links', args: ['validate'],
67
69
  description: 'Doc↔code link graph verdict: forward links, backlink contracts, and anchor targets, with finding codes.' },
68
70
  { uri: 'pan://cost', name: 'Token cost', verb: 'cost', args: ['report'],
@@ -138,7 +140,51 @@ const FORBIDDEN_VERB = /(^|-)(push|reset|rebase|force)($|-)/;
138
140
  // tools into one advertised list. Required after SPAWN_TOOLS/FORBIDDEN_VERB so the
139
141
  // native module (which imports nothing back from here) composes cleanly — no cycle.
140
142
  const { NATIVE_TOOLS } = require('./native-tools.cjs');
141
- const TOOLS = [...SPAWN_TOOLS, ...NATIVE_TOOLS];
143
+
144
+ // ─── Per-call project root (ADR-0045 D6, 2026-09) ───────────────────────────
145
+ //
146
+ // The server resolves its project as `opts.cwd || PAN_PROJECT_ROOT || process.cwd()`.
147
+ // Under Claude Code the process cwd IS the project. Under an Agent Plugins client
148
+ // the spec makes the PLUGIN ROOT the default working directory of a stdio server,
149
+ // so every verb would read `.planning/` from inside the plugin cache and report an
150
+ // empty project — cleanly, which is the worst kind of failure. So every TOOL takes
151
+ // an optional `cwd`: the absolute path of the project to operate on, honoured for
152
+ // that call only. Applied here, centrally, so a tool added later cannot miss it.
153
+ //
154
+ // Resources deliberately do NOT get it: their argv is a static array and the
155
+ // safety argument of ADR-0041 is that no client input reaches it.
156
+ const PROJECT_CWD_PROPERTY = Object.freeze({
157
+ type: 'string',
158
+ description: 'Absolute path of the PAN project to operate on. Optional: defaults to the directory the server was started in. Pass it when the server was launched from a plugin directory (Agent Plugins clients do this by default), or to address another project.',
159
+ });
160
+
161
+ const PROJECT_CWD_MAX = 1024;
162
+
163
+ /**
164
+ * Shape-validate a per-call project root: a non-empty absolute path with no NUL,
165
+ * within a sane length. Existence is the SERVER's check (it has fs); this module
166
+ * stays pure. Throws a message fit for a -32602 on failure.
167
+ */
168
+ function validateProjectCwd(value) {
169
+ if (typeof value !== 'string' || value.length === 0 || value.length > PROJECT_CWD_MAX) {
170
+ throw new Error(`Invalid "cwd": must be a non-empty string of at most ${PROJECT_CWD_MAX} chars`);
171
+ }
172
+ if (value.includes('\0')) throw new Error('Invalid "cwd": contains a NUL byte');
173
+ // Absolute on either platform family: `/…`, `C:\…`, `C:/…`, or a UNC `\\host\share`.
174
+ if (!/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(value)) throw new Error('Invalid "cwd": must be an absolute path');
175
+ return value;
176
+ }
177
+
178
+ /** Return a copy of a tool descriptor whose inputSchema also accepts `cwd`. Never mutates the source. */
179
+ function withProjectCwd(tool) {
180
+ const schema = tool.inputSchema || { type: 'object', additionalProperties: false, properties: {} };
181
+ return {
182
+ ...tool,
183
+ inputSchema: { ...schema, properties: { ...(schema.properties || {}), cwd: PROJECT_CWD_PROPERTY } },
184
+ };
185
+ }
186
+
187
+ const TOOLS = [...SPAWN_TOOLS, ...NATIVE_TOOLS].map(withProjectCwd);
142
188
 
143
189
  const byToolName = Object.create(null);
144
190
  for (const t of TOOLS) byToolName[t.name] = t;
@@ -148,4 +194,5 @@ for (const r of RESOURCES) byResourceUri[r.uri] = r;
148
194
  module.exports = {
149
195
  TOOLS, SPAWN_TOOLS, NATIVE_TOOLS, RESOURCES, byToolName, byResourceUri, FORBIDDEN_VERB,
150
196
  AGENT_RE, PHASE_RE, QUERY_RE, str,
197
+ PROJECT_CWD_PROPERTY, validateProjectCwd, withProjectCwd,
151
198
  };
@@ -11,8 +11,8 @@ PAN uses three abstract tiers instead of hardcoded model names:
11
11
  | Tier | Purpose | Anthropic | OpenAI | Google |
12
12
  |------|---------|-----------|--------|--------|
13
13
  | `reasoning` | Architecture, planning, complex decisions | inherit (your session's top-tier model) | inherit | inherit |
14
- | `mid` | Execution, research, verification | Sonnet | mid | mid |
15
- | `fast` | Read-only extraction, budget tasks | Haiku | fast | fast |
14
+ | `mid` | Execution, research, verification | Sonnet | mid | gemini-2.5-flash |
15
+ | `fast` | Read-only extraction, budget tasks | Haiku | fast | gemini-2.5-flash-lite |
16
16
 
17
17
  **Why `inherit` for reasoning?** Host runtimes map "opus" to a specific model version. PAN returns `inherit` for reasoning-tier agents, so they use whatever top-tier model the user has configured. This avoids version conflicts and silent fallbacks.
18
18
 
@@ -152,6 +152,7 @@ Report final status.
152
152
  | E003 | error | roadmap.md not found | No |
153
153
  | E004 | error | state.md not found | Yes |
154
154
  | E005 | error | config.json parse error | Yes |
155
+ | E006 | error | `.planning/` belongs to another tool (gsd-core markers found); PAN stops before E002-E005 and `--repair` writes nothing | No |
155
156
  | W001 | warning | project.md missing required section | No |
156
157
  | W002 | warning | state.md references invalid phase | Yes |
157
158
  | W003 | warning | config.json not found | Yes |
@@ -161,6 +162,7 @@ Report final status.
161
162
  | W007 | warning | Phase on disk but not in ROADMAP | No |
162
163
  | I001 | info | Plan without SUMMARY (may be in progress) | No |
163
164
  | I002 | info | Phase in ROADMAP ahead of current phase, not planned yet | No |
165
+ | I003 | info | Focus-model or campaign tree — the phase-model checks do not apply | No |
164
166
  | STATE_REQ_DRIFT | warning | state.md complete but REQUIREMENTS.md has unchecked boxes | Yes |
165
167
  | STATE_ROADMAP_DRIFT | warning | state.md complete but roadmap.md has unchecked plan boxes | Yes |
166
168
  | VERIFICATION_GATE_MISSING | warning | Phase has completed plans but no verification record | No |
@@ -13,7 +13,7 @@ ZCode through the one interface it speaks: **MCP**.
13
13
 
14
14
  ## How it fits
15
15
 
16
- ```
16
+ ```text
17
17
  ZCode harness (GLM-5.2) primary Agent drives everything; ported subagents fan out
18
18
  │ MCP · local stdio
19
19
  pan-wizard-core/mcp (SHARED) a thin, zero-dep bridge — verbs → MCP tools/resources