@marcomigozzi/trailhead 0.14.0 → 0.15.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 (92) hide show
  1. package/README.it.md +118 -30
  2. package/README.md +107 -29
  3. package/bin/base-preflight-docs.test.js +65 -0
  4. package/bin/execute-split-docs.test.js +146 -0
  5. package/bin/isolation-answer-docs.test.js +41 -0
  6. package/bin/isolation-copy-docs.test.js +28 -0
  7. package/bin/lib/codex-projection.js +1 -1
  8. package/bin/lib/codex-projection.test.js +41 -0
  9. package/bin/report-status-docs.test.js +195 -0
  10. package/bin/resolve-helpers-docs.test.js +36 -0
  11. package/bin/scope-confirm-skip-docs.test.js +70 -0
  12. package/bin/trailhead.js +3 -3
  13. package/bin/trailhead.test.js +341 -1
  14. package/bin/uat-setup-docs.test.js +65 -0
  15. package/package.json +1 -1
  16. package/plugins/trailhead/.claude-plugin/plugin.json +1 -1
  17. package/plugins/trailhead/agents/trailhead-code-review.md +15 -2
  18. package/plugins/trailhead/agents/trailhead-codebase-map.md +20 -1
  19. package/plugins/trailhead/agents/trailhead-debug.md +20 -1
  20. package/plugins/trailhead/agents/trailhead-executor.md +29 -2
  21. package/plugins/trailhead/agents/trailhead-fix.md +29 -2
  22. package/plugins/trailhead/agents/trailhead-plan.md +20 -1
  23. package/plugins/trailhead/agents/trailhead-research.md +22 -3
  24. package/plugins/trailhead/agents/trailhead-verify.md +15 -2
  25. package/plugins/trailhead/hooks/lib/base-preflight.test.js +513 -0
  26. package/plugins/trailhead/hooks/lib/commit-message-check.js +1 -1
  27. package/plugins/trailhead/hooks/lib/commit-message-check.test.js +3 -2
  28. package/plugins/trailhead/hooks/lib/commit-msg-module-repo.test.js +116 -0
  29. package/plugins/trailhead/hooks/lib/commit-msg-sync.test.js +100 -9
  30. package/plugins/trailhead/hooks/lib/dashboard.test.js +409 -0
  31. package/plugins/trailhead/hooks/lib/fixtures/commit-msg-legacy-js +104 -0
  32. package/plugins/trailhead/hooks/lib/isolation-answer.test.js +258 -0
  33. package/plugins/trailhead/hooks/lib/isolation-copy.test.js +298 -0
  34. package/plugins/trailhead/hooks/lib/issue-body.test.js +470 -0
  35. package/plugins/trailhead/hooks/lib/report-status.test.js +366 -0
  36. package/plugins/trailhead/hooks/lib/shell-scan.js +36 -1
  37. package/plugins/trailhead/hooks/lib/shell-scan.test.js +14 -0
  38. package/plugins/trailhead/hooks/lib/uat-backfill.test.js +150 -0
  39. package/plugins/trailhead/hooks/lib/uat-setup.test.js +340 -0
  40. package/plugins/trailhead/hooks/lib/work-state.test.js +45 -0
  41. package/plugins/trailhead/hooks/mod/README.md +38 -6
  42. package/plugins/trailhead/hooks/mod/map-pane-view.ts +168 -15
  43. package/plugins/trailhead/hooks/mod/map-pane.tsx +275 -106
  44. package/plugins/trailhead/hooks/mod/register.tsx +15 -2
  45. package/plugins/trailhead/hooks/mod/work-state-view.ts +17 -0
  46. package/plugins/trailhead/hooks/trailhead-install-guard.js +169 -34
  47. package/plugins/trailhead/hooks/trailhead-install-guard.test.js +180 -1
  48. package/plugins/trailhead/hooks/trailhead-search-guard.js +43 -7
  49. package/plugins/trailhead/hooks/trailhead-search-guard.test.js +66 -2
  50. package/plugins/trailhead/skills/_shared/choices.md +4 -2
  51. package/plugins/trailhead/skills/_shared/configuration-reference.md +15 -3
  52. package/plugins/trailhead/skills/_shared/load-first.md +3 -3
  53. package/plugins/trailhead/skills/_shared/multi-map.md +2 -2
  54. package/plugins/trailhead/skills/_shared/session-handoff.md +1 -1
  55. package/plugins/trailhead/skills/_shared/substrate-commands.md +22 -11
  56. package/plugins/trailhead/skills/_shared/substrate.md +6 -4
  57. package/plugins/trailhead/skills/_shared/teamwork.md +16 -7
  58. package/plugins/trailhead/skills/_shared/techniques/acceptance-testing.md +17 -9
  59. package/plugins/trailhead/skills/_shared/techniques/code-review.md +1 -1
  60. package/plugins/trailhead/skills/_shared/techniques/codebase-map.md +1 -1
  61. package/plugins/trailhead/skills/_shared/techniques/debug.md +2 -0
  62. package/plugins/trailhead/skills/_shared/techniques/research.md +4 -2
  63. package/plugins/trailhead/skills/_shared/techniques/verify.md +1 -1
  64. package/plugins/trailhead/skills/_shared/techniques.md +12 -2
  65. package/plugins/trailhead/skills/trailhead/SKILL.md +1 -1
  66. package/plugins/trailhead/skills/trailhead-capture/SKILL.md +1 -1
  67. package/plugins/trailhead/skills/trailhead-capture/references/capture.md +2 -2
  68. package/plugins/trailhead/skills/trailhead-chart/SKILL.md +1 -1
  69. package/plugins/trailhead/skills/trailhead-chart/references/charting.md +1 -1
  70. package/plugins/trailhead/skills/trailhead-manage/SKILL.md +1 -1
  71. package/plugins/trailhead/skills/trailhead-manage/references/auditing.md +1 -1
  72. package/plugins/trailhead/skills/trailhead-view/SKILL.md +8 -6
  73. package/plugins/trailhead/skills/trailhead-work/SKILL.md +14 -12
  74. package/plugins/trailhead/skills/trailhead-work/references/auto.md +4 -4
  75. package/plugins/trailhead/skills/trailhead-work/references/executor-brief.md +29 -0
  76. package/plugins/trailhead/skills/trailhead-work/references/ticket-engines.md +26 -10
  77. package/plugins/trailhead/templates/trailhead-base-preflight.js +305 -0
  78. package/plugins/trailhead/templates/trailhead-commit-msg +38 -102
  79. package/plugins/trailhead/templates/trailhead-commit-msg-sync.js +58 -27
  80. package/plugins/trailhead/templates/trailhead-commit-msg.cjs +114 -0
  81. package/plugins/trailhead/templates/trailhead-dashboard.js +340 -0
  82. package/plugins/trailhead/templates/trailhead-isolation-answer.js +227 -0
  83. package/plugins/trailhead/templates/trailhead-isolation-copy.js +239 -0
  84. package/plugins/trailhead/templates/trailhead-issue-body.js +459 -0
  85. package/plugins/trailhead/templates/trailhead-report-status.js +274 -0
  86. package/plugins/trailhead/templates/trailhead-uat-backfill.js +114 -0
  87. package/plugins/trailhead/templates/trailhead-uat-setup.js +385 -0
  88. package/plugins/trailhead/templates/trailhead-work-state.js +25 -7
  89. package/plugins/trailhead/tests/map-pane-ui.test.ts +566 -19
  90. package/plugins/trailhead/tests/map-pane-view.test.ts +304 -16
  91. package/plugins/trailhead/tests/work-state-view.test.ts +25 -1
  92. package/plugins/trailhead/types/index.d.ts +37 -3
