@skitterbyte/skitterspec-jira 2.9.1 → 2.11.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.
package/src/env/live.js CHANGED
@@ -18,8 +18,10 @@
18
18
 
19
19
  const fs = require('node:fs')
20
20
  const path = require('node:path')
21
+ const { spawnSync } = require('node:child_process')
21
22
  const { globToRegExp } = require('./glob.js')
22
23
  const { shellPath } = require('./project.js')
24
+ const { planTriggered, noTriggered } = require('./triggered.js')
23
25
 
24
26
  const REQUIRED = ['spec', 'branch', 'holder', 'heldSince', 'baseMainCommit']
25
27
 
@@ -190,6 +192,40 @@ function migrationsHit(files, patterns) {
190
192
  return files.some((f) => res.some((r) => r.test(f)))
191
193
  }
192
194
 
195
+ // Lockfiles/manifests whose change means a dev server needs a restart, not HMR.
196
+ // Always checked, so a project whose `when` globs name only (say) a schema file
197
+ // keeps the warning it had before those globs existed.
198
+ const DEPS_RE = /(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock)$/
199
+
200
+ // True when the branch changes a dependency manifest: the npm set above, or any
201
+ // file a `setup` entry's `when` globs name. Those globs are the project saying
202
+ // "this file changing means setup must re-run" — a .csproj, a go.mod — and a
203
+ // change that needs setup re-run needs the running app restarted for the same
204
+ // reason. Reading them keeps the engine ignorant of what stack it is in.
205
+ function depsChanged(files, setupTriggers) {
206
+ if (!Array.isArray(files) || !files.length) return false
207
+ const globs = (Array.isArray(setupTriggers) ? setupTriggers : []).flatMap((t) =>
208
+ t && Array.isArray(t.when) ? t.when : [],
209
+ )
210
+ const res = globs.map(globToRegExp)
211
+ return files.some((f) => DEPS_RE.test(f) || res.some((r) => r.test(f)))
212
+ }
213
+
214
+ // One reminder per `reload: "restart"` dev entry — an IDE-hosted app sees the
215
+ // branch switch on disk but runs the old build until someone restarts it.
216
+ function restartReminders(names, when) {
217
+ return names.map((name) => `restart ${name} ${when} — it does not hot-reload`)
218
+ }
219
+
220
+ // `live.afterSwitch` decided for one switch, to run in the primary checkout.
221
+ // Anything but a list in `changedFiles` is an unknown range — a caller that
222
+ // did not supply it said nothing about what changed.
223
+ function afterSwitchFor(config, c) {
224
+ const raw = config && config.live ? config.live.afterSwitch : []
225
+ const range = Array.isArray(c.changedFiles) ? c.changedFiles : null
226
+ return planTriggered(raw, c.primaryPath, range)
227
+ }
228
+
193
229
  // --- take planner ---------------------------------------------------------
194
230
 
195
231
  /**
@@ -208,15 +244,26 @@ function migrationsHit(files, patterns) {
208
244
  * clean boolean — primary checkout working tree is clean
209
245
  * worktreeClean boolean — the SPEC WORKTREE's tree is clean (the rebase runs there)
210
246
  * worktreeExists boolean — the spec's worktree is on disk
211
- * base resolved base branch name (rebase target)
247
+ * base resolved base branch name (the workbench release returns to)
248
+ * rebaseOnto the rebase target — `<remote>/<base>` under PR landing,
249
+ * else omitted, meaning `base`
250
+ * rebaseNote string|null — why the target fell back to local base
212
251
  * baseMainCommit primary HEAD before the switch (receipt / crash recovery)
213
252
  * serverUp true | false | null — null = no canonical ports declared → no gate
214
- * canonicalPorts number[] — declared canonical (frontPort) ports, for messages
253
+ * canonicalPorts number[] — declared canonical (frontPort) ports of the HOT
254
+ * dev entries, for messages
255
+ * restartApps string[] — names of `reload: "restart"` dev entries; never
256
+ * probed, each named in a restart reminder instead
215
257
  * migrationsHit boolean — the branch diff touches configured migration globs
216
258
  * depsChanged boolean — the branch diff touches a lockfile/manifest (→ warn)
259
+ * changedFiles string[] — the files `onto...branch` changes, or anything
260
+ * else (null) when git would not say: decides `afterSwitch`
217
261
  * holder,heldSince receipt provenance (injected by the CLI; no Date.now here)
218
262
  *
219
- * @returns {object} { blocked, reason, commands, warnings, receipt, base, branch, worktreePath }
263
+ * @returns {object} { blocked, reason, commands, warnings, receipt, base, branch,
264
+ * worktreePath, afterSwitch } — `afterSwitch` is `config.live.afterSwitch`
265
+ * decided against `changedFiles`, to run in the primary checkout after the
266
+ * checkout; empty on a refusal, since nothing switched.
220
267
  */
