@skitterbyte/skitterspec 23.23.3 → 23.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/env/config.js CHANGED
@@ -344,6 +344,16 @@ const DEFAULT_CONFIG = Object.freeze({
344
344
  // adapter, `{name, command, format}` is bring-your-own.
345
345
  reviewers: Object.freeze([]),
346
346
  }),
347
+ // Autonomous runs (`spec-env run`, feat-autonomous-run). `default` is the
348
+ // mode a spec runs in when neither its `> **Run:**` header nor a flag says:
349
+ // "supervised" (stop on every phase's page, today's behaviour) or "auto"
350
+ // (build every phase, commit each, stop only on a stop condition). `then` is
351
+ // how an autonomous run ends: "pause" (one final page that waits), "push"
352
+ // (push the branch) or "pr" (`/spec-complete`'s PR run). Configuring push or
353
+ // pr IS the push consent for runs that take it. `maxFixAttempts` bounds the
354
+ // tries at a red phase before the run stops. An unrecognised value falls back
355
+ // to its default — never to "auto": a typo must not make a run unattended.
356
+ auto: Object.freeze({ default: 'supervised', then: 'pause', maxFixAttempts: 3 }),
347
357
  // Live overlay (`spec-env live`). `migrations` is a list of globs marking
348
358
  // migration files; a branch that changes any of them is treated as stateful and
349
359
  // `live take` refuses it (code-only v1). Default: none (nothing is stateful).
@@ -458,6 +468,7 @@ function defaults() {
458
468
  guards: { ...DEFAULT_CONFIG.guards },
459
469
  teardown: { ...DEFAULT_CONFIG.teardown },
460
470
  review: { ...DEFAULT_CONFIG.review, reviewers: [] },
471
+ auto: { ...DEFAULT_CONFIG.auto },
461
472
  live: { migrations: [], afterSwitch: [] },
462
473
  hotfix: { ...DEFAULT_CONFIG.hotfix, targets: [] },
463
474
  }
@@ -858,6 +869,13 @@ function mergeConfig(base, parsed) {
858
869
  }
859
870
  }
860
871
 
872
+ if (isObject(parsed.auto)) {
873
+ if (parsed.auto.default === 'auto' || parsed.auto.default === 'supervised') base.auto.default = parsed.auto.default
874
+ if (['pause', 'push', 'pr'].includes(parsed.auto.then)) base.auto.then = parsed.auto.then
875
+ const n = parsed.auto.maxFixAttempts
876
+ if (Number.isInteger(n) && n >= 0) base.auto.maxFixAttempts = n
877
+ }
878
+
861
879
  if (isObject(parsed.spec) && Array.isArray(parsed.spec.companionPaths)) {
862
880
  base.spec.companionPaths = normalizeFileList(parsed.spec.companionPaths)
863
881
  }