@@ -0,0 +1,385 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // trailhead UAT setup (self-contained, ships in templates/ so it reaches every
4
+ // install channel: bin/trailhead.js copies templates/ wholesale for Claude/npm
5
+ // and Codex). Reads the project's `uat.setup` / `uat.accounts` config, reports
6
+ // what a UAT needs, and runs the setup steps in order. #252.
7
+ //
8
+ // CLI:
9
+ // node trailhead-uat-setup.js plan --repo <working-root> [--config-root <project-root>]
10
+ // node trailhead-uat-setup.js run --repo <working-root> [--config-root <project-root>]
11
+ // [--from <i>] [--only <i>] [--ready-timeout <s>] [--step-timeout <s>]
12
+ // --config-root is the original checkout the effective config was loaded from
13
+ // (defaults to --repo); a worktree/clone workspace never re-resolves config.
14
+ //
15
+ // Config: `uat.setup` (ordered array of {name, run, check?, note?}) and `uat.accounts`
16
+ // ({role: {user, secret}}, secret a bare $ENV reference, never a literal), nested
17
+ // ({"uat":{"setup":[...]}}) or flat ({"uat.setup":[...]}); nested wins when a file
18
+ // carries both. The project file (read from --config-root) replaces the global one
19
+ // (${CLAUDE_CONFIG_DIR:-~/.claude}/trailhead/config.json) key by key as a whole value.
20
+ //
21
+ // plan: validates, lists the steps (index, name, note, check present) and the $ENV
22
+ // names each step / account references with whether each is set. Runs nothing, prints
23
+ // no value.
24
+ // run: per step, every referenced $NAME / ${NAME} must be set and non-empty (else
25
+ // missing-env, nothing runs); a passing `check` -> skipped; else `run` via `sh -c` at
26
+ // --repo (non-zero -> failed); with a `check`, poll it after `run` until it passes or
27
+ // --ready-timeout (default 60 s) elapses (-> not-ready). Each run/check invocation is
28
+ // killed after --step-timeout (default 600 s): a run -> timeout; a check counts as
29
+ // failing; while polling, each check is capped at the remaining ready time. Stops at the
30
+ // first failing step. A `run`'s output goes to a temp file, never a pipe, so a backgrounded
31
+ // process (a dev server) cannot block the helper; it should redirect its own output, else
32
+ // it keeps writing to that (deleted) file. A `check`'s output is ignored.
33
+ // `$NAME` / `${NAME}` inside single quotes, in a `#` comment or written `\$NAME` is not a
34
+ // reference; with an unbalanced quote every `$NAME` counts. Timeouts are capped at 86400 s.
35
+ // Prints one JSON line:
36
+ // {"status","steps":[{index,name,result,code?,output?,missing?}],"failedStep"?,
37
+ // "accounts"?,"warnings":[],"message"?}
38
+ // status: unconfigured | none | invalid | ready | failed
39
+ // result: skipped | ran | failed | missing-env | not-ready | timeout
40
+ // Only the failing step carries `output`: the last 2000 chars, with the value of every
41
+ // referenced variable redacted to its $NAME (best effort, not a guarantee).
42
+ // Fail closed: only ready and none let the caller go on; unconfigured goes to the probe.
43
+ // Exit 0 whenever a JSON line is printed; exit 2 only on a usage error.
44
+
45
+ const fs = require('fs');
46
+ const os = require('os');
47
+ const path = require('path');
48
+ const { spawnSync } = require('child_process');
49
+
50
+ const CONFIG_REL = path.join('.trailhead', 'config.json');
51
+ const OUTPUT_TAIL = 2000;
52
+ const READ_BYTES = 65536;
53
+ const POLL_MS = 500;
54
+ const DEFAULT_READY_S = 60;
55
+ const DEFAULT_STEP_S = 600;
56
+ const MAX_TIMEOUT_S = 86400;
57
+ const STEP_KEYS = ['name', 'run', 'check', 'note'];
58
+ const ACCOUNT_KEYS = ['user', 'secret'];
59
+ const VALUED = ['repo', 'config-root', 'from', 'only', 'ready-timeout', 'step-timeout'];
60
+ const COMMANDS = ['plan', 'run'];
61
+ const REF = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g;
62
+ const BARE_REF = /^(?:\$([A-Za-z_][A-Za-z0-9_]*)|\$\{([A-Za-z_][A-Za-z0-9_]*)\})$/;
63
+
64
+ function parseArgs(argv) {
65
+ const command = argv[0];
66
+ if (!COMMANDS.includes(command)) return { error: `usage: first argument must be one of ${COMMANDS.join(', ')}` };
67
+ const out = { command };
68
+ for (let i = 1; i < argv.length; i++) {
69
+ const a = argv[i];
70
+ const name = a.startsWith('--') ? a.slice(2) : null;
71
+ if (!name || !VALUED.includes(name)) return { error: `usage: unknown argument ${a}` };
72
+ const v = argv[++i];
73
+ if (v === undefined || v.startsWith('--')) return { error: `usage: ${a} needs a value` };
74
+ out[name] = v;
75
+ }
76
+ if (!out.repo) return { error: 'usage: missing --repo <working-root>' };
77
+ for (const k of ['from', 'only']) {
78
+ if (out[k] !== undefined && !/^\d+$/.test(out[k])) return { error: `usage: --${k} needs a non-negative integer` };
79
+ }
80
+ for (const k of ['ready-timeout', 'step-timeout']) {
81
+ if (out[k] !== undefined && !(Number.isFinite(Number(out[k])) && Number(out[k]) > 0 && Number(out[k]) <= MAX_TIMEOUT_S)) return { error: `usage: --${k} needs a positive number of seconds, at most ${MAX_TIMEOUT_S}` };
82
+ }
83
+ if (out.from !== undefined && out.only !== undefined) return { error: 'usage: --from and --only are exclusive' };
84
+ return out;
85
+ }
86
+
87
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
88
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
89
+ const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
90
+
91
+ // Reads and parses one config file. { state: 'unset' } | { state: 'ok', cfg } | { state: 'invalid', message }
92
+ function readFile(file, fs_) {
93
+ let text;
94
+ try {
95
+ text = fs_.readFileSync(file, 'utf8');
96
+ } catch (err) {
97
+ if (err && err.code === 'ENOENT') return { state: 'unset' };
98
+ return { state: 'invalid', message: `cannot read ${file}: ${err && err.message ? err.message : err}` };
99
+ }
100
+ let cfg;
101
+ try {
102
+ cfg = JSON.parse(text);
103
+ } catch (err) {
104
+ return { state: 'invalid', message: `${file} is not valid JSON` };
105
+ }
106
+ if (!isObject(cfg)) return { state: 'invalid', message: `${file} is not a JSON object` };
107
+ if (has(cfg, 'uat') && !isObject(cfg.uat)) return { state: 'invalid', message: `uat in ${file} must be an object` };
108
+ return { state: 'ok', cfg };
109
+ }
110
+
111
+ // Picks `uat.<key>` out of a parsed config: { found, value, warning? }.
112
+ function pick(cfg, key, file) {
113
+ const nested = isObject(cfg.uat) && has(cfg.uat, key);
114
+ const flat = has(cfg, `uat.${key}`);
115
+ if (!nested && !flat) return { found: false };
116
+ const out = { found: true, value: nested ? cfg.uat[key] : cfg[`uat.${key}`] };
117
+ if (nested && flat) out.warning = `${file} sets uat.${key} in both nested and flat form; the nested form wins`;
118
+ return out;
119
+ }
120
+
121
+ function globalConfigPath(env) {
122
+ const base = env.CLAUDE_CONFIG_DIR || path.join(env.HOME || os.homedir(), '.claude');
123
+ return path.join(base, 'trailhead', 'config.json');
124
+ }
125
+
126
+ function validateSetup(value, where) {
127
+ if (!Array.isArray(value)) return `uat.setup in ${where} must be an array of steps`;
128
+ for (let i = 0; i < value.length; i++) {
129
+ const s = value[i];
130
+ if (!isObject(s)) return `uat.setup[${i}] in ${where} must be an object`;
131
+ const extra = Object.keys(s).find((k) => !STEP_KEYS.includes(k));
132
+ if (extra) return `uat.setup[${i}] in ${where} has an unknown key: ${extra}`;
133
+ if (!nonEmpty(s.name)) return `uat.setup[${i}] in ${where} needs a non-empty string name`;
134
+ if (!nonEmpty(s.run)) return `uat.setup[${i}] in ${where} needs a non-empty string run`;
135
+ for (const k of ['check', 'note']) {
136
+ if (has(s, k) && !nonEmpty(s[k])) return `uat.setup[${i}].${k} in ${where} must be a non-empty string`;
137
+ }
138
+ }
139
+ return null;
140
+ }
141
+
142
+ function validateAccounts(value, where) {
143
+ if (!isObject(value)) return `uat.accounts in ${where} must be an object of role -> {user, secret}`;
144
+ for (const [role, a] of Object.entries(value)) {
145
+ if (!isObject(a)) return `uat.accounts.${role} in ${where} must be an object`;
146
+ const extra = Object.keys(a).find((k) => !ACCOUNT_KEYS.includes(k));
147
+ if (extra) return `uat.accounts.${role} in ${where} has an unknown key: ${extra}`;
148
+ if (!nonEmpty(a.user)) return `uat.accounts.${role} in ${where} needs a non-empty string user`;
149
+ if (typeof a.secret !== 'string' || !BARE_REF.test(a.secret)) {
150
+ return `uat.accounts.${role}.secret in ${where} must be a bare $ENV reference ($NAME or \${NAME}), never a literal`;
151
+ }
152
+ }
153
+ return null;
154
+ }
155
+
156
+ const VALIDATORS = { setup: validateSetup, accounts: validateAccounts };
157
+
158
+ // Effective { setup, accounts } (undefined when unset) or { error }. The project file
159
+ // replaces the global one key by key as a whole value.
160
+ function readConfig(configRoot, env, fs_, warnings) {
161
+ const files = [path.join(configRoot, CONFIG_REL), globalConfigPath(env)];
162
+ const parsed = [];
163
+ for (const file of files) {
164
+ const r = readFile(file, fs_);
165
+ if (r.state === 'invalid') return { error: r.message };
166
+ parsed.push({ file, cfg: r.state === 'ok' ? r.cfg : null });
167
+ }
168
+ const out = {};
169
+ for (const key of ['setup', 'accounts']) {
170
+ for (const { file, cfg } of parsed) {
171
+ if (!cfg) continue;
172
+ const p = pick(cfg, key, file);
173
+ if (!p.found) continue;
174
+ const problem = VALIDATORS[key](p.value, file);
175
+ if (problem) return { error: problem };
176
+ if (p.warning) warnings.push(p.warning);
177
+ out[key] = p.value;
178
+ break;
179
+ }
180
+ }
181
+ return out;
182
+ }
183
+
184
+ // Text with the spans that are never env references blanked out: single-quoted spans
185
+ // and backslash-escaped characters (`\$`) and comments (a `#` at a word start outside quotes,
186
+ // to end of line). A single quote inside double quotes is literal. Fail closed: a quote span
187
+ // still open at the end drops every exemption, so every `$NAME` counts.
188
+ function liveText(t) {
189
+ let out = '';
190
+ let single = false;
191
+ let double = false;
192
+ for (let i = 0; i < t.length; i++) {
193
+ const c = t[i];
194
+ if (single) {
195
+ if (c === "'") single = false;
196
+ out += ' ';
197
+ } else if (c === '\\') {
198
+ i++;
199
+ out += ' ';
200
+ } else if (c === '#' && !double && (i === 0 || /[\s;&|()]/.test(t[i - 1]))) {
201
+ while (i < t.length && t[i] !== '\n') { out += ' '; i++; }
202
+ if (i < t.length) out += '\n';
203
+ } else if (c === "'" && !double) {
204
+ single = true;
205
+ out += ' ';
206
+ } else {
207
+ if (c === '"') double = !double;
208
+ out += c;
209
+ }
210
+ }
211
+ return single || double ? t : out;
212
+ }
213
+
214
+ function refsOf(...texts) {
215
+ const names = [];
216
+ for (const t of texts) {
217
+ if (typeof t !== 'string') continue;
218
+ for (const m of liveText(t).matchAll(REF)) {
219
+ const n = m[1] || m[2];
220
+ if (!names.includes(n)) names.push(n);
221
+ }
222
+ }
223
+ return names;
224
+ }
225
+
226
+ const bareName = (s) => { const m = BARE_REF.exec(s); return m ? m[1] || m[2] : null; };
227
+
228
+ function describe(setup, accounts, env) {
229
+ const state = (name) => ({ name, set: typeof env[name] === 'string' && env[name] !== '' });
230
+ const steps = setup.map((s, index) => ({
231
+ index,
232
+ name: s.name,
233
+ ...(s.note ? { note: s.note } : {}),
234
+ check: Boolean(s.check),
235
+ env: refsOf(s.run, s.check).map(state),
236
+ }));
237
+ const accts = Object.entries(accounts).map(([role, a]) => {
238
+ const userEnv = bareName(a.user);
239
+ return { role, user: userEnv ? null : a.user, userEnv: userEnv ? state(userEnv) : null, secretEnv: state(bareName(a.secret)) };
240
+ });
241
+ return { steps, accounts: accts };
242
+ }
243
+
244
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
245
+
246
+ // Redacts the value of every referenced variable to its $NAME, longest value first.
247
+ function redactor(names, env) {
248
+ const pairs = names
249
+ .filter((n) => typeof env[n] === 'string' && env[n] !== '')
250
+ .map((n) => [n, env[n]])
251
+ .sort((a, b) => b[1].length - a[1].length);
252
+ return (text) => pairs.reduce((t, [n, v]) => t.split(v).join(`$${n}`), text);
253
+ }
254
+
255
+ // Runs `sh -c command` at repo; the output of a `run` goes to a temp file (a check's is ignored). Returns
256
+ // { code, timedOut, tail } where tail is the bounded last chunk of the output.
257
+ function sh(command, repo, env, timeoutMs, wantOutput) {
258
+ const timeout = Math.max(1, Math.ceil(timeoutMs));
259
+ if (!wantOutput) {
260
+ const r = spawnSync('sh', ['-c', command], { cwd: repo, env, stdio: 'ignore', timeout, killSignal: 'SIGKILL' });
261
+ const timedOut = Boolean(r.error && r.error.code === 'ETIMEDOUT');
262
+ return { code: r.status, timedOut, spawnError: r.error && !timedOut ? r.error.message : null, tail: '' };
263
+ }
264
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trailhead-uat-'));
265
+ const file = path.join(dir, 'out');
266
+ const fd = fs.openSync(file, 'w');
267
+ try {
268
+ const r = spawnSync('sh', ['-c', command], { cwd: repo, env, stdio: ['ignore', fd, fd], timeout, killSignal: 'SIGKILL' });
269
+ const timedOut = Boolean(r.error && r.error.code === 'ETIMEDOUT');
270
+ const res = { code: r.status, timedOut, spawnError: r.error && !timedOut ? r.error.message : null, tail: '' };
271
+ if (wantOutput) {
272
+ const size = fs.fstatSync(fd).size;
273
+ const len = Math.min(size, READ_BYTES);
274
+ const buf = Buffer.alloc(len);
275
+ const rfd = fs.openSync(file, 'r');
276
+ try { fs.readSync(rfd, buf, 0, len, size - len); } finally { fs.closeSync(rfd); }
277
+ res.tail = buf.toString('utf8');
278
+ }
279
+ return res;
280
+ } finally {
281
+ fs.closeSync(fd);
282
+ fs.rmSync(dir, { recursive: true, force: true });
283
+ }
284
+ }
285
+
286
+ const passes = (r) => !r.timedOut && !r.spawnError && r.code === 0;
287
+
288
+ function finalTail(text, redact, extra) {
289
+ const t = redact(text) + (extra || '');
290
+ return t.length > OUTPUT_TAIL ? '...' + t.slice(t.length - OUTPUT_TAIL) : t;
291
+ }
292
+
293
+ function runStep(step, index, ctx) {
294
+ const { repo, env, stepMs, readyMs, redact } = ctx;
295
+ const base = { index, name: step.name };
296
+ const missing = refsOf(step.run, step.check).filter((n) => typeof env[n] !== 'string' || env[n] === '');
297
+ if (missing.length > 0) return { ...base, result: 'missing-env', missing };
298
+ if (step.check && passes(sh(step.check, repo, env, stepMs, false))) return { ...base, result: 'skipped' };
299
+ const r = sh(step.run, repo, env, stepMs, true);
300
+ if (r.timedOut) return { ...base, result: 'timeout', output: finalTail(r.tail, redact, `\n(timed out after ${stepMs / 1000}s)`) };
301
+ if (r.spawnError || r.code !== 0) {
302
+ return { ...base, result: 'failed', code: r.code, output: finalTail(r.tail, redact, r.spawnError ? `\n${r.spawnError}` : '') };
303
+ }
304
+ if (!step.check) return { ...base, result: 'ran' };
305
+ const deadline = Date.now() + readyMs;
306
+ for (;;) {
307
+ const remaining = deadline - Date.now();
308
+ if (passes(sh(step.check, repo, env, Math.max(1, Math.min(stepMs, remaining)), false))) return { ...base, result: 'ran' };
309
+ const left = deadline - Date.now();
310
+ if (left <= 0) break;
311
+ sleep(Math.min(POLL_MS, left));
312
+ }
313
+ return { ...base, result: 'not-ready', output: finalTail(r.tail, redact, `\n(check "${step.check}" did not pass within ${readyMs / 1000}s)`) };
314
+ }
315
+
316
+ function execute(parsed, cwd, env, fs_) {
317
+ const repo = path.resolve(cwd, parsed.repo);
318
+ const configRoot = path.resolve(cwd, parsed['config-root'] || parsed.repo);
319
+ const warnings = [];
320
+ const result = { status: 'invalid', steps: [], warnings };
321
+ const cfg = readConfig(configRoot, env, fs_, warnings);
322
+ if (cfg.error) return { ...result, message: cfg.error };
323
+
324
+ const accounts = cfg.accounts || {};
325
+ const merged = { ...process.env, ...env };
326
+ const view = describe(cfg.setup || [], accounts, merged);
327
+ const accountsOut = view.accounts.length > 0 ? { accounts: view.accounts } : {};
328
+ if (cfg.setup === undefined) return { ...result, status: 'unconfigured', ...accountsOut };
329
+ if (cfg.setup.length === 0) return { ...result, status: 'none', ...accountsOut };
330
+
331
+ if (parsed.command === 'plan') return { ...result, status: 'ready', steps: view.steps, ...accountsOut };
332
+
333
+ const total = cfg.setup.length;
334
+ const pickIndex = parsed.only !== undefined ? Number(parsed.only) : parsed.from !== undefined ? Number(parsed.from) : 0;
335
+ if (pickIndex >= total) return { ...result, message: `step index ${pickIndex} is out of range (${total} steps)` };
336
+ const indexes = parsed.only !== undefined ? [pickIndex] : cfg.setup.map((_, i) => i).filter((i) => i >= pickIndex);
337
+
338
+ const names = [...new Set([...view.steps.flatMap((s) => s.env.map((e) => e.name)), ...view.accounts.flatMap((a) => [a.userEnv, a.secretEnv].filter(Boolean).map((e) => e.name))])];
339
+ const ctx = {
340
+ repo,
341
+ env: merged,
342
+ stepMs: Number(parsed['step-timeout'] || DEFAULT_STEP_S) * 1000,
343
+ readyMs: Number(parsed['ready-timeout'] || DEFAULT_READY_S) * 1000,
344
+ redact: redactor(names, merged),
345
+ };
346
+ for (const i of indexes) {
347
+ let r;
348
+ try {
349
+ r = runStep(cfg.setup[i], i, ctx);
350
+ } catch (err) {
351
+ return { ...result, message: 'error: ' + (err && err.message ? err.message : String(err)) };
352
+ }
353
+ result.steps.push(r);
354
+ if (!['skipped', 'ran'].includes(r.result)) return { ...result, status: 'failed', failedStep: i };
355
+ }
356
+ return { ...result, status: 'ready' };
357
+ }
358
+
359
+ function main(argv, { cwd, stdout, env, fs: fsMod } = {}) {
360
+ const cwd_ = cwd || process.cwd();
361
+ const out = stdout || process.stdout;
362
+ const env_ = env || process.env;
363
+ const fs_ = fsMod || fs;
364
+
365
+ const parsed = parseArgs(argv || []);
366
+ if (parsed.error) {
367
+ process.stderr.write(parsed.error + '\n');
368
+ return 2;
369
+ }
370
+ let result;
371
+ try {
372
+ result = execute(parsed, cwd_, env_, fs_);
373
+ } catch (err) {
374
+ result = { status: 'invalid', steps: [], warnings: [], message: 'error: ' + (err && err.message ? err.message : String(err)) };
375
+ }
376
+ out.write(JSON.stringify(result) + '\n');
377
+ return 0;
378
+ }
379
+
380
+ module.exports = { parseArgs, readConfig, main };
381
+
382
+ if (require.main === module) {
383
+ const code = main(process.argv.slice(2), { cwd: process.cwd(), stdout: process.stdout, env: process.env });
384
+ process.exit(code);
385
+ }
@@ -9,14 +9,17 @@
9
9
  // node trailhead-work-state.js set [--repo <dir>] [--map <n>|none] [--ticket <n>]