221
268
  function planTake(spec, config, ctx) {
222
269
  const c = ctx || {}
@@ -229,8 +276,10 @@ function planTake(spec, config, ctx) {
229
276
  warnings: [],
230
277
  receipt: null,
231
278
  base,
279
+ onto: c.rebaseOnto || base,
232
280
  branch,
233
281
  worktreePath: spec.worktreePath,
282
+ afterSwitch: noTriggered(),
234
283
  }
235
284
  /**
236
285
  * A refusal, and — only where one exists — the way out of it.
@@ -332,21 +381,28 @@ function planTake(spec, config, ctx) {
332
381
  }
333
382
 
334
383
  const warnings = []
384
+ const restartApps = Array.isArray(c.restartApps) ? c.restartApps : []
335
385
  if (c.depsChanged) {
336
386
  warnings.push('dependencies changed on this branch — restart your dev server after the switch')
337
387
  }
338
- if (c.serverUp === null) {
388
+ // An app that restarts rather than hot-reloads is the operator's to restart,
389
+ // so its absence from the ports is the normal state — the IDE is closed, or
390
+ // will be restarted anyway — and "nothing to hot-reload" would only mislead.
391
+ if (c.serverUp === null && !restartApps.length) {
339
392
  warnings.push('no canonical dev ports configured — nothing to hot-reload; switching anyway')
340
393
  }
394
+ warnings.push(...restartReminders(restartApps, 'after the switch'))
395
+ if (c.rebaseNote) warnings.push(c.rebaseNote)
341
396
 
342
397
  return {
343
398
  ...result,
344
399
  commands: [
345
- `git -C ${shellPath(spec.worktreePath)} rebase ${base}`,
400
+ `git -C ${shellPath(spec.worktreePath)} rebase ${c.rebaseOnto || base}`,
346
401
  `git -C ${shellPath(spec.worktreePath)} switch --detach`,
347
402
  `git -C ${shellPath(c.primaryPath)} checkout ${branch}`,
348
403
  ],
349
404
  warnings,
405
+ afterSwitch: afterSwitchFor(config, c),
350
406
  receipt: {
351
407
  spec: spec.folder,
352
408
  branch,
@@ -367,8 +423,12 @@ function planTake(spec, config, ctx) {
367
423
  * In the branch-switch model `take` never moves the base ref, so release is just
368
424
  * `checkout base` (frees the branch) then re-attach it to the worktree — no reset.
369
425
  *
370
- * ctx: { primary:{onBase,branch}, primaryPath, base, clean, worktreeExists }
371
- * @returns {object} { blocked, noop, reason, commands, clears, base, branch, worktreePath }
426
+ * ctx: { primary:{onBase,branch}, primaryPath, base, clean, worktreeExists, restartApps,
427
+ * changedFiles }
428
+ * `changedFiles` is `base...branch` — the same files take brought in, which the
429
+ * switch back reverts, so `afterSwitch` is decided against the same set.
430
+ * @returns {object} { blocked, noop, reason, commands, warnings, clears, base, branch,
431
+ * worktreePath, afterSwitch }
372
432
  */
373
433
  function planRelease(spec, config, ctx) {
374
434
  const c = ctx || {}
@@ -379,10 +439,12 @@ function planRelease(spec, config, ctx) {
379
439
  noop: false,
380
440
  reason: null,
381
441
  commands: [],
442
+ warnings: [],
382
443
  clears: false,
383
444
  base,
384
445
  branch,
385
446
  worktreePath: spec.worktreePath,
447
+ afterSwitch: noTriggered(),
386
448
  }
387
449
 
388
450
  // Nothing live — the primary checkout is already on base.
@@ -408,7 +470,8 @@ function planRelease(spec, config, ctx) {
408
470
 
409
471
  const commands = [`git -C ${shellPath(c.primaryPath)} checkout ${base}`]
410
472
  if (c.worktreeExists) commands.push(`git -C ${shellPath(spec.worktreePath)} switch ${branch}`)
411
- return { ...result, commands, clears: true }
473
+ const warnings = restartReminders(Array.isArray(c.restartApps) ? c.restartApps : [], `on ${base}`)
474
+ return { ...result, commands, warnings, clears: true, afterSwitch: afterSwitchFor(config, c) }
412
475
  }
413
476
 
414
477
  // --- abort planner --------------------------------------------------------
@@ -463,7 +526,86 @@ function planAbort(config, ctx) {
463
526
  return { ...result, commands, clears: true, branch }
464
527
  }
465
528
 
529
+ // --- after-switch runner --------------------------------------------------
530
+
531
+ // How much of a failed command's output to show — enough to see why, not a
532
+ // whole install log in a report that is relayed verbatim.
533
+ const FAIL_TAIL = 20
534
+
535
+ /**
536
+ * Run a plan's `afterSwitch` commands in order, in its `cwd` (the primary
537
+ * checkout), and return the lines that report them. The ENGINE runs these,
538
+ * unlike `afterLand`: `/spec-live` and the page's live action are pre-executed
539
+ * with no caller turn to run anything after them.
540
+ *
541
+ * Output is CAPTURED, not streamed — the report is relayed verbatim, so a full
542
+ * install log would bury it. Only a failure shows output, and only its tail.
543
+ *
544
+ * STOPS AT THE FIRST FAILURE AND NEVER UNDOES THE SWITCH. Rolling the branch
545
+ * back over a failed install would hide the cause and swap one broken tree for
546
+ * another; the operator is told what failed and what did not run.
547
+ *
548
+ * An empty list returns no lines at all, so a project without the key prints
549
+ * exactly what it printed before the key existed.
550
+ *
551
+ * @param {object} afterSwitch a planner's `afterSwitch` ({ cwd, commands, entries, range })
552
+ * @param {function} [spawn] spawnSync-shaped, injectable for tests
553
+ * @returns {{ lines: string[], failed: boolean }}
554
+ */
555
+ function runAfterSwitch(afterSwitch, spawn = spawnSync) {
556
+ const entries = afterSwitch && Array.isArray(afterSwitch.entries) ? afterSwitch.entries : []
557
+ if (!entries.length) return { lines: [], failed: false }
558
+ const cwd = afterSwitch.cwd
559
+ const toRun = entries.filter((e) => e.decision !== 'skipped')
560
+ const skipped = entries.filter((e) => e.decision === 'skipped')
561
+ const width = Math.max(...entries.map((e) => e.run.length))
562
+ // A shell COMMENT for the reason, as `afterLand` prints it, so a line copied
563
+ // out of the report is still one command.
564
+ const why = (e) =>
565
+ e.decision === 'matched' ? ` # ${e.matched} changed` : e.decision === 'unknown' ? ' # range unknown' : ''
566
+ const lines = []
567
+ let failed = false
568
+
569
+ if (!toRun.length) {
570
+ lines.push(` after switch (in ${cwd}): nothing to run.`)
571
+ } else {
572
+ lines.push(` after switch (in ${cwd}):`)
573
+ for (let i = 0; i < toRun.length; i++) {
574
+ const e = toRun[i]
575
+ const res = spawn(e.run, {
576
+ cwd,
577
+ shell: true,
578
+ stdio: ['ignore', 'pipe', 'pipe'],
579
+ encoding: 'utf8',
580
+ maxBuffer: 64 * 1024 * 1024,
581
+ })
582
+ if (!res.error && res.status === 0) {
583
+ lines.push(` ran: ${why(e) ? e.run.padEnd(width) + why(e) : e.run}`)
584
+ continue
585
+ }
586
+ failed = true
587
+ const status = res.error ? res.error.message : res.signal ? `signal ${res.signal}` : `exit ${res.status}`
588
+ lines.push(` ! after switch: ${e.run} failed (${status}) — the switch stands; fix it in ${cwd}`)
589
+ // Joined on a newline: stdout without a trailing one would otherwise run
590
+ // its last line into stderr's first.
591
+ const output = `${res.stdout || ''}\n${res.stderr || ''}`.split('\n').filter((l) => l.trim())
592
+ for (const l of output.slice(-FAIL_TAIL)) lines.push(` ${l}`)
593
+ for (const rest of toRun.slice(i + 1)) lines.push(` not run: ${rest.run}`)
594
+ break
595
+ }
596
+ }
597
+ if (toRun.some((e) => e.decision === 'unknown')) {
598
+ lines.push(" the switch's changed files are unknown here, so the conditional entries run.")
599
+ }
600
+ if (skipped.length) {
601
+ lines.push(' skipped (nothing in the switch matched):')
602
+ for (const e of skipped) lines.push(` ${e.run.padEnd(width)} # when ${e.when.join(', ')}`)
603
+ }
604
+ return { lines, failed }
605
+ }
606
+
466
607
  module.exports = {
608
+ runAfterSwitch,
467
609
  receiptPath,
468
610
  renderReceipt,
469
611
  readReceipt,
@@ -472,6 +614,7 @@ module.exports = {
472
614
  summarizeReceipt,
473
615
  globToRegExp,
474
616
  migrationsHit,
617
+ depsChanged,
475
618
  planTake,
476
619
  planRelease,
477
620
  planAbort,
@@ -0,0 +1,389 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The project guard — is this session about to work on ANOTHER project?
5
+ *
6
+ * A session belongs to the project it was started in. A ta-da list read across
7
+ * every project once ended on another repo's `/spec-complete`, the session ran
8
+ * it, `cd`-ed into that repo and started completing a spec there — work nobody
9
+ * in that project's own sessions could see, from a session whose rules, hooks
10
+ * and context were somebody else's. Reports may still SUGGEST work elsewhere;
11
+ * this is what stops a suggestion becoming an act.
12
+ *
13
+ * WHAT IT REFUSES, and nothing wider:
14
+ * - a write tool whose path lands in another skitterspec project
15
+ * - a `skitterspec …` lifecycle verb, or a git command that changes
16
+ * something, whose directory is another skitterspec project
17
+ * Reads stay open — `git log` there, `skitterspec tada` — and so does every
18
+ * other program: this is a guard on lifecycle work, not a sandbox for the shell.
19
+ *
20
+ * "ANOTHER SKITTERSPEC PROJECT" IS A POSITIVE SIGNAL: a git checkout with a
21
+ * `specs/.core/` folder, which the installer always writes, at or above the
22
+ * path. This repo and every worktree of it share one git common dir and are
23
+ * home. A sibling folder with no `specs/.core` is nobody's project to guard.
24
+ *
25
+ * IT FAILS OPEN. A path git cannot place, a command it cannot parse, a
26
+ * directory that is gone — each allows (`.claude/rules/negative-checks.md`).
27
+ * Being wrong that way costs one unguarded act the skills also warn against;
28
+ * being wrong the other way refuses ordinary work with no reason anyone can see.
29
+ */
30
+
31
+ const fs = require('node:fs')
32
+ const os = require('node:os')
33
+ const path = require('node:path')
34
+
35
+ // Where the lifts live. Gitignored and beside the registry, like the main
36
+ // guard's allow: one person's decision about one session.
37
+ const ALLOW_FILE = 'project-allow.json'
38
+
39
+ // The engine under every name a distribution ships it as.
40
+ const ENGINES = new Set(['skitterspec', 'skitterspec-linear', 'skitterspec-jira', 'skitterspec-github', 'skitterspec-azure-boards'])
41
+
42
+ // git subcommands that only read. Anything else is a change.
43
+ //
44
+ // WHAT WOULD FOOL THIS: an alias (`git co`) or a subcommand added to git later
45
+ // reads as a change and is refused in another project — the strict side, and
46
+ // the refusal names the exit. A read missing from this list costs one
47
+ // `/allow-project`; a write wrongly on it would let the guard be walked past.
48
+ const GIT_READS = new Set([
49
+ 'status', 'log', 'diff', 'show', 'rev-parse', 'ls-files', 'ls-tree', 'blame', 'describe',
50
+ 'shortlog', 'for-each-ref', 'cat-file', 'grep', 'reflog', 'merge-base', 'rev-list', 'name-rev',
51
+ ])
52
+
53
+ // skitterspec verbs that only read, as `verb` or `verb sub`.
54
+ const ENGINE_READS = new Set([
55
+ 'tada', 'todo', 'status', 'help', '--help', '-h', '--version', '-v',
56
+ 'spec-env status', 'spec-env resolve',
57
+ 'epic status', 'epic check', 'gating check', 'spec-sync ownership', 'spec-sync board',
58
+ ])
59
+
60
+ function allowPath(rootDir, config) {
61
+ return path.resolve(rootDir, path.dirname(config.registry), ALLOW_FILE)
62
+ }
63
+
64
+ /** The recorded lifts. Missing or unreadable is none — the strict, safe answer. */
65
+ function readAllows(rootDir, config) {
66
+ try {
67
+ const parsed = JSON.parse(fs.readFileSync(allowPath(rootDir, config), 'utf-8'))
68
+ return Array.isArray(parsed && parsed.allows) ? parsed.allows.filter((a) => a && typeof a === 'object') : []
69
+ } catch {
70
+ return []
71
+ }
72
+ }
73
+
74
+ function writeAllows(rootDir, config, allows) {
75
+ const file = allowPath(rootDir, config)
76
+ fs.mkdirSync(path.dirname(file), { recursive: true })
77
+ fs.writeFileSync(file, JSON.stringify({ allows }, null, 2) + '\n')
78
+ }
79
+
80
+ /**
81
+ * Does a recorded lift cover `project` for `sessionId`? Pure.
82
+ *
83
+ * A lift names the project by its root, or by its folder name when it was typed
84
+ * as a name — and a SESSION lift with no session id to compare does not apply,
85
+ * for the main guard's reason: "cannot tell whose session" must not widen a
86
+ * session lift into a permanent one.
87
+ */
88
+ function liftApplies(lift, project, sessionId) {
89
+ const names = lift.root ? lift.root === project.root : lift.name === project.name
90
+ if (!names) return false
91
+ if (lift.scope === 'repo') return true
92
+ return lift.scope === 'session' && Boolean(sessionId) && lift.session === sessionId
93
+ }
94
+
95
+ function real(p) {
96
+ try {
97
+ return fs.realpathSync.native(p)
98
+ } catch {
99
+ return null
100
+ }
101
+ }
102
+
103
+ /**
104
+ * The skitterspec project a path is in, or null when it is in none.
105
+ *
106
+ * NEAREST EXISTING ANCESTOR first, because a `Write` usually creates its file —
107
+ * and `git -C` on a folder that does not exist yet fails, which read as "no
108
+ * repo" would wave through exactly the new file in another project.
109
+ *
110
+ * @param {string} target
111
+ * @param {(dir: string) => (args: string[]) => string|null} gitAt
112
+ * @returns {{ common, root, name } | null}
113
+ */
114
+ function projectAt(target, gitAt) {
115
+ let at = path.resolve(target)
116
+ while (!fs.existsSync(at)) {
117
+ const up = path.dirname(at)
118
+ if (up === at) return null
119
+ at = up
120
+ }
121
+ if (!fs.statSync(at).isDirectory()) at = path.dirname(at)
122
+ const git = gitAt(at)
123
+ const top = git(['rev-parse', '--show-toplevel'])
124
+ const common = git(['rev-parse', '--path-format=absolute', '--git-common-dir'])
125
+ if (!top || !common) return null
126
+ // A `specs/.core/` between the path and its checkout's top — a project may
127
+ // sit in a subfolder of its repo, so the top alone is not enough to ask.
128
+ let skitterspec = false
129
+ for (let d = at; ; d = path.dirname(d)) {
130
+ if (fs.existsSync(path.join(d, 'specs', '.core'))) {
131
+ skitterspec = true
132
+ break
133
+ }
134
+ if (real(d) === real(top) || path.dirname(d) === d) break
135
+ }
136
+ if (!skitterspec) return null
137
+ const commonReal = real(common.trim())
138
+ if (!commonReal) return null
139
+ // The primary checkout's folder names the project, whichever worktree the
140
+ // path is in — `ereqs`, never `perf-alerts`.
141
+ const root = path.basename(commonReal) === '.git' ? path.dirname(commonReal) : commonReal
142
+ return { common: commonReal, root, name: path.basename(root) }
143
+ }
144
+
145
+ /** The home project's git common dir, or null when it cannot be read. */
146
+ function homeCommon(home, gitAt) {
147
+ const common = gitAt(home)(['rev-parse', '--path-format=absolute', '--git-common-dir'])
148
+ return common ? real(common.trim()) : null
149
+ }
150
+
151
+ function refusal(project, what) {
152
+ return {
153
+ refuse: true,
154
+ project,
155
+ reason:
156
+ `${what} is in ${project.name} (${project.root}), and this session belongs to another project. ` +
157
+ 'A session works on the project it was started in — reports may suggest work elsewhere, ' +
158
+ 'but doing it belongs to a session opened there.\n\n' +
159
+ ` open a session in ${project.root} and run it there\n\n` +
160
+ `If this session really should act on ${project.name}, the USER types /allow-project ${project.name} — ` +
161
+ 'it is theirs to run, not yours.',
162
+ }
163
+ }
164
+
165
+ const ALLOWS = { refuse: false, reason: null }
166
+
167
+ /**
168
+ * Should a write to `target` be refused? `home` is the session's project dir.
169
+ *
170
+ * WHAT WOULD FOOL THIS: a symlink from inside this repo into another one is
171
+ * resolved by git to where it points, so a write through it is judged by the
172
+ * other project — the strict side, and the refusal names the exit.
173
+ */
174
+ function checkPath({ home, target, gitAt, allows = [], sessionId = null }) {
175
+ try {
176
+ const mine = homeCommon(home, gitAt)
177
+ if (!mine) return ALLOWS
178
+ const other = projectAt(target, gitAt)
179
+ if (!other || other.common === mine) return ALLOWS
180
+ if (allows.some((l) => liftApplies(l, other, sessionId))) return ALLOWS
181
+ return refusal(other, `${target}`)
182
+ } catch {
183
+ return ALLOWS
184
+ }
185
+ }
186
+
187
+ /**
188
+ * A shell command split into segments, each with the directory it runs in.
189
+ * Returns null when it cannot be read — unbalanced quotes, a heredoc — and
190
+ * the caller allows.
191
+ *
192
+ * Segments split on `&&`, `||`, `;`, `|` and newlines; a `cd <dir>` moves every
193
+ * later segment, as it does in the shell. Subshell parentheses are dropped,
194
+ * so `(cd x && …)` is read as if it changed the directory for the rest — the
195
+ * strict side, refusing more, never less.
196
+ */
197
+ function segmentsOf(command, cwd) {
198
+ if (typeof command !== 'string') return null
199
+ if (/<<-?\s*['"]?\w+/.test(command)) return null
200
+ const tokens = []
201
+ let cur = ''
202
+ let quote = null
203
+ let has = false
204
+ const push = () => {
205
+ if (has) tokens.push({ word: cur })
206
+ cur = ''
207
+ has = false
208
+ }
209
+ for (let i = 0; i < command.length; i++) {
210
+ const c = command[i]
211
+ if (quote) {
212
+ if (c === quote) quote = null
213
+ else if (c === '\\' && quote === '"' && i + 1 < command.length) cur += command[++i]
214
+ else cur += c
215
+ continue
216
+ }
217
+ if (c === '"' || c === "'") {
218
+ quote = c
219
+ has = true
220
+ } else if (c === '\\' && i + 1 < command.length) {
221
+ cur += command[++i]
222
+ has = true
223
+ } else if (/\s/.test(c) && c !== '\n') {
224
+ push()
225
+ } else if (c === '\n' || c === ';' || c === '(' || c === ')') {
226
+ push()
227
+ tokens.push({ op: true })
228
+ } else if ((c === '&' || c === '|') && command[i + 1] === c) {
229
+ push()
230
+ tokens.push({ op: true })
231
+ i++
232
+ } else if (c === '|' || c === '&') {
233
+ push()
234
+ tokens.push({ op: true })
235
+ } else {
236
+ cur += c
237
+ has = true
238
+ }
239
+ }
240
+ if (quote) return null
241
+ push()
242
+
243
+ const segments = []
244
+ let dir = cwd
245
+ let words = []
246
+ const close = () => {
247
+ if (!words.length) return
248
+ if (words[0] === 'cd' || words[0] === 'pushd') {
249
+ const to = words[1]
250
+ if (to && to !== '-') dir = path.resolve(dir, to.replace(/^~(?=$|\/)/, os.homedir()))
251
+ } else {
252
+ segments.push({ dir, words })
253
+ }
254
+ words = []
255
+ }
256
+ for (const t of tokens) {
257
+ if (t.op) close()
258
+ else words.push(t.word)
259
+ }
260
+ close()
261
+ return segments
262
+ }
263
+
264
+ /**
265
+ * What a segment runs, if it is one this guard is about: `{ kind, dir, verb }`
266
+ * for git or the engine, null for anything else. `dir` is where it acts — its
267
+ * `-C` or `--dir` when it names one.
268
+ */
269
+ function lifecycleOf(seg) {
270
+ let w = seg.words.slice()
271
+ // Leading `VAR=value` assignments and `env` are not the program.
272
+ while (w.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0]) || w[0] === 'env')) w.shift()
273
+ // A package runner in front of the engine.
274
+ if (['pnpm', 'npm', 'yarn', 'bunx', 'npx'].includes(w[0])) {
275
+ w = w.slice(1)
276
+ while (w.length && (w[0] === 'exec' || w[0] === 'dlx' || w[0] === 'run' || w[0].startsWith('-'))) w.shift()
277
+ }
278
+ if (!w.length) return null
279
+ const prog = path.basename(w[0]).replace(/\.c?js$/, '')
280
+ if (prog === 'git') {
281
+ let dir = seg.dir
282
+ let i = 1
283
+ for (; i < w.length; i++) {
284
+ if (w[i] === '-C' && w[i + 1]) dir = path.resolve(dir, w[++i])
285
+ else if (w[i] === '-c' && w[i + 1]) i++
286
+ else if (!w[i].startsWith('-')) break
287
+ }
288
+ const sub = w[i] || ''
289
+ const rest = w.slice(i + 1)
290
+ let read = GIT_READS.has(sub)
291
+ if (sub === 'worktree') read = rest[0] === 'list'
292
+ if (sub === 'branch') read = rest.every((a) => ['--show-current', '-a', '-r', '--list', '-v', '-vv', '--all', '--remotes'].includes(a))
293
+ if (sub === 'remote') read = rest.every((a) => a === '-v' || a === 'show' || a === 'get-url')
294
+ if (sub === 'config') read = rest.some((a) => a === '--get' || a === '--list' || a === '-l' || a === '--get-all')
295
+ if (sub === 'stash') read = rest[0] === 'list' || rest[0] === 'show'
296
+ if (sub === 'tag') read = rest.length === 0 || rest.every((a) => a === '-l' || a === '--list' || a.startsWith('--points-at') || a.startsWith('--contains'))
297
+ return read ? null : { kind: 'git', dir, verb: sub }
298
+ }
299
+ if (ENGINES.has(prog)) {
300
+ let dir = seg.dir
301
+ const args = []
302
+ for (let i = 1; i < w.length; i++) {
303
+ if (w[i] === '--dir' && w[i + 1]) dir = path.resolve(dir, w[++i])
304
+ else args.push(w[i])
305
+ }
306
+ const verbs = args.filter((a) => !a.startsWith('--') || ['--help', '--version'].includes(a))
307
+ const one = verbs[0] || 'help'
308
+ const two = verbs.slice(0, 2).join(' ')
309
+ if (ENGINE_READS.has(one) || ENGINE_READS.has(two)) return null
310
+ // `review waiting`, and a guard's own `status`/`check`, read. Lifting a
311
+ // guard in another project (`main allow`, `project allow`) does not.
312
+ if (two === 'spec-env review' && verbs[2] === 'waiting') return null
313
+ if ((two === 'spec-env main' || two === 'spec-env project') && ['status', 'check', undefined].includes(verbs[2])) return null
314
+ // `project` without --name/--category reads.
315
+ if (one === 'project' && !args.some((a) => a === '--name' || a === '--category')) return null
316
+ return { kind: 'skitterspec', dir, verb: two || one }
317
+ }
318
+ return null
319
+ }
320
+
321
+ /**
322
+ * Should `command`, run from `cwd`, be refused?
323
+ *
324
+ * WHAT WOULD FOOL THIS: anything that is not git or the engine — `rm`, `sed -i`,
325
+ * a script that commits for you. Parsing arbitrary shell for its effects cannot
326
+ * be done reliably, so it is not tried; the guard covers lifecycle work and
327
+ * the skills carry the rule for the rest. A variable in a path (`cd $REPO`) is
328
+ * taken literally and lands nowhere real, so it allows.
329
+ */
330
+ function checkCommand({ home, cwd, command, gitAt, allows = [], sessionId = null }) {
331
+ try {
332
+ const mine = homeCommon(home, gitAt)
333
+ if (!mine) return ALLOWS
334
+ const segments = segmentsOf(command, cwd)
335
+ if (!segments) return ALLOWS
336
+ for (const seg of segments) {
337
+ const act = lifecycleOf(seg)
338
+ if (!act) continue
339
+ const other = projectAt(act.dir, gitAt)
340
+ if (!other || other.common === mine) continue
341
+ if (allows.some((l) => liftApplies(l, other, sessionId))) continue
342
+ return refusal(other, `\`${act.kind === 'git' ? 'git' : 'skitterspec'} ${act.verb}\` in ${act.dir}`)
343
+ }
344
+ return ALLOWS
345
+ } catch {
346
+ return ALLOWS
347
+ }
348
+ }
349
+
350
+ /**
351
+ * Record a lift. `what` is a path (judged to its project's root) or a name.
352
+ * Returns the lift written, or `{ error }` when a path names no project.
353
+ */
354
+ function recordLift(rootDir, config, { what, sessionId = null, gitAt, at = null }) {
355
+ let lift
356
+ if (what && (what.includes('/') || what.includes(path.sep) || what === '.' || what === '..')) {
357
+ const project = projectAt(path.resolve(what), gitAt)
358
+ if (!project) return { error: `${what} is not in a skitterspec project` }
359
+ lift = { root: project.root, name: project.name }
360
+ } else {
361
+ lift = { name: what }
362
+ }
363
+ lift = sessionId ? { ...lift, scope: 'session', session: sessionId, at } : { ...lift, scope: 'repo', at }
364
+ const kept = readAllows(rootDir, config).filter((l) => !(l.name === lift.name && l.session === lift.session && l.scope === lift.scope))
365
+ writeAllows(rootDir, config, [...kept, lift])
366
+ return lift
367
+ }
368
+
369
+ /** Clear every lift for `name` (any session). Returns how many were cleared. */
370
+ function clearLift(rootDir, config, name) {
371
+ const all = readAllows(rootDir, config)
372
+ const kept = all.filter((l) => l.name !== name)
373
+ if (kept.length !== all.length) writeAllows(rootDir, config, kept)
374
+ return all.length - kept.length
375
+ }
376
+
377
+ module.exports = {
378
+ ALLOW_FILE,
379
+ allowPath,
380
+ readAllows,
381
+ liftApplies,
382
+ projectAt,
383
+ segmentsOf,
384
+ lifecycleOf,
385
+ checkPath,
386
+ checkCommand,
387
+ recordLift,
388
+ clearLift,
389
+ }