package/src/env/epic.js CHANGED
@@ -419,7 +419,7 @@ function formatEpicStatus(s) {
419
419
  if (!s.found && !s.members.length) {
420
420
  return `no epic named ${s.epic}, and no spec names it as its Epic${s.here ? ` in ${s.here}` : ''}.\n`
421
421
  }
422
- const lanes = s.lanes === null ? 'no lane cap' : `${s.lanes} lanes, ${s.freeLanes} free`
422
+ const lanes = s.lanes === null ? 'no lane cap' : `${s.lanes} ${s.lanes === 1 ? 'lane' : 'lanes'}, ${s.freeLanes} free`
423
423
  const where = s.here ? ` · headers from ${s.here}` : s.found ? '' : ' · epic not on the base branch'
424
424
  const out = []
425
425
  if (!s.members.length) {
@@ -62,7 +62,7 @@ function stepItem(st, freeLanes) {
62
62
  }
63
63
 
64
64
  function renderEpicPage(answer, { refreshSeconds = REFRESH_SECONDS, project = null } = {}) {
65
- const lanes = answer.lanes === null ? 'no lane cap' : `${answer.lanes} lanes, ${answer.freeLanes} free`
65
+ const lanes = answer.lanes === null ? 'no lane cap' : `${answer.lanes} ${answer.lanes === 1 ? 'lane' : 'lanes'}, ${answer.freeLanes} free`
66
66
  const { rows, next } = answer.rows ? { rows: answer.rows, next: answer.next } : epicRows(answer)
67
67
  const { progress, groups, steps } = answer.steps ? answer : epicPlan(answer, { rows, next })
68
68
  const byName = new Map(rows.map((r) => [r.spec, r]))
package/src/env/hooks.js CHANGED
@@ -82,7 +82,18 @@ const HOOKS = [
82
82
  matcher: 'Edit|Write|NotebookEdit|MultiEdit|Bash',
83
83
  timeout: HOOK_TIMEOUT,
84
84
  },
85
- ].map((h) => ({ ...h, script: `${h.stem}.cjs`, re: hookStemRe(h.stem) }))
85
+ {
86
+ // Notes a context compaction against the phase an autonomous run is
87
+ // building (feat-autonomous-run). A different EVENT, not a different
88
+ // matcher: it fires before the harness compacts, on either trigger, so it
89
+ // carries no matcher at all. It decides nothing and never blocks.
90
+ key: 'run-compact',
91
+ stem: '.claude/hooks/run-compact',
92
+ event: 'PreCompact',
93
+ matcher: null,
94
+ timeout: HOOK_TIMEOUT,
95
+ },
96
+ ].map((h) => ({ event: 'PreToolUse', ...h, script: `${h.stem}.cjs`, re: hookStemRe(h.stem) }))
86
97
 
87
98
  function isObject(value) {
88
99
  return value !== null && typeof value === 'object' && !Array.isArray(value)
@@ -105,10 +116,17 @@ function commandFor(script) {
105
116
  }
106
117
 
107
118
  function hookEntry(hook = HOOKS[0]) {
108
- return {
109
- matcher: hook.matcher,
110
- hooks: [{ type: 'command', command: commandFor(hook.script), timeout: hook.timeout }],
111
- }
119
+ const hooks = [{ type: 'command', command: commandFor(hook.script), timeout: hook.timeout }]
120
+ // An event with no matcher (PreCompact here) is written without the key, so
121
+ // it fires on every trigger rather than on a matcher of the empty string.
122
+ return hook.matcher ? { matcher: hook.matcher, hooks } : { hooks }
123
+ }
124
+
125
+ // Every hook entry this package writes, grouped by the event it belongs under.
126
+ function entriesByEvent() {
127
+ const out = {}
128
+ for (const h of HOOKS) (out[h.event] = out[h.event] || []).push(hookEntry(h))
129
+ return out
112
130
  }
113
131
 
114
132
  /**
@@ -149,7 +167,8 @@ function registeredHooks(preToolUse, hook = HOOKS[0]) {
149
167
  */
150
168
  function ensureOneHook(parsed, hook) {
151
169
  const hooks = isObject(parsed.hooks) ? parsed.hooks : {}
152
- const preToolUse = Array.isArray(hooks.PreToolUse) ? hooks.PreToolUse : []
170
+ const event = hook.event || 'PreToolUse'
171
+ const preToolUse = Array.isArray(hooks[event]) ? hooks[event] : []
153
172
 
154
173
  // Registered already — but possibly under a path that no longer exists, since
155
174
  // the script's extension changed. Rewrite the path IN PLACE rather than
@@ -166,7 +185,7 @@ function ensureOneHook(parsed, hook) {
166
185
  return { changed: true, reason: 'migrated' }
167
186
  }
168
187
 
169
- parsed.hooks = { ...hooks, PreToolUse: [...preToolUse, hookEntry(hook)] }
188
+ parsed.hooks = { ...hooks, [event]: [...preToolUse, hookEntry(hook)] }
170
189
  return { changed: true, reason: 'added' }
171
190
  }
172
191
 
@@ -192,7 +211,7 @@ function ensureHooks(dir, { local = false } = {}) {
192
211
  raw = fs.readFileSync(file, 'utf-8')
193
212
  } catch (error) {
194
213
  if (error.code === 'ENOENT') {
195
- writeSettings(file, { hooks: { PreToolUse: HOOKS.map((h) => hookEntry(h)) } })
214
+ writeSettings(file, { hooks: entriesByEvent() })
196
215
  return { changed: true, reason: 'created' }
197
216
  }
198
217
  throw error
@@ -241,25 +260,30 @@ function removeHooks(dir, { local = false, dryRun = false } = {}) {
241
260
  return { removed: 0, emptied: false, reason: error.code === 'ENOENT' ? 'absent' : 'malformed' }
242
261
  }
243
262
  if (!isObject(parsed)) return { removed: 0, emptied: false, reason: 'malformed' }
244
- const pre = isObject(parsed.hooks) && Array.isArray(parsed.hooks.PreToolUse) ? parsed.hooks.PreToolUse : null
245
- if (!pre) return { removed: 0, emptied: false, reason: 'none' }
263
+ if (!isObject(parsed.hooks)) return { removed: 0, emptied: false, reason: 'none' }
246
264
 
247
265
  let removed = 0
248
266
  const ours = (h) => isObject(h) && typeof h.command === 'string' && HOOKS.some((k) => k.re.test(h.command))
249
- const kept = []
250
- for (const group of pre) {
251
- if (!isObject(group) || !Array.isArray(group.hooks)) {
252
- kept.push(group)
253
- continue
267
+ // Every event this package registers under — and only those, so another
268
+ // event's hooks are never even looked at.
269
+ for (const event of [...new Set(HOOKS.map((h) => h.event))]) {
270
+ const pre = Array.isArray(parsed.hooks[event]) ? parsed.hooks[event] : null
271
+ if (!pre) continue
272
+ const kept = []
273
+ for (const group of pre) {
274
+ if (!isObject(group) || !Array.isArray(group.hooks)) {
275
+ kept.push(group)
276
+ continue
277
+ }
278
+ const rest = group.hooks.filter((h) => !ours(h))
279
+ removed += group.hooks.length - rest.length
280
+ if (rest.length) kept.push(rest.length === group.hooks.length ? group : { ...group, hooks: rest })
254
281
  }
255
- const rest = group.hooks.filter((h) => !ours(h))
256
- removed += group.hooks.length - rest.length
257
- if (rest.length) kept.push(rest.length === group.hooks.length ? group : { ...group, hooks: rest })
282
+ if (kept.length) parsed.hooks[event] = kept
283
+ else delete parsed.hooks[event]
258
284
  }
259
285
  if (!removed) return { removed: 0, emptied: false, reason: 'none' }
260
286
 
261
- if (kept.length) parsed.hooks.PreToolUse = kept
262
- else delete parsed.hooks.PreToolUse
263
287
  if (!Object.keys(parsed.hooks).length) delete parsed.hooks
264
288
  const emptied = !Object.keys(parsed).length
265
289
  if (!emptied && !dryRun) writeSettings(file, parsed)
@@ -0,0 +1,192 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The phase report on the review page (feat-autonomous-run, phase 2).
5
+ *
6
+ * Every lifecycle skill ends with a block — a verdict sentence and a table of
7
+ * fields (`.claude/rules/spec-reports.md`). Until now that block lived only in
8
+ * the terminal, so its Notes and Follow-ups were lost to anyone reading the
9
+ * page later, and an autonomous run would leave them nowhere at all.
10
+ *
11
+ * `spec-env review --report <file>` hands the block's rows to the engine, which
12
+ * keeps them per phase in a `.report.json` sidecar beside the notes and
13
+ * renders the latest at the top of the page. The served page re-renders from
14
+ * disk on every request, which is why the rows are STORED rather than passed
15
+ * straight into one render.
16
+ *
17
+ * The rows are what the model already wrote for the terminal. Nothing here
18
+ * reads the diff, and every value is escaped: it is model-authored text
19
+ * arriving through a file, which is exactly the input never trusted as markup.
20
+ */
21
+
22
+ const fs = require('node:fs')
23
+ const path = require('node:path')
24
+
25
+ const REPORT_VERSION = 1
26
+ const REPORT_SUFFIX = '.report.json'
27
+
28
+ // The field vocabulary, in the order `spec-reports.md` defines. A field not in
29
+ // it is kept (a skill may know a field this engine does not) and sorts after
30
+ // the known ones, before `Follow-ups` and `Next`, which always close the table.
31
+ const FIELD_ORDER = Object.freeze([
32
+ 'Tracker',
33
+ 'Why',
34
+ 'Branch',
35
+ 'Spec',
36
+ 'Cause',
37
+ 'Built',
38
+ 'Tests',
39
+ 'Notes',
40
+ 'Landed',
41
+ 'Worktree',
42
+ 'Untouched',
43
+ 'Review',
44
+ 'Follow-ups',
45
+ 'Next',
46
+ ])
47
+ const CLOSING = ['Follow-ups', 'Next']
48
+
49
+ // The fields a later page collects across phases (phase 3's aggregate).
50
+ const CARRIED = Object.freeze(['Notes', 'Follow-ups'])
51
+
52
+ function reviewReportPath(outPath) {
53
+ return outPath.replace(/\.html$/, '') + REPORT_SUFFIX
54
+ }
55
+
56
+ function emptyReport(specFolder) {
57
+ return { version: REPORT_VERSION, spec: specFolder, phases: {} }
58
+ }
59
+
60
+ /** Never throws. Absent is ordinary; unparseable is `corrupt` and never written over. */
61
+ function readReport(outPath, specFolder) {
62
+ let raw
63
+ try {
64
+ raw = fs.readFileSync(reviewReportPath(outPath), 'utf8')
65
+ } catch {
66
+ return { report: emptyReport(specFolder), corrupt: false, present: false }
67
+ }
68
+ try {
69
+ const parsed = JSON.parse(raw)
70
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not an object')
71
+ const phases = parsed.phases && typeof parsed.phases === 'object' && !Array.isArray(parsed.phases) ? parsed.phases : {}
72
+ return { report: { version: REPORT_VERSION, spec: specFolder, phases }, corrupt: false, present: true }
73
+ } catch {
74
+ return { report: emptyReport(specFolder), corrupt: true, present: true }
75
+ }
76
+ }
77
+
78
+ function writeReport(outPath, report) {
79
+ fs.mkdirSync(path.dirname(outPath), { recursive: true })
80
+ fs.writeFileSync(reviewReportPath(outPath), JSON.stringify(report, null, 2) + '\n')
81
+ }
82
+
83
+ /**
84
+ * Validate what a skill handed in. Two shapes: a bare array of rows, or
85
+ * `{ title, rows }` where `title` is the block's verdict sentence.
86
+ *
87
+ * A row is `{ field, value }`. An EMPTY field continues the row above it —
88
+ * the shape `Next` takes when it lists open manual steps a row each — and is
89
+ * kept attached to that row rather than sorted on its own.
90
+ *
91
+ * @returns {{ ok: true, title: string|null, rows: Array<{field: string, value: string, more: string[]}> }
92
+ * | { ok: false, reason: string }}
93
+ */
94
+ function validateReport(raw) {
95
+ const body = Array.isArray(raw) ? { rows: raw } : raw
96
+ if (!body || typeof body !== 'object' || !Array.isArray(body.rows)) {
97
+ return { ok: false, reason: 'a report is an array of {field, value} rows, or {title, rows}' }
98
+ }
99
+ const rows = []
100
+ for (const [i, r] of body.rows.entries()) {
101
+ if (!r || typeof r !== 'object' || typeof r.value !== 'string') {
102
+ return { ok: false, reason: `row ${i + 1} needs a string value` }
103
+ }
104
+ const field = typeof r.field === 'string' ? r.field.replace(/\*\*/g, '').trim() : ''
105
+ if (!field) {
106
+ if (!rows.length) return { ok: false, reason: 'the first row needs a field' }
107
+ rows[rows.length - 1].more.push(r.value)
108
+ continue
109
+ }
110
+ rows.push({ field, value: r.value, more: [] })
111
+ }
112
+ const title = typeof body.title === 'string' && body.title.trim() ? body.title.trim() : null
113
+ return { ok: true, title, rows: orderRows(rows) }
114
+ }
115
+
116
+ function rank(field) {
117
+ if (CLOSING.includes(field)) return 1000 + CLOSING.indexOf(field)
118
+ const i = FIELD_ORDER.indexOf(field)
119
+ return i === -1 ? 500 : i
120
+ }
121
+
122
+ // A stable sort, so two unknown fields keep the order they were written in.
123
+ function orderRows(rows) {
124
+ return rows.map((r, i) => [r, i]).sort((a, b) => rank(a[0].field) - rank(b[0].field) || a[1] - b[1]).map(([r]) => r)
125
+ }
126
+
127
+ /** Record one phase's report. Pure. Re-recording a phase replaces it. */
128
+ function recordReport(report, { phase, title = null, rows, at }) {
129
+ const key = phase == null || phase === '' ? 'current' : String(phase)
130
+ return { ...report, phases: { ...report.phases, [key]: { phase: key, title, rows, at } } }
131
+ }
132
+
133
+ /** The most recently recorded entry, or null — what the page shows. */
134
+ function latestReport(report) {
135
+ const entries = Object.values((report && report.phases) || {}).filter((e) => e && Array.isArray(e.rows))
136
+ if (!entries.length) return null
137
+ return entries.reduce((a, b) => (String(b.at) > String(a.at) ? b : a))
138
+ }
139
+
140
+ function escapeHtml(s) {
141
+ return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c])
142
+ }
143
+
144
+ // The two inline marks the terminal block uses most: `code` and **bold**.
145
+ // Applied AFTER escaping, to escaped text, so nothing a value carries can open
146
+ // a tag — the marks only ever produce <code> and <strong>.
147
+ function inline(text) {
148
+ return escapeHtml(text)
149
+ .replace(/`([^`]+)`/g, '<code>$1</code>')
150
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
151
+ }
152
+
153
+ /**
154
+ * The report as HTML. Empty string when there is nothing to show, so a page
155
+ * rendered without `--report` is byte-identical to one rendered before this
156
+ * existed.
157
+ */
158
+ function renderReportBlock(entry) {
159
+ if (!entry || !Array.isArray(entry.rows) || !entry.rows.length) return ''
160
+ const heading = entry.phase && entry.phase !== 'current' ? `Phase ${escapeHtml(entry.phase)} report` : 'Report'
161
+ const parts = ['<section class="report">', `<h2 class="report-heading">${heading}</h2>`]
162
+ if (entry.title) parts.push(`<p class="report-title">${inline(entry.title)}</p>`)
163
+ parts.push('<table class="report-table"><tbody>')
164
+ for (const r of entry.rows) {
165
+ const more = (r.more || []).map((m) => `<br>${inline(m)}`).join('')
166
+ parts.push(`<tr><th scope="row">${escapeHtml(r.field)}</th><td>${inline(r.value)}${more}</td></tr>`)
167
+ }
168
+ parts.push('</tbody></table>', '</section>')
169
+ return parts.join('\n')
170
+ }
171
+
172
+ /** The stored report's latest entry as HTML; '' when absent or unreadable. */
173
+ function reportHtmlFor(outPath, specFolder) {
174
+ const read = readReport(outPath, specFolder)
175
+ return read.corrupt ? '' : renderReportBlock(latestReport(read.report))
176
+ }
177
+
178
+ module.exports = {
179
+ reportHtmlFor,
180
+ REPORT_VERSION,
181
+ REPORT_SUFFIX,
182
+ FIELD_ORDER,
183
+ CARRIED,
184
+ reviewReportPath,
185
+ emptyReport,
186
+ readReport,
187
+ writeReport,
188
+ validateReport,
189
+ recordReport,
190
+ latestReport,
191
+ renderReportBlock,
192
+ }
@@ -232,13 +232,18 @@ function readOverview(specDir, { overviewFile = '00-overview.md', identifierFiel
232
232
  const problem = sectionOf(text, 'Problem') || sectionOf(text, 'Symptom')
233
233
  const impact = impactRows(sectionOf(text, 'Impact'))
234
234
  const ticket = readTicket(text, identifierField)
235
+ // The `> **Product:**` the spec belongs to, where one tracker project holds
236
+ // several: a reader of a review needs to know whose work this is.
237
+ const productLine = /^>\s*\*\*Product:\*\*\s*(.+)$/m.exec(text)
238
+ const product = productLine ? productLine[1].trim().replace(/^`(.*)`$/, '$1').trim() || null : null
235
239
  // The ticket counts towards "is there anything to say": a spec linked to a
236
240
  // tracker but carrying neither section still has a header worth drawing.
237
- if (!problem && !impact && !ticket) return null
241
+ if (!problem && !impact && !ticket && !product) return null
238
242
  return {
239
243
  ...(problem ? { problem } : {}),
240
244
  ...(impact ? { impact } : {}),
241
245
  ...(ticket ? { ticket } : {}),
246
+ ...(product ? { product } : {}),
242
247
  }
243
248
  }
244
249
 
package/src/env/review.js CHANGED
@@ -589,11 +589,19 @@ const NOTES_VERSION = 1
589
589
  * below and is therefore structurally incapable of clearing an armed gate: a
590
590
  * phase that ended still owes a committing verdict or a recorded skip.
591
591
  */
592
+ // `complete`, `push` and `pr` are the FINAL page's verdicts (feat-autonomous-
593
+ // run): an autonomous run that ended on `pause` has committed every phase, so
594
+ // what is left to decide is the ending — land and tear down (`complete`, which
595
+ // is `/spec-complete`), push the branch (`push`), or open the PR (`pr`). They
596
+ // are committing in the gate's sense: each is the answer a finished run owes.
592
597
  const VERDICTS = [
593
598
  'commit',
594
599
  'commit-continue',
595
600
  'commit-start',
596
601
  'commit-land',
602
+ 'complete',
603
+ 'push',
604
+ 'pr',
597
605
  'continue',
598
606
  'changes',
599
607
  'discuss',
@@ -913,7 +921,7 @@ function tailnetLabel(url) {
913
921
  // obligation that outlives the turn. A mid-run reader saying "carry on" has
914
922
  // answered the offer in front of them and nothing else, so the gate a finished
915
923
  // phase armed must survive it untouched.
916
- const COMMITTING = ['commit', 'commit-continue', 'commit-start', 'commit-land']
924
+ const COMMITTING = ['commit', 'commit-continue', 'commit-start', 'commit-land', 'complete', 'push', 'pr']
917
925
 
918
926
  /**
919
927
  * Which set of buttons a rendered page shows.
@@ -972,7 +980,11 @@ const COMMITTING = ['commit', 'commit-continue', 'commit-start', 'commit-land']
972
980
  * serve daemon, so one name covering two renders would be ambiguous exactly
973
981
  * where it is used to decide something.
974
982
  */
975
- const BUTTON_SETS = ['committing', 'midrun', 'authoring', 'refresh', 'nospec', 'fix']
983
+ // `snapshot` is a kept phase page of an autonomous run: read-only, no verdict
984
+ // at all, because the run committed that phase and carried on. `final` is the
985
+ // page an autonomous run ends on under `pause`: `complete`, `push`, `pr`, plus
986
+ // `changes` and `discuss`.
987
+ const BUTTON_SETS = ['committing', 'midrun', 'authoring', 'refresh', 'nospec', 'fix', 'snapshot', 'final']
976
988
  const DEFAULT_BUTTON_SET = 'committing'
977
989
 
978
990
  /**
package/src/env/run.js ADDED
@@ -0,0 +1,226 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Autonomous runs (feat-autonomous-run): the engine behind
5
+ * `skitterspec spec-env run <resolve|phase|stop|compacted|end|status>`.
6
+ *
7
+ * A run is a spec built from one phase to the last without stopping for a
8
+ * verdict at each one. This module answers two questions and keeps one record:
9
+ *
10
+ * - is this run autonomous or supervised, and how does it end?
11
+ * (`resolveRun`: flag > an active run > the spec's `Run:` header > config
12
+ * > supervised)
13
+ * - what happened during it? (`.spec-env/runs/<spec>.json`: the phases it
14
+ * committed, the stops, the compactions, how it ended)
15
+ *
16
+ * The record is HISTORY plus one piece of state — whether a run is active —
17
+ * and that one piece is what lets a run stopped on a red phase resume in its
18
+ * own mode and ending when `Commit & Continue` is pressed. Nothing here
19
+ * refuses a commit, arms a gate or decides a verdict; the skills do that.
20
+ *
21
+ * Pure apart from `readRun` / `writeRun`. `cli.js` does the resolving.
22
+ */
23
+
24
+ const fs = require('node:fs')
25
+ const path = require('node:path')
26
+
27
+ const MODES = Object.freeze(['auto', 'supervised'])
28
+ const ENDINGS = Object.freeze(['pause', 'push', 'pr'])
29
+ const RUN_VERSION = 1
30
+
31
+ // Same grammar as `resume.js`'s headerValue: a blockquote `**Field:**` line.
32
+ function headerValue(text, field) {
33
+ const m = new RegExp(`^>\\s*\\*\\*${field}:\\*\\*[ \\t]*(.*)$`, 'm').exec(String(text || ''))
34
+ return m ? m[1].trim() : null
35
+ }
36
+
37
+ /**
38
+ * The spec's own opt in/out: `> **Run:** auto` or `> **Run:** supervised`.
39
+ *
40
+ * Anything else — a typo, a trailing remark, an empty value — is cannot-tell
41
+ * and answers null, so the config decides. A typo must never make a run
42
+ * autonomous, and it must not make one supervised that the project configured
43
+ * otherwise either: neither reading is safe to act on, so neither is taken.
44
+ */
45
+ function parseRunHeader(text) {
46
+ const v = headerValue(text, 'Run')
47
+ if (!v) return null
48
+ const word = v.toLowerCase()
49
+ return MODES.includes(word) ? word : null
50
+ }
51
+
52
+ /**
53
+ * Which mode and ending this run takes, and where each came from.
54
+ *
55
+ * Precedence, per half: a flag on the command; else the ACTIVE run's own
56
+ * choice (a stopped run resumes as it started); else, for the mode, the spec's
57
+ * header; else config; else supervised / pause.
58
+ *
59
+ * Flags are the one input that refuses rather than falls back, because a
60
+ * person typed them: `--auto --supervised` together, or `--then` with a word
61
+ * that is not an ending, is a mistake to say out loud, not one to guess past.
62
+ *
63
+ * @param {{ flags?: {auto?: boolean, supervised?: boolean, then?: string|null},
64
+ * header?: string|null, config?: object, active?: object|null }} input
65
+ */
66
+ function resolveRun({ flags = {}, header = null, config = {}, active = null } = {}) {
67
+ if (flags.auto && flags.supervised) {
68
+ return { ok: false, reason: '--auto and --supervised contradict each other — pass one' }
69
+ }
70
+ if (flags.then != null && !ENDINGS.includes(flags.then)) {
71
+ return { ok: false, reason: `--then ${flags.then} is not an ending — use ${ENDINGS.join(', ')}` }
72
+ }
73
+ const auto = (config && config.auto) || {}
74
+ const live = active && active.active ? active : null
75
+
76
+ let mode
77
+ let modeFrom
78
+ if (flags.auto) [mode, modeFrom] = ['auto', 'flag']
79
+ else if (flags.supervised) [mode, modeFrom] = ['supervised', 'flag']
80
+ else if (live) [mode, modeFrom] = [live.mode, 'run']
81
+ else if (header) [mode, modeFrom] = [header, 'header']
82
+ else if (MODES.includes(auto.default) && auto.default !== DEFAULT_AUTO.default) [mode, modeFrom] = [auto.default, 'config']
83
+ else [mode, modeFrom] = ['supervised', 'default']
84
+
85
+ let then
86
+ let thenFrom
87
+ if (flags.then) [then, thenFrom] = [flags.then, 'flag']
88
+ else if (live && ENDINGS.includes(live.then)) [then, thenFrom] = [live.then, 'run']
89
+ else if (ENDINGS.includes(auto.then) && auto.then !== DEFAULT_AUTO.then) [then, thenFrom] = [auto.then, 'config']
90
+ else [then, thenFrom] = ['pause', 'default']
91
+
92
+ const n = Number(auto.maxFixAttempts)
93
+ const maxFixAttempts = Number.isInteger(n) && n >= 0 ? n : DEFAULT_AUTO.maxFixAttempts
94
+ return { ok: true, mode, modeFrom, then, thenFrom, maxFixAttempts }
95
+ }
96
+
97
+ // What `env.config.json` → `auto` means when unset. Supervised is today's
98
+ // behaviour, so a project that never heard of autonomous runs sees none.
99
+ const DEFAULT_AUTO = Object.freeze({ default: 'supervised', then: 'pause', maxFixAttempts: 3 })
100
+
101
+ /* --------------------------------------------------------------------------
102
+ * The run record
103
+ * ------------------------------------------------------------------------ */
104
+
105
+ function runPath(stateDir, spec) {
106
+ return path.join(stateDir, 'runs', `${spec}.json`)
107
+ }
108
+
109
+ /**
110
+ * Read the record. Never throws. Three states, as every sidecar here:
111
+ * absent (`record: null`), readable, or `corrupt` — which callers treat as
112
+ * cannot-tell: no run is resumed from it and nothing is written over it.
113
+ */
114
+ function readRun(stateDir, spec) {
115
+ let raw
116
+ try {
117
+ raw = fs.readFileSync(runPath(stateDir, spec), 'utf8')
118
+ } catch {
119
+ return { record: null, corrupt: false }
120
+ }
121
+ try {
122
+ const parsed = JSON.parse(raw)
123
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { record: null, corrupt: true }
124
+ return { record: parsed, corrupt: false }
125
+ } catch {
126
+ return { record: null, corrupt: true }
127
+ }
128
+ }
129
+
130
+ function writeRun(stateDir, spec, record) {
131
+ const p = runPath(stateDir, spec)
132
+ fs.mkdirSync(path.dirname(p), { recursive: true })
133
+ fs.writeFileSync(p, JSON.stringify(record, null, 2) + '\n')
134
+ return p
135
+ }
136
+
137
+ /**
138
+ * Open a run, or keep the one already open. Pure.
139
+ *
140
+ * An active run is KEPT, not restarted: resolve runs again when a stopped run
141
+ * resumes, and restarting would lose the phases, stops and compactions it has
142
+ * already recorded. A flag given on the resume does replace the mode or
143
+ * ending, because a person asked for it.
144
+ */
145
+ function openRun(record, resolved, { spec, at, startPhase = null }) {
146
+ if (record && record.active) {
147
+ return { ...record, mode: resolved.mode, then: resolved.then, maxFixAttempts: resolved.maxFixAttempts }
148
+ }
149
+ const start = Number(startPhase)
150
+ return {
151
+ version: RUN_VERSION,
152
+ spec,
153
+ active: true,
154
+ startedAt: at,
155
+ endedAt: null,
156
+ mode: resolved.mode,
157
+ then: resolved.then,
158
+ maxFixAttempts: resolved.maxFixAttempts,
159
+ startPhase: Number.isInteger(start) && start > 0 ? start : 1,
160
+ phases: [],
161
+ stops: [],
162
+ compactions: [],
163
+ outcome: null,
164
+ // The record of the PREVIOUS run, if any, is history and is not carried:
165
+ // a run is one start-to-end, and a second run on the same spec is its own.
166
+ }
167
+ }
168
+
169
+ /** The phase being built right now: one past the last committed, or the start. */
170
+ function currentPhase(record) {
171
+ const done = (record.phases || []).map((p) => p.n).filter(Number.isInteger)
172
+ return done.length ? Math.max(...done) + 1 : record.startPhase || 1
173
+ }
174
+
175
+ function recordPhase(record, { n, commit = null, snapshot = null, at }) {
176
+ const num = Number(n)
177
+ if (!Number.isInteger(num) || num < 1) return { record, ok: false, reason: `phase ${n} is not a phase number` }
178
+ const phases = (record.phases || []).filter((p) => p.n !== num)
179
+ phases.push({ n: num, commit: commit || null, snapshot: snapshot || null, at })
180
+ phases.sort((a, b) => a.n - b.n)
181
+ return { record: { ...record, phases }, ok: true }
182
+ }
183
+
184
+ function recordStop(record, { reason, at }) {
185
+ const stops = (record.stops || []).concat({ phase: currentPhase(record), reason: String(reason || '').trim() || 'stopped', at })
186
+ return { ...record, stops }
187
+ }
188
+
189
+ function recordCompaction(record, { at }) {
190
+ const compactions = (record.compactions || []).concat({ phase: currentPhase(record), at })
191
+ return { ...record, compactions }
192
+ }
193
+
194
+ function endRun(record, { at, outcome = null }) {
195
+ return { ...record, active: false, endedAt: at, outcome: outcome || record.then }
196
+ }
197
+
198
+ /**
199
+ * One line a report can carry: `compacted 2×, during phases 3 and 5`.
200
+ * Empty when there were none — a run that never compacted says nothing.
201
+ */
202
+ function compactionSummary(record) {
203
+ const list = (record && record.compactions) || []
204
+ if (!list.length) return ''
205
+ const phases = [...new Set(list.map((c) => c.phase))].sort((a, b) => a - b)
206
+ const named = phases.length === 1 ? `phase ${phases[0]}` : `phases ${phases.slice(0, -1).join(', ')} and ${phases[phases.length - 1]}`
207
+ return `compacted ${list.length}×, during ${named}`
208
+ }
209
+
210
+ module.exports = {
211
+ MODES,
212
+ ENDINGS,
213
+ DEFAULT_AUTO,
214
+ parseRunHeader,
215
+ resolveRun,
216
+ runPath,
217
+ readRun,
218
+ writeRun,
219
+ openRun,
220
+ currentPhase,
221
+ recordPhase,
222
+ recordStop,
223
+ recordCompaction,
224
+ endRun,
225
+ compactionSummary,
226
+ }