10
10
  // [--title <t>] [--step <step>] [--auto true|false] [--auto-done <n>]
11
11
  // node trailhead-work-state.js clear [--repo <dir>]
12
+ // `clear` removes both work-state.json and the session-ticket marker, each
13
+ // attempted independently.
12
14
  // --repo defaults to cwd. `set` merges the given fields onto the existing file
13
15
  // (only --step at each step change); a --ticket other than the one on file
14
16
  // starts from an empty state. File shape:
15
17
  // { map, ticket, title, step, auto, autoDone, session, updatedAt }
16
18
  // autoDone: tickets resolved so far in the autonomous run (non-negative
17
19
  // integer, default 0; reset to 0 whenever auto is false).
18
- // Prints one JSON line {"status","path","state"?,"message"?}.
20
+ // Prints one JSON line {"status","path","state"?,"sessionTicket"?,"message"?}.
19
21
  // status: written | cleared | absent | skipped
22
+ // sessionTicket (clear only): removed | absent | skipped
20
23
  // Exit 0 on every normal outcome and on any unexpected I/O error (it must
21
24
  // never block the caller: status skipped with the message); exit 2 only on a
22
25
  // usage or validation error (nothing is written).
@@ -27,6 +30,7 @@ const crypto = require('crypto');
27
30
 
