@skitterbyte/skitterspec-jira 2.10.0 → 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
 
@@ -215,6 +217,15 @@ function restartReminders(names, when) {
215
217
  return names.map((name) => `restart ${name} ${when} — it does not hot-reload`)
216
218
  }
217
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
+
218
229
  // --- take planner ---------------------------------------------------------
219
230
 
220
231
  /**
@@ -245,9 +256,14 @@ function restartReminders(names, when) {
245
256
  * probed, each named in a restart reminder instead
246
257
  * migrationsHit boolean — the branch diff touches configured migration globs
247
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`
248
261
  * holder,heldSince receipt provenance (injected by the CLI; no Date.now here)
249
262
  *
250
- * @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.
251
267
  */
252
268
  function planTake(spec, config, ctx) {
253
269
  const c = ctx || {}
@@ -263,6 +279,7 @@ function planTake(spec, config, ctx) {
263
279
  onto: c.rebaseOnto || base,
264
280
  branch,
265
281
  worktreePath: spec.worktreePath,
282
+ afterSwitch: noTriggered(),
266
283
  }
267
284
  /**
268
285
  * A refusal, and — only where one exists — the way out of it.
@@ -385,6 +402,7 @@ function planTake(spec, config, ctx) {
385
402
  `git -C ${shellPath(c.primaryPath)} checkout ${branch}`,
386
403
  ],
387
404
  warnings,
405
+ afterSwitch: afterSwitchFor(config, c),
388
406
  receipt: {
389
407
  spec: spec.folder,
390
408
  branch,
@@ -405,8 +423,12 @@ function planTake(spec, config, ctx) {
405
423
  * In the branch-switch model `take` never moves the base ref, so release is just
406
424
  * `checkout base` (frees the branch) then re-attach it to the worktree — no reset.
407
425
  *
408
- * ctx: { primary:{onBase,branch}, primaryPath, base, clean, worktreeExists, restartApps }
409
- * @returns {object} { blocked, noop, reason, commands, warnings, 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 }
410
432
  */
411
433
  function planRelease(spec, config, ctx) {
412
434
  const c = ctx || {}
@@ -422,6 +444,7 @@ function planRelease(spec, config, ctx) {
422
444
  base,
423
445
  branch,
424
446
  worktreePath: spec.worktreePath,
447
+ afterSwitch: noTriggered(),
425
448
  }
426
449
 
427
450
  // Nothing live — the primary checkout is already on base.
@@ -448,7 +471,7 @@ function planRelease(spec, config, ctx) {
448
471
  const commands = [`git -C ${shellPath(c.primaryPath)} checkout ${base}`]
449
472
  if (c.worktreeExists) commands.push(`git -C ${shellPath(spec.worktreePath)} switch ${branch}`)
450
473
  const warnings = restartReminders(Array.isArray(c.restartApps) ? c.restartApps : [], `on ${base}`)
451
- return { ...result, commands, warnings, clears: true }
474
+ return { ...result, commands, warnings, clears: true, afterSwitch: afterSwitchFor(config, c) }
452
475
  }
453
476
 
454
477
  // --- abort planner --------------------------------------------------------
@@ -503,7 +526,86 @@ function planAbort(config, ctx) {
503
526
  return { ...result, commands, clears: true, branch }
504
527
  }
505
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
+
506
607
  module.exports = {
608
+ runAfterSwitch,
507
609
  receiptPath,
508
610
  renderReceipt,
509
611
  readReceipt,
@@ -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
+ }
@@ -0,0 +1,50 @@
1
+ 'use strict'
2
+
3
+ const { globToRegExp } = require('./glob.js')
4
+
5
+ /**
6
+ * Decide a list of `{ run, when }` command entries against the files a change
7
+ * brings in — shared by `afterLand` (a land) and `live.afterSwitch` (a live
8
+ * switch), which are the same question asked about two different moves.
9
+ *
10
+ * `range` is those files: a list (possibly empty) when known, null when it is
11
+ * not. Each entry gets a decision — `always` (no `when`), `matched` (with the
12
+ * first path that hit), `skipped`, or `unknown` — and `commands` is every entry
13
+ * but the skipped ones, in config order.
14
+ *
15
+ * AN UNKNOWN RANGE RUNS THE CONDITIONAL ENTRIES. A move made elsewhere, or a
16
+ * diff git would not answer, says nothing about what changed, and only one
17
+ * reading is harmless: a redundant generate costs seconds, a skipped one leaves
18
+ * the tree broken with nothing pointing at why (`.claude/rules/negative-checks.md`
19
+ * rule 4). An EMPTY known range is not unknown — a change that touches no files
20
+ * is healthy, and it skips them.
21
+ */
22
+ function planTriggered(raw, cwd, range = null) {
23
+ const list = Array.isArray(raw) ? raw : []
24
+ const entries = list.map((e) => decide(asEntry(e), range))
25
+ const commands = entries.filter((e) => e.decision !== 'skipped').map((e) => e.run)
26
+ return { cwd: entries.length ? cwd : null, commands, entries, range }
27
+ }
28
+
29
+ function decide(entry, range) {
30
+ if (!entry.when) return { ...entry, decision: 'always', matched: null }
31
+ if (range === null) return { ...entry, decision: 'unknown', matched: null }
32
+ const res = entry.when.map(globToRegExp)
33
+ const matched = range.find((f) => res.some((r) => r.test(f)))
34
+ return matched === undefined
35
+ ? { ...entry, decision: 'skipped', matched: null }
36
+ : { ...entry, decision: 'matched', matched }
37
+ }
38
+
39
+ // Normalised config holds `{ run, when }`; a pure caller may still hand over
40
+ // the plain string an entry is written as.
41
+ function asEntry(entry) {
42
+ return typeof entry === 'string' ? { run: entry, when: null } : { run: entry.run, when: entry.when || null }
43
+ }
44
+
45
+ // The empty form: a blocked or no-op plan, where nothing moved and nothing follows.
46
+ function noTriggered() {
47
+ return { cwd: null, commands: [], entries: [], range: null }
48
+ }
49
+
50
+ module.exports = { planTriggered, noTriggered }