28
31
  const STATE_DIR = '.trailhead';
29
32
  const STATE_FILE = 'work-state.json';
33
+ const TICKET_MARKER = 'session-ticket';
30
34
  const STEPS = ['discuss', 'plan', 'execute', 'verify', 'resolve', 'paused'];
31
35
  const TITLE_MAX = 200;
32
36
 
@@ -145,6 +149,18 @@ function writeAtomic(dir, file, text, fsMod) {
145
149
  }
146
150
  }
147
151
 
152
+ // Removes one file; never throws. Returns { status, message? } where status is
153
+ // doneLabel (removed), absentLabel (not there) or skipped (I/O error).
154
+ function removeFile(file, fsMod, doneLabel, absentLabel) {
155
+ try {
156
+ if (!fsMod.existsSync(file)) return { status: absentLabel };
157
+ fsMod.unlinkSync(file);
158
+ return { status: doneLabel };
159
+ } catch (err) {
160
+ return { status: 'skipped', message: 'error: ' + (err && err.message ? err.message : String(err)) };
161
+ }
162
+ }
163
+
148
164
  function writeResult(stdout, result) {
149
165
  stdout.write(JSON.stringify(result) + '\n');
150
166
  }
@@ -166,12 +182,14 @@ function main(argv, { cwd, stdout, env, fs: fsMod, now } = {}) {
166
182
  const file = path.join(dir, STATE_FILE);
167
183
  try {
168
184
  if (parsed.command === 'clear') {
169
- if (!fs_.existsSync(file)) {
170
- writeResult(out, { status: 'absent', path: file });
171
- return 0;
172
- }
173
- fs_.unlinkSync(file);
174
- writeResult(out, { status: 'cleared', path: file });
185
+ // Both markers are removed independently: a missing or failing first
186
+ // removal never skips the second (#253).
187
+ const state = removeFile(file, fs_, 'cleared', 'absent');
188
+ const marker = removeFile(path.join(dir, TICKET_MARKER), fs_, 'removed', 'absent');
189
+ const result = { status: state.status, path: file, sessionTicket: marker.status };
190
+ const message = [state.message, marker.message].filter(Boolean).join('; ');
191
+ if (message) result.message = message;
192
+ writeResult(out, result);
175
193
  return 0;
176
194
  }
177
195