Core infrastructure for Claude Code: persistent agent identity, session lifecycle hooks, operational memory, and meta skills. Provides a customizable framework…

hooks/register.ts 2031 lines1// workbench-core's hooks module, beside the command hooks in hooks.json. A
2// bash guard moved here once its port held parity with it, and its command
3// hook was then removed.
4//
5// $.workbench the noun other plugins build on: the brief, the scratch
6// roots, orchestrator mode, the lane, the shell reader
7// (types/index.d.ts is its contract)
8// question rule every question to Mike goes through AskUserQuestion, with
9// its context in prose right above the call
10// request meter turns, and each API request's cost, on the status line
11// cache meter each request's cache read against its cache creation, and
12// the system-prompt section that changed at a creation spike
13// status line beside the meter: memory health, orchestrator mode, reply
14// rows, learnings due for compaction, warmup notices
15// commands /orchestrator, /memory-status, /notices and
16// /process-pending-summaries, answered here with no model turn
17// vault writes the memory MCP's write, edit and append get a vault-relative
18// path, valid frontmatter on a new note, and path links
19// deferred start the warmup's pending-summary drain and Chat-skill scan,
20// started once the SessionStart hooks are done
21// log checkpoint hooks/session-log.sh after each main-loop turn, interrupted
22// ones included, and at session end, SIGHUP and SIGTERM too
23// memory capture the live session's durable findings, asked of a fork and
24// written to the vault, with no turn shown and no question
25// recall vault hits for a prompt or a content search, filtered and
26// injected at the tail, never into the system prompt
27// learnings a skill's vault learnings, merged into its text
28// intake nudge the first Edit of a task with no intake block on screen
29// guards the peer message gate, the provisioning, summary-writer,
30// credential, whole-disk search and outbound prose guards,
31// judged before a tool call runs, and refusing when they
32// cannot judge
33// prompt rules the workbench rules as shared system-prompt sections, the
34// same bytes in every session, and a sub-agent's copy at its
35// start; the harness's memory section and the block an older
36// warmup spliced into CLAUDE.md are left out
37//
38// The logic is pure and lives in mods/. Every hook that touches `$` lives in
39// this file, because the engine follows `$` into no imported function, and a
40// plugin registers each event once: so each event below has one hook, and the
41// hook branches where several features share the event.
42
43import { atom, read, update } from 'claude-code'
44import type { EngineInterface, FsEntry, InstructionFile, PromptComposeSection, Register, RenderElement, ToolCallResult, TurnUsage } from 'claude-code'
45
46import type { CacheState, ChurnEvent, PaneContent, WorkbenchCallerLane, WorkbenchShellParse } from '../types'
47import { BRIEF_SLOTS, checkBrief } from './mods/brief'
48import type { CaptureNote } from './mods/capture'
49import { FIRST, REPEAT, capturePrompt, duplicateOf, isCaptureDue, isNotFound, notesOf, replacedText, savedText, thresholdOf, writeOutcome } from './mods/capture'
50import type { CheckpointMode } from './mods/checkpoint'
51import { checkpointRequest, endTimeoutOf } from './mods/checkpoint'
52import { NUDGE, intakeShown } from './mods/intake'
53import { learningsPath, withLearnings } from './mods/learnings'
54import type { PromptLane } from './mods/prompt-rules'
55import {
56 HARNESS_MEMORY,
57 OMITS_CLAUDE_MD,
58 contributionPathsOf,
59 contributionsOf,
60 promptLaneOf,
61 rulesOwnersOf,
62 sectionsFor,
63 splicedBodiesOf,
64 subagentContextOf,
65 withShared,
66 withoutSplice,
67} from './mods/prompt-rules'
68import type { Hit } from './mods/recall'
69import {
70 CLASSIFY_TIMEOUT_MS,
71 FETCH_FACTOR,
72 LABELS as RELEVANCE_LABELS,
73 PROMPT_LIMIT,
74 PROMPT_MIN_SCORE,
75 SCAN_LIMIT,
76 SCAN_MIN_SCORE,
77 blockOf,
78 candidatesOf,
79 hitsOf,
80 mayScan,
81 promptQuery,
82 relevanceText,
83 relevantOf,
84 scanQuery,
85 tokensOf,
86} from './mods/recall'
87import {
88 EMPTY_CACHE,
89 cacheFactsOf,
90 cacheRequestOf,
91 changedSections,
92 churnText,
93 countCache,
94 hashesOf,
95 isSpike,
96 recordFileOf,
97 recordOf,
98 withChurn,
99} from './mods/cache-meter'
100import type { Action, ApiWrite, AskFacts, Commit, Gated, Head, Pick, Refs, RequestedCall } from './mods/commit-approval'
101import {
102 AGENT_MERGE_REFUSAL,
103 AGENT_RELEASE_REFUSAL,
104 ALIAS_REFUSAL,
105 API_WRITE_REFUSAL,
106 GATED_REFUSALS,
107 MOVE_REFUSAL,
108 ONE_REFUSAL,
109 PATHSPEC_REFUSAL,
110 RELEASE_REFUSAL,
111 REWRITE_REFUSAL,
112 SHARED_LINE_REFUSAL,
113 UNREAD_TREE_REFUSAL,
114 agentReleaseRefusalOf,
115 agentUnreadRefusalOf,
116 aliasSetsOf,
117 apiWritesOf,
118 approvalAfter,
119 askRefusalOf,
120 bindingRefusalOf,
121 filesOf,
122 gateOf,
123 messageOf,
124 lineKindOf,
125 isOtherRepo,
126 linePickOf,
127 originRepoOf,
128 remoteTargetOf,
129 isDefaultRef,
130 rewritesAt,
131 rewritesOf,
132 bundleRefusalOf,
133 dirOf,
134 headsOf,
135 isDefaultBranch,
136 isPaidByPick,
137 mergeNamesOf,
138 mergeTargetRefusalOf,
139 mergesOf,
140 movesHead,
141 pickOf,
142 refOf,
143 changesIndexBeside,
144 requestedCallsOf,
145 leftOutOf,
146 leftOutRefusal,
147 readLine,
148 releaseCountOf,
149 requestedOf,
150 shapeOf,
151 unnamedOf,
152} from './mods/commit-approval'
153import { FAILED_REFUSAL, commitVerdict } from './mods/commit-guard'
154import { subjectVerdict } from './mods/commit-subject'
155import { isAttendedPrompt, isAttendedSession, isScheduledFire, laneOf } from './mods/lane'
156import { bareSetRefusal, repairedNotice, runsGit } from './mods/false-bare'
157import { parseShell } from './mods/shell'
158import {
159 AGENT_WORKTREE_REFUSAL,
160 ENTER_WORKTREE_REFUSAL,
161 EXIT_WORKTREE_REFUSAL,
162 GUARDED,
163 PEER_ADVICE,
164 PEER_REFUSAL,
165 SEARCH_UNREAD,
166 bodyTargets,
167 credentialPathRefusal,
168 credentialRefusal,
169 hiddenCommandRefusal,
170 isPartlyRead,
171 mentionsSearch,
172 peerVerdict,
173 provisioningRefusal,
174 resolvePath,
175 searchRefusal,
176 searchRoots,
177 summaryWriterRefusal,
178 toolSearchRoots,
179} from './mods/guards'
180import type { SearchRoot } from './mods/guards'
181import { SQL_FILE_CAP, databaseRefusal, fileKey } from './mods/destructive-database'
182import type { Fact, FactGetter, ScopeContext, ScopeVerdict } from './mods/destructive-scope'
183import { NO_ONE_TO_ASK, dirKey, getterOf, needsScope, scopeVerdict, stepOf } from './mods/destructive-scope'
184import { needsVaultGit, vaultGitRefusal } from './mods/vault-git'
185import type { BodyPart } from './mods/outbound-prose'
186import { PROSE_TOOL_SUFFIXES, UNREAD_BODY, bashBodies, isProseTool, mcpBody, proseFindings, proseOfJson, proseRefusal } from './mods/outbound-prose'
187import {
188 REFUSAL,
189 STORE_KEY,
190 USAGE,
191 isPersonOrigin,
192 legacyFileOf,
193 offSessionsOf,
194 reportOf,
195 toggleOf,
196 withMode,
197} from './mods/orchestrator'
198import { denyOf as dispatchDenyOf, hintOf as dispatchHintOf } from './mods/dispatch'
199import { isInScope, isWorkType, outsideDenyOf, unreadableDenyOf, workdirPathsOf } from './mods/project-scope'
200import { REMIND_STORE_KEY, hasDotPart, isInRoots, isWholeFileWrite, reminderOf, remindedOf, splitTarget, targetOf } from './mods/delegation'
201import {
202 ASKS_NOTHING,
203 ASKS_USER,
204 LABELS,
205 REPROMPT_REASON,
206 aboveOf,
207 agentResultForwards,
208 classifierText,
209 endsOnQuestion,
210 hasCandidate,
211 notificationForwards,
212 proseOf,
213 questionRefusalOf,
214 shownTextOf,
215} from './mods/question-rule'
216import {
217 DOORBELL_MS,
218 FV_SERVE,
219 RUN_TIMEOUT_MS,
220 SCRIPT as MEETING_SCRIPT,
221 NO_DISPATCH_REFUSAL,
222 UNREAD_NOTE_REFUSAL,
223 WRITER_TOOL_REFUSAL,
224 idRefusal,
225 isInside,
226 meetingIdOf,
227 meetingWriterPathRefusal,
228 meetingWriterRefusal,
229 meetingsDirOf,
230 overwriteRefusal,
231} from './mods/meetings'
232import { NAME as PENDING, REFUSAL as PENDING_REFUSAL, USAGE as PENDING_USAGE, outcomeOf, reportOf as pendingReportOf, requestOf } from './mods/pending-summaries'
233import { EMPTY, countRequest, countTurn, statusOf } from './mods/request-meter'
234import { countOf, factsOf, healthOf, learningsAfter, lineOf, noticesOf, rowsOf, skillNameOf } from './mods/status-line'
235import type { VaultTool } from './mods/vault-write'
236import {
237 TEXT_FIELD,
238 fixPath,
239 frontmatterProblems,
240 frontmatterRefusal,
241 isNote,
242 needsRoot,
243 resolvedOf,
244 rewriteLinks,
245 vaultToolOf,
246 wikiTargets,
247} from './mods/vault-write'
248
249const meter = atom({ plugin: 'workbench-core', key: 'meter' } as const, EMPTY)
250const cache = atom({ plugin: 'workbench-core', key: 'cache' } as const, EMPTY_CACHE)
251// Whether a person opened the current turn, so the question rule applies.
252const turnAttended = atom({ plugin: 'workbench-core', key: 'turnAttended' } as const, false)
253// Whether the question rule already re-prompted in the current turn.
254const reprompted = atom({ plugin: 'workbench-core', key: 'reprompted' } as const, false)
255const delegationReminded = atom({ plugin: 'workbench-core', key: 'delegationReminded' } as const, '')
256const commitApproval = atom({ plugin: 'workbench-core', key: 'commitApproval' } as const, 'none')
257const turnRequest = atom({ plugin: 'workbench-core', key: 'turnRequest' } as const, [])
258const pendingLines = atom({ plugin: 'workbench-core', key: 'pendingLines' } as const, {})
259// Whether a schedule opened the current turn, so a commit in it is not gated.
260const turnScheduled = atom({ plugin: 'workbench-core', key: 'turnScheduled' } as const, false)
261const turnForwards = atom({ plugin: 'workbench-core', key: 'turnForwards' } as const, false)
262const statusLine = atom({ plugin: 'workbench-core', key: 'statusLine' } as const, null)
263const learnings = atom({ plugin: 'workbench-core', key: 'learnings' } as const, {})
264const replyRows = atom({ plugin: 'workbench-core', key: 'replyRows' } as const, null)
265const notices = atom({ plugin: 'workbench-core', key: 'notices' } as const, [])
266const pane = atom({ plugin: 'workbench-core', key: 'pane' } as const, { title: '', text: '' })
267const capture = atom({ plugin: 'workbench-core', key: 'capture' } as const, { turns: 0, hasFired: false, written: [] })
268const recall = atom({ plugin: 'workbench-core', key: 'recall' } as const, { seen: [], queries: [] })
269const intake = atom({ plugin: 'workbench-core', key: 'intake' } as const, { task: 0, checked: 0 })
270const TRANSCRIPT = { plugin: 'workbench-core', key: 'transcriptPath' } as const
271// Unset until known: a status entry for a fact not known yet is left out.
272const ORCHESTRATOR_ON = { plugin: 'workbench-core', key: 'orchestratorOn' } as const
273const MEMORY_HEALTH = { plugin: 'workbench-core', key: 'memoryHealth' } as const
274const STARTED_AT = { plugin: 'workbench-core', key: 'startedAt' } as const
275const NOTICES_MTIME = { plugin: 'workbench-core', key: 'noticesMtime' } as const
276
277// The one pane: /memory-status and /notices each fill it.
278const PANE = 'workbench-core'
279const COMMANDS = [
280 { name: 'orchestrator', description: 'Orchestrator mode for this session: on, off, or status', argumentHint: '[on|off|status]' },
281 { name: 'memory-status', description: "The shared memory server's facts, in a pane" },
282 { name: 'notices', description: 'The warmup notices from this session start, in a pane' },
283 {
284 name: PENDING,
285 description: 'Dispatch summary-writers for the pending session summaries, or for one session by id',
286 argumentHint: '[<session-id> [--overwrite]]',
287 },
288] as const
289const OURS: ReadonlySet<string> = new Set(COMMANDS.map(command => command.name))
290// How long after session start the first memory probe and the first notices
291// read run, and the second read: memory-server-up.sh can hold SessionStart up to
292// 15 s before session-warmup.sh writes the notices file. Each probe after that
293// reads the file again when it changed.
294const SETTLE_MS = 3000
295const NOTICES_LATE_MS = 20_000
296// Every session reads the one notices file, and every session start rewrites
297// it. A rewrite later than this after this session's start is another
298// session's, so it is not shown here.
299const NOTICES_WINDOW_MS = 120_000
300const PROBE_EVERY_MS = 60_000
301// The warmup's deferred half starts as soon as the SessionStart hooks are done,
302// and may take this long: a few detached spawns and a scan of the plugins.
303// session-warmup.sh's DEFERRED_TIMEOUT_S states the same figure: a deferred
304// run older than it is taken as dead.
305const DEFERRED_MS = 0
306const DEFERRED_TIMEOUT_MS = 120_000
307
308// Whether a finished reply leaves a question for Mike in prose. A classifier
309// that fails, or answers with neither label, falls back to the deterministic
310// reading, so a question is never let through only because the classifier
311// could not answer.
312async function asksInProse($: EngineInterface, reply: string): Promise<boolean> {
313 const prose = proseOf(reply)
314 if (!hasCandidate(prose)) return false
315 try {
316 const label = await $.model.classify(classifierText(prose), LABELS)
317 if (label === ASKS_USER) return true
318 if (label === ASKS_NOTHING) return false
319 } catch {
320 // The deterministic reading below decides.
321 }
322 return endsOnQuestion(prose)
323}
324
325// Whether this load drew a status line yet. A clear with nothing drawn is
326// skipped, so a session start with nothing to show draws nothing.
327let hasDrawn = false
328
329// The status line: the meter, then every workbench fact known so far.
330async function drawStatus($: EngineInterface): Promise<void> {
331 const figures = await read($, meter)
332 const { value: isOn } = await $.state.get(ORCHESTRATOR_ON)
333 const { value: health } = await $.state.get(MEMORY_HEALTH)
334 const rows = await read($, replyRows)
335 const facts = factsOf({
336 memoryHealth: health,
337 orchestratorOn: isOn,
338 replyRows: rows ?? undefined,
339 learnings: await read($, learnings),
340 notices: await read($, notices),
341 })
342 const isMetered = figures.turns > 0 || figures.first !== null
343 const line = lineOf(isMetered ? statusOf(figures) : undefined, [...cacheFactsOf(await read($, cache)), ...facts])
344 if (line === undefined && !hasDrawn) return
345 hasDrawn = true
346 await update($, statusLine, () => line ?? null)
347}
348
349// The legacy file the bash gates read for this session, or undefined when the
350// session id cannot name one.
351async function legacyFile($: EngineInterface): Promise<string | undefined> {
352 return legacyFileOf(await $.session.id(), await $.env.get('WORKBENCH_ORCHESTRATOR_STATE_DIR'), await $.env.get('HOME'))
353}
354
355// Orchestrator mode for this session. Seeded once, from the mode stored for
356// this session id, else from the legacy file an older build may have left.
357async function orchestratorOn($: EngineInterface): Promise<boolean> {
358 const { value } = await $.state.get(ORCHESTRATOR_ON)
359 if (value !== undefined) return value
360 const id = await $.session.id()
361 const stored = offSessionsOf(await $.store.get(STORE_KEY), await $.clock.now())
362 const file = await legacyFile($)
363 const isOn = !(id in stored) && !(file !== undefined && isOffFile(await legacyEntry($, file)))
364 await $.state.set(ORCHESTRATOR_ON, isOn)
365 return isOn
366}
367
368// The legacy file's directory entry as it stands, a symbolic link included and
369// never followed, or undefined when there is none.
370async function legacyEntry($: EngineInterface, file: string): Promise<FsEntry | undefined> {
371 const cut = file.lastIndexOf('/')
372 const entries = await $.fs.list(file.slice(0, cut)).catch(() => [])
373 return entries.find(entry => entry.name === file.slice(cut + 1))
374}
375
376// What counts as off, here and in both bash gates (`[ -f ] && [ ! -L ]`): a
377// regular file that is not a symbolic link. A directory or a link planted at
378// the path is not a mode anyone chose.
379const isOffFile = (entry: FsEntry | undefined): boolean => entry !== undefined && entry.kind === 'file' && !entry.isLink
380
381// Puts the legacy path in line with the mode: a regular file when off, nothing
382// when on. Anything else there, a directory or a symbolic link, is removed with
383// `rm -rf -- <path>`, which removes that one entry and never follows a link,
384// and is never written through. The entry is listed again before the write, so
385// a link or directory planted after the removal is left unwritten: the gates
386// then find no regular file and stay on. A link planted in the instant between
387// that listing and the write is the one race left, as $.fs.write has no
388// no-follow mode.
389async function mirror($: EngineInterface, isOn: boolean): Promise<void> {
390 const file = await legacyFile($)
391 if (file === undefined) return
392 const entry = await legacyEntry($, file)
393 if (!isOn && isOffFile(entry)) return
394 if (entry !== undefined) await $.process.run(['rm', '-rf', '--', file])
395 if (isOn) return
396 if ((await legacyEntry($, file)) === undefined) await $.fs.write(file, '')
397}
398
399async function setOrchestrator($: EngineInterface, isOn: boolean): Promise<void> {
400 const id = await $.session.id()
401 const now = await $.clock.now()
402 await $.state.set(ORCHESTRATOR_ON, isOn)
403 await $.store.set(STORE_KEY, withMode(offSessionsOf(await $.store.get(STORE_KEY), now), id, isOn, now))
404 await mirror($, isOn)
405}
406
407// ─── the delegation reminder (hooks/mods/delegation.ts) ─────────────────────
408
409const isLinkAt = ($: EngineInterface, path: string): Promise<boolean> =>
410 $.fs.stat(path).then(
411 stat => stat.isLink,
412 () => false,
413 )
414const isDirAt = ($: EngineInterface, path: string): Promise<boolean> =>
415 $.fs.stat(path).then(
416 stat => stat.kind === 'dir',
417 () => false,
418 )
419
420// The physical path a write target would land at, or undefined when it cannot
421// be settled: a relative path, a name that is empty, `.` or `..`, a target or
422// a missing folder that is a symbolic link (Write writes through it), a `.` or
423// `..` below the deepest existing folder, or a folder that does not resolve.
424// The deepest existing folder is resolved through realPath, so
425// `<root>/link/x` and `<root>/../x` cannot pass a prefix test.
426async function physicalTarget($: EngineInterface, path: string): Promise<string | undefined> {
427 const split = splitTarget(path)
428 if (split === undefined || (await isLinkAt($, path))) return undefined
429 let { dir, name: rest } = split
430 while (dir !== '' && !(await isDirAt($, dir))) {
431 if (await isLinkAt($, dir)) return undefined
432 const cut = dir.lastIndexOf('/')
433 rest = `${dir.slice(cut + 1)}/${rest}`
434 dir = dir.slice(0, cut)
435 }
436 if (hasDotPart(rest)) return undefined
437 const real = (await $.fs.stat(dir || '/', { resolve: true })).realPath
438 return real === undefined ? undefined : `${real.replace(/\/+$/, '')}/${rest}`
439}
440
441// Whether a workbench-dev-team plugin is installed: any
442// $HOME/.claude/plugins/cache/<marketplace>/workbench-dev-team folder.
443async function hasDevTeam($: EngineInterface, home: string): Promise<boolean> {
444 const cache = `${home}/.claude/plugins/cache`
445 const entries = await $.fs.list(cache).catch(() => [])
446 for (const entry of entries) {
447 if (await isDirAt($, `${cache}/${entry.name}/workbench-dev-team`)) return true
448 }
449 return false
450}
451
452// The reminder for one main-loop whole-file write, or undefined for silence.
453// Rejects on any failure, and the caller reads a rejection as silence.
454async function delegationReminder($: EngineInterface, e: { tool: string; agentId?: string; file_path?: unknown; notebook_path?: unknown }): Promise<string | undefined> {
455 if (!isWholeFileWrite(e.tool)) return undefined
456 if ((await $.workbench.callerLane(e.agentId === undefined ? {} : { agentId: e.agentId })) !== 'main') return undefined
457 if (!(await $.workbench.orchestratorIsOn())) return undefined
458 const target = await physicalTarget($, targetOf(e))
459 if (target !== undefined && isInRoots(target, await $.workbench.scratchRoots())) return undefined
460 const home = await $.env.get('HOME')
461 if (!home) return undefined
462 // Once per session. The store is read first, so a session reminded in an
463 // earlier process stays quiet. Then the $.state change decides a race: only
464 // the change that saw another session's id wins. The store is written last,
465 // and a write that fails rejects, so the reminder is never shown unrecorded.
466 const id = await $.session.id()
467 const now = await $.clock.now()
468 const stored = remindedOf(await $.store.get(REMIND_STORE_KEY), now)
469 if (id in stored) return undefined
470 let isFirst = false
471 await update($, delegationReminded, seen => {
472 isFirst = seen !== id
473 return id
474 })
475 if (!isFirst) return undefined
476 await $.store.set(REMIND_STORE_KEY, { ...stored, [id]: now })
477 return reminderOf(await hasDevTeam($, home))
478}
479
480// The agent dispatch gate's verdict for one main-loop Agent call: a refusal, a
481// hint, or neither. The brief check is pure (checkBrief), so the only failures
482// are the reads around it, and any that rejects reaches the tool.call hook's
483// .catch, which refuses Agent because Agent is in GUARDED. The dev-team probe
484// only adds a line to a refusal, so a failed probe drops the line.
485async function dispatchVerdict($: EngineInterface, prompt: unknown): Promise<{ deny?: string; hint?: string }> {
486 // The mode is read from $.state and $.store (orchestratorOn), so a legacy
487 // file that cannot be named (HOME unset, or a session id that cannot name a
488 // file) never stands this gate down.
489 if ((await $.workbench.callerLane({})) !== 'main') return {}
490 if ((await $.env.get('WORKBENCH_ORCHESTRATOR')) === '0' || !(await orchestratorOn($))) return {}
491 const text = typeof prompt === 'string' ? prompt : ''
492 const check = checkBrief(text)
493 if (check.isComplete) return check.shape === 'brief' ? { hint: dispatchHintOf(text) } : {}
494 const home = await $.env.get('HOME')
495 const hasTeam = home ? await hasDevTeam($, home).catch(() => false) : false
496 return { deny: dispatchDenyOf(check.missing, BRIEF_SLOTS, hasTeam) }
497}
498
499async function probeMemory($: EngineInterface): Promise<void> {
500 const { stdout } = await $.process.run(['bash', `${$.plugin.root}/scripts/memory-health.sh`], { timeoutMs: 15_000 })
501 const health = healthOf(stdout)
502 if (health !== undefined) await $.state.set(MEMORY_HEALTH, health)
503 await drawStatus($)
504}
505
506async function repairFalseBare($: EngineInterface, dir: string): Promise<string | undefined> {
507 const { stdout } = await $.process.run(['bash', `${$.plugin.root}/hooks/lib/false-bare.sh`, dir], { timeoutMs: 10_000 })
508 const repo = stdout.trim()
509 return repo.startsWith('/') ? repo : undefined
510}
511
512async function repairBeforeGit($: EngineInterface, line: unknown, isAttended: boolean): Promise<void> {
513 if (typeof line !== 'string' || !line.includes('git') || !runsGit(parseShell(line))) return
514 const repo = await repairFalseBare($, await $.session.cwd())
515 if (repo !== undefined && isAttended) $.ui.toast(repairedNotice(repo), { timeoutMs: 10_000 })
516}
517
518const noticesFile = async ($: EngineInterface): Promise<string | undefined> => {
519 const home = await $.env.get('HOME')
520 return home ? `${home}/.claude-workbench/warmup-notices.md` : undefined
521}
522
523// The warmup notices reach Mike here, never through the model: a toast naming
524// each one, a count on the status line, and the whole file behind /notices.
525// A file older than the session is the previous session's, still waiting for
526// session-warmup.sh to rewrite it, so it is left for a later read. A file read
527// once is read again only when its mtime changes, and only within
528// NOTICES_WINDOW_MS of the start: a later rewrite is another session's.
529async function deliverNotices($: EngineInterface): Promise<void> {
530 const file = await noticesFile($)
531 if (file === undefined || !(await $.fs.exists(file))) return
532 const { mtimeMs } = await $.fs.stat(file)
533 const { value: startedAt = 0 } = await $.state.get(STARTED_AT)
534 const { value: shown } = await $.state.get(NOTICES_MTIME)
535 if (mtimeMs < startedAt || mtimeMs > startedAt + NOTICES_WINDOW_MS || mtimeMs === shown) return
536 const headings = noticesOf(await $.fs.read(file))
537 await $.state.set(NOTICES_MTIME, mtimeMs)
538 await update($, notices, () => headings)
539 await drawStatus($)
540 if (headings.length > 0) $.ui.toast(`Warmup notices: ${headings.join('; ')}. Run /notices to read them.`, { timeoutMs: 10_000 })
541}
542
543async function showPane($: EngineInterface, content: PaneContent): Promise<void> {
544 await update($, pane, () => content)
545 await $.ui.open({ id: PANE, title: content.title })
546}
547
548// Whether the commit approval rule applies to a call: the main loop of an
549// interactive session, in any turn but a scheduled one. It reads the session
550// and the lane, never the question rule's turn reading: a peer, channel, SDK or
551// plugin turn in Mike's session is gated, because it carries outside text and
552// a deny, unlike a re-prompt, cannot loop. The exemptions are the lanes that
553// commit unattended by design:
554// - a session nobody sits at (`claude -p`, the SDK, a top-level --agent run,
555// WORKBENCH_DEV_TEAM_PIPELINE=1), from session.start; unknown before it,
556// which is read as attended, the gate's side
557// - the pipeline's flag, read here as well, so no lane answer can gate it
558// - a sub-agent or top-level agent, from $.workbench.callerLane; a rejection
559// is read as `main`, the gate's side
560// - a turn a schedule opened (the origin, or the `<scheduled-task ` wrapper)
561async function isCommitGated($: EngineInterface, sessionAttended: boolean | undefined, agentId: string | undefined): Promise<boolean> {
562 if (sessionAttended === false || (await $.env.get('WORKBENCH_DEV_TEAM_PIPELINE')) === '1') return false
563 const lane = await $.workbench.callerLane(agentId === undefined ? {} : { agentId }).catch((): WorkbenchCallerLane => 'main')
564 if (lane !== 'main') return false
565 return !(await read($, turnScheduled))
566}
567
568async function isAgentLane($: EngineInterface, agentId: string | undefined, sessionAttended: boolean | undefined): Promise<boolean> {
569 if (agentId !== undefined || sessionAttended === false || (await $.env.get('WORKBENCH_DEV_TEAM_PIPELINE')) === '1') return true
570 return (await $.workbench.callerLane({}).catch((): WorkbenchCallerLane => 'main')) !== 'main'
571}
572
573async function releaseRefusalOf($: EngineInterface, line: string, agentId: string | undefined, sessionAttended: boolean | undefined): Promise<string | undefined> {
574 const agentRelease = agentReleaseRefusalOf(line)
575 return agentRelease !== undefined && (await isAgentLane($, agentId, sessionAttended)) ? agentRelease : undefined
576}
577
578async function askRefusal($: EngineInterface, missing: readonly Gated[], command: string, dir: string, commit: Commit | undefined): Promise<string> {
579 const kind = lineKindOf(missing, command)
580 if (kind !== undefined) await update($, pendingLines, lines => ({ ...lines, [command]: kind }))
581 return askRefusalOf(missing, await askFactsOf($, command, dir, commit))
582}
583
584async function commitGuardOf($: EngineInterface, command: unknown, agentId: string | undefined, sessionAttended: boolean | undefined): Promise<string | undefined> {
585 const line = typeof command === 'string' ? command : ''
586 const lane = await $.workbench.callerLane(agentId === undefined ? {} : { agentId }).catch(() => undefined)
587 const isUnattended = sessionAttended !== true || !(await read($, turnAttended))
588 return commitVerdict(parseShell(line), line, { lane, isUnattended })?.deny
589}
590
591async function unreadRefusalOf($: EngineInterface, line: string, agentId: string | undefined, sessionAttended: boolean | undefined): Promise<string | undefined> {
592 const refusal = agentUnreadRefusalOf(line)
593 return refusal !== undefined && (await isAgentLane($, agentId, sessionAttended)) ? refusal : undefined
594}
595
596// HEAD and the push target of the repository at `dir`, each undefined when git
597// cannot say. Read with $.process.run, which runs git with repo hooks off.
598async function refsOf($: EngineInterface, dir: string): Promise<Refs> {
599 const ref = (name: string) =>
600 $.process
601 .run(['git', '-C', dir, 'rev-parse', '--verify', '--quiet', name], { timeoutMs: 10_000 })
602 .then(({ exitCode, stdout }) => (exitCode === 0 && stdout.trim() !== '' ? stdout.trim() : undefined), () => undefined)
603 return { head: await ref('HEAD'), pushed: await ref('@{push}') }
604}
605
606const gitOut = ($: EngineInterface, dir: string, args: readonly string[]): Promise<string | undefined> =>
607 $.process
608 .run(['git', '-C', dir, ...args], { timeoutMs: 10_000 })
609 .then(({ exitCode, stdout }) => (exitCode === 0 && stdout.trim() !== '' ? stdout.trim() : undefined), () => undefined)
610
611async function headsAt($: EngineInterface): Promise<Head[]> {
612 return headsOf((await gitOut($, await $.session.cwd(), ['worktree', 'list', '--porcelain'])) ?? '')
613}
614
615async function bindingRefusal($: EngineInterface, pick: Pick, dir: string | undefined): Promise<string | undefined> {
616 if (dir === undefined) return bindingRefusalOf(pick, undefined, undefined)
617 const top = await gitOut($, dir, ['rev-parse', '--show-toplevel'])
618 const ref = refOf(await gitOut($, dir, ['symbolic-ref', '-q', 'HEAD']), await gitOut($, dir, ['rev-parse', '--verify', '--quiet', 'HEAD']))
619 return bindingRefusalOf(pick, top, ref)
620}
621
622async function askFactsOf($: EngineInterface, command: string, dir: string, commit: Commit | undefined): Promise<AskFacts> {
623 const remote = remoteTargetOf(command, originRepoOf(await gitOut($, await $.session.cwd(), ['config', '--get', 'remote.origin.url'])))
624 const repo = remote === undefined ? await gitOut($, dir, ['rev-parse', '--show-toplevel']) : `${remote.repo} on GitHub`
625 const branch = remote === undefined ? await gitOut($, dir, ['symbolic-ref', '-q', 'HEAD']) : remote.branch
626 const facts: AskFacts = { command, ...(repo === undefined ? {} : { repo }), ...(branch === undefined ? {} : { branch }) }
627 if (commit === undefined) return facts
628 const status = await $.process
629 .run(['git', '-C', dir, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], { timeoutMs: 10_000 })
630 .then(({ exitCode, stdout }) => (exitCode === 0 ? stdout : undefined), () => undefined)
631 const message = messageOf(commit.args)
632 return { ...facts, ...(message === undefined ? {} : { message }), ...(status === undefined ? {} : { files: filesOf(status) }) }
633}
634
635async function apiWritesIntoDefault($: EngineInterface, writes: readonly ApiWrite[]): Promise<number> {
636 const originHead = await gitOut($, await $.session.cwd(), ['symbolic-ref', '-q', 'refs/remotes/origin/HEAD'])
637 const origin = originRepoOf(await gitOut($, await $.session.cwd(), ['config', '--get', 'remote.origin.url']))
638 return writes.filter(write => write.branch === null || isDefaultRef(write.branch, originHead) || isOtherRepo(write.repo, origin)).length
639}
640
641async function isPipelineRewrite($: EngineInterface, line: string, agentId: string | undefined): Promise<boolean> {
642 if (agentId !== undefined || (await $.env.get('WORKBENCH_DEV_TEAM_PIPELINE')) !== '1') return false
643 for (const rewrite of rewritesAt(line)) {
644 const at = rewrite.dir === null ? undefined : rewrite.dir === '' ? await $.session.cwd() : rewrite.dir
645 if (at === undefined) return false
646 const originHead = await gitOut($, at, ['symbolic-ref', '-q', 'refs/remotes/origin/HEAD'])
647 if (isDefaultBranch(await gitOut($, at, ['symbolic-ref', '-q', 'HEAD']), originHead)) return false
648 if ((rewrite.refs ?? []).some(ref => isDefaultRef(ref, originHead))) return false
649 }
650 return true
651}
652
653async function mergesIntoDefault($: EngineInterface, dirs: readonly (string | null)[]): Promise<number> {
654 let count = 0
655 for (const dir of dirs) {
656 const at = dir === null ? undefined : dir === '' ? await $.session.cwd() : dir
657 const branch = at === undefined ? undefined : await gitOut($, at, ['symbolic-ref', '-q', 'HEAD'])
658 const originHead = at === undefined ? undefined : await gitOut($, at, ['symbolic-ref', '-q', 'refs/remotes/origin/HEAD'])
659 if (isDefaultBranch(branch, originHead)) count++
660 }
661 return count
662}
663
664const PLAN_FILE = 'A plan file in the login home\'s .claude/plans folder, written by the main session.'
665
666async function isPlanFile($: EngineInterface, input: unknown): Promise<boolean> {
667 if ((await $.workbench.callerLane({})) !== 'main') return false
668 const path = targetOf((input ?? {}) as { file_path?: unknown })
669 const real = path === '' ? undefined : await physicalTarget($, path)
670 if (real === undefined || real !== path) return false
671 return isInRoots(real, (await $.workbench.scratchRoots()).filter(root => /\/\.claude\/plans$/.test(root)))
672}
673
674async function isApprovedLine($: EngineInterface, line: string, request: readonly Action[]): Promise<boolean> {
675 const calls = requestedCallsOf(line, request)
676 if (calls === undefined) return false
677 for (const call of calls) {
678 if (!(await isApprovedCall($, call, request))) return false
679 }
680 return true
681}
682
683async function isApprovedCall($: EngineInterface, call: RequestedCall, request: readonly Action[]): Promise<boolean> {
684 if (call.action === 'release' || call.action === 'merge') return (await $.env.get('GH_REPO')) === undefined
685 const dir = call.dir === undefined ? await $.session.cwd() : await projectDirOf($, call.dir)
686 if (dir === undefined) return false
687 if (call.action === 'commit' || call.ref === undefined) return true
688 const git = (args: string[]) =>
689 $.process
690 .run(['git', '-C', dir, ...args], { timeoutMs: 10_000 })
691 .then(({ exitCode, stdout }) => (exitCode === 0 && stdout.trim() !== '' ? stdout.trim() : undefined), () => undefined)
692 const branch = await git(['symbolic-ref', '--short', '-q', 'HEAD'])
693 if (branch === undefined || call.remote !== (await git(['config', '--get', `branch.${branch}.remote`]))) return false
694 if (call.ref === branch || call.ref === `refs/heads/${branch}`) return true
695 if (!request.includes('release')) return false
696 const tagged = await git(['rev-parse', '--verify', '-q', `refs/tags/${call.ref.replace(/^refs\/tags\//, '')}^{commit}`])
697 return tagged !== undefined && tagged === (await git(['rev-parse', '--verify', '-q', 'HEAD']))
698}
699
700async function projectDirOf($: EngineInterface, path: string): Promise<string | undefined> {
701 const project = await answerFact($, dirKey(await $.session.root()))
702 const real = await answerFact($, dirKey(path))
703 if (project === null || project === '/' || real === null) return undefined
704 const repo = await repoOf($, project)
705 if (repo === undefined) return undefined
706 if (isInScope(real, [project, repo.top])) return real
707 return (await repoOf($, real))?.common === repo.common ? real : undefined
708}
709
710async function treeRefusalOf($: EngineInterface, line: string, commit: Commit | undefined, toolUseId: string | undefined): Promise<string | undefined> {
711 if (commit === undefined || commit.args === null) return UNREAD_TREE_REFUSAL
712 const shape = shapeOf(commit.args)
713 if (shape.isPartial) return PATHSPEC_REFUSAL
714 if (changesIndexBeside(line)) return SHARED_LINE_REFUSAL
715 const dir = dirOf(commit.dir, await $.session.cwd(), await $.env.get('HOME'))
716 if (dir === undefined) return UNREAD_TREE_REFUSAL
717 const status = await $.process
718 .run(['git', '-C', dir, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], { timeoutMs: 10_000 })
719 .then(({ exitCode, stdout, isStdoutTruncated }) => (exitCode === 0 && !isStdoutTruncated ? stdout : undefined), () => undefined)
720 if (status === undefined) return UNREAD_TREE_REFUSAL
721 const leftOut = leftOutOf(status, shape.isAll)
722 if (leftOut.length === 0) return undefined
723 const shown = await $.session.messages({ as: 'api' }).then(messages => shownTextOf(messages, toolUseId), () => undefined)
724 const unnamed = unnamedOf(leftOut, shown ?? '')
725 return unnamed.length === 0 ? undefined : leftOutRefusal(unnamed)
726}
727
728type VaultCall = Record<string, unknown> & { path?: unknown }
729
730// The vault write checks on one memory MCP call: the call to pass on, fixed
731// where it needed fixing, or the refusal. scripts/vault-resolve.sh runs only
732// when the call needs the vault root or holds a [[link]]. When it cannot run,
733// an absolute path is refused and every link is left as written.
734async function checkVaultWrite($: EngineInterface, e: VaultCall, tool: VaultTool): Promise<{ deny: string } | { call: VaultCall }> {
735 const { path } = e
736 if (typeof path !== 'string') return { call: e }
737 const field = TEXT_FIELD[tool]
738 const text = typeof e[field] === 'string' ? (e[field] as string) : undefined
739 const targets = text !== undefined && isNote(path) ? wikiTargets(text) : []
740 const createsNote = isNote(path) && (tool === 'write' || (tool === 'append' && e.create_if_missing === true))
741 const facts =
742 needsRoot(path) || targets.length > 0 || (tool === 'append' && createsNote)
743 ? resolvedOf(
744 await $.process
745 .run(['bash', `${$.plugin.root}/scripts/vault-resolve.sh`, ...targets], { timeoutMs: 10_000 })
746 .then(({ stdout }) => stdout, () => ''),
747 )
748 : resolvedOf('')
749 const fixed = fixPath(path, facts.root, await $.env.get('HOME'))
750 if ('refusal' in fixed) return { deny: fixed.refusal }
751 // A write replaces the whole note, frontmatter included. An append creates
752 // one only where none is, and a note it cannot see is taken as new.
753 const isNew =
754 tool === 'write' ||
755 (createsNote && (facts.root === undefined || !(await $.fs.exists(`${facts.root}/${fixed.path}`).catch(() => false))))
756 if (createsNote && isNew) {
757 const problems = frontmatterProblems(tool === 'write' ? e.frontmatter : undefined, text)
758 if (problems.length > 0) return { deny: frontmatterRefusal(problems) }
759 }
760 const linked = text !== undefined && facts.paths.size > 0 ? rewriteLinks(text, facts.paths) : text
761 if (fixed.path === path && linked === text) return { call: e }
762 return { call: { ...e, path: fixed.path, ...(linked !== text ? { [field]: linked } : {}) } }
763}
764
765// One main-loop request on the cache meter. The system prompt is read on the
766// first request, for the baseline, and on every request that created cache:
767// at a creation spike, to name the sections that changed since the last
768// reading, and on any other, so a change that cost no spike is not blamed on a
769// later one. A request that only read the cache could not follow a prompt
770// change, so it is not read then. A prompt that cannot be read names none, and
771// the next reading compares with the last one that could. Only
772// a spike that names a section is shown, and only to a person at the session;
773// the record file is kept for those sessions, for measuring a change.
774async function meterCache($: EngineInterface, usage: TurnUsage, isAttended: boolean): Promise<void> {
775 const before = await read($, cache)
776 const request = cacheRequestOf(before.count + 1, usage)
777 let state: CacheState = countCache(before, request)
778 if (request.n === 1 || request.creation > 0) {
779 const hashes = await $.prompt.compose().then(({ sections }) => hashesOf(sections), () => null)
780 if (isSpike(request)) {
781 const sections = hashes === null || before.hashes === null ? null : changedSections(before.hashes, hashes)
782 const event: ChurnEvent = { n: request.n, read: request.read, creation: request.creation, sections }
783 state = withChurn(state, event)
784 if (isAttended && sections !== null && sections.length > 0) $.ui.toast(churnText(event), { timeoutMs: 10_000 })
785 }
786 if (hashes !== null) state = { ...state, hashes }
787 }
788 await update($, cache, () => state)
789 if (!isAttended) return
790 const home = await $.env.get('HOME')
791 const file = home === undefined ? undefined : recordFileOf(home, await $.session.id())
792 if (file !== undefined) await $.fs.write(file, recordOf(state)).catch(() => undefined)
793}
794
795async function meetingsDir($: EngineInterface): Promise<string | undefined> {
796 if ((await $.env.get('WORKBENCH_SKIP_WARMUP')) === '1') return undefined
797 const home = await $.env.get('HOME')
798 if (home === undefined || !(await $.fs.exists(FV_SERVE))) return undefined
799 const dir = meetingsDirOf(home)
800 const entry = await $.fs.stat(dir).catch(() => undefined)
801 return entry?.kind === 'dir' ? dir : undefined
802}
803
804let isMeetingRunning = false
805let isMeetingDue = false
806let isDoorbellSet = false
807
808async function meetingNotes($: EngineInterface): Promise<void> {
809 if (isMeetingRunning) {
810 isMeetingDue = true
811 return
812 }
813 isMeetingRunning = true
814 try {
815 do {
816 isMeetingDue = false
817 await $.process.run(['bash', `${$.plugin.root}/scripts/${MEETING_SCRIPT}`], { timeoutMs: RUN_TIMEOUT_MS }).catch(() => undefined)
818 } while (isMeetingDue)
819 } finally {
820 isMeetingRunning = false
821 }
822}
823
824function ringDoorbell($: EngineInterface): void {
825 if (isDoorbellSet) return
826 isDoorbellSet = true
827 $.clock.after(DOORBELL_MS, () => {
828 isDoorbellSet = false
829 void meetingNotes($).catch(() => undefined)
830 })
831}
832
833async function meetingWriterVaultRefusal($: EngineInterface, call: VaultCall, tool: VaultTool): Promise<string | undefined> {
834 if ((await $.env.get('WORKBENCH_MEETING_WRITER')) !== '1') return undefined
835 const path = String(call.path)
836 const outside = meetingWriterPathRefusal(path)
837 if (outside !== undefined) return outside
838 if (tool !== 'write') return WRITER_TOOL_REFUSAL
839 const dispatched = await $.env.get('WORKBENCH_MEETING_ID')
840 const fields = call.frontmatter as Record<string, unknown> | undefined
841 const incoming = typeof fields?.meeting_id === 'string' ? fields.meeting_id : meetingIdOf(typeof call.content === 'string' ? call.content : '')
842 const unmatched = idRefusal(path, dispatched, incoming)
843 if (unmatched !== undefined || dispatched === undefined) return unmatched ?? NO_DISPATCH_REFUSAL
844 const root = await vaultRoot($).catch(() => undefined)
845 if (root === undefined) return UNREAD_NOTE_REFUSAL
846 const file = `${root}/${path}`
847 const existing = await $.fs
848 .exists(file)
849 .then(isThere => (isThere ? $.fs.read(file) : undefined))
850 .catch(() => null)
851 if (existing === null) return UNREAD_NOTE_REFUSAL
852 return overwriteRefusal(path, dispatched, existing)
853}
854
855// The warmup's deferred half (hooks/session-warmup.sh --deferred): the
856// pending-summary drain and the Chat-skill scan. Its output reaches nobody.
857async function deferredWarmup($: EngineInterface, payload: string): Promise<void> {
858 await $.process.run(['bash', `${$.plugin.root}/hooks/session-warmup.sh`, '--deferred'], { stdin: payload, timeoutMs: DEFERRED_TIMEOUT_MS })
859}
860
861// /process-pending-summaries: the script's outcome, reported in a toast. It
862// asks nothing: the script decides whether a summary is redone.
863async function processPendingSummaries($: EngineInterface, args: string): Promise<void> {
864 const request = requestOf(args)
865 if (request === undefined) {
866 $.ui.toast(PENDING_USAGE)
867 return
868 }
869 const { sid } = request
870 const argv = sid === undefined ? [] : request.overwrite ? [sid, '--overwrite'] : [sid]
871 const outcome = outcomeOf(
872 await $.process
873 .run(['bash', `${$.plugin.root}/scripts/process-pending-summaries.sh`, ...argv], { timeoutMs: 60_000 })
874 .then(({ stdout }) => stdout, () => ''),
875 )
876 $.ui.toast(pendingReportOf(outcome, sid), { timeoutMs: 10_000 })
877}
878
879// The memory server's name as $.mcp.call takes it: core's own manifest server,
880// connected on first use. Kept for the module's life; a reload asks again.
881let memoryServerName: string | undefined
882async function memoryServer($: EngineInterface): Promise<string> {
883 if (memoryServerName !== undefined) return memoryServerName
884 const connected = await $.mcp.connect('memory')
885 if (!connected.isConnected) throw new Error(`memory: ${connected.message}`)
886 memoryServerName = connected.server
887 return memoryServerName
888}
889
890// One log checkpoint through hooks/session-log.sh (hooks/mods/checkpoint.ts).
891// A session whose transcript is unknown, or names another session, is left to
892// the settings hooks and the start-up reconciler.
893async function checkpointLog($: EngineInterface, sessionId: string, mode: CheckpointMode, reason: string | undefined, timeoutMs: number): Promise<void> {
894 const { value: transcript } = await $.state.get(TRANSCRIPT)
895 const request = checkpointRequest(sessionId, transcript, mode, reason)
896 if (request === undefined) return
897 await $.process.run(['bash', `${$.plugin.root}/hooks/session-log.sh`], { ...request, timeoutMs })
898}
899
900// The memory capture checkpoint (hooks/mods/capture.ts): a fork of the session
901// lists what it learned, and each note that passes the checks is written
902// through the memory MCP. No turn is shown and nothing is asked. Mike sees one
903// toast when a note is saved, and nothing when none is.
904//
905// $.mcp.call passes no tool.call hook of this module, so each write goes
906// through checkVaultWrite here: the vault write checks a model's write gets,
907// [[link]] rewrite included. A note is written only when the vault holds
908// nothing like it: a search on its name finds no duplicate (another session
909// may have saved it), and a read of its path answers a definite "not found".
910// Any other answer, an error included, skips the note. The write replaces any
911// note at the path, so a write that answers `created: false` replaced one
912// another session wrote after the read: that is an error, shown in a toast,
913// and the note does not count as saved (writeOutcome).
914async function captureNote($: EngineInterface, server: string, note: CaptureNote): Promise<boolean> {
915 const found = await $.mcp.call(server, 'search', { query: note.frontmatter.name, limit: 3 })
916 if (found.isError) return false
917 const duplicate = duplicateOf(note, hitsOf(found.content))
918 if (duplicate !== undefined) {
919 // One line per skip, so the share of captures held back can be measured.
920 $.ui.log(`workbench capture: skipped "${note.frontmatter.name}" (${duplicate})`, { to: 'debug' })
921 return false
922 }
923 if (!isNotFound(await $.mcp.call(server, 'read', { path: note.path }))) return false
924 const checked = await checkVaultWrite($, { path: note.path, content: note.content, frontmatter: note.frontmatter }, 'write')
925 if ('deny' in checked) return false
926 const outcome = writeOutcome(await $.mcp.call(server, 'write', checked.call))
927 if (outcome === 'replaced') {
928 const path = typeof checked.call.path === 'string' ? checked.call.path : note.path
929 $.ui.log(`workbench capture: replaced an existing note at ${path}`, { to: 'debug' })
930 $.ui.toast(replacedText(path), { timeoutMs: 10_000 })
931 }
932 return outcome === 'created'
933}
934
935async function captureMemory($: EngineInterface): Promise<void> {
936 const reply = await $.model.fork({ prompt: capturePrompt((await read($, capture)).written) })
937 if (!reply.isAnswered) return
938 const date = new Date(await $.clock.now()).toISOString().slice(0, 10)
939 const notes = notesOf(reply.text, date).filter(note => frontmatterProblems(note.frontmatter, note.content).length === 0)
940 if (notes.length === 0) return
941 const server = await memoryServer($)
942 const written: string[] = []
943 for (const note of notes) {
944 if (await captureNote($, server, note).catch(() => false)) written.push(note.path)
945 }
946 if (written.length === 0) return
947 await update($, capture, state => ({ ...state, written: [...state.written, ...written] }))
948 $.ui.toast(savedText(written), { timeoutMs: 10_000 })
949}
950
951// Whether this session counts turns toward a capture: a session a person sits
952// at, in a turn no schedule opened, with the old hook's switches honoured
953// (WORKBENCH_CAPTURE_STOP=0 and WORKBENCH_MEMORY_NUDGE=0 turn it off), and
954// never in a summary-writer.
955async function isCaptureOn($: EngineInterface, sessionAttended: boolean | undefined): Promise<boolean> {
956 if (sessionAttended !== true || (await read($, turnScheduled))) return false
957 if ((await $.env.get('WORKBENCH_CAPTURE_STOP')) === '0' || (await $.env.get('WORKBENCH_MEMORY_NUDGE')) === '0') return false
958 return (await $.env.get('WORKBENCH_SUMMARY_WRITER')) !== '1'
959}
960
961// The relevance labels for `hits`, one each, or undefined when the classifier
962// failed or ran past CLASSIFY_TIMEOUT_MS: the caller then keeps every hit.
963async function labelsOf($: EngineInterface, task: string, hits: readonly Hit[]): Promise<(string | undefined)[] | undefined> {
964 const pass = Promise.all(hits.map(hit => $.model.classify(relevanceText(task, hit), RELEVANCE_LABELS))).catch(() => undefined)
965 const timeout = $.clock.sleep(CLASSIFY_TIMEOUT_MS).then(
966 () => undefined,
967 () => undefined,
968 )
969 return Promise.race([pass, timeout])
970}
971
972// One recall (hooks/mods/recall.ts): the vault search through the memory MCP,
973// the threshold, the types and the session's dedupe set, then the relevance
974// pass. The hits it shows join the dedupe set. Its figures go to the debug log.
975async function recallBlock($: EngineInterface, query: string, limit: number, minScore: number, scan?: string): Promise<string | undefined> {
976 const started = await $.clock.now()
977 const server = await memoryServer($)
978 const found = await $.mcp.call(server, 'search', { query, limit: limit * FETCH_FACTOR })
979 if (found.isError) return undefined
980 const candidates = candidatesOf(hitsOf(found.content), (await read($, recall)).seen, limit, minScore)
981 if (candidates.length === 0) return undefined
982 const labels = await labelsOf($, scan ?? query, candidates)
983 const kept = labels === undefined ? candidates : relevantOf(candidates, labels)
984 if (kept.length === 0) return undefined
985 await update($, recall, state => ({ ...state, seen: [...state.seen, ...kept.map(hit => hit.path)] }))
986 const block = blockOf(kept, scan)
987 const ms = (await $.clock.now()) - started
988 const fallback = labels === undefined ? ', classifier fallback' : ''
989 $.ui.log(`workbench recall: ${kept.length} of ${candidates.length} hits, about ${tokensOf(block)} tokens, ${ms} ms${fallback}`, { to: 'debug' })
990 return block
991}
992
993// Whether recall and the nudges stay out: a lane nobody answers in, as
994// $.workbench.isUnattended reads it, or a lane it cannot read.
995const isQuiet = ($: EngineInterface): Promise<boolean> => $.workbench.isUnattended().catch(() => true)
996
997// Recall on a prompt: a new turn a person opened, with a query worth a search.
998// The search attempt is stamped where session-warmup.sh's recall liveness
999// check reads it, as hooks/memory-recall.sh did.
1000async function promptRecall($: EngineInterface, text: string): Promise<string | undefined> {
1001 if ((await $.env.get('WORKBENCH_MEMORY_RECALL')) === '0' || (await isQuiet($))) return undefined
1002 const query = promptQuery(text)
1003 if (query === undefined) return undefined
1004 const home = await $.env.get('HOME')
1005 const stateDir = (await $.env.get('WORKBENCH_MEMORY_RECALL_STATE')) || (home ? `${home}/.claude-workbench/memory-recall` : undefined)
1006 const now = Math.floor((await $.clock.now()) / 1000)
1007 if (stateDir !== undefined) await $.fs.write(`${stateDir}/last-attempt`, `${now}\n`).catch(() => undefined)
1008 return recallBlock($, query, PROMPT_LIMIT, PROMPT_MIN_SCORE)
1009}
1010
1011// Recall on a content search in the main loop (grep, rg, ag, ack, git grep in
1012// a Bash call; this CLI has no Grep tool): the search's own query, read by
1013// hooks/lib/scan-query.py, once per query per session.
1014async function scanRecall($: EngineInterface, tool: 'Bash', raw: string): Promise<string | undefined> {
1015 if ((await $.env.get('WORKBENCH_MEMORY_RECALL')) === '0' || (await $.env.get('WORKBENCH_MEMORY_SCAN_RECALL')) === '0') return undefined
1016 if (!mayScan(raw) || (await isQuiet($))) return undefined
1017 const { stdout } = await $.process.run(['python3', `${$.plugin.root}/hooks/lib/scan-query.py`, tool], { stdin: raw, timeoutMs: 5_000 })
1018 const query = scanQuery(stdout)
1019 if (query === undefined || (await read($, recall)).queries.includes(query)) return undefined
1020 await update($, recall, state => ({ ...state, queries: [...state.queries, query] }))
1021 return recallBlock($, query, SCAN_LIMIT, SCAN_MIN_SCORE, query)
1022}
1023
1024// A tool's result with recall's block beside it, when the call was a main-loop
1025// content search with something to recall. A refused or failed call gets none.
1026async function withScanRecall<R extends ToolCallResult>($: EngineInterface, tool: 'Bash', raw: unknown, agentId: string | undefined, result: R): Promise<R> {
1027 if (agentId !== undefined || typeof raw !== 'string' || result.deny !== undefined || result.isError === true) return result
1028 const block = await scanRecall($, tool, raw).catch(() => undefined)
1029 return block === undefined ? result : { ...result, context: [...(result.context ?? []), block] }
1030}
1031
1032// The intake nudge (hooks/mods/intake.ts): checked once per task, on the
1033// task's first Edit in the main loop, and only in a lane a person answers.
1034async function isIntakeDue($: EngineInterface, sessionAttended: boolean | undefined): Promise<boolean> {
1035 if (sessionAttended !== true || (await isQuiet($))) return false
1036 const { task, checked } = await read($, intake)
1037 if (task === 0 || checked === task) return false
1038 await update($, intake, state => ({ ...state, checked: task }))
1039 return !intakeShown(await $.session.messages())
1040}
1041
1042// The vault root, from scripts/vault-resolve.sh: read once per load.
1043let vaultRootMemo: string | undefined
1044async function vaultRoot($: EngineInterface): Promise<string | undefined> {
1045 if (vaultRootMemo !== undefined) return vaultRootMemo
1046 const { stdout } = await $.process.run(['bash', `${$.plugin.root}/scripts/vault-resolve.sh`], { timeoutMs: 10_000 })
1047 vaultRootMemo = resolvedOf(stdout).root
1048 return vaultRootMemo
1049}
1050
1051// The workbench sections for this load (hooks/mods/prompt-rules.ts): the lane
1052// and each sibling plugin's session-warmup.md, read once and kept, so every
1053// prompt.compose and SubagentStart answers from the one reading and the bytes
1054// cannot change within a load. session.start reads them again, as a reload
1055// does. A reading that fails gives the rules alone, the agent lane's set:
1056// losing the rules is the worse failure, and a lane that cannot be read may be
1057// an unattended one, which gets no memory routing.
1058type SectionsReading = { lane: PromptLane; contributions: { plugin: string; text: string | undefined }[] }
1059let sectionsMemo: Promise<SectionsReading> | undefined
1060// The plugins that sent a `<plugin>:rules` section of their own at the last
1061// compose. A sub-agent's start reads it, since its context names no section.
1062let rulesOwners: ReadonlySet<string> = new Set()
1063async function workbenchSections($: EngineInterface, owners: ReadonlySet<string> = rulesOwners): Promise<PromptComposeSection[]> {
1064 sectionsMemo ??= readSections($).catch((): SectionsReading => ({ lane: 'agent', contributions: [] }))
1065 const { lane, contributions } = await sectionsMemo
1066 return sectionsFor(lane, contributionsOf(contributions.filter(({ plugin }) => !owners.has(plugin)).map(({ text }) => text)))
1067}
1068
1069// The lane from the environment, and each sibling plugin's session-warmup.md.
1070// A file that cannot be read is left out, and the rules stand without it.
1071async function readSections($: EngineInterface): Promise<SectionsReading> {
1072 const lane = promptLaneOf(await $.env.get('WORKBENCH_SKIP_WARMUP'), await $.env.get('CLAUDE_CODE_AGENT'))
1073 if (lane === 'none') return { lane, contributions: [] }
1074 const home = await $.env.get('HOME')
1075 const installed = home ? await readIfAny($, `${home}/.claude/plugins/installed_plugins.json`) : undefined
1076 const sources = installed === undefined ? [] : contributionPathsOf(installed)
1077 const contributions: SectionsReading['contributions'] = []
1078 for (const { plugin, path } of sources) contributions.push({ plugin, text: await readIfAny($, path) })
1079 return { lane, contributions }
1080}
1081
1082const readIfAny = async ($: EngineInterface, path: string): Promise<string | undefined> =>
1083 (await $.fs.exists(path).catch(() => false)) ? $.fs.read(path).catch(() => undefined) : undefined
1084
1085// An instruction file of the user's tier with the block an older warmup
1086// spliced into it left out, read against the file on disk. Undefined when the
1087// file holds no such block, or the block is not found whole in its text.
1088async function unspliced($: EngineInterface, file: InstructionFile): Promise<InstructionFile | undefined> {
1089 if (file.kind !== 'user') return undefined
1090 const raw = await readIfAny($, file.path)
1091 const content = raw === undefined ? file.content : withoutSplice(file.content, splicedBodiesOf(raw))
1092 return content === file.content ? undefined : { ...file, content }
1093}
1094
1095const GUARD_FAILED =
1096 'Workbench guards (workbench-core): the guards that judge this call could not finish, so the call is refused. Try the call again. If it is refused again, stop and tell Mike which call it was.'
1097
1098type Guarded = Record<string, unknown> & { tool: string; agentId?: string }
1099
1100const JUDGED_TOOL = new RegExp(`^(${[...GUARDED].join('|')})$|^mcp__.*(${PROSE_TOOL_SUFFIXES.join('|')})$`)
1101
1102const IN_SCOPE = 'Destructive-scope guard (workbench-core): every path this command destroys lies inside the project or a scratch root.'
1103
1104// Each root with where it lands once its symbolic links are followed. A path
1105// that does not resolve keeps its spelling alone.
1106async function withRealPaths($: EngineInterface, roots: readonly SearchRoot[]): Promise<SearchRoot[]> {
1107 return Promise.all(
1108 roots.map(async root => {
1109 if (root.path === undefined) return root
1110 const stat = await $.fs.stat(root.path, { resolve: true }).catch(() => undefined)
1111 return stat?.realPath === undefined ? root : { ...root, real: stat.realPath }
1112 }),
1113 )
1114}
1115
1116// The heredoc targets that are missing or regular files right now, followed
1117// through any symbolic link. A FIFO, a socket, a device, a folder, or a
1118// target the stat cannot answer for is left out, so its body is read.
1119async function regularFiles($: EngineInterface, targets: readonly string[], home: string | undefined): Promise<ReadonlySet<string>> {
1120 const regular = new Set<string>()
1121 for (const target of targets) {
1122 // A relative target lands in the Bash tool's live directory, not the engine's.
1123 const path = resolvePath(target, await $.session.cwd(), home)
1124 if (path === undefined) continue
1125 const kind = await $.fs.stat(path, { resolve: true }).then(
1126 stat => stat.kind,
1127 () => undefined,
1128 )
1129 // A stat that fails counts as missing only when nothing is at the path.
1130 const isMissing = kind === undefined && !(await $.fs.exists(path).catch(() => true))
1131 if (kind === 'file' || isMissing) regular.add(target)
1132 }
1133 return regular
1134}
1135
1136// ─── facts for the destructive-scope, database and vault-git guards ─────────
1137//
1138// Each of those guards is a pure judge that asks for a fact by key
1139// (hooks/mods/destructive-scope.ts names the keys). settled() runs the judge,
1140// answers the fact it asked for, and runs it again, until it reaches a
1141// verdict. An answer that cannot be had is null, which every judge reads the
1142// closed way. A judge that asks too many questions throws, and the guards'
1143// .catch refuses the call.
1144
1145const MAX_FACT_ROUNDS = 400
1146
1147const factsScript = ($: EngineInterface): string => `${$.plugin.root}/hooks/lib/scope-facts.sh`
1148
1149async function gitFact($: EngineInterface, question: string, dir: string, arg: string): Promise<Fact> {
1150 const git = (argv: readonly string[]) => $.process.run(['git', ...argv], { timeoutMs: 10_000 })
1151 switch (question) {
1152 case 'builtins': {
1153 const { exitCode, stdout } = await git(['--list-cmds=builtins'])
1154 const names = stdout.split(/\s+/).filter(Boolean)
1155 return exitCode === 0 && names.length > 0 ? names.join(' ') : null
1156 }
1157 case 'top': {
1158 const { exitCode, stdout } = await git(['-C', dir, 'rev-parse', '--show-toplevel'])
1159 return exitCode === 0 ? stdout.trim() : ''
1160 }
1161 case 'tracked': {
1162 const { exitCode } = await git(['-C', dir, 'ls-files', '--error-unmatch', '--', arg])
1163 return exitCode === 0 ? 'yes' : exitCode === 1 ? 'no' : null
1164 }
1165 case 'commit': {
1166 const { exitCode } = await git(['-C', dir, 'rev-parse', '--verify', '--quiet', '--end-of-options', `${arg}^{commit}`])
1167 return exitCode === 0 ? 'yes' : 'no'
1168 }
1169 case 'remotes': {
1170 const { exitCode, stdout } = await git(['-C', dir, 'for-each-ref', '--format=%(refname)', `refs/remotes/*/${arg}`])
1171 return exitCode === 0 ? String(stdout.split(/\s+/).filter(Boolean).length) : null
1172 }
1173 case 'alias': {
1174 const { exitCode, stdout } = await git(['-C', dir, 'config', '--get', `alias.${arg}`])
1175 return exitCode === 1 ? 'none' : exitCode === 0 ? `=${stdout.replace(/\n$/, '')}` : null
1176 }
1177 default:
1178 return null
1179 }
1180}
1181
1182async function answerFact($: EngineInterface, key: string): Promise<Fact> {
1183 const [kind = '', a = '', b = '', c = ''] = key.split('\t')
1184 switch (kind) {
1185 case 'dir': {
1186 const { stdout } = await $.process.run(['bash', factsScript($), 'dir', a], { timeoutMs: 10_000 })
1187 const path = stdout.replace(/\n$/, '')
1188 return path.startsWith('/') ? path : null
1189 }
1190 case 'entry': {
1191 const { stdout } = await $.process.run(['bash', factsScript($), 'entry', a], { timeoutMs: 10_000 })
1192 return stdout.trim() === '' ? null : stdout.trim()
1193 }
1194 case 'name': {
1195 const { stdout } = await $.process.run(['bash', factsScript($), 'name', a, b], { timeoutMs: 10_000 })
1196 const name = stdout.replace(/\n$/, '')
1197 return name === '' || name.includes('\n') ? null : name
1198 }
1199 case 'file': {
1200 // A regular file only: a FIFO would hold the read open.hooks/mods/brief.ts 59 lines1// The six-slot brief, as $.workbench.briefSlots() and $.workbench.briefCheck()
2// answer it, and as the agent dispatch gate (hooks/mods/dispatch.ts) checks it.
3// SLOTS below is the one definition of the slots. It began as a port of the
4// retired bash gate's template and of its prompt checks.
5//
6// The verdict must be the bash gate's, case for case. tests/brief-cases.ts is
7// a frozen record of every prompt case of that gate's suite with the verdict it
8// gave, and tests/workbench.test.ts runs this check over the same list.
9//
10// Whitespace is the gate's ASCII set, never \s: whether NBSP is whitespace
11// depends on the C library under grep, so the gate lists five characters, and
12// \s here would take NBSP and U+3000 as spaces where the gate does not. Newline
13// is absent for grep's reason: the gate matches within one line, so the prompt
14// is split on \n and every pattern runs on one line. JavaScript's ^ and $ under
15// the m flag also stop at \r, U+2028 and U+2029, which grep does not, so no
16// pattern here uses the m flag.
17//
18// Pure functions only: the engine follows `$` into no imported function.
19
20import type { WorkbenchBriefCheck, WorkbenchBriefSlot } from '../../types'
21
22const WS = ' \\t\\r\\v\\f'
23
24// Order is the template's order, as the gate's deny message lists the slots.
25const SLOTS: readonly (WorkbenchBriefSlot & { pattern: RegExp })[] = [
26 ['Workdir:', 'absolute path of the tree to work in, and the branch or worktree if one was settled'],
27 ['Goal:', 'one or two sentences, measurable'],
28 ['Context:', 'why the task exists, and what the agent cannot derive'],
29 ['Constraints:', 'hard limits, or none'],
30 ['Acceptance:', 'the criteria the work is graded against, one per line'],
31 ['Done when:', 'observable finish line'],
32].map(([header, description]) => ({
33 header: header as string,
34 description: description as string,
35 pattern: new RegExp(`^[${WS}]*${(header as string).replace(' ', `[${WS}]+`)}`, 'i'),
36}))
37
38export const BRIEF_SLOTS: readonly WorkbenchBriefSlot[] = SLOTS.map(({ header, description }) => ({ header, description }))
39
40const NONBLANK = new RegExp(`[^${WS}]`)
41const ITEM_ID = new RegExp(`^[${WS}]*Item ID:[${WS}]*[0-9]+[${WS}]*$`)
42const REPO_SWEEP = new RegExp(`^[${WS}]*Repo sweep:[${WS}]*[^${WS}/]+/[^${WS}/]+[${WS}]*$`)
43
44// The gate's verdict on one prompt. A prompt with no character outside the
45// ASCII set is blank, and the gate lets it through; so does a prompt whose
46// one non-blank line is a machine-built shape. Every other prompt is a brief,
47// complete when all six headers open a line.
48export function checkBrief(prompt: string): WorkbenchBriefCheck {
49 const lines = prompt.split('\n')
50 const filled = lines.filter(line => NONBLANK.test(line))
51 if (filled.length === 0) return { isComplete: true, missing: [], shape: 'blank' }
52 if (filled.length === 1) {
53 if (lines.some(line => ITEM_ID.test(line))) return { isComplete: true, missing: [], shape: 'item-id' }
54 if (lines.some(line => REPO_SWEEP.test(line))) return { isComplete: true, missing: [], shape: 'repo-sweep' }
55 }
56 const missing = SLOTS.filter(slot => !lines.some(line => slot.pattern.test(line))).map(slot => slot.header)
57 return { isComplete: missing.length === 0, missing, shape: 'brief' }
58}
59hooks/mods/capture.ts 192 lines1// The memory capture checkpoint: the live session's durable findings, written
2// to the vault while the session still holds the context that formed them.
3//
4// It replaces hooks/memory-capture-stop.sh, an asyncRewake Stop hook that woke
5// the model with a new turn Mike saw ("Memory capture checkpoint"). Vault work
6// must be invisible to him (vault: feedback/memory-vault-activity-fully-
7// transparent), so the question now goes to $.model.fork: one tool-less
8// completion over the session's own transcript, served from the prompt cache,
9// whose answer no one sees. hooks/register.ts writes each note it returns
10// through $.mcp.call, never as a turn.
11//
12// The fire policy is the old hook's, measured over 467 transcripts of this
13// project: the first capture on the 5th main-loop turn (88% of sessions reach
14// it), then every 40th, for findings that form late in a long session. Both
15// are overridable as before. The reply may hold nothing, and usually should:
16// a manufactured memory is worse than none.
17//
18// Pure functions only: the engine follows `$` into no imported function.
19
20import { TITLE_MAX_CHARS, lineOf } from './recall'
21
22export const FIRST = 5
23export const REPEAT = 40
24// At most this many notes per capture, so one confused reply cannot flood the
25// vault.
26export const MAX_NOTES = 3
27
28// A capture threshold from its environment variable: a positive integer, else
29// the default, as the bash hook clamped it.
30export function thresholdOf(value: string | undefined, fallback: number): number {
31 const n = value !== undefined && /^[0-9]+$/.test(value) ? Number(value) : NaN
32 return Number.isInteger(n) && n >= 1 ? n : fallback
33}
34
35// Whether the turn just counted fires a capture. `count` includes this turn
36// and restarts at each fire, so the threshold is REPEAT once one has fired.
37export const isCaptureDue = (count: number, hasFired: boolean, first: number, repeat: number): boolean =>
38 count >= (hasFired ? repeat : first)
39
40// The note types a capture may write, and the folder each one goes in
41// (references/vault-conventions.md, "Vault structure").
42export const FOLDERS: Readonly<Record<string, string>> = {
43 decision: 'decisions',
44 insight: 'insights',
45 feedback: 'feedback',
46 project: 'projects',
47}
48
49// The question the fork answers. Written for a reply nobody reads but this
50// module: JSON or the word NONE.
51export function capturePrompt(written: readonly string[]): string {
52 const already =
53 written.length > 0 ? `\nThese notes were already written by an earlier checkpoint of this session, so leave out what they hold:\n${written.map(path => `- ${path}`).join('\n')}\n` : ''
54 return `Memory capture checkpoint. This is an automatic background question from the workbench-core plugin, not from the user, and your answer is never shown to anyone.
55
56List the durable knowledge from this session so far that the memory vault does not hold yet: a decision and its rationale, a root cause, a non-obvious insight or gotcha, a correction to how to work, or a project outcome. Leave out anything this session already wrote to the vault, routine code edits, facts the repo or git already holds, and chatter.
57${already}
58Link another vault note by its path, as [display text](/folder/file-stem.md), never as [[name]].
59
60If nothing qualifies, answer with the single word NONE. That is the expected answer for most checkpoints: a manufactured memory is worse than none.
61
62Otherwise answer with a JSON array and nothing else, at most ${MAX_NOTES} items, each:
63{"type": "decision" | "insight" | "feedback" | "project", "slug": "kebab-case-file-name", "name": "Short title", "summary": "One sentence.", "tags": ["tag"], "body": "The note in Markdown: what, why, and how to apply it."}`
64}
65
66export type CaptureNote = {
67 path: string
68 content: string
69 frontmatter: { name: string; type: string; date: string; summary: string; tags: string[] }
70}
71
72const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
73
74// The notes in a fork's reply, each checked field by field, with the path
75// built here from the type, the date and the slug: the reply is model output,
76// so it never names a path, a folder or a frontmatter field of its own. An
77// item that fails any check is left out. NONE, an empty reply, and anything
78// that is not a JSON array give no notes.
79export function notesOf(reply: string, date: string): CaptureNote[] {
80 const text = reply.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '')
81 if (!text.startsWith('[')) return []
82 let items: unknown
83 try {
84 items = JSON.parse(text)
85 } catch {
86 return []
87 }
88 if (!Array.isArray(items)) return []
89 const notes: CaptureNote[] = []
90 const paths = new Set<string>()
91 for (const item of items) {
92 if (notes.length >= MAX_NOTES) break
93 if (typeof item !== 'object' || item === null) continue
94 const { type, slug, name, summary, tags, body } = item as Record<string, unknown>
95 if (typeof type !== 'string' || !Object.hasOwn(FOLDERS, type)) continue
96 if (typeof slug !== 'string' || !SLUG.test(slug) || slug.length > 80) continue
97 if (!isLine(name, 120) || !isLine(summary, 400) || !isText(body, 20_000)) continue
98 const tagList = Array.isArray(tags) ? tags.filter((tag): tag is string => typeof tag === 'string' && SLUG.test(tag)).slice(0, 8) : []
99 const path = `${FOLDERS[type]}/${date}-${slug}.md`
100 if (paths.has(path)) continue
101 paths.add(path)
102 notes.push({
103 path,
104 content: (body as string).trim(),
105 frontmatter: { name: (name as string).trim(), type, date, summary: (summary as string).trim(), tags: tagList },
106 })
107 }
108 return notes
109}
110
111const isText = (value: unknown, max: number): value is string => typeof value === 'string' && value.trim() !== '' && value.length <= max
112// A frontmatter value on one line: a newline in a name or summary would break
113// the note's frontmatter and every listing that shows it.
114const isLine = (value: unknown, max: number): value is string => isText(value, max) && !/[\r\n]/.test(value)
115
116// Whether the server's answer to a `read` is a definite "no note there", the
117// one answer a capture writes after. The server words it "Document not found:
118// '<path>'", a prefix its own docs say callers match on, and only that prefix
119// counts. Any other error (the server down, a refusal) leaves the note
120// unwritten.
121export const isNotFound = (result: { isError: boolean; content: readonly { type: string; text?: string }[] }): boolean =>
122 result.isError && result.content.some(block => typeof block.text === 'string' && /^Document not found:/.test(block.text.trimStart()))
123
124export type WriteOutcome = 'created' | 'replaced' | 'unconfirmed'
125export function writeOutcome(result: { isError: boolean; content: readonly { type: string; text?: string }[] }): WriteOutcome {
126 if (result.isError) return 'unconfirmed'
127 for (const block of result.content) {
128 try {
129 const created = (JSON.parse(block.text ?? '') as { created?: unknown } | null)?.created
130 if (created === true) return 'created'
131 if (created === false) return 'replaced'
132 } catch {
133 // Not JSON: the next block may carry the flag.
134 }
135 }
136 return 'unconfirmed'
137}
138
139// The toast for a capture that replaced a note another session had just
140// written. The note is not counted as saved, and Mike learns where to look.
141export const replacedText = (path: string): string =>
142 `Memory checkpoint replaced a note another session had just written at ${path}. Restore that note from the vault history.`
143
144// A score at or above this is a note both retrievers rank first, close to the
145// most a hybrid search scores (2/61). Measured on the live vault 2026-10-07: a
146// note both rank near the top scores 0.02 to 0.035, one retriever alone at most
147// about 0.016.
148//
149// It reads only hybrid-search scores. The search passes no mode, so a vault
150// with no embeddings (a fresh install, or a failed embeddings build) answers
151// with keyword search, whose BM25 scores are well above 1: the rule would then
152// call every note a duplicate. Such hits are labelled `keyword`. A hybrid
153// search labels its hits `semantic` or `hybrid`, and on this server every hit
154// is labelled `semantic` whichever retrievers ranked it (measured 2026-10-07),
155// so a gate on the `hybrid` label alone would never apply the rule. A hit with
156// no label is not scored either.
157//
158// The label alone cannot tell a fused score from a raw one: a vault configured
159// with DEFAULT_SEARCH_MODE=semantic answers with cosine-like similarities,
160// labelled `semantic` too, and most notes score far above 0.032 there. So the
161// score counts only inside the fusion range, below RRF_CEILING. A fused score
162// cannot reach it: two first ranks give 2/61, about 0.033, and folder weights
163// measured on the live vault lift that to 0.035 at most. A higher score is
164// read as not fused, and the note is matched by name and slug alone.
165export const DUPLICATE_SCORE = 0.032
166export const RRF_CEILING = 0.1
167const FUSED: ReadonlySet<string> = new Set(['hybrid', 'semantic'])
168
169export type DuplicateHit = { path: string; title: string; score: number; searchType?: string }
170
171// Why the vault already holds the note a capture would write, by a search on
172// its name: a note with the same name, the same slug, or one both retrievers
173// rank first for that name (another session may have saved it). Undefined when
174// it holds none. The name is cut to one line and capped as recall caps a hit's
175// title, so a long name still matches its own note.
176export function duplicateOf(note: CaptureNote, hits: readonly DuplicateHit[]): string | undefined {
177 const name = lineOf(note.frontmatter.name, TITLE_MAX_CHARS).toLowerCase()
178 const slug = note.path.replace(/^.*\/\d{4}-\d{2}-\d{2}-|\.md$/g, '')
179 for (const hit of hits) {
180 const stem = hit.path.replace(/^.*\//, '').replace(/\.md$/, '').replace(/^\d{4}-\d{2}-\d{2}-/, '')
181 if (lineOf(hit.title, TITLE_MAX_CHARS).toLowerCase() === name) return `same name as ${hit.path}`
182 if (stem === slug) return `same slug as ${hit.path}`
183 const isFused = hit.searchType !== undefined && FUSED.has(hit.searchType) && hit.score < RRF_CEILING
184 if (isFused && hit.score >= DUPLICATE_SCORE) return `ranked first by both retrievers: ${hit.path}`
185 }
186 return undefined
187}
188
189// The one line that tells Mike notes were saved: a toast, never a turn.
190export const savedText = (paths: readonly string[]): string =>
191 `Memory checkpoint saved ${paths.length === 1 ? 'a note' : `${paths.length} notes`} to the vault: ${paths.join(', ')}.`
192hooks/mods/checkpoint.ts 48 lines1// The session log checkpoint, written as the session runs instead of only when
2// it ends.
3//
4// SessionEnd does not fire on a reboot or a kill, the Stop hook does not fire
5// on an interrupted turn, and every SessionEnd hook shares one 1.5 s budget.
6// So hooks/register.ts runs hooks/session-log.sh after each main-loop turn,
7// answered or interrupted (turn.complete), and at session.end, which also
8// fires on SIGHUP and SIGTERM. session-log.sh stays the one writer of the raw
9// log, the log-checkpoints/<sid>.json `next_line`, and the pending-summary
10// marker, so the turn checkpoint, the settings SessionEnd hook and the
11// start-up reconciler read and advance one checkpoint and never log a line
12// twice. Its per-session lock serializes the writers that overlap.
13//
14// Pure functions only: the engine follows `$` into no imported function.
15
16export type CheckpointMode = 'turn' | 'final'
17
18export type CheckpointRequest = { stdin: string; env: Record<string, string> }
19
20// What session-log.sh is run with for one checkpoint: its payload on stdin,
21// shaped like a hook's, and the mode in WORKBENCH_LOG_MODE. Undefined when the
22// transcript is unknown or names another session: a checkpoint never copies a
23// file it cannot tie to the session id.
24export function checkpointRequest(
25 sessionId: string,
26 transcript: string | undefined,
27 mode: CheckpointMode,
28 reason?: string,
29): CheckpointRequest | undefined {
30 if (transcript === undefined || sessionId === '' || !transcript.endsWith(`/${sessionId}.jsonl`)) return undefined
31 const payload = {
32 session_id: sessionId,
33 transcript_path: transcript,
34 hook_event_name: mode === 'turn' ? 'TurnComplete' : 'SessionEnd',
35 ...(reason === undefined ? {} : { reason }),
36 }
37 return { stdin: JSON.stringify(payload), env: { WORKBENCH_LOG_MODE: mode } }
38}
39
40// How long the session.end checkpoint may run: what the exit budget has left,
41// less a margin for the hooks after it, and never past END_MAX_MS. Undefined
42// when too little is left to start one.
43export const END_MAX_MS = 1200
44export function endTimeoutOf(remainingMs: number): number | undefined {
45 const ms = Math.min(END_MAX_MS, Math.floor(remainingMs) - 150)
46 return ms >= 100 ? ms : undefined
47}
48hooks/mods/intake.ts 40 lines1// The intake nudge: on the first Edit of a task in Mike's session, a reminder
2// to show the intake block (skills/intake/SKILL.md) when none is on screen.
3// It never denies. It replaces hooks/intake-nudge.sh, which read the
4// transcript file and kept its own state file per session.
5//
6// A task is what one prompt Mike sends starts. The nudge is checked once per
7// task, tracked in $.state by hooks/register.ts, and fires only when no
8// heading naming Intake is on screen: in this task's replies so far, or in the
9// closing reply of the turn before the prompt, where an intake block shown
10// for Mike's answer sits.
11//
12// Pure functions only: the engine follows `$` into no imported function.
13
14import type { SessionMessage } from 'claude-code'
15
16export const NUDGE =
17 '📋 Intake nudge (advisory, nothing was blocked): this is the first Edit for the current task, and no intake block is on screen for it. Before more work, run /workbench-core:intake: show the goal, the context, and the acceptance criteria you are working to, under a heading that names Intake. If the task is trivial, carry on without it.'
18
19const HEADING = /(^|\n)[ \t]*#{1,6}[ \t]+[^\n]*\bintake\b/i
20
21const isPrompt = (message: SessionMessage): boolean =>
22 message.role === 'user' && (message.toolResults === undefined || message.toolResults.length === 0) && message.text.trim() !== ''
23
24// Whether an intake heading is on screen for the task the last prompt opened.
25// It reads the replies after that prompt, and the replies before it back to
26// the last message with a tool call or result, as far as the prompt before.
27export function intakeShown(messages: readonly SessionMessage[]): boolean {
28 let at = messages.length - 1
29 while (at >= 0 && !isPrompt(messages[at] as SessionMessage)) at -= 1
30 if (at < 0) return false
31 const seen = messages.slice(at + 1).filter(message => message.role === 'assistant')
32 const closing: SessionMessage[] = []
33 for (let i = at - 1; i >= 0; i -= 1) {
34 const message = messages[i] as SessionMessage
35 if (isPrompt(message) || message.toolUses.length > 0 || (message.toolResults?.length ?? 0) > 0) break
36 if (message.role === 'assistant') closing.push(message)
37 }
38 return [...closing, ...seen].some(message => HEADING.test(message.text))
39}
40hooks/mods/learnings.ts 35 lines1// Skill learnings, merged into the skill's own text through skill.prompt.
2//
3// Every skill can keep learnings in the vault, at skills/<name>.learnings.md:
4// corrections, failures and confirmed approaches from past runs. The retired
5// hooks/skill-learnings.sh handed the file over as PreToolUse context, an
6// extra block beside the call. Merged into the text the skill expands to, it
7// is one block, the same bytes for the same file, and no row of its own.
8//
9// A file past MAX_CHARS is not merged whole: the skill text gets the file's
10// vault path instead, with the instruction to read it through the memory MCP.
11// The limit is the old hook's: it keeps a skill that ran long from carrying a
12// 68 KB file into every run (memory-lint.learnings.md once reached that).
13//
14// Pure functions only: the engine follows `$` into no imported function.
15
16export const MAX_CHARS = 9000
17
18export const RULE =
19 'Add to this file only when this run taught something a future run needs: the user corrected the approach, something failed and you learned why, or the user confirmed a non-obvious approach. Append it through the memory MCP as `## YYYY-MM-DD - short title` followed by what to do next time. A routine run adds nothing.'
20
21// The vault-relative path of a skill's learnings file, by its bare name.
22export const learningsPath = (name: string): string => `skills/${name}.learnings.md`
23
24// The skill's text with its learnings after it.
25export function withLearnings(text: string, name: string, learnings: string): string {
26 const rel = learningsPath(name)
27 const body = learnings.trim()
28 if (body === '') return text
29 const merged =
30 body.length > MAX_CHARS
31 ? `## Learnings from past runs\n\nThe \`${name}\` skill has learnings from its past runs, too large to include here. Read the whole file with the memory MCP \`read\` tool, at the vault path \`${rel}\`, before you start, and apply it to this run. ${RULE}`
32 : `## Learnings from past runs\n\nLearnings for the \`${name}\` skill, recorded from its past runs at \`${rel}\` in the memory vault. Apply them to this run.\n\n${body}\n\n${RULE}`
33 return `${text.replace(/\s+$/, '')}\n\n${merged}\n`
34}
35hooks/mods/prompt-rules.ts 294 lines1// The workbench rules in the system prompt, as prompt.compose sections.
2//
3// They used to reach a session three ways, each one paid for in every session:
4// - a block session-warmup.sh spliced into ~/.claude/CLAUDE.md on every start
5// (the gates, the scratch roots, and each sibling plugin's
6// session-warmup.md), which rewrote the user's own file
7// - the warmup's stdout (memory routing, and the destructive commands, which
8// stated the scratch roots a second time)
9// - a MEMORY.md router stub in the harness's per-project memory folder, which
10// restated the memory routing beside the harness's own memory section
11// All three sat in the first message, which a session creates afresh. Here the
12// rules are `shared` sections: the same bytes in every session of a lane, so
13// the cache that holds them is read, not created, from the second session on.
14// The harness's `memory` section, which told the model to keep memories in a
15// per-project folder, is dropped: the vault is the one store.
16//
17// The rules are stated once. A section holds no date, count, version, session
18// id or path read from the machine: the same lane always gets the same bytes,
19// and the plugins' own files are the only input (their session-warmup.md,
20// whose bytes change only when the plugin does).
21//
22// Who gets what, as the copies it replaces reached them:
23// main the main loop of a session the warmup ran in: interactive or
24// `claude -p`. Rules, memory routing, plugin contributions.
25// agent a top-level `claude -p --agent` run (CLAUDE_CODE_AGENT), which the
26// warmup skipped and the CLAUDE.md block reached. Rules and plugin
27// contributions.
28// none a summary-writer (WORKBENCH_SKIP_WARMUP=1), which runs with no
29// CLAUDE.md and no warmup on purpose. Nothing.
30// A sub-agent gets its parent's set through SubagentStart, as the CLAUDE.md
31// block and the router stub reached the sub-agents that load CLAUDE.md. An
32// agent that leaves CLAUDE.md out (OMITS_CLAUDE_MD: Explore, Plan and the
33// rest) never saw either, and gets none. A fork inherits its parent's system
34// prompt, so it gets none either.
35//
36// The block an older warmup left in ~/.claude/CLAUDE.md is left out of the
37// first message at render time (splicedBodiesOf, withoutSplice), so the rules
38// are not paid for twice before setup takes the block out of the file
39// (scripts/setup-config.sh unsplice-claude-md).
40//
41// Pure functions only: the engine follows `$` into no imported function, so the
42// hooks that read the files live in hooks/register.ts.
43
44import type { PromptComposeSection } from 'claude-code'
45
46export type PromptLane = 'main' | 'agent' | 'none'
47
48export const RULES_ID = 'workbench-core:rules'
49export const MEMORY_ID = 'workbench-core:memory'
50export const PLUGINS_ID = 'workbench-core:plugins'
51
52// The harness section this plugin drops.
53export const HARNESS_MEMORY = 'memory'
54
55export const RULES = `# Workbench gates and scratch roots
56
57These hooks guard every session. Each deny explains its own way through, so read the deny and follow it. A deny is the system working. Report it, and do not route around it.
58
59| Gate | What it protects |
60|---|---|
61| Delegation gate | Whole-file work belongs in a sub-agent. It never denies: a main-agent \`Write\` or \`NotebookEdit\` goes ahead with a reminder, once per session. Plans and scratch roots draw none. The user's \`/orchestrator off\` silences it. |
62| Agent dispatch gate | A main-agent \`Agent\` dispatch must carry the six-slot brief. |
63| Project scope guard | A main-agent \`Agent\` dispatch of any type but \`Explore\` and \`Plan\` must name a \`Workdir:\` inside this project, a git worktree of its repository, or a scratch root. |
64| Destructive scope guard | The destructive commands below run only when every target resolves inside the project or a scratch root. |
65| Destructive database guard | Database resets, drops, and destructive SQL are refused. |
66| Provisioning guard | Agents do not create worktrees or databases, and do not destroy a worktree they did not create. |
67| Vault git guard | Git writes aimed at the memory vault are refused. |
68| Credential guard | Reading, linking or copying \`~/.ssh\`, \`~/.aws\`, \`~/.gnupg\`, \`.env\` files, a keychain folder such as \`~/Library/Keychains\`, or Claude's credential store is refused. It judges no \`security\` subcommand, only the paths a line names: the secrets rules below cover the keychain entries. |
69| Outbound prose guard | \`gh\`, board-MCP and GitHub-MCP prose must pass the output style's mechanical checks. |
70| Peer message gate | A sub-agent messages only its orchestrator or the agents it spawned. |
71| Whole-disk search guard | A search (\`find\`, \`fd\`, \`rg\`, \`grep -r\`, \`mdfind\`, \`Grep\`, \`Glob\`) may not start at \`/\`, a home folder, \`~/Library\`, \`/Users\`, \`/System\`, \`/Library\`, \`/Applications\`, \`/Volumes\`, \`/private\`, \`/var\`, \`/opt\` or \`/usr\`. |
72
73Every guard refuses a Bash line whose command it cannot name: a command name from a variable or a substitution, a wrapper option it cannot read, or a script piped into a shell. Write the command name out plainly. A plain \`"$NAME/…"\` or \`"\${NAME}/…"\`, inside double quotes, in front of a literal path is fine.
74
75## Scratch roots and destructive commands
76
77- A scratch root is the session scratchpad, \`~/Developer/scratchpad\`, or a \`mktemp -d\` sandbox. Make new scratch in the session scratchpad or \`~/Developer/scratchpad\`. Never create it anywhere under \`/tmp\` outside your session scratchpad, and do not put new scratch in an old \`claude-*scratch*\` folder there either.
78- \`rm\`, \`rmdir\`, \`git reset --hard\`, \`git clean\`, \`git stash clear\`/\`drop\`, and git commands that discard working-tree changes (such as \`git restore\`, \`git checkout -- <path>\`, or \`git mv -f\`, also through an alias) run with no prompt when every path they act on resolves inside the project or a scratch root. \`rm\` and \`rmdir\` may also remove a leftover \`/tmp/claude-*scratch*\` folder you own, the folder itself included. It is not a root, so \`git\` verbs there are still denied.
79- Outside those roots the guard DENIES, and so does any target it cannot read: a \`$variable\`, a glob, \`bash -c\`, \`ssh\`, \`xargs\`, \`find -delete\`, or a loop body. Spell paths out literally and keep the delete its own command. Never hand the user a \`!\` command to delete your own scratch. A target outside every root that is not scratch is the user's call, and they run it with the \`!\` prefix.
80
81## Plan files
82
83- Create and edit plan files in \`~/.claude/plans\` without asking first, never in prose and never in a question. No permission prompt opens for a main-session write there. The user still approves a plan's content when you present it.
84
85## One project per session
86
87- A session works only for its own project, the repository it started in. That project's live session owns its context, its work in progress, its review and its commits.
88- Work for another project goes to that project's session. Do not dispatch an agent into it, and do not edit it. Run \`ListAgents\`, find the session named after that project, and send it the finding and the acceptance criteria with \`SendMessage\`, as \`/workbench-core:cross-session-messaging\` describes. When no session for that project is live, ask the user.
89- \`Explore\` and \`Plan\` only read, so they may still read other projects.
90
91## Commits and code comments
92
93- A commit takes every uncommitted file in the tree, in one commit with one message that covers the whole set. Stage tracked changes and untracked files alike, including files this session did not create and files that appeared during it. Never split the work into several commits, never leave a file out because it looks unrelated, and never ask which files to include. The user asks for several commits when they want several.
94- The one exception is content that must never ship, such as a secret or a stray build artifact. Leave it out, and tell the user about it in one sentence. Never leave a file out silently.
95- Stage the whole tree with \`git add -A\` on a line of its own, then commit with no paths. The commit gate refuses a commit that leaves any file out, and names the files. It lets a never-ship file stay out only when the reply above the commit names that file's path to the user.
96- A prompt in which the user asks for a commit, a push, a merge or a release, or any mix of them, approves exactly those actions for the turn that prompt opened, in the user's own words, such as "go ahead and commit the changes". Run them with no follow-up question. A release covers the version-bump commit, its push, the push of its tag and \`gh release create\`. A commit approval approves no push and no merge. The user's next prompt ends the approval.
97- Run each approved action as a plain line, and no permission prompt opens: \`git commit -m <message>\` or \`-F <file>\`, \`git push\` or \`git push <remote> <current branch>\`, a plain \`gh pr merge\`, and \`gh release create\` for this repository. \`git -C <path>\` is fine when the path is inside this project or one of its worktrees. Any other form opens the prompt, such as a \`-c\` option, \`--amend\`, \`--no-verify\`, \`--tags\`, another branch or remote, or \`-R\` naming another repository.
98- A prompt that negates, defers, sets a condition or asks approves nothing, such as "don't commit yet", "commit later", "commit if the tests pass" or "should I commit?". Only the user's own prompts and picks count, never a peer, channel, scheduled, SDK or plugin turn, and never a sub-agent.
99- Work the user did not ask to commit waits for their review and their pick. Ask the commit question alone, with words that name only the commit. A pick of an option that approves committing, such as "Commit it", approves one commit on the branch HEAD held when the user picked, and no push and no merge. Run it as a plain line, and no permission prompt opens. Run no checkout, switch, stash or reset between the pick and the commit.
100- Once the commit has landed, ask about the push in a question of its own. How a branch lands, a pull request or a local merge into the default branch, is the user's choice: ask that in a question of its own too, and recommend a pull request. A pick on that question approves one push or one merge, and a merge pick only the pull request number or branch its question named. Only the user's own next prompt ends a pick not yet used.
101- In the user's own turn, a commit, push, merge into the default branch, release, history rewrite (cherry-pick, revert, am, rebase, update-ref, filter-branch, replace, \`commit --amend\`, a reset that moves a branch, or a branch, fetch or push that moves a ref), \`gh alias set\`, or write to the default branch through the GitHub API (REST contents or refs, merge-upstream, a branch rename, \`gh repo sync\`, or a GraphQL ref mutation) that no request or pick approved is denied. No hook dialog ever approves one. A write to another repository counts as one to its default branch. A write through \`repos/{owner}/{repo}\` or a \`gh repo sync\` that names no repository counts as this repository's, even when \`GH_REPO\` or \`gh repo set-default\` points gh elsewhere, so one to a named feature branch runs. The deny names the exact line, the action, the repository and the branch, and for a commit the message and every file \`git status\` lists. Ask the user that question on its own, never beside another, and name each of them in it. Run the line again, unchanged, after the user picks. For a release, a history rewrite, \`gh alias set\` or an API write, write the line in the question in backticks and offer "Run it": that pick approves that one line, once. A line that needs two approvals is split into one line per action, unless it is a single command, which one pick on its line covers. In a turn another sender opened in the user's session, each of these but a release is refused. A release is denied with the instruction to ask wherever a question can reach the user, a scheduled tick of an interactive session included. A sub-agent, a \`-p\` run, the pipeline and an agent run cannot ask, so each of them is refused a release in any spelling. A sub-agent never commits, pushes or merges. A \`-p\` run, the pipeline and a scheduled tick commit and push as they always have, and never merge into the default branch, set a gh alias, or write the default branch through the API. A sub-agent, a \`-p\` run and a scheduled tick never rewrite history. The dev-team pipeline may rewrite history on its own feature branches, never on the default branch or a branch the gate cannot read.
102- Write no comments or docblocks in code, in any project, plugin code that agents maintain included. The only exception is a comment that the project's linter or config requires, such as a PHPCS docblock rule. Functional lines such as a shebang or a directive that a tool reads are not comments, and they stay.
103- Leave the existing comments in code you do not change as they are. When a change makes a comment wrong, delete the comment rather than rewrite it. Comments drift from the code, and every edit then has to update them as well, which costs tokens for no gain.
104
105## Pull request reviews
106
107- Never request a review on a pull request. The user requests every review themselves.
108- This covers every route. Do not name a reviewer when you create a pull request, such as with \`gh pr create --reviewer\`. Do not add a reviewer to a pull request that already exists, such as with \`gh pr edit --add-reviewer\`. Do not call the requested-reviewers API, through \`gh api\` or a GitHub MCP tool. Do not post a comment that asks a bot or a person to review, such as \`@coderabbitai review\`.
109
110## Secrets
111
112- You may read the keychain entries that your own processes use, such as the token a setup step needs. No hook judges a \`security\` subcommand, so these rules are yours to keep.
113- Store a secret only in the macOS keychain. Never put one in your memory, the vault, a document, a file, a config, a commit message or any other store.
114- Never show a secret. Do not print, echo, log or trace one, and do not paste one into the transcript or into a tool's output.
115- Always pass a secret through a variable, straight to the program that needs it, and on its input rather than its arguments, which the process list shows. For example, run \`X=$(security find-generic-password -s <service> -a <account> -w)\` and then \`printf 'Authorization: Bearer %s' "$X" | curl -H @- …\`.`
116
117// The search mode is left to the server: its default picks hybrid when the
118// vault has embeddings and keyword when it does not, and naming one broke that
119// fallback once. The two recall bullets carry their reasons, because the
120// hooks module's recall searches only a prompt's wording and the patterns of
121// file searches, and the task's own words are the better query.
122export const MEMORY = `## Memory routing
123
124- The workbench memory vault is the CANONICAL durable memory store, served by the \`memory\` MCP (\`mcp__plugin_workbench-core_memory__search\` / \`write\` / etc.).
125- Proactively CAPTURE durable knowledge without asking: a decision (+ rationale), a troubleshooting root-cause, a design choice and the options weighed, a non-obvious insight or gotcha, a project/plan outcome, or feedback on how to work — \`write\` it to the vault immediately with frontmatter \`name\` + \`type\` (decision | insight | project | feedback | reference) plus tags/summary/date per vault conventions, then note the save in one line. This is standing authorization: a memory-capture write needs no options round and no confirmation. Do NOT ask first.
126- Before saving, \`search\` for an existing memory to UPDATE rather than duplicate. Skip the trivial: routine code edits, facts already in the repo or git, ephemeral chatter. Capture what would otherwise be a "by the way, should I remember this?".
127- Recall = vault \`search\`, not directory reads. Omit \`mode\`: the server picks hybrid when the vault has embeddings and keyword when it does not.
128- Recall comes FIRST: the moment a task turns up a topic — an error, a tool, a design choice, a repo or file you have worked before — \`search\` the vault BEFORE you scan the repo for the answer. Auto-recall searches only the wording of each prompt and the patterns of your file searches, so a topic that reaches you any other way has had NO memory searched against it unless you search it yourself.
129- Build the recall QUERY from the TASK, not from the prompt: name the thing you are about to produce or decide — the convention, the format, the procedure, the tool, the error — in the words a note about it would use, and search THAT. Auto-recall can only ever run wording that was already typed, so your advantage over it is asking the better question; a recorded rule filed under another phrase is one query away and will not arrive on its own.`
130
131// Agent types that leave CLAUDE.md out (`omitClaudeMd: true` in their
132// definition). They never saw the CLAUDE.md block or the router stub, so they
133// get no workbench rules either. No hooks-module API says which types set it:
134// agent.offer gives a type's name, description and source, and $.agent.list()
135// lists running agents. So they are named. The built-ins are the ones the CLI
136// defines with it: Explore, Plan, web-fetch and comment-thread-analyst.
137// summary-writer is core's own, which runs with no CLAUDE.md and no warmup on
138// purpose. CI holds this list to the pinned CLI's definitions and to
139// agents/*.md (scripts/omit-claude-md-check.py), so drift turns CI red.
140export const OMITS_CLAUDE_MD: ReadonlySet<string> = new Set([
141 'Explore',
142 'Plan',
143 'web-fetch',
144 'comment-thread-analyst',
145 'summary-writer',
146 'workbench-core:summary-writer',
147 'meeting-writer',
148 'workbench-core:meeting-writer',
149])
150
151// A sub-agent's system prompt may still carry the harness's own memory section,
152// which prompt.section drops for the main loop. So its copy of the memory
153// routing says which store wins.
154export const SUBAGENT_MEMORY_NOTE =
155 'The workbench memory vault overrides any instruction to keep memories in a per-project memory directory or its MEMORY.md: save to the vault and recall from it.'
156
157// The lane, from the environment the warmup reads for its own skip guards.
158export function promptLaneOf(skipWarmup: string | undefined, agent: string | undefined): PromptLane {
159 if (skipWarmup === '1') return 'none'
160 return agent ? 'agent' : 'main'
161}
162
163// Where each sibling plugin's session-warmup.md is, from the text of
164// ~/.claude/plugins/installed_plugins.json: every plugin of the claude-workbench
165// marketplace but this one, in the file's order, at its active install path,
166// with the plugin's name. A file that does not parse, or names no install
167// path, gives none.
168export function contributionPathsOf(installed: string): { plugin: string; path: string }[] {
169 let parsed: unknown
170 try {
171 parsed = JSON.parse(installed)
172 } catch {
173 return []
174 }
175 const plugins = (parsed as { plugins?: unknown } | null)?.plugins
176 if (typeof plugins !== 'object' || plugins === null) return []
177 const paths: { plugin: string; path: string }[] = []
178 for (const [key, installs] of Object.entries(plugins)) {
179 if (!key.endsWith('@claude-workbench') || key.startsWith('workbench-core@')) continue
180 const path = Array.isArray(installs) ? (installs[0] as { installPath?: unknown } | undefined)?.installPath : undefined
181 if (typeof path === 'string' && path.startsWith('/')) paths.push({ plugin: key.slice(0, -'@claude-workbench'.length), path: `${path.replace(/\/+$/, '')}/session-warmup.md` })
182 }
183 return paths
184}
185
186// The plugins that send their rules as a section of their own,
187// `<plugin>:rules`, among the sections a compose answered. Such a plugin's
188// session-warmup.md is left out of the contributions, so its rules go out
189// once whichever of the two a release ships. The installed copy can be older
190// than the one that runs, so the file's presence alone says nothing.
191export function rulesOwnersOf(sections: readonly PromptComposeSection[]): ReadonlySet<string> {
192 return new Set(sections.flatMap(section => (section.id.endsWith(':rules') && section.id !== RULES_ID ? [section.id.slice(0, -':rules'.length)] : [])))
193}
194
195// The contributions as one section's text, blank-line separated, or undefined
196// when there is none.
197export function contributionsOf(texts: readonly (string | undefined)[]): string | undefined {
198 const kept = texts.map(text => text?.trim() ?? '').filter(text => text !== '')
199 return kept.length === 0 ? undefined : kept.join('\n\n')
200}
201
202// The sections a lane gets, in order. Every one is `shared`: its bytes are the
203// same in every session of the lane.
204export function sectionsFor(lane: PromptLane, contributions: string | undefined): PromptComposeSection[] {
205 if (lane === 'none') return []
206 const rules: PromptComposeSection = { id: RULES_ID, text: RULES, scope: 'shared' }
207 const memory: PromptComposeSection = { id: MEMORY_ID, text: MEMORY, scope: 'shared' }
208 const plugins: PromptComposeSection[] = contributions === undefined ? [] : [{ id: PLUGINS_ID, text: contributions, scope: 'shared' }]
209 return lane === 'main' ? [rules, memory, ...plugins] : [rules, ...plugins]
210}
211
212// The engine's sections with ours after its last `shared` one, so every shared
213// section still comes before every session one. Ours already in the list (a
214// second compose of the same list) are not added twice. The engine joins the
215// sections of one side with a blank line, but sends the two sides as they
216// are, so the last shared section ends in a blank line when a session section
217// follows it: its last sentence would run into the next text otherwise.
218//
219// Only the last shared section carries that pad. Another plugin's hook may run
220// inside this one and pad its own section, the last shared one it saw. Ours
221// now follow that section, so its pad comes off, or the join would leave two
222// blank lines. A plugin whose hook runs outside this one must do the same to
223// ours. workbench-dev-team re-exports this function for that.
224const PAD = /\n[ \t]*\n\s*$/
225const padded = (section: PromptComposeSection): PromptComposeSection => ({ ...section, text: `${section.text.replace(/\s+$/, '')}\n\n` })
226const unpadded = (section: PromptComposeSection): PromptComposeSection => (PAD.test(section.text) ? { ...section, text: section.text.replace(/\s+$/, '') } : section)
227
228export function withShared(sections: readonly PromptComposeSection[], ours: readonly PromptComposeSection[]): PromptComposeSection[] {
229 const ids = new Set(ours.map(section => section.id))
230 const theirs = sections.filter(section => !ids.has(section.id))
231 const cut = theirs.findIndex(section => section.scope === 'session')
232 const at = cut === -1 ? theirs.length : cut
233 const last = ours[ours.length - 1]
234 if (last === undefined) return [...theirs]
235 const before = theirs.slice(0, at).map((section, i) => (i === at - 1 ? unpadded(section) : section))
236 const placed = cut === -1 ? ours : [...ours.slice(0, -1), padded(last)]
237 return [...before, ...placed, ...theirs.slice(at)]
238}
239
240// What a sub-agent's SubagentStart adds: the sections' texts, or undefined
241// when there are none.
242export function subagentContextOf(sections: readonly PromptComposeSection[]): string | undefined {
243 if (sections.length === 0) return undefined
244 const texts = sections.flatMap(section => (section.id === MEMORY_ID ? [section.text, SUBAGENT_MEMORY_NOTE] : [section.text]))
245 return texts.join('\n\n')
246}
247
248const SPLICE_MARKERS: readonly (readonly [string, string])[] = [
249 ['<!-- workbench-identity:start -->', '<!-- workbench-identity:end -->'],
250 ['<!-- workbench-warmup:start -->', '<!-- workbench-warmup:end -->'],
251]
252
253// The text an older warmup spliced into a CLAUDE.md, read from the file on
254// disk: each marked region's lines between its two markers, with no blank
255// lines at either end and no carriage returns. A pair is taken only when the
256// file holds exactly one start line and one end line of it, the start first:
257// a marker line of the user's own, such as one quoted in a code fence, makes
258// the region's extent a guess, and a guess could take the user's text.
259export function splicedBodiesOf(raw: string): string[] {
260 const lines = raw.split('\n').map(line => line.replace(/\r$/, ''))
261 const bodies: string[] = []
262 for (const [start, end] of SPLICE_MARKERS) {
263 const starts = lines.flatMap((line, i) => (line === start ? [i] : []))
264 const ends = lines.flatMap((line, i) => (line === end ? [i] : []))
265 const [from, to] = [starts[0], ends[0]]
266 if (starts.length !== 1 || ends.length !== 1 || from === undefined || to === undefined || to < from) continue
267 const body = lines.slice(from + 1, to).join('\n').replace(/^\n+|\n+$/g, '')
268 if (body !== '') bodies.push(body)
269 }
270 return bodies
271}
272
273// The instruction file's text with each spliced body taken out. The engine's
274// text has the markers stripped as comments, so a body is found by its own
275// text, and only where it stands whole and once (with LF or CRLF line ends).
276// Only the line breaks that touch the cut are rewritten: the text on either
277// side is joined by one blank line, or by nothing at the file's start or end.
278// Every other byte is the user's and stays as it was. Nothing found gives the
279// text back unchanged.
280export function withoutSplice(content: string, bodies: readonly string[]): string {
281 let text = content
282 for (const body of bodies) {
283 const crlf = body.replace(/\n/g, '\r\n')
284 const [found, eol] = text.includes(body) ? [body, '\n'] : text.includes(crlf) ? [crlf, '\r\n'] : [undefined, '\n']
285 if (found === undefined) continue
286 const at = text.indexOf(found)
287 if (text.indexOf(found, at + 1) !== -1) continue
288 const before = text.slice(0, at).replace(/(\r?\n)+$/, '')
289 const after = text.slice(at + found.length).replace(/^(\r?\n)+/, '')
290 text = before === '' ? after : after === '' ? `${before}${eol}` : `${before}${eol}${eol}${after}`
291 }
292 return text
293}
294hooks/mods/recall.ts 161 lines1// Vault recall: memories that bear on what the session is doing, injected at
2// the tail of the conversation and never into the system prompt.
3//
4// Two triggers, as the bash hooks had (hooks/memory-recall.sh on each prompt,
5// hooks/memory-scan-recall.sh on each Grep or Bash content search). Those cost
6// about 850 tokens and 1.6 s per prompt, and in the Phase 0 sample none of
7// their hits was used. So each hit now passes four filters before it is shown:
8//
9// 1. A score threshold. The server's hybrid score fuses a keyword rank and a
10// semantic rank (reciprocal rank fusion, k = 60): a note one retriever
11// ranks first scores just under 1/61 (0.0158 to 0.0164 measured), the
12// ones after it 0.015 and falling, and a note both retrievers rank near
13// the top scores 0.02 to 0.035. Measured on the live vault 2026-10-07, every hit is labelled
14// `semantic` whichever retrievers ranked it, so the label cannot tell
15// them apart and the score must. A prompt keeps the top hits of either
16// retriever (PROMPT_MIN_SCORE), and the classifier judges them. A scan
17// fires far more often, so it keeps only what both retrievers rank
18// (SCAN_MIN_SCORE), the agreement the bash hook's label gate meant to
19// require. A keyword-only vault scores in BM25 units, far above both,
20// and the classifier is its filter.
21// 2. The note types worth recalling (TYPES).
22// 3. A per-session dedupe set: a note is shown once per session.
23// 4. A relevance pass through $.model.classify, one label per hit. A pass
24// that fails or runs past CLASSIFY_TIMEOUT_MS falls back to the hits the
25// first three filters kept, so a slow classifier never costs a recall.
26//
27// The search runs through $.mcp.call on the memory server in core's manifest,
28// where the bash hooks started the markdown-vault-mcp CLI, about 1 s each.
29//
30// Pure functions only: the engine follows `$` into no imported function.
31
32export const PROMPT_MIN_SCORE = 0.015
33export const SCAN_MIN_SCORE = 0.02
34export const PROMPT_LIMIT = 2
35export const SCAN_LIMIT = 1
36// Hits fetched per hit wanted: the filters drop most of them.
37export const FETCH_FACTOR = 4
38export const CLASSIFY_TIMEOUT_MS = 2500
39export const RELEVANT = 'relevant'
40export const UNRELATED = 'unrelated'
41export const LABELS = [RELEVANT, UNRELATED] as const
42export const TYPES: ReadonlySet<string> = new Set([
43 'decision',
44 'insight',
45 'topic',
46 'feedback',
47 'reference',
48 'project',
49 'skill-learnings',
50 'recurring-issue',
51])
52
53const PROMPT_MIN_CHARS = 16
54const SCAN_MIN_CHARS = 6
55const QUERY_MAX_CHARS = 500
56const SUMMARY_MAX_CHARS = 160
57export const TITLE_MAX_CHARS = 100
58const PATH_MAX_CHARS = 200
59
60// One line of at most `max` characters: a note's title or summary is the
61// vault's text, so a newline in it must not open a line of its own in the
62// block the model reads.
63export const lineOf = (text: string, max: number): string => {
64 const line = text.replace(/\s+/g, ' ').trim()
65 return line.length > max ? `${line.slice(0, max)}…` : line
66}
67const ACKS = /^(y|n|ok|okay|yes|no|yep|nope|sure|thanks|thank you|ty|go|go ahead|do it|continue|proceed|next|done|stop|wait)[.!? ]*$/i
68
69// The search query a prompt carries, or undefined when it carries none: a
70// slash command, a scheduled tick, an acknowledgement, or under 16 characters.
71// The same substance gate hooks/memory-recall.sh applied.
72export function promptQuery(text: string): string | undefined {
73 const trimmed = text.replace(/\n/g, ' ').trim()
74 if (trimmed.startsWith('/') || trimmed.startsWith('<scheduled-task ')) return undefined
75 if (trimmed.length < PROMPT_MIN_CHARS || ACKS.test(trimmed)) return undefined
76 return trimmed.slice(0, QUERY_MAX_CHARS)
77}
78
79// Whether a Bash command can hold a content search at all, before the
80// extractor (hooks/lib/scan-query.py) is started to read it.
81export const mayScan = (command: string): boolean => command.includes('grep') || /(^|[^\w-])(rg|ripgrep|ag|ack)([^\w-]|$)/.test(command)
82
83// The query scan-query.py read out of a search, or undefined when it is too
84// thin to search on: under 6 characters without spaces, no letter, or one
85// plain word. A camelCase identifier is a topic, and passes.
86export function scanQuery(extracted: string): string | undefined {
87 const query = extracted.trim()
88 if (query.replace(/ /g, '').length < SCAN_MIN_CHARS || !/[A-Za-z]/.test(query)) return undefined
89 if (!query.includes(' ') && !/[a-z][A-Z]/.test(query)) return undefined
90 return query
91}
92
93// `searchType` is the server's label for how the hit was found: `keyword`
94// when the vault has no embeddings and the search fell back to BM25, whose
95// score is in its own units; `semantic` or `hybrid` from a hybrid search, whose
96// score is a rank-fusion value. Absent when the server sent none.
97export type Hit = { path: string; title: string; type: string; summary: string; score: number; searchType?: string }
98
99// The hits in a memory MCP search result: the text block's JSON, either a list
100// or `{ result: [...] }`. Anything else is no hits.
101export function hitsOf(content: readonly { type: string; text?: string }[]): Hit[] {
102 const text = content.find(block => block.type === 'text' && typeof block.text === 'string')?.text
103 if (text === undefined) return []
104 let parsed: unknown
105 try {
106 parsed = JSON.parse(text)
107 } catch {
108 return []
109 }
110 const rows = Array.isArray(parsed) ? parsed : (parsed as { result?: unknown } | null)?.result
111 if (!Array.isArray(rows)) return []
112 const hits: Hit[] = []
113 for (const row of rows) {
114 if (typeof row !== 'object' || row === null) continue
115 const { path, title, score, frontmatter, sections, search_type: searchType } = row as Record<string, unknown>
116 if (typeof path !== 'string' || path === '' || typeof score !== 'number') continue
117 const fm = (typeof frontmatter === 'object' && frontmatter !== null ? frontmatter : {}) as Record<string, unknown>
118 const first = Array.isArray(sections) ? (sections[0] as { content?: unknown } | undefined) : undefined
119 const summary = typeof fm.summary === 'string' ? fm.summary : typeof first?.content === 'string' ? first.content : ''
120 hits.push({
121 path,
122 title: lineOf(typeof title === 'string' && title.trim() !== '' ? title : typeof fm.name === 'string' ? fm.name : path, TITLE_MAX_CHARS),
123 type: typeof fm.type === 'string' ? fm.type : 'note',
124 summary: lineOf(summary, 400),
125 score,
126 ...(typeof searchType === 'string' ? { searchType } : {}),
127 })
128 }
129 return hits
130}
131
132// Filters 1 to 3: the threshold, the types, and the notes this session has
133// seen, best first, at most `limit`.
134export const candidatesOf = (hits: readonly Hit[], seen: readonly string[], limit: number, minScore: number): Hit[] =>
135 hits
136 .filter(hit => hit.score >= minScore && TYPES.has(hit.type) && !seen.includes(hit.path))
137 .filter((hit, i, all) => all.findIndex(other => other.path === hit.path) === i)
138 .slice(0, limit)
139
140// What the classifier reads for one hit: the task, then the note.
141export const relevanceText = (task: string, hit: Hit): string =>
142 `Would this note from a memory vault help with the task? Answer ${RELEVANT} or ${UNRELATED}.\n\nTask: ${task}\n\nNote: ${hit.title} [${hit.type}] - ${hit.summary.slice(0, 400)}`
143
144// Filter 4: the hits whose label is not UNRELATED. A label that is neither
145// keeps its hit, as the fallback does: only a definite "unrelated" drops one.
146export const relevantOf = (hits: readonly Hit[], labels: readonly (string | undefined)[]): Hit[] =>
147 hits.filter((_, i) => labels[i] !== UNRELATED)
148
149// The one compact block the model reads beside the prompt or the tool result.
150export function blockOf(hits: readonly Hit[], scan?: string): string {
151 const header =
152 scan === undefined
153 ? '🧠 Vault recall (verify against current code before acting; these reflect what was true when written):'
154 : `🧠 Vault recall for this scan, "${scan.slice(0, 60)}" (verify against current code before acting):`
155 const bullets = hits.map(hit => `• ${lineOf(hit.title, TITLE_MAX_CHARS)} [${lineOf(hit.type, 40)}] - ${lineOf(hit.summary, SUMMARY_MAX_CHARS)} (${lineOf(hit.path, PATH_MAX_CHARS)})`)
156 return [header, ...bullets].join('\n')
157}
158
159// About four characters to a token: the measure the recall figures use.
160export const tokensOf = (text: string): number => Math.ceil(text.length / 4)
161hooks/mods/cache-meter.ts 119 lines1// The cache meter and its churn view.
2//
3// Every main-loop API request is recorded with its cache read against its
4// cache creation, as the API reported them for that response. The status line
5// shows the latest request's hit share ("cache 97%"). A request that creates
6// more than it reads, past the first, is a creation spike: something before
7// the cached tail changed, or the cache expired. The meter then hashes each
8// section of the system prompt and names the sections whose hash changed since
9// the last reading, which is the churn the mods plan's first design rule asks
10// to find. A spike with no changed section was not the system prompt's doing:
11// an expired cache, a compaction, or a large tool result. It is recorded, and
12// only a spike that names a section is shown to Mike.
13//
14// Nothing here writes to the system prompt. The figures change every request,
15// so they go to the status line, a toast and a file under ~/.claude-workbench,
16// all of which the model never reads.
17//
18// Pure functions only: the engine follows `$` into no imported function, so the
19// hooks that keep the records live in hooks/register.ts.
20
21import type { TurnUsage } from 'claude-code'
22
23import type { CacheRequest, CacheState, ChurnEvent } from '../../types'
24
25// The section hashes of a reading, by section id.
26export type SectionHashes = Readonly<Record<string, string>>
27
28export const EMPTY_CACHE: CacheState = { count: 0, requests: [], churn: [], hashes: null }
29
30// The record keeps the latest requests only, so a long session stays small.
31// types/index.d.ts states the same figure.
32export const KEPT = 500
33// Below this, a request is too small to be a spike: the API caches no prefix
34// shorter than about 1,024 tokens.
35export const SPIKE_MIN = 1024
36
37// FNV-1a over the UTF-16 code units, as eight hex digits. Two texts that differ
38// almost always hash apart, and the same text always hashes the same.
39export function hashOf(text: string): string {
40 let hash = 0x811c9dc5
41 for (let i = 0; i < text.length; i++) {
42 hash ^= text.charCodeAt(i)
43 hash = Math.imul(hash, 0x01000193) >>> 0
44 }
45 return hash.toString(16).padStart(8, '0')
46}
47
48export const hashesOf = (sections: readonly { id: string; text: string }[]): Record<string, string> =>
49 Object.fromEntries(sections.map(section => [section.id, hashOf(section.text)]))
50
51// The sections whose text changed, or that are new, in prompt order, then the
52// sections that went away.
53export function changedSections(before: SectionHashes, after: SectionHashes): string[] {
54 const changed = Object.keys(after).filter(id => before[id] !== after[id])
55 const gone = Object.keys(before).filter(id => !(id in after))
56 return [...changed, ...gone]
57}
58
59export function cacheRequestOf(n: number, usage: TurnUsage): CacheRequest {
60 return { n, read: usage.cache_read_input_tokens, creation: usage.cache_creation_input_tokens, input: usage.input_tokens }
61}
62
63export const countCache = (state: CacheState, request: CacheRequest): CacheState => ({
64 ...state,
65 count: request.n,
66 requests: [...state.requests, request].slice(-KEPT),
67})
68
69// The share of the request's input read from the cache, in whole percent.
70// Undefined for a request with no input.
71export function hitOf(request: CacheRequest): number | undefined {
72 const total = request.read + request.creation + request.input
73 return total === 0 ? undefined : Math.round((100 * request.read) / total)
74}
75
76// Whether the request re-created more of the prompt than it read. The first
77// request creates the cache by design, so it is never a spike.
78export const isSpike = (request: CacheRequest): boolean =>
79 request.n > 1 && request.creation >= SPIKE_MIN && request.creation > request.read
80
81export const withChurn = (state: CacheState, event: ChurnEvent): CacheState => ({ ...state, churn: [...state.churn, event] })
82
83// The spikes that named a changed section.
84export const sectionChurn = (state: CacheState): readonly ChurnEvent[] =>
85 state.churn.filter(event => event.sections !== null && event.sections.length > 0)
86
87// The status line's facts: the latest hit share, and the number of spikes a
88// section change caused, when there was one.
89export function cacheFactsOf(state: CacheState): string[] {
90 const last = state.requests[state.requests.length - 1]
91 const hit = last === undefined ? undefined : hitOf(last)
92 if (hit === undefined) return []
93 const churned = sectionChurn(state).length
94 return churned > 0 ? [`cache ${hit}%`, `churn ${churned}`] : [`cache ${hit}%`]
95}
96
97const tokens = (n: number): string => n.toLocaleString('en-US')
98
99// The toast for a spike that named a section.
100export function churnText(event: ChurnEvent): string {
101 const names = (event.sections ?? []).join(', ')
102 const noun = (event.sections ?? []).length === 1 ? 'section' : 'sections'
103 return `Prompt cache churn at request ${event.n}: system-prompt ${noun} ${names} changed, and ${tokens(event.creation)} tokens were cached again.`
104}
105
106// What the record file holds: every kept request with its hit share, and every
107// spike. Stable key order, so two writes of one state are byte-identical.
108export function recordOf(state: CacheState): string {
109 const requests = state.requests.map(request => ({ ...request, hit: hitOf(request) ?? null }))
110 return `${JSON.stringify({ count: state.count, requests, churn: state.churn }, null, 1)}\n`
111}
112
113// The record file for a session, or undefined when the session id or home
114// cannot name one safely.
115export function recordFileOf(home: string | undefined, sessionId: string): string | undefined {
116 if (!home || !home.startsWith('/') || !/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(sessionId)) return undefined
117 return `${home.replace(/\/+$/, '')}/.claude-workbench/cache-meter/${sessionId}.json`
118}
119hooks/mods/commit-approval.ts 1443 lines1// The check never decides which tool the model uses: it governs what a commit
2// needs, and a command that only mentions git is let through.
3//
4// THE SHELL READER is hooks/mods/shell.ts, the one reader core and
5// workbench-dev-team share through $.workbench.parseShell. This check reads a
6// line through its commandsOf(): quotes, backslashes, separators, redirects
7// dropped with their targets, $( ), backticks and <( ), and heredoc bodies
8// taken out as bash takes them out. The rules here err toward finding a
9// commit, so a doubt costs a "Commit it" question and never a commit nobody
10// approved. A command is read past assignments, wrappers (env, sudo, nice,
11// timeout, xargs, ...) up to the first word named git, `bash -c` and `eval`
12// scripts, and git's global options, and `git` and its subcommand are matched
13// without regard to case, as macOS finds `GIT` on its case-insensitive disk.
14// A `-c alias.<name>=<value>` that names commit or push counts as that.
15//
16// A heredoc body is read as a script only when it feeds a shell or eval
17// (`bash <<EOF`), and the $( ) and backticks of a body with an unquoted
18// delimiter are read, as bash runs them.
19//
20// A word with any $'…' backslash escape is marked ESCAPED by the reader. Such
21// a word as a command name, or among git's options and subcommand, counts as
22// a commit and a push: `$'\x67it' push` is git push, and an escape the reader
23// does not decode (\u, \U, \c) could spell anything.
24//
25// Where the line commits, it also says where: the `cd` and `pushd` targets
26// before it, then git's -C values. hooks/register.ts reads HEAD there before
27// and after the line, so the approval follows what the repository shows.
28// A cd or pushd is recorded only in the one certain shape: the first word of a
29// command before any && or || on a line with no pipe, no lone &, no ( or
30// backtick and no heredoc, outside any shell -c script (eval keeps it), with a
31// target that is absolute, under ~, or starts with ./ or ../, and dirOf then
32// leaves any target holding `..` unknown. A bare relative
33// target (`cd sub`) is always unknown, because CDPATH can redirect it, and a
34// line can set CDPATH under a name built at run time. The cost is one new pick
35// when a `cd sub; git commit` line also fails. A pushd counts only as
36// `pushd <dir>`. The directory is UNKNOWN, which uses the approval up, when
37// the line holds:
38// - any other cd or pushd, or any popd, source or . command word: behind
39// if, {, !, command or an assignment, in a pipeline (bash runs the stages
40// in children, zsh runs the last here), behind &, in a subshell, a
41// substitution, a heredoc, or a shell -c script
42// - GIT_DIR or GIT_WORK_TREE, --git-dir, --work-tree, env -C or --chdir
43// - a cd or -C target with a variable, a substitution, `-`, or an escape
44// - any `..` in a cd or -C target, which the shell and git resolve apart
45// when the directory before it is a symlink (dirOf)
46// - an escaped command word
47//
48// Pure functions only: the engine follows `$` into no imported function.
49
50import type { WorkbenchShellStatement as ShellStatement } from '../../types'
51import { MERGE_MUTATION, findOps } from './commit-guard'
52import { hiddenCommandRefusal, isPartlyRead } from './guards'
53import { ASSIGNMENT, GIT_VALUE_OPTIONS, KEYWORDS, SHELLS, WRAPPERS, commandsOf, decodedOf, expandingOf, isEscaped, isExpanded, nameOf, parseShell, shellScriptOf } from './shell'
54
55export { commandsOf }
56
57export const COMMIT_REFUSAL =
58 'This git commit was refused: Mike has not approved it. A prompt of his own ' +
59 'that asks for a commit or a release approves the commits of the turn it ' +
60 'opened. Ask first for work he did not ask to commit. Once he says his ' +
61 'review is done, ask the commit question through AskUserQuestion, alone, ' +
62 'with the branch and the proposed message, and run the commit again after ' +
63 'he picks "Commit it". One pick approves one commit on the branch HEAD held ' +
64 'when he picked, and no push and no merge. Only his own next prompt ends a ' +
65 'pick not yet used.'
66
67export const PUSH_REFUSAL =
68 'This git push was refused: Mike has not approved it. A prompt of his own ' +
69 'that asks for a push or a release approves the pushes of the turn it ' +
70 'opened. A commit approval, typed or picked, approves no push. Once the ' +
71 'commit has landed, ask about the push in an AskUserQuestion call of its ' +
72 'own, with the branch, the remote and the commits it sends, and push after ' +
73 'he picks "Push". One pick approves one push of the branch HEAD held when ' +
74 'he picked.'
75
76export const MERGE_ASK_REFUSAL =
77 'This merge was refused: Mike has not approved a merge into the default ' +
78 'branch. How a branch lands, a pull request or a local merge, is his ' +
79 'choice. A commit or push approval approves no merge. Ask him in an ' +
80 'AskUserQuestion call of its own about the merge, once the commit and the ' +
81 'push have landed, and recommend a pull request. A prompt of his own that ' +
82 'asks for the merge approves it too, for the turn it opened.'
83
84export const MERGE_TARGET_REFUSAL =
85 'This merge was refused: it does not merge the pull request or branch Mike\'s ' +
86 'merge pick named. A merge pick approves only the pull request number or the ' +
87 'branch its question named, so write that number or branch on the line, such ' +
88 'as `gh pr merge 12` or `git merge fix/x`. To merge anything else, ask him again.'
89
90export const REWRITE_REFUSAL =
91 'This history rewrite was refused: git cherry-pick, revert, am, rebase, update-ref, ' +
92 'a reset that moves a branch, and a shell alias need Mike\'s pick in his own turn, ' +
93 'and nobody can give one here. A sub-agent, a -p run and a turn ' +
94 'nobody attends never rewrite history. The pipeline rewrites only its own ' +
95 'feature branches, and never the default branch or a branch the gate cannot ' +
96 'read. Report that the change is ready, and leave it to Mike\'s session.'
97
98export const API_WRITE_REFUSAL =
99 'This GitHub API write was refused: a gh api write to repos/<owner>/<repo>/contents ' +
100 'or git/refs changes the default branch here, or a branch the gate cannot read, ' +
101 'and that needs Mike\'s pick in his own turn. Nobody can give one ' +
102 'here. Name a feature branch in its branch= field or its refs/heads/ path, or ' +
103 'leave the change to Mike\'s session.'
104
105export const ALIAS_REFUSAL =
106 'This gh alias set was refused: a gh alias can run any command under a new ' +
107 'name, so setting one needs Mike\'s pick in his own turn, and nobody can give ' +
108 'one here. Run the gh command itself instead.'
109
110export const AGENT_MERGE_REFUSAL =
111 'This git merge or pull was refused: HEAD is on the default branch, or the ' +
112 'gate cannot tell which branch it is on, and a sub-agent, an --agent run or a ' +
113 'turn nobody attends does not merge into the default branch. How a branch ' +
114 'lands is Mike\'s choice. Report that the branch is ready, and leave the merge ' +
115 'to his session. Merging the default branch into a feature branch is not refused.'
116
117export const RELEASE_REFUSAL =
118 'This release was refused: nobody can approve it here. A prompt of Mike\'s own ' +
119 'that asks for a release approves one, for the turn it opened, and so does his ' +
120 'pick in his interactive session. Report that the release is ready.'
121
122export const MOVE_REFUSAL =
123 'This line was refused: it runs git checkout, switch, stash or reset while ' +
124 'Mike\'s commit or push pick is not yet used. The pick is tied to the branch ' +
125 'HEAD held when he picked, and to the tree he saw. Run the approved commit or ' +
126 'push first, on that branch. If the work needs another branch, tell Mike, and ' +
127 'ask the question again once he says how to go on.'
128
129export const branchRefusal = (seen: string, now: string): string =>
130 `This git commit or push was refused: Mike picked it while HEAD was on ${seen}, ` +
131 `and HEAD is now on ${now}. A pick approves only the branch HEAD held when he ` +
132 'picked, so this pick is used up. Ask the question again, and name the branch ' +
133 'HEAD is on now.'
134
135export const AGENT_RELEASE_REFUSAL =
136 'This release was refused: a sub-agent, a -p run, the pipeline and an --agent ' +
137 'run cannot ask Mike, so none of them releases. A gh release command, releases ' +
138 'endpoint or GraphQL Release mutation is refused here in any spelling, as is a ' +
139 'gh line whose command or subcommand is not written as plain text, and a line ' +
140 'the shell reader cannot read whole, because either may spell one. If the work ' +
141 'needs a release, report that it is ready, and leave it to the session that ' +
142 'dispatched you. For any other gh command, write gh and its subcommand as plain words.'
143
144export const ONE_REFUSAL =
145 'This line runs more than one git commit, git push, merge or release. Run ' +
146 'each as a line of its own. One pick approves one commit, one push or one ' +
147 'merge, so ask first for each further one that no request of Mike\'s covers.'
148
149export const UNREAD_TREE_REFUSAL =
150 'This git commit was refused: the gate cannot read which files it leaves ' +
151 'out, because it cannot tell which repository the line commits in, or how ' +
152 'the commit is spelled. Run the commit as a plain line of its own, such as ' +
153 '`git -C <absolute repository path> commit -F <message file>`.'
154
155export const PATHSPEC_REFUSAL =
156 'This git commit was refused: it names paths or picks hunks, so it leaves ' +
157 'the rest of the tree out. A commit takes every uncommitted file. Stage the ' +
158 'whole tree with `git add -A` on a line of its own, then commit with no paths.'
159
160export const SHARED_LINE_REFUSAL =
161 'This git commit was refused: another git command on its line may change ' +
162 'what is staged after the gate reads the tree, such as `git reset`, ' +
163 '`git restore --staged` or `git rm --cached`. Run the commit on a line of ' +
164 'its own, after the staging is done.'
165
166export const leftOutRefusal =(paths: readonly string[]): string =>
167 `This git commit was refused: it leaves these files out of the commit: ${paths.join(', ')}. ` +
168 'A commit takes every uncommitted file in the tree, tracked changes and ' +
169 'untracked files alike. Stage the whole tree with `git add -A` on a line of ' +
170 'its own, then run the commit again. The one exception is content that must ' +
171 'never ship, such as a secret or a stray build artifact. To leave such a ' +
172 'file out, name its path to Mike in your reply, with the reason, before you ' +
173 'run the commit again.'
174
175export const BUNDLE_REFUSAL =
176 'AskUserQuestion was refused: it offers a commit, push, merge or gated-line option ' +
177 'beside another question. Ask that question alone, in an AskUserQuestion ' +
178 'call of its own, and ask the other questions in a separate call.'
179
180export const NAMED_BUNDLE_REFUSAL =
181 'AskUserQuestion was refused: its commit question also names a push, a merge ' +
182 'or a release, and one pick approves one commit and nothing more. Ask the ' +
183 'commit question alone, with words that name only the commit. Once the ' +
184 'commit has landed, ask about the push, and then about how the branch lands, ' +
185 'each in a question of its own.'
186
187export const LINES_BUNDLE_REFUSAL =
188 'AskUserQuestion was refused: its question names more than one gated line, and ' +
189 'one pick approves one line. Ask about each line in an AskUserQuestion call of its own.'
190
191const COMMIT_OPTION = /^\s*commit\b/i
192
193// Words that stand before the command they run: the shell reader's wrappers
194// and keywords. After one, the command is the first later word named git, or
195// a shell or eval to read again, so a wrapper's options and their values never
196// hide it.
197const WRAPPER_WORDS: ReadonlySet<string> = new Set([...Object.keys(WRAPPERS), ...KEYWORDS])
198
199// How many commits and pushes a command or a line runs.
200export type Writes = { commits: number; pushes: number }
201
202const NONE: Writes = { commits: 0, pushes: 0 }
203const sum = (a: Writes, b: Writes): Writes => ({ commits: a.commits + b.commits, pushes: a.pushes + b.pushes })
204
205// Past this depth of nested scripts, a line is taken as a commit.
206const MAX_DEPTH = 4
207
208// What a line runs, as the reader walks it: the commits and pushes, the
209// directories `cd` and `pushd` moved to so far, and where the first commit or
210// push runs: the steps from the session's directory (`cd` targets, then git's
211// -C values), null when a step is a substitution or a variable the reader
212// cannot follow, and undefined until a commit or push is found.
213export type Commit = { dir: readonly string[] | null; args: readonly string[] | null }
214export type Line = { writes: Writes; dir: readonly string[] | null | undefined; commit?: Commit }
215// `isUnfollowed` is set by any directory change the walk does not record.
216// `isCompat` reads the line as the gate before the shared reader did (readLine).
217type Walk = { writes: Writes; cds: string[]; dir: string[] | null | undefined; commit?: Commit; isUnfollowed: boolean; isCompat: boolean }
218
219// The command words that move the shell or change its environment: a
220// directory change, or a sourced file, which may set GIT_DIR.
221const PLACE_WORDS: ReadonlySet<string> = new Set(['cd', 'pushd', 'popd', 'source', '.'])
222
223// Whether words[i] is a command word: every word before it is an assignment,
224// a wrapper or keyword (if, {, !, command, ...), or an option.
225const isCommandWord = (words: readonly string[], i: number): boolean =>
226 words.slice(0, i).every(word => ASSIGNMENT.test(word) || WRAPPER_WORDS.has(nameOf(word)) || word.startsWith('-'))
227
228// Whether every command of a line runs in this shell, one after another: no
229// pipe and no lone & (bash runs those stages in a child, and zsh runs the
230// last one here), and no ( or backtick, which may open a subshell or a
231// substitution, and no heredoc, whose body may feed a child shell. A | or &
232// inside quotes counts too, which only costs a recorded cd.
233const isSimpleLine = (line: string): boolean =>
234 !/[(`]/.test(line) && !line.includes('<<') && !/[|&]/.test(line.replace(/\|\||&&|[<>]&|&>/g, ''))
235
236const BOTH: Writes = { commits: 1, pushes: 1 }
237
238// A step the reader cannot follow: the directory is then unknown, which counts
239// as done.
240const UNKNOWN = '$'
241
242// What moves git to a repository the steps do not show.
243const GIT_PLACE = /^GIT_(DIR|WORK_TREE)=/
244const GIT_PLACE_OPTION = /^--(git-dir|work-tree)(=|$)/
245const ENV_CHDIR = /^(-[A-Za-z]*C|--chdir(=|$))/
246
247const stepsOf = (steps: string[]): string[] | null =>
248 steps.some(step => step.includes('$') || step === '-' || isEscaped(step)) ? null : steps
249
250function found(walk: Walk, writes: Writes, steps: string[], args: readonly string[] | null = null): void {
251 walk.writes = sum(walk.writes, writes)
252 if (walk.dir === undefined) walk.dir = stepsOf(steps)
253 if (writes.commits > 0 && walk.commit === undefined) walk.commit = { dir: stepsOf(steps), args }
254}
255
256// One simple command, behind any wrapper, assignment, shell script or global
257// option. `isHere` says the command surely runs in this shell, in order: its
258// line is simple (isSimpleLine) and not inside a shell -c script. eval keeps
259// it, as eval runs in this shell.
260function walkCommand(words: readonly string[], depth: number, isHere: boolean, walk: Walk): void {
261 // GIT_DIR or GIT_WORK_TREE, as a prefix, through env, or exported, points
262 // git elsewhere for this command or for the rest of the line.
263 if (words.some(word => GIT_PLACE.test(word))) walk.cds.push(UNKNOWN)
264 // THE DIRECTORY RULE. A cd or pushd is recorded only as the first word of a
265 // command that surely runs in this shell, before any && or || on its line,
266 // with a target that is absolute, under ~, or starts with ./ or ../. A bare
267 // relative target (`cd sub`) is always unknown, because CDPATH can redirect
268 // it and the line can set CDPATH under a name built at run time. A pushd
269 // that is not `pushd <dir>` (no target, +N, -N or an option rotates the
270 // stack or stays put) is unknown too. Every other cd, pushd, popd, source or . in a
271 // command-word place leaves the directory unknown: behind if, {, !, command
272 // or an assignment, in a pipeline, behind &, in a subshell, a substitution,
273 // a heredoc or a shell -c script.
274 const placeAt = words.findIndex((word, j) => PLACE_WORDS.has(nameOf(word)) && isCommandWord(words, j))
275 const head = nameOf(words[0] ?? '')
276 if (placeAt === 0 && isHere && !isEscaped(words[0] ?? '') && (head === 'cd' || head === 'pushd')) {
277 const target = words.slice(1).find(word => !word.startsWith('-') || word === '-') ?? '~'
278 const isPlainPushd = words.length === 2 && !/^[+-]/.test(words[1] ?? '')
279 const isUnknown = isBareRelative(target) || (head === 'pushd' && !isPlainPushd)
280 walk.cds.push(isUnknown ? UNKNOWN : target)
281 return
282 }
283 if (placeAt !== -1) walk.isUnfollowed = true
284 let i = 0
285 while (i < words.length) {
286 const word = words[i] as string
287 const name = nameOf(word)
288 if (ASSIGNMENT.test(word)) {
289 i++
290 } else if (isEscaped(word)) {
291 // A command name with an escape may be git, a shell, or a cd.
292 walk.isUnfollowed = true
293 found(walk, BOTH, [...walk.cds])
294 return
295 } else if (name === 'eval') {
296 walkLine(words.slice(i + 1).join(' '), depth + 1, isHere, walk)
297 return
298 } else if (SHELLS.has(name)) {
299 // The script is the first operand after the options, when an option
300 // cluster holds `c` (shellScriptOf, which `--` and -o values do not
301 // fool). A shell with none runs a file. The script runs in a child
302 // shell, so no cd in it moves this one. The compat reading takes the
303 // word after the first option holding `c`, as the gate before did.
304 const at = words.findIndex((option, j) => j > i && /^-[^-]*c/.test(option))
305 // FROZEN compat branch: delete only, once the bash/zsh check retires compat.
306 const script = walk.isCompat ? (at === -1 ? undefined : (words[at + 1] ?? '')) : shellScriptOf(words.slice(i + 1)).script
307 if (script !== undefined) walkLine(script, depth + 1, false, walk)
308 return
309 } else if (WRAPPER_WORDS.has(name)) {
310 const at = words.findIndex((later, j) => j > i && (isEscaped(later) || ['git', 'eval', ...SHELLS].includes(nameOf(later))))
311 if (at === -1) return
312 if (name === 'env' && words.slice(i + 1, at).some(option => ENV_CHDIR.test(option))) walk.cds.push(UNKNOWN)
313 i = at
314 } else {
315 break
316 }
317 }
318 if (nameOf(words[i] ?? '') !== 'git') return
319 const steps = [...walk.cds]
320 let aliased: Writes = NONE
321 for (i++; i < words.length; i++) {
322 const word = words[i] as string
323 // An escaped option or subcommand may spell commit, push, or -C.
324 if (isEscaped(word)) {
325 found(walk, BOTH, steps)
326 return
327 }
328 if (!word.startsWith('-')) {
329 const sub = word.toLowerCase()
330 if (sub === 'commit') found(walk, { commits: 1, pushes: 0 }, steps, words.slice(i + 1))
331 else if (sub === 'push') found(walk, { commits: 0, pushes: 1 }, steps)
332 else if (aliased !== NONE) found(walk, aliased, steps)
333 return
334 }
335 if (word === '-C') steps.push(words[i + 1] ?? UNKNOWN)
336 if (GIT_PLACE_OPTION.test(word)) steps.push(UNKNOWN)
337 if (word === '-c') {
338 // `-c alias.ci=commit` makes `ci` a commit. The alias's name is not
339 // matched against the subcommand: naming commit or push is enough.
340 const value = /^alias\.[^=]*=(.*)$/is.exec(words[i + 1] ?? '')?.[1] ?? ''
341 if (/\bcommit\b/i.test(value)) aliased = sum(aliased, { commits: 1, pushes: 0 })
342 if (/\bpush\b/i.test(value)) aliased = sum(aliased, { commits: 0, pushes: 1 })
343 }
344 if (GIT_VALUE_OPTIONS.has(word)) i++
345 }
346 if (aliased !== NONE) found(walk, aliased, steps)
347}
348
349// How many commands of a line come before its first && or ||: those surely
350// run. A command after one may be skipped, so a cd there is not certain. The
351// cut is read on the raw text, so a && inside quotes cuts early, which only
352// costs a recorded cd: a cut text never holds more commands than the line.
353// FROZEN compat branch: delete only, once the bash/zsh check retires compat.
354function certainCount(line: string, isCompat: boolean): number {
355 const cut = line.search(/&&|\|\|/)
356 // FROZEN compat branch: delete only, once the bash/zsh check retires compat.
357 return cut === -1 ? Infinity : commandsOf(line.slice(0, cut), isCompat).length
358}
359
360function walkLine(line: string, depth: number, isHere: boolean, walk: Walk): void {
361 if (depth > MAX_DEPTH) {
362 found(walk, { commits: 1, pushes: 0 }, [UNKNOWN])
363 return
364 }
365 const isHereLine = isHere && isSimpleLine(line)
366 // FROZEN compat branch: delete only, once the bash/zsh check retires compat.
367 const certain = certainCount(line, walk.isCompat)
368 // FROZEN compat branch: delete only, once the bash/zsh check retires compat.
369 commandsOf(line, walk.isCompat).forEach((words, at) => walkCommand(words, depth, isHereLine && at < certain, walk))
370}
371
372// Whether a cd target may resolve through CDPATH: a relative path that does
373// not start with /, ~, ./ or ../ (`-`, the previous directory, is unknown
374// through stepsOf).
375const isBareRelative = (target: string): boolean => !/^(\/|~|\.\.?(\/|$)|-$)/.test(target)
376
377// What a Bash command line runs: its commits and pushes, and where. A
378// directory change the walk did not record (walkCommand's directory rule)
379// leaves the directory unknown, which uses the approval up.
380//
381// The line is read twice: as bash reads it, and as the gate of 77bb2f3 read
382// it, before the shared reader read bash more exactly (commandsOf's
383// isCompat). The larger count of each is kept, so the gate never finds fewer
384// commits than that one did. When the two readings differ, the directory is
385// unknown.
386export function readLine(line: string): Line {
387 // FROZEN compat branch: delete only, once the bash/zsh check retires compat.
388 const [exact, compat] = [false, true].map(isCompat => {
389 // FROZEN compat branch: delete only, once the bash/zsh check retires compat.
390 const walk: Walk = { writes: NONE, cds: [], dir: undefined, isUnfollowed: false, isCompat }
391 walkLine(line, 0, true, walk)
392 const commit = walk.commit && (walk.isUnfollowed ? { ...walk.commit, dir: null } : walk.commit)
393 return { writes: walk.writes, dir: walk.isUnfollowed && walk.dir !== undefined ? null : walk.dir, ...(commit ? { commit } : {}) }
394 }) as [Line, Line]
395 const writes = { commits: Math.max(exact.writes.commits, compat.writes.commits), pushes: Math.max(exact.writes.pushes, compat.writes.pushes) }
396 const isSame = JSON.stringify(exact) === JSON.stringify(compat)
397 const commit = writes.commits === 0 ? {} : { commit: isSame && exact.commit ? exact.commit : { dir: null, args: null } }
398 return { writes, dir: isSame ? exact.dir : writes.commits + writes.pushes > 0 ? null : undefined, ...commit }
399}
400
401// How many commits and pushes a Bash command line runs.
402export const writesOf = (line: string): Writes => readLine(line).writes
403
404// The directory `steps` lead to from the session's `cwd`, or undefined when
405// they cannot be followed: a substitution, a variable, `cd -`, a `~` with no
406// home to expand it, or any `..`. The shell resolves `..` by the path as
407// written (`./link/..` is `.`), while git -C, and so the refs read there,
408// resolves it through the real path, so the two can land in different
409// repositories whenever the directory before it is a symlink: a named step,
410// the session's directory (a session in /tmp is in /private/tmp), or $HOME.
411export function dirOf(steps: readonly string[] | null | undefined, cwd: string, home: string | undefined): string | undefined {
412 if (steps === null) return undefined
413 let dir = cwd
414 for (const step of steps ?? []) {
415 let path = step
416 if (path === '~' || path.startsWith('~/')) {
417 if (!home) return undefined
418 path = `${home}${path.slice(1)}`
419 } else if (path.startsWith('~')) {
420 return undefined
421 }
422 if (step.split('/').includes('..')) return undefined
423 dir = path.startsWith('/') ? path : `${dir.replace(/\/+$/, '')}/${path}`
424 }
425 return dir
426}
427
428export type PickAction = 'commit' | 'push' | 'merge'
429export type LineKind = 'release' | 'rewrite' | 'alias' | 'api'
430export type Head = { top: string; ref: string }
431export type Pick = { action: PickAction | LineKind; heads: readonly Head[]; names?: MergeNames; line?: string }
432export type Approval = 'none' | Pick
433export type PendingLines = Readonly<Record<string, LineKind>>
434
435const LINE_KINDS: ReadonlySet<string> = new Set<LineKind>(['release', 'rewrite', 'alias', 'api'])
436const isLineKind = (kind: string): kind is LineKind => LINE_KINDS.has(kind)
437
438export type Action = PickAction | 'release'
439
440export type Gated = 'commit' | 'push' | 'merge' | 'release' | 'rewrite' | 'alias' | 'api'
441export type Counts = { writes: Writes; releases: number; merges: number; rewrites: number; aliases: number; apiWrites: number }
442export type Gate = { isOne: boolean; missing: readonly Gated[] }
443
444export const GATED_REFUSALS: Readonly<Record<Gated, string>> = {
445 commit: COMMIT_REFUSAL,
446 push: PUSH_REFUSAL,
447 merge: MERGE_ASK_REFUSAL,
448 release: RELEASE_REFUSAL,
449 rewrite: REWRITE_REFUSAL,
450 alias: ALIAS_REFUSAL,
451 api: API_WRITE_REFUSAL,
452}
453
454const GATED_NAMES: Readonly<Record<Gated, string>> = {
455 commit: 'git commit',
456 push: 'git push',
457 merge: 'merge into the default branch',
458 release: 'release',
459 rewrite: 'history rewrite',
460 alias: 'gh alias set',
461 api: 'GitHub API write to the default branch',
462}
463
464export function gateOf(counts: Counts, approval: Approval, request: readonly Action[], line = ''): Gate {
465 const { writes, releases, merges, rewrites, aliases, apiWrites } = counts
466 const picked = approval === 'none' || approval.line !== undefined ? undefined : approval.action
467 const missing: Gated[] = []
468 if (releases === 1 && !request.includes('release')) missing.push('release')
469 if (writes.commits === 1 && picked !== 'commit' && !grants(request, 'commit')) missing.push('commit')
470 if (writes.pushes === 1 && picked !== 'push' && !grants(request, 'push')) missing.push('push')
471 if (merges === 1 && picked !== 'merge' && !request.includes('merge')) missing.push('merge')
472 if (rewrites > 0) missing.push('rewrite')
473 if (aliases > 0) missing.push('alias')
474 if (apiWrites > 0) missing.push('api')
475 const isOne = writes.commits > 1 || writes.pushes > 1 || merges > 1 || releases > 1
476 const many: Readonly<Record<Gated, boolean>> = { commit: false, push: false, merge: false, release: false, rewrite: rewrites > 1, alias: aliases > 1, api: apiWrites > 1 }
477 const isLined = approval !== 'none' && approval.line !== undefined && approval.line === line && missing.includes(approval.action)
478 return { isOne, missing: isLined ? missing.filter(kind => many[kind]) : missing }
479}
480
481export function lineKindOf(missing: readonly Gated[], command: string): LineKind | undefined {
482 const kinds = missing.filter(isLineKind)
483 if (missing.length === 1 || kinds.length === 0) return kinds[0]
484 return parseShell(command).statements.length === 1 ? (kinds.includes('rewrite') ? 'rewrite' : kinds[0]) : undefined
485}
486
487export function refusalOf(counts: Counts, approval: Approval, request: readonly Action[]): string | undefined {
488 const gate = gateOf(counts, approval, request)
489 if (gate.isOne) return ONE_REFUSAL
490 const [first] = gate.missing
491 return first === undefined ? undefined : GATED_REFUSALS[first]
492}
493
494const namesOfGated = (missing: readonly Gated[]): string => missing.map(gated => GATED_NAMES[gated]).join(' and ')
495
496const SHOWN_ESCAPES: Readonly<Record<string, string>> = { '\n': '\\n', '\r': '\\r', '\t': '\\t', '`': '\\`', '\\': '\\\\' }
497
498const HIDDEN = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Zs}\u034f\u115f\u1160\u180b-\u180d\u180f\u2800\u3164\ufe00-\ufe0f\uffa0\u{e0100}-\u{e01ef}`\\]/gu
499
500const codeOf = (char: string): string => {
501 const point = char.codePointAt(0) ?? 0
502 return point > 0xffff ? `\\u{${point.toString(16)}}` : `\\u${point.toString(16).padStart(4, '0')}`
503}
504
505export const shownOf = (text: string): string => text.replace(HIDDEN, char => (char === ' ' ? char : (SHOWN_ESCAPES[char] ?? codeOf(char))))
506
507export type AskFacts = { command: string; repo?: string; branch?: string; message?: string; files?: readonly string[] }
508
509const LINE_HOW =
510 'Write the line in the question in backticks, exactly as it stands here, and offer "Run it" and "Not now". ' +
511 'A "Run it" pick approves this one line, once.'
512
513const ASK_HOW: Readonly<Record<Gated, string>> = {
514 commit:
515 'Ask only once he says his review is done, and offer "Commit it" and "Not yet". ' +
516 'A "Commit it" pick approves one commit on the branch HEAD holds when he picks, and no push and no merge.',
517 push: 'Name the push in plain words, such as "Push main to origin?", and offer "Push" and "Not yet". A "Push" pick approves one push of the branch HEAD holds when he picks.',
518 merge:
519 'Name the pull request number or the branch it merges in plain words, such as "Merge PR 12 into main?", recommend a pull request, and offer "Merge it". ' +
520 'A merge pick approves one merge of what its question names.',
521 release: LINE_HOW,
522 rewrite: LINE_HOW,
523 alias: LINE_HOW,
524 api: LINE_HOW,
525}
526
527export function askRefusalOf(missing: readonly Gated[], facts: AskFacts): string {
528 const [kind] = missing
529 if (kind === undefined || (missing.length > 1 && lineKindOf(missing, facts.command) === undefined)) {
530 return (
531 `This line was refused: it runs a ${namesOfGated(missing)}, and Mike has approved none of them. ` +
532 'One pick approves one action, so run each as a line of its own, and ask him about each one through AskUserQuestion, alone.'
533 )
534 }
535 const names = namesOfGated(missing)
536 const repo = facts.repo === undefined ? 'a repository the gate cannot read' : shownOf(facts.repo)
537 const branch = facts.branch === undefined ? 'a branch the gate cannot read' : shownOf(facts.branch.replace(/^refs\/heads\//, ''))
538 const parts = [
539 `This ${names} was refused: Mike has not approved it.`,
540 'Ask him through AskUserQuestion, with this question alone in its call.',
541 `In the question, name the exact line \`${shownOf(facts.command)}\`, the action (${names}), the repository ${repo}, and the branch ${branch}.`,
542 ]
543 if (missing.includes('commit')) {
544 const files = facts.files?.map(shownOf)
545 const listed = files === undefined ? 'every file git status lists' : files.length === 0 ? 'that git status lists no files' : `every file git status lists: ${files.join(', ')}`
546 parts.push(`Name the message, ${facts.message === undefined ? 'as the line gives it' : shownOf(facts.message)}, and ${listed}.`)
547 }
548 parts.push(missing.length === 1 ? ASK_HOW[kind] : LINE_HOW, 'After he picks, run the line again, unchanged.')
549 return parts.join(' ')
550}
551
552export function messageOf(args: readonly string[] | null): string | undefined {
553 if (args === null) return undefined
554 for (let i = 0; i < args.length; i++) {
555 const arg = args[i] ?? ''
556 if (arg === '-m' || arg === '--message') return JSON.stringify(args[i + 1] ?? '')
557 if (arg.startsWith('--message=')) return JSON.stringify(arg.slice('--message='.length))
558 if (/^-[a-z]*m./.test(arg) && !arg.startsWith('--')) return JSON.stringify(arg.slice(arg.indexOf('m') + 1))
559 if (arg === '-F' || arg === '--file') return `the text of ${args[i + 1] ?? 'a file'}`
560 if (arg.startsWith('--file=')) return `the text of ${arg.slice('--file='.length)}`
561 }
562 return undefined
563}
564
565export function filesOf(status: string): string[] {
566 const fields = status.split('\0')
567 const paths: string[] = []
568 for (let i = 0; i < fields.length; i++) {
569 const entry = fields[i] as string
570 if (entry.length < 4) continue
571 if ('RC'.includes(entry[0] as string) || 'RC'.includes(entry[1] as string)) i++
572 paths.push(entry.slice(3))
573 }
574 return paths
575}
576
577const grants = (request: readonly Action[], action: 'commit' | 'push'): boolean => request.includes(action) || request.includes('release')
578
579export function isPaidByPick(writes: Writes, merges: number, approval: Approval, request: readonly Action[]): boolean {
580 if (approval === 'none' || approval.line !== undefined) return false
581 if (approval.action === 'commit') return writes.commits === 1 && !grants(request, 'commit')
582 if (approval.action === 'push') return writes.pushes === 1 && !grants(request, 'push')
583 return merges === 1 && !request.includes('merge')
584}
585
586const DETACHED = 'detached at '
587
588export function headsOf(porcelain: string): Head[] {
589 return porcelain.split(/\n\n+/).flatMap(block => {
590 const lines = block.split('\n')
591 const field = (name: string) => lines.find(line => line.startsWith(`${name} `))?.slice(name.length + 1)
592 const top = field('worktree')
593 const ref = refOf(field('branch'), field('HEAD'))
594 return top === undefined || ref === undefined ? [] : [{ top, ref }]
595 })
596}
597
598export const refOf = (branch: string | undefined, sha: string | undefined): string | undefined =>
599 branch ?? (sha === undefined ? undefined : `${DETACHED}${sha}`)
600
601const shownRef = (ref: string | undefined, what: string): string => (ref === undefined ? what : ref.replace(/^refs\/heads\//, ''))
602
603export function bindingRefusalOf(pick: Pick, top: string | undefined, ref: string | undefined): string | undefined {
604 const seen = top === undefined ? undefined : pick.heads.find(head => head.top === top)
605 if (seen !== undefined && ref !== undefined && seen.ref === ref) return undefined
606 return branchRefusal(shownRef(seen?.ref, 'a branch the gate could not read'), shownRef(ref, 'a branch the gate cannot read'))
607}
608
609const SHELL_ALIAS = '!'
610const CONFIGURED = /(^|[^A-Za-z0-9_])GIT_CONFIG\w*=/
611
612export function gitSubOf(st: ShellStatement, line = ''): string | undefined {
613 if (st.name !== 'git' || st.subcommandAt < 0) return undefined
614 if (CONFIGURED.test(line) || st.assignments.some(assignment => /^GIT_CONFIG\w*=/.test(assignment))) return SHELL_ALIAS
615 const sub = (st.args[st.subcommandAt] ?? '').toLowerCase()
616 const globals = st.args.slice(0, st.subcommandAt)
617 for (let i = 0; i < globals.length; i++) {
618 const word = globals[i] ?? ''
619 const pair = word === '-c' ? globals[++i] : word.startsWith('-c') ? word.slice(2) : undefined
620 const alias = pair === undefined ? null : /^alias\.([^=]*)=(.*)$/is.exec(pair)
621 if (alias === null || (alias[1] ?? '').toLowerCase() !== sub) continue
622 const value = (alias[2] ?? '').trim()
623 return value.startsWith(SHELL_ALIAS) ? SHELL_ALIAS : (value.split(/\s+/)[0] ?? '').toLowerCase()
624 }
625 return sub
626}
627
628const restOf = (st: ShellStatement): readonly string[] => st.args.slice(st.subcommandAt + 1)
629
630const positionalsOf = (args: readonly string[], values: ReadonlySet<string>): string[] => {
631 const found: string[] = []
632 for (let i = 0; i < args.length; i++) {
633 const arg = args[i] ?? ''
634 if (values.has(arg)) i++
635 else if (!arg.startsWith('-')) found.push(arg)
636 }
637 return found
638}
639
640const HEAD_WRITERS: ReadonlySet<string> = new Set(['checkout', 'switch', 'update-ref', 'filter-branch', 'replace', 'bisect', SHELL_ALIAS])
641const SYMREF_VALUES: ReadonlySet<string> = new Set(['-m'])
642const REBASE_VALUES: ReadonlySet<string> = new Set(['--onto', '-s', '--strategy', '-X', '--strategy-option', '-x', '--exec'])
643const UPDATE_REF_VALUES: ReadonlySet<string> = new Set(['-m'])
644const BRANCH_VALUES: ReadonlySet<string> = new Set(['-u', '--set-upstream-to', '-t', '--track'])
645const PUSH_VALUES: ReadonlySet<string> = new Set(['-o', '--push-option', '--repo', '--receive-pack', '--exec'])
646const REWRITE_STOPS: ReadonlySet<string> = new Set(['--abort', '--quit'])
647const BISECT_READS: ReadonlySet<string> = new Set(['log', 'visualize', 'view', 'help', 'terms'])
648
649const isLongFor = (arg: string, full: string): boolean => arg.length >= 3 && arg.startsWith('--') && !arg.includes('=') && full.startsWith(arg)
650const longValuesOf = (rest: readonly string[], values: ReadonlySet<string>): Set<string> => {
651 const longs = [...values].filter(value => value.startsWith('--'))
652 return new Set([...values, ...rest.filter(arg => longs.some(full => isLongFor(arg, full)))])
653}
654const isBranchWrite = (arg: string): boolean => /^-[A-Za-z]*[mMfcC][A-Za-z]*$/.test(arg) || ['--move', '--force', '--copy'].some(full => isLongFor(arg, full))
655
656const refspecsOf = (rest: readonly string[], values: ReadonlySet<string> = new Set()): string[] =>
657 positionalsOf(rest, longValuesOf(rest, values)).filter(arg => arg.includes(':'))
658const destinationOf = (refspec: string): string => refspec.slice(refspec.lastIndexOf(':') + 1).replace(/^\+/, '')
659const isLocalRemote = (remote: string | undefined): boolean => remote === undefined || remote === '.' || /^(?:\/|\.\.?\/|~|file:)/.test(remote)
660const pushRemoteOf = (rest: readonly string[]): string | undefined => {
661 const at = rest.findIndex(arg => arg === '--repo' || isLongFor(arg, '--repo'))
662 const attached = rest.map(arg => /^--rep?o?=(.*)$/.exec(arg)?.[1]).find(value => value !== undefined)
663 if (attached !== undefined) return attached
664 return at === -1 ? positionalsOf(rest, longValuesOf(rest, PUSH_VALUES))[0] : rest[at + 1]
665}
666
667const rebaseNamesBranch = (rest: readonly string[]): boolean => {
668 if (rest.some(arg => REWRITE_STOPS.has(arg))) return false
669 const count = positionalsOf(rest, longValuesOf(rest, REBASE_VALUES)).length
670 const isRoot = rest.some(arg => arg === '--root' || isLongFor(arg, '--root'))
671 return count >= 2 || (count >= 1 && isRoot) || rest.some(arg => isLongFor(arg, '--update-refs'))
672}
673
674function writesHead(st: ShellStatement, sub: string | undefined): boolean {
675 if (sub === undefined) return false
676 const rest = restOf(st)
677 if (sub === 'replace') return !rest.some(arg => arg === '-l' || isLongFor(arg, '--list'))
678 if (sub === 'bisect') return !BISECT_READS.has(rest[0] ?? '')
679 if (HEAD_WRITERS.has(sub)) return true
680 if (sub === 'symbolic-ref') return rest.some(arg => arg === '-d' || isLongFor(arg, '--delete')) || positionalsOf(rest, SYMREF_VALUES).length >= 2
681 if (sub === 'branch') return rest.some(isBranchWrite)
682 if (sub === 'rebase') return rebaseNamesBranch(rest)
683 if (sub === 'fetch' || sub === 'pull') return refspecsOf(rest).length > 0
684 if (sub === 'push') return refspecsOf(rest, PUSH_VALUES).length > 0 && isLocalRemote(pushRemoteOf(rest))
685 return false
686}
687
688const breaksPlace = (st: ShellStatement, sub: string | undefined): boolean => sub !== 'update-ref' && writesHead(st, sub)
689
690const MOVES: ReadonlySet<string> = new Set(['stash', 'reset'])
691
692export function movesHead(line: string): boolean {
693 return parseShell(line).statements.some(st => {
694 const sub = gitSubOf(st, line)
695 if (writesHead(st, sub)) return true
696 return sub !== undefined && MOVES.has(sub) && !(sub === 'stash' && ['list', 'show'].includes(restOf(st)[0] ?? ''))
697 })
698}
699
700const isPlacedLine = (line: string, statements: readonly ShellStatement[]): boolean =>
701 !/(^|[^A-Za-z0-9_])GIT_(DIR|WORK_TREE)=/.test(line) && !statements.some(st => PLACE_WORDS.has(st.name) || breaksPlace(st, gitSubOf(st, line)))
702
703const REWRITES: ReadonlySet<string> = new Set(['cherry-pick', 'revert', 'am', 'rebase', 'update-ref', 'filter-branch', SHELL_ALIAS])
704
705const movesBranch = (rest: readonly string[]): boolean => {
706 const cut = rest.indexOf('--')
707 const targets = (cut === -1 ? rest : rest.slice(0, cut)).filter(arg => !arg.startsWith('-'))
708 return targets.length > 0 && !(targets.length === 1 && targets[0] === 'HEAD')
709}
710
711const isRewrite = (st: ShellStatement, sub: string | undefined): boolean => {
712 if (sub === undefined) return false
713 const rest = restOf(st)
714 if (sub === 'reset') return movesBranch(rest)
715 if (sub === 'commit') return rest.some(arg => /^--am/.test(arg))
716 if (sub === 'replace' || sub === 'fetch' || sub === 'push') return writesHead(st, sub)
717 if (sub === 'branch') return rest.some(isBranchWrite)
718 return REWRITES.has(sub) && !rest.some(arg => REWRITE_STOPS.has(arg))
719}
720
721export type Rewrite = { dir: string | null; refs?: readonly string[] }
722
723const UNPLACED_REWRITES: ReadonlySet<string> = new Set([SHELL_ALIAS, 'filter-branch', 'replace'])
724
725export function rewritesAt(line: string): Rewrite[] {
726 const parse = parseShell(line)
727 const isPlaced = isPlacedLine(line, parse.statements)
728 return parse.statements
729 .filter(st => isRewrite(st, gitSubOf(st, line)))
730 .map(st => {
731 const sub = gitSubOf(st, line)
732 const rest = restOf(st)
733 const placed = sub === 'branch' || sub === 'fetch' || sub === 'push' ? isPlacedLine(line, parse.statements.filter(other => other !== st)) : isPlaced
734 const dir = UNPLACED_REWRITES.has(sub ?? '') || (sub === 'rebase' && rebaseNamesBranch(rest)) ? null : mergeDirOf(st, placed)
735 if (sub === 'update-ref') return { dir, refs: [rest.includes('--stdin') ? '' : (positionalsOf(rest, UPDATE_REF_VALUES)[0] ?? '')] }
736 if (sub === 'fetch') return { dir, refs: refspecsOf(rest).map(destinationOf) }
737 if (sub === 'push') return { dir, refs: refspecsOf(rest, PUSH_VALUES).map(destinationOf) }
738 if (sub === 'branch') {
739 const names = positionalsOf(rest, longValuesOf(rest, BRANCH_VALUES))
740 return { dir, refs: names.length === 0 ? [''] : names }
741 }
742 return { dir }
743 })
744}
745
746export const rewritesOf = (line: string): number => rewritesAt(line).length
747
748const defaultNameOf = (originHead: string): string => originHead.replace(/^refs\/remotes\/[^/]+\//, '').toLowerCase()
749
750export const isDefaultRef = (ref: string, originHead: string | undefined): boolean => {
751 if (originHead === undefined) return true
752 const name = defaultNameOf(originHead)
753 const plain = ref.toLowerCase()
754 return plain === '' || plain === 'head' || plain === name || plain === `refs/heads/${name}` || plain === `heads/${name}`
755}
756
757export function aliasSetsOf(line: string): number {
758 return parseShell(line).statements.filter(st => {
759 if (st.name !== 'gh' || st.subcommandAt < 0 || (st.args[st.subcommandAt] ?? '').toLowerCase() !== 'alias') return false
760 return ['set', 'import'].includes((st.args[st.subcommandAt + 1] ?? '').toLowerCase())
761 }).length
762}
763
764export type ApiWrite = { branch: string | null; repo?: string | null | undefined }
765
766const REPO = String.raw`(?:repos\/([^\s/]+\/[^\s/]+)|repositories\/[^\s/]+)`
767const CONTENTS = new RegExp(String.raw`(?:^|\/)${REPO}\/contents(?:[/?]|$)`, 'i')
768const GIT_REFS = new RegExp(String.raw`(?:^|\/)${REPO}\/git\/refs(?:\/([^\s?]*))?(?:\?|$)`, 'i')
769const MERGE_UPSTREAM = new RegExp(String.raw`(?:^|\/)${REPO}\/merge-upstream(?:\?|$)`, 'i')
770const BRANCH_RENAME = new RegExp(String.raw`(?:^|\/)${REPO}\/branches\/([^\s?]+)\/rename(?:\?|$)`, 'i')
771const ANY_REPO = new RegExp(String.raw`(?:^|\/)${REPO}(?:\/|$)`, 'i')
772const REF_MUTATION = /\b(?:createCommitOnBranch|updateRefs?|createRef|deleteRef|mergeBranch)\b/
773const UNREAD_VALUE = /^@|[$`{}%#]|\/$/
774const UNREAD_ENDPOINT = /[%#]|\/\/|(?:^|\/)\.\.?(?:\/|$)/
775const BUILT_BRANCH_ENDPOINT = /[$`].*(?:contents|git\/refs|merge-upstream|branches|merges)|(?:contents|git\/refs|merge-upstream|branches|merges).*[$`]/i
776
777const lastField = (fields: readonly string[], name: string): string | undefined =>
778 [...fields].reverse().map(value => new RegExp(`^${name}=(.*)$`, 's').exec(value)?.[1]).find(value => value !== undefined)
779const readBranch = (branch: string | undefined): string | null => (branch === undefined || branch === '' || UNREAD_VALUE.test(branch) ? null : branch)
780const repoOf = (endpoint: string): string | null | undefined => {
781 const match = ANY_REPO.exec(endpoint)
782 const repo = match?.[1]?.toLowerCase()
783 if (repo === '{owner}/{repo}') return undefined
784 return repo === undefined || /[$`{}%#]/.test(repo) ? null : repo
785}
786
787const expandsAt = (st: ShellStatement, at: number): boolean => {
788 const expanding = expandingOf(st)
789 return expanding === undefined ? /[$`]/.test(st.words[at] ?? '') : expanding.includes(at)
790}
791
792export const hasExpandedField = (st: ShellStatement): boolean => st.words.some((_, at) => at > st.nameAt && expandsAt(st, at))
793
794function apiWriteOf(st: ShellStatement): ApiWrite[] {
795 const api = apiOf(st)
796 const fields = api.fields.map(field => field.value ?? '')
797 const words = [...restOf(st), ...st.heredocs.map(heredoc => heredoc.body)]
798 if (/graphql/i.test(api.endpoint)) return words.some(word => REF_MUTATION.test(word)) || hasExpandedField(st) ? [{ branch: null }] : []
799 const isWriteImplied = fields.length > 0 || api.options.some(option => option.name === '--input')
800 const method = (api.methods.at(-1)?.value ?? (isWriteImplied ? 'POST' : 'GET')).toUpperCase()
801 if (method === 'GET' || method === 'HEAD') return []
802 const repo = repoOf(api.endpoint)
803 const endpoint = api.endpoint.replace(/\{owner\}|\{repo\}/g, 'x')
804 if (UNREAD_ENDPOINT.test(endpoint) || BUILT_BRANCH_ENDPOINT.test(endpoint)) return [{ branch: null, repo }]
805 if (CONTENTS.test(api.endpoint) || MERGE_UPSTREAM.test(api.endpoint)) return [{ branch: readBranch(lastField(fields, 'branch')), repo }]
806 const renamed = BRANCH_RENAME.exec(api.endpoint)
807 if (renamed !== null) return [{ branch: readBranch(renamed[2]), repo }, { branch: readBranch(lastField(fields, 'new_name')), repo }]
808 const refs = GIT_REFS.exec(api.endpoint)
809 if (refs === null) return []
810 const path = refs[2] !== undefined && refs[2] !== '' ? refs[2] : (lastField(fields, 'ref') ?? '').replace(/^refs\//, '')
811 if (/^tags\//i.test(path) && !UNREAD_VALUE.test(path)) return []
812 return [{ branch: readBranch(/^heads\/(.+)$/i.exec(path)?.[1]), repo }]
813}
814
815const SYNC_VALUES: ReadonlySet<string> = new Set(['-b', '--branch', '-s', '--source'])
816
817function repoSyncOf(st: ShellStatement): ApiWrite[] {
818 const rest = restOf(st)
819 if ((rest[0] ?? '').toLowerCase() !== 'sync') return []
820 const at = rest.findIndex(arg => arg === '-b' || arg === '--branch')
821 const attached = rest.map(arg => /^--branch=(.+)$/.exec(arg)?.[1]).find(value => value !== undefined)
822 const isElsewhere = rest.some(arg => /^(?:-R|--repo)/.test(arg)) || positionalsOf(rest.slice(1), SYNC_VALUES).length > 0
823 return [{ branch: readBranch(at === -1 ? attached : rest[at + 1]), repo: isElsewhere ? null : undefined }]
824}
825
826export function apiWritesOf(line: string): ApiWrite[] {
827 return parseShell(line).statements.flatMap(st => {
828 if (st.name !== 'gh' || st.subcommandAt < 0) return []
829 const group = (st.args[st.subcommandAt] ?? '').toLowerCase()
830 if (group === 'api') return apiWriteOf(st)
831 return group === 'repo' ? repoSyncOf(st) : []
832 })
833}
834
835export const originRepoOf = (url: string | undefined): string | undefined =>
836 url === undefined || !/github\.com[:/]/i.test(url) ? undefined : /[:/]([^/:\s]+\/[^/\s]+?)(?:\.git)?\/?$/.exec(url.trim())?.[1]?.toLowerCase()
837
838export const isOtherRepo = (repo: string | null | undefined, origin: string | undefined): boolean =>
839 repo !== undefined && (repo === null || origin === undefined || repo !== origin)
840
841export type RemoteTarget = { repo: string; branch?: string }
842
843const ghRepoOf = (st: ShellStatement): string | undefined => {
844 const assigned = st.assignments.map(word => /^GH_REPO=(.+)$/.exec(word)?.[1]).find(value => value !== undefined)
845 for (let i = 0; i < st.args.length; i++) {
846 const arg = st.args[i] as string
847 if (arg === '-R' || arg === '--repo') return st.args[i + 1]
848 const attached = /^(?:-R|--repo=)(.+)$/.exec(arg)?.[1]
849 if (attached !== undefined) return attached
850 }
851 return assigned
852}
853
854export function remoteTargetOf(line: string, origin: string | undefined): RemoteTarget | undefined {
855 const write = apiWritesOf(line).find(each => typeof each.repo === 'string' && isOtherRepo(each.repo, origin))
856 if (write !== undefined && typeof write.repo === 'string') return { repo: write.repo, ...(write.branch === null ? {} : { branch: write.branch }) }
857 const release = parseShell(line).statements.find(st => st.name === 'gh' && st.args.includes('release'))
858 const repo = release === undefined ? undefined : ghRepoOf(release)
859 return repo === undefined || !isOtherRepo(repo.toLowerCase(), origin) ? undefined : { repo, branch: `the default branch of ${repo}` }
860}
861
862export type MergeTarget ={ pr?: string; refs: readonly string[]; bases?: readonly string[] }
863export type Merges = { local: readonly (string | null)[]; pr: number; targets: readonly MergeTarget[] }
864
865const MERGE_STOPS: ReadonlySet<string> = new Set(['--abort', '--quit'])
866const PULL_MERGE = /pulls\/([^\s/]+)\/merge(?![A-Za-z0-9_/-])/i
867const BRANCH_MERGE = /(?:^|\/)repos\/\S+\/merges(?:\?|$)/i
868const GH_MERGE_VALUES: ReadonlySet<string> = new Set(['-b', '--body', '-F', '--body-file', '-t', '--subject', '-A', '--author-email', '--match-head-commit', '-R', '--repo'])
869const GIT_MERGE_VALUES: ReadonlySet<string> = new Set(['-m', '-F', '--file', '-s', '--strategy', '-X', '--strategy-option', '--into-name', '--cleanup'])
870const REMOTE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
871const REMOTE_CHANGES: ReadonlySet<string> = new Set(['set-url', 'add', 'rename'])
872
873const fieldOf = (words: readonly string[], name: string): string | undefined =>
874 [...words].reverse().map(word => new RegExp(`^(?:-[fF]|--(?:raw-)?field=)?${name}=(.+)$`).exec(word)?.[1]).find(value => value !== undefined)
875
876const prTargetOf = (st: ShellStatement): MergeTarget | undefined => {
877 if (st.name !== 'gh' || st.subcommandAt < 0) return undefined
878 const sub = (st.args[st.subcommandAt] ?? '').toLowerCase()
879 const rest = restOf(st)
880 if (sub === 'pr') {
881 const at = rest.findIndex(arg => arg.toLowerCase() === 'merge')
882 if (at === -1) return undefined
883 const [first] = positionalsOf(rest.slice(at + 1), GH_MERGE_VALUES)
884 const pr = first === undefined ? undefined : (/^#?(\d+)$/.exec(first) ?? /\/pull\/(\d+)/.exec(first))?.[1]
885 return pr !== undefined ? { pr, refs: [] } : { refs: first === undefined ? [] : [first] }
886 }
887 if (sub !== 'api') return undefined
888 const words = [...rest, ...st.heredocs.map(heredoc => heredoc.body)]
889 const pull = words.map(word => PULL_MERGE.exec(word)?.[1]).find(pr => pr !== undefined)
890 if (pull !== undefined) return { pr: pull, refs: [] }
891 if (rest.some(word => BRANCH_MERGE.test(word))) {
892 const head = fieldOf(rest, 'head')
893 const base = fieldOf(rest, 'base')
894 return { refs: head === undefined ? [] : [head], bases: base === undefined ? [] : [base] }
895 }
896 return words.some(word => MERGE_MUTATION.test(word)) ? { refs: [] } : undefined
897}
898
899const localTargetOf = (st: ShellStatement, sub: string | undefined, isRemoteChanged: boolean): MergeTarget => {
900 const found = positionalsOf(restOf(st), GIT_MERGE_VALUES)
901 if (sub !== 'pull') return { refs: sub === SHELL_ALIAS ? [] : found }
902 const [remote] = found
903 return { refs: isRemoteChanged || remote === undefined || !REMOTE_NAME.test(remote) ? [] : found.slice(1) }
904}
905
906const mergeDirOf = (st: ShellStatement, isPlaced: boolean): string | null => {
907 const globals = st.args.slice(0, st.subcommandAt)
908 if (!isPlaced || globals.some(word => GIT_PLACE_OPTION.test(word))) return null
909 const at = globals.lastIndexOf('-C')
910 if (at === -1) return ''
911 const dir = globals[at + 1] ?? ''
912 return dir.startsWith('/') && !/[$`]/.test(dir) && !hasDotStep(dir) ? dir : null
913}
914
915export function mergesOf(line: string): Merges {
916 const parse = parseShell(line)
917 const isPlaced = isPlacedLine(line, parse.statements)
918 const isRemoteChanged = parse.statements.some(st => gitSubOf(st, line) === 'remote' && REMOTE_CHANGES.has(restOf(st)[0] ?? ''))
919 const merging = parse.statements
920 .filter(st => ['merge', 'pull', SHELL_ALIAS].includes(gitSubOf(st, line) ?? ''))
921 .filter(st => !restOf(st).some(arg => MERGE_STOPS.has(arg)))
922 const prs = parse.statements.map(prTargetOf).filter((target): target is MergeTarget => target !== undefined)
923 const hidden = prs.length === 0 && findOps(parse, line).ops.has('merge') ? [{ refs: [] }] : []
924 return {
925 local: merging.map(st => mergeDirOf(st, isPlaced)),
926 pr: prs.length + hidden.length,
927 targets: [...merging.map(st => localTargetOf(st, gitSubOf(st, line), isRemoteChanged)), ...prs, ...hidden],
928 }
929}
930
931export const isDefaultBranch = (branch: string | undefined, originHead: string | undefined): boolean => {
932 if (branch === undefined || originHead === undefined) return true
933 return branch.replace(/^refs\/heads\//, '').toLowerCase() === defaultNameOf(originHead)
934}
935
936export type MergeNames = { prs: readonly string[]; words: readonly string[]; bases?: readonly string[] }
937
938const DESTINATION = /\b(?:into|onto|to|on|in)\s+[`"']?([A-Za-z0-9._/-]+)/gi
939
940export function mergeNamesOf(questions: unknown): MergeNames {
941 const text = Array.isArray(questions) ? (questions as Question[]).map(question => `${textOf(question?.question)} ${textOf(question?.header)}`).join(' ') : ''
942 const prs = [...text.matchAll(/(?:#|\b(?:pr|pull request|pull)\s*#?)(\d+)\b/gi)].map(match => match[1] as string)
943 const bases = [...text.matchAll(DESTINATION)].map(match => (match[1] as string).replace(/[.]+$/, '').toLowerCase())
944 const subject = text.replace(DESTINATION, ' ')
945 const words = (subject.match(/[A-Za-z0-9._/-]+/g) ?? []).map(word => word.replace(/[.]+$/, '').toLowerCase())
946 return { prs: [...new Set(prs)], words: [...new Set(words)], bases: [...new Set(bases)] }
947}
948
949const bare = (ref: string): string => ref.toLowerCase().replace(/^(?:origin|upstream)\//, '')
950
951const isNamed = (target: MergeTarget, names: MergeNames): boolean => {
952 if (target.pr !== undefined) return names.prs.includes(target.pr)
953 if (target.bases !== undefined && !(target.bases.length > 0 && target.bases.every(base => (names.bases ?? []).includes(bare(base))))) return false
954 return target.refs.length > 0 && target.refs.every(ref => names.words.includes(bare(ref)))
955}
956
957export function mergeTargetRefusalOf(names: MergeNames | undefined, targets: readonly MergeTarget[]): string | undefined {
958 return names !== undefined && targets.length > 0 && targets.every(target => isNamed(target, names)) ? undefined : MERGE_TARGET_REFUSAL
959}
960
961const RELEASE_API = /(^|\/)releases(\/|$|\?)/
962const API_WRITE = /^(-x|--method|-f|--field|--raw-field|--input)(=|$)|^-[xf]\S/
963const RELEASE_MUTATION = /createrelease/
964const isExpansion = (word: string): boolean => /[$`]/.test(word)
965
966const ghWordsOf = (st: ShellStatement): string[] | undefined => {
967 const at = st.words.findIndex(word => nameOf(word) === 'gh')
968 return at === -1 ? undefined : st.words.slice(at + 1).map(word => word.toLowerCase())
969}
970
971const isRelease = (rest: readonly string[], line: string): boolean => {
972 const sub = rest.indexOf('release')
973 if (sub !== -1 && rest.slice(sub + 1).includes('create')) return true
974 if (!rest.includes('api')) return false
975 if (rest.includes('graphql') && /createrelease/i.test(line)) return true
976 return (rest.some(word => RELEASE_API.test(word)) && rest.some(word => API_WRITE.test(word))) || rest.some(word => RELEASE_MUTATION.test(word))
977}
978
979const GH_LONG_VALUES: ReadonlySet<string> = new Set([
980 '--repo', '--hostname', '--method', '--field', '--raw-field', '--header', '--input', '--jq', '--template', '--cache', '--preview',
981])
982const GH_SHORT_VALUES: ReadonlySet<string> = new Set(['R', 'X', 'H', 'f', 'F', 'q', 't', 'p'])
983const GH_FIELDS: ReadonlySet<string> = new Set(['-f', '-F', '--field', '--raw-field'])
984const REFUSED_GROUPS: ReadonlySet<string> = new Set(['release', 'alias', 'extension', 'extensions', 'ext'])
985const BRACE_EXPANSION = /\{[^{}]*(,|\.\.)[^{}]*\}/
986const GLOB = /[*?[]/
987const RELEASE_MUTATION_NAME = /[a-z_]release\s*[({]/i
988const PLAIN_OPTION = /^--?[A-Za-z][A-Za-z0-9-]*$/
989
990type GhOption = { name: string; value?: string; valueAt?: number }
991
992function readGh(args: readonly string[]): { options: GhOption[]; positionals: number[] } {
993 const options: GhOption[] = []
994 const positionals: number[] = []
995 for (let i = 0; i < args.length; i++) {
996 const word = args[i] ?? ''
997 if (word === '--') {
998 for (let k = i + 1; k < args.length; k++) positionals.push(k)
999 break
1000 }
1001 if (word.startsWith('--')) {
1002 const eq = word.indexOf('=')
1003 const name = (eq === -1 ? word : word.slice(0, eq)).toLowerCase()
1004 if (eq !== -1) options.push({ name, value: word.slice(eq + 1), valueAt: i })
1005 else if (GH_LONG_VALUES.has(name)) options.push({ name, value: args[i + 1] ?? '', valueAt: ++i })
1006 else options.push({ name })
1007 continue
1008 }
1009 if (!word.startsWith('-') || word === '-') {
1010 positionals.push(i)
1011 continue
1012 }
1013 for (let k = 1; k < word.length; k++) {
1014 const letter = word[k] as string
1015 if (!GH_SHORT_VALUES.has(letter)) {
1016 options.push({ name: `-${letter}` })
1017 continue
1018 }
1019 const rest = word.slice(k + 1)
1020 options.push(rest === '' ? { name: `-${letter}`, value: args[i + 1] ?? '', valueAt: ++i } : { name: `-${letter}`, value: rest, valueAt: i })
1021 break
1022 }
1023 }
1024 return { options, positionals }
1025}
1026
1027const optionHeadOf = (word: string): string => {
1028 if (word.startsWith('--')) return word.split('=')[0] ?? ''
1029 for (let k = 1; k < word.length; k++) {
1030 if (!/[A-Za-z]/.test(word[k] as string) || GH_SHORT_VALUES.has(word[k] as string)) return word.slice(0, k + 1)
1031 }
1032 return word
1033}
1034
1035const takesNextValue = (word: string): boolean => {
1036 if (word.startsWith('--')) return !word.includes('=') && GH_LONG_VALUES.has(word.toLowerCase())
1037 return GH_SHORT_VALUES.has(word.at(-1) ?? '') && optionHeadOf(word) === word
1038}
1039
1040const plainOf = (st: ShellStatement): ((at: number) => boolean) => {
1041 const expanding = expandingOf(st)
1042 const decoded = decodedOf(st)
1043 return at => {
1044 const word = st.words[at] ?? ''
1045 const expands = expanding === undefined ? isExpansion(word) : expanding.includes(at)
1046 const isDecoded = decoded === undefined || decoded.includes(at)
1047 return !expands && !isDecoded && !st.escaped.includes(at) && !BRACE_EXPANSION.test(word) && !GLOB.test(word)
1048 }
1049}
1050
1051const hasPlainCommand = (st: ShellStatement): boolean => {
1052 const isPlain = plainOf(st)
1053 if (!isPlain(st.nameAt)) return false
1054 const end = st.subcommandAt === -1 ? st.args.length - 1 : st.subcommandAt
1055 for (let j = 0; j <= end; j++) {
1056 const word = st.args[j] ?? ''
1057 if (!word.startsWith('-') || word === '-') {
1058 if (!isPlain(st.nameAt + 1 + j)) return false
1059 continue
1060 }
1061 if (st.escaped.includes(st.nameAt + 1 + j) || !PLAIN_OPTION.test(optionHeadOf(word))) return false
1062 if (takesNextValue(word)) j++
1063 }
1064 return true
1065}
1066
1067const mayRunGh = (st: ShellStatement, isAgent: boolean): boolean => {
1068 if (st.nameAt === -1 || st.words[st.nameAt] === '[' || st.words[st.nameAt] === '[[') return false
1069 if (st.name === 'gh') return true
1070 const word = st.words[st.nameAt] ?? ''
1071 if (st.escaped.includes(st.nameAt) && word.includes('\\')) return true
1072 if (BRACE_EXPANSION.test(word)) return /g/i.test(word) && /h/i.test(word)
1073 return isAgent && GLOB.test(word)
1074}
1075
1076const groupOf = (st: ShellStatement): string => (st.subcommandAt === -1 ? '' : (st.args[st.subcommandAt] ?? '').toLowerCase())
1077
1078const apiOf = (st: ShellStatement) => {
1079 const { options, positionals } = readGh(st.args)
1080 const endpointAt = positionals[1]
1081 const methods = options.filter(option => option.name === '-X' || option.name === '--method')
1082 const fields = options.filter(option => GH_FIELDS.has(option.name))
1083 const canWrite = methods.some(method => (method.value ?? '').toUpperCase() !== 'GET') || fields.length > 0 || options.some(option => option.name === '--input')
1084 return { endpointAt, endpoint: endpointAt === undefined ? '' : (st.args[endpointAt] ?? ''), methods, fields, options, canWrite }
1085}
1086
1087const isHiddenApiCall = (st: ShellStatement): boolean => {
1088 const isPlain = plainOf(st)
1089 const hidden = (j: number | undefined) => j !== undefined && !isPlain(st.nameAt + 1 + j)
1090 const api = apiOf(st)
1091 if (api.canWrite && hidden(api.endpointAt)) return true
1092 if (api.methods.some(method => hidden(method.valueAt))) return true
1093 const expanding = expandingOf(st)
1094 const expands = (j: number | undefined) => j !== undefined && (expanding === undefined ? isExpansion(st.args[j] ?? '') : expanding.includes(st.nameAt + 1 + j))
1095 return /graphql/i.test(api.endpoint) && api.fields.some(field => /^query=/i.test(field.value ?? '') && expands(field.valueAt))
1096}
1097
1098const isAgentApiRelease = (st: ShellStatement, line: string): boolean => {
1099 const api = apiOf(st)
1100 if (RELEASE_API.test(api.endpoint.toLowerCase())) return true
1101 if (/\bmutation\b/i.test(line) && RELEASE_MUTATION_NAME.test(line)) return true
1102 if (!/graphql/i.test(api.endpoint)) return false
1103 if (/\\u[0-9a-f]{4}/i.test(line)) return true
1104 if (api.options.some(option => option.name === '--input') && st.heredocs.length === 0) return true
1105 return api.fields.some(field => /(^|=)@/.test(field.value ?? ''))
1106}
1107
1108const isAgentRisk = (st: ShellStatement, line: string): boolean => {
1109 if (!mayRunGh(st, true)) return false
1110 if (st.name !== 'gh' || !hasPlainCommand(st)) return true
1111 const group = groupOf(st)
1112 if (REFUSED_GROUPS.has(group)) return true
1113 return group === 'api' && (isHiddenApiCall(st) || isAgentApiRelease(st, line))
1114}
1115
1116const isPlainRelease = (st: ShellStatement, line: string): boolean => {
1117 const rest = ghWordsOf(st)
1118 return rest !== undefined && isRelease(rest, line)
1119}
1120
1121const isUnreadRelease = (st: ShellStatement, line: string): boolean => {
1122 if (!mayRunGh(st, false)) return false
1123 if (st.name !== 'gh' || !hasPlainCommand(st)) return true
1124 if (isRelease(st.args.map(word => word.toLowerCase()), line)) return false
1125 const verbAt = st.subcommandAt + 1
1126 return groupOf(st) === 'release' && verbAt < st.args.length && !plainOf(st)(st.nameAt + 1 + verbAt)
1127}
1128
1129const isPlainReleaseCreate = (st: ShellStatement): boolean => hasPlainCommand(st) && plainOf(st)(st.nameAt + 2)
1130
1131export function releasesOf(line: string): number {
1132 return parseShell(line).statements.filter(st => isPlainRelease(st, line)).length
1133}
1134
1135export function unreadReleasesOf(line: string): number {
1136 return parseShell(line).statements.filter(st => isUnreadRelease(st, line)).length
1137}
1138
1139export function releaseCountOf(line: string): number {
1140 return parseShell(line).statements.filter(st => isPlainRelease(st, line) || isUnreadRelease(st, line)).length
1141}
1142
1143export const UNREAD_LINE_REFUSAL =
1144 'Workbench guards (workbench-core): the shell reader cannot read all of this line, such as an escape it ' +
1145 'does not decode, a substitution left open, or scripts nested too deep, so no guard can tell what it runs. ' +
1146 'Write the line out plainly, with every escape, quote and substitution closed, and run it again.'
1147
1148export function agentReleaseRefusalOf(line: string): string | undefined {
1149 const parse = parseShell(line)
1150 if (releasesOf(line) > 0 || parse.statements.some(st => isAgentRisk(st, line))) return AGENT_RELEASE_REFUSAL
1151 return isPartlyRead(parse) && hiddenCommandRefusal(parse) === undefined && parse.statements.some(st => mayRunGh(st, true)) ? AGENT_RELEASE_REFUSAL : undefined
1152}
1153
1154export function agentUnreadRefusalOf(line: string): string | undefined {
1155 const parse = parseShell(line)
1156 return isPartlyRead(parse) && hiddenCommandRefusal(parse) === undefined ? UNREAD_LINE_REFUSAL : undefined
1157}
1158
1159const LEAD_WORDS: ReadonlySet<string> = new Set([
1160 'please', 'pls', 'plz', 'ok', 'okay', 'yes', 'yep', 'yeah', 'sure', 'great', 'good', 'cool', 'nice', 'perfect',
1161 'awesome', 'excellent', 'thanks', 'thank', 'you', 'alright', 'all', 'right', 'now', 'so', 'and', 'then', 'also',
1162 'just', 'go', 'ahead', 'lgtm', 'looks', 'fine', 'done', 'finally', 'next', "let's", 'lets', 'work', 'well',
1163])
1164const OBJECT_STARTS: ReadonlySet<string> = new Set(['it', 'this', 'that', 'these', 'those', 'them', 'everything', 'all', 'origin', 'main', 'master', 'again'])
1165const WORK_OBJECTS: ReadonlySet<string> = new Set([
1166 'the', 'my', 'our', 'your', 'its', 'both', 'what', 'changes', 'change', 'work', 'fix', 'fixes', 'files', 'tree', 'diff', 'code', 'edits',
1167 'branch', 'pr', 'up', 'locally', 'with', 'here', 'now', 'too', 'staged', 'current', 'latest', 'rest', 'please',
1168])
1169const VERB_OBJECTS: Readonly<Record<string, ReadonlySet<string>>> = { push: new Set(['to']), merge: new Set(['into', 'to']) }
1170
1171const isObject = (verb: Action, after: string): boolean =>
1172 OBJECT_STARTS.has(after) || (verb !== 'release' && WORK_OBJECTS.has(after)) || (VERB_OBJECTS[verb]?.has(after) ?? false)
1173const MAX_REQUEST_LINES = 5
1174const MAX_REQUEST_WORDS = 80
1175const CONNECTORS: ReadonlySet<string> = new Set(['and', 'then', '&', '+', 'also', 'finally', 'please', 'now'])
1176const RELEASE_VERBS: ReadonlySet<string> = new Set(['cut', 'create', 'make', 'do', 'publish', 'ship', 'tag'])
1177const ACTION_WORD = /\b(commit(s|ted|ting)?|push(es|ed|ing)?|merg(e|es|ed|ing)|releas(e|es|ed|ing))\b/i
1178const VETO_WORD =
1179 /\b(not|no|never|nothing|don't|dont|do not|doesn't|didn't|won't|wouldn't|shouldn't|can't|cannot|without|later|yet|after|afterwards|before|once|when|whenever|until|till|unless|if|whether|should|would|could|might|may|maybe|perhaps|wait|hold|tomorrow|soon|eventually|instead|as long as|so long as|assuming|assume|provided|providing|given|pending|in case|supposing|depending|barring|isn't|isnt|hasn't|hasnt|haven't|aren't|wasn't|weren't|needn't|mustn't|must not|need not|only)\b/i
1180
1181const verbAt = (words: readonly string[], i: number): [Action, number] | undefined => {
1182 const word = words[i]
1183 if (word === 'commit' || word === 'push' || word === 'merge' || word === 'release') return [word, i + 1]
1184 if (!RELEASE_VERBS.has(word ?? '')) return undefined
1185 let k = i + 1
1186 while (['a', 'the', 'new'].includes(words[k] ?? '')) k++
1187 return words[k] === 'release' ? ['release', k + 1] : undefined
1188}
1189
1190const actionsOf = (words: readonly string[]): Action[] =>
1191 words.flatMap((word, i) => {
1192 const verb = verbAt(words, i)
1193 const before = words.slice(0, i)
1194 if (verb === undefined || !(before.every(lead => LEAD_WORDS.has(lead)) || CONNECTORS.has(words[i - 1] ?? ''))) return []
1195 const after = words[verb[1]]
1196 return after === undefined || CONNECTORS.has(after) || isObject(verb[0], after) || /^v?\d/.test(after) ? [verb[0]] : []
1197 })
1198
1199export function requestedOf(prompt: string): Action[] {
1200 const text = prompthooks/mods/commit-guard.ts 489 lines1import type { WorkbenchCallerLane as CallerLane, WorkbenchShellParse as ShellParse, WorkbenchShellStatement as Statement, WorkbenchShellUnknown } from '../../types'
2import { expandingOf } from './shell'
3
4export type Caller = { lane: CallerLane | undefined; isUnattended: boolean }
5
6type Op = 'commit' | 'push' | 'merge'
7
8export type Refusal = { deny: string }
9
10type Found = {
11 ops: Set<Op>
12 isForce: boolean
13 isHidden: boolean
14}
15
16const W = '[^A-Za-z0-9_.-]'
17const SEG = '[^;&|\\n]'
18const GIT_OP = `git${W}(?:${SEG}*[^A-Za-z0-9_-])?(commit|push)(?:$|[^A-Za-z0-9_-])`
19const MERGE_OP = `gh${W}(?:${SEG}*[^A-Za-z0-9_-])?(?:pr\\s+merge|api${W}${SEG}*pulls/[^\\s/]+/merge|api${W}${SEG}*repos/\\S+/merges)(?:$|[^A-Za-z0-9_/-])`
20const MENTION = new RegExp(`(?:^|${W})(?:${GIT_OP}|${MERGE_OP})`, 'im')
21const FORCE_TEXT = new RegExp(
22 `(?:^|${W})git${W}(?:${SEG}*[^A-Za-z0-9_-])?push${SEG}*\\s(?:--(?:forc|m|de|pru)|-[A-Za-z0-9]*[fd]|[+:]\\S)`,
23 'im',
24)
25const LOOSE = /commit|push|merge/i
26
27const READERS: ReadonlySet<string> = new Set([
28 'echo', 'printf', 'cat', 'head', 'tail', 'wc', 'ls', 'grep', 'egrep', 'fgrep', 'rg', 'jq', 'cd', 'pwd', 'true',
29 'false', 'test', '[', '[[', '((', ':', 'printenv', 'basename', 'dirname', 'realpath', 'readlink', 'stat', 'file',
30 'which', 'type', 'command', 'diff', 'cmp', 'comm', 'cut', 'tr', 'sort', 'uniq', 'column', 'nl', 'tee', 'mkdir',
31 'touch', 'rm', 'rmdir', 'mv', 'cp', 'ln', 'chmod', 'date', 'sleep', 'export', 'local', 'declare', 'readonly',
32 'unset', 'set',
33])
34
35const ASK_STRIPPED: ReadonlySet<string> = new Set(['timeout', 'time', 'nice', 'nohup', 'stdbuf', 'command', 'builtin', 'noglob'])
36
37const BUILT_NAME = /[{}*?[\]]|^=/
38
39const SEARCHERS: ReadonlySet<string> = new Set(['grep', 'egrep', 'fgrep', 'rg'])
40const TEXT_TOOLS: ReadonlySet<string> = new Set(['grep', 'egrep', 'fgrep', 'cut', 'head', 'tail', 'wc', 'tr', 'cat'])
41const SORT_ARG = /^(?:[^-].*|-|--|-[bcCdfghiMnrRsuVz]*(?:[kt].+)?)$/
42const UNIQ_ARG = /^-[cdDiuz]+$/
43const RG_ARG = /^(?:[^-].*|-|--|-[nioFwcHlLsSvxINU]+)$/
44
45const isQuietTool = (s: Statement): boolean =>
46 TEXT_TOOLS.has(s.name) ||
47 (s.name === 'sort' && s.args.every(arg => SORT_ARG.test(arg))) ||
48 (s.name === 'uniq' && s.args.every(arg => UNIQ_ARG.test(arg))) ||
49 (s.name === 'rg' && s.args.every(arg => RG_ARG.test(arg)))
50
51const SED_ADDRESS = String.raw`(?:\d+(?:~\d+)?|\$|/(?:[^/\\\n]|\\.)*/[IM]*)`
52const SED_PRINTS = new RegExp(String.raw`^(?:\s*(?:${SED_ADDRESS}(?:\s*,\s*(?:${SED_ADDRESS}|[+~]\d+))?)?\s*!?\s*[p=l]\s*(?:;|\n|$))+\s*$`)
53const SED_QUIET = /^(?:-[nEr]*n[nEr]*|--quiet|--silent)$/
54const SED_READ_OPTION = /^(?:-[nEr]+|--quiet|--silent|--regexp-extended)$/
55
56function isPrintingSed(s: Statement): boolean {
57 if (s.name !== 'sed' || !s.args.some(arg => SED_QUIET.test(arg))) return false
58 const scripts: string[] = []
59 let hasExpression = false
60 let operands = 0
61 for (let i = 0; i < s.args.length; i++) {
62 const arg = s.args[i] ?? ''
63 if (arg === '-e' || arg === '--expression') {
64 hasExpression = true
65 const script = s.args[++i]
66 if (script === undefined) return false
67 scripts.push(script)
68 } else if (arg.startsWith('--expression=')) {
69 hasExpression = true
70 scripts.push(arg.slice('--expression='.length))
71 } else if (arg.startsWith('-') && arg !== '-') {
72 if (!SED_READ_OPTION.test(arg)) return false
73 } else if (!hasExpression && operands++ === 0) {
74 scripts.push(arg)
75 }
76 }
77 return scripts.length > 0 && scripts.every(script => SED_PRINTS.test(script))
78}
79
80const AWK_PRINT = /^\{\s*print(?:\s+\$[0-9]+(?:\s*,\s*\$[0-9]+)*)?\s*;?\s*\}$/
81
82const awkProgramOf = (args: readonly string[]): string | undefined => {
83 if (args.length === 1) return args[0]
84 if (args.length === 2 && /^-F./.test(args[0] ?? '')) return args[1]
85 return args.length === 3 && args[0] === '-F' ? args[2] : undefined
86}
87
88const runsOrWrites = (s: Statement): boolean =>
89 (s.name === 'rg' && s.args.some(arg => arg.startsWith('--pre') || arg.startsWith('--hostname-bin'))) ||
90 (s.name === 'sort' && !s.args.every(arg => SORT_ARG.test(arg))) ||
91 (s.name === 'uniq' && s.args.filter(arg => !/^-./.test(arg)).length > 1)
92
93const isReader = (s: Statement): boolean => (READERS.has(s.name) && !runsOrWrites(s)) || isEditOnly(s)
94
95const runsNothing = (s: Statement): boolean =>
96 s.nameAt >= 0 &&
97 s.wrappers.length === 0 &&
98 s.assignments.length === 0 &&
99 s.isPlaced &&
100 ((isQuietTool(s) && isReader(s)) || isPrintingSed(s) || (s.name === 'awk' && AWK_PRINT.test(awkProgramOf(s.args) ?? '')))
101
102const PLAIN_TOOLS: ReadonlySet<string> = new Set(['grep', 'egrep', 'fgrep', 'column', 'head', 'tail', 'wc', 'cut', 'nl', 'tr', 'cat'])
103const UNIQ_READ_ARG = /^(?:-[cdDiuz]+|-[fsw]\d+)$/
104
105const isQuietRedirect = (s: Statement): boolean => s.redirects.every(r => !r.op.includes('>') || r.target === '/dev/null' || (r.op.endsWith('&') && /^(?:\d+|-)$/.test(r.target)))
106
107function isReadOnlyStage(s: Statement): boolean {
108 if (s.nameAt < 0 || s.wrappers.length > 0 || s.assignments.length > 0 || !s.isPlaced || s.heredocs.length > 0 || s.escaped.length > 0) return false
109 if (s.words[s.nameAt] !== s.name || !isQuietRedirect(s)) return false
110 if (PLAIN_TOOLS.has(s.name)) return true
111 if (s.name === 'rg') return !runsOrWrites(s) && !s.args.some(arg => /^--search-zip|^-[A-Za-z]*z/.test(arg))
112 if (s.name === 'sort') return s.args.every(arg => SORT_ARG.test(arg))
113 if (s.name === 'uniq') return s.args.every(arg => UNIQ_READ_ARG.test(arg) || !arg.startsWith('-')) && s.args.filter(arg => !arg.startsWith('-')).length <= 1
114 if (s.name === 'awk') return AWK_PRINT.test(awkProgramOf(s.args) ?? '')
115 return isPrintingSed(s)
116}
117
118export const isReadOnlyPipeline = (parse: ShellParse): boolean =>
119 parse.unknowns.length === 0 && parse.statements.length > 0 && parse.statements.every(isReadOnlyStage) && parse.statements.some(s => SEARCHERS.has(s.name))
120
121const withoutComments = (text: string): string =>
122 text
123 .split('\n')
124 .filter(line => !/^\s*(?:#|\/\/)/.test(line))
125 .join('\n')
126
127const opsIn = (text: string): Op[] => {
128 const ops: Op[] = []
129 const match = new RegExp(MENTION.source, 'gim')
130 for (const m of text.matchAll(match)) ops.push(m[1] === undefined ? 'merge' : (m[1].toLowerCase() as Op))
131 return ops
132}
133
134function configOf(args: readonly string[], end: number): { key: string; value: string }[] {
135 const config: { key: string; value: string }[] = []
136 for (let i = 0; i < end; i++) {
137 const arg = args[i] ?? ''
138 const pair = arg === '-c' ? args[++i] : arg.startsWith('-c') ? arg.slice(2) : undefined
139 if (pair === undefined) continue
140 const at = pair.indexOf('=')
141 config.push({ key: (at < 0 ? pair : pair.slice(0, at)).toLowerCase(), value: at < 0 ? '' : pair.slice(at + 1) })
142 }
143 return config
144}
145
146const isBuilt = (word: string): boolean => word.includes('$')
147
148const GLOBAL_VALUES: ReadonlySet<string> = new Set([
149 '-C', '-c', '--git-dir', '--work-tree', '--namespace', '--super-prefix', '--config-env', '--exec-path', '-R', '--repo',
150])
151
152const carriesValue = (arg: string): boolean =>
153 [...GLOBAL_VALUES].some(o => (o.startsWith('--') ? arg.startsWith(`${o}=`) : arg.startsWith(o) && arg.length > o.length))
154
155function decidesBuilt(s: Statement): boolean {
156 const at = s.subcommandAt
157 const end = at < 0 ? s.args.length : Math.min(s.args.length, at + 1)
158 for (let i = 0; i < end; i++) {
159 const arg = s.args[i] ?? ''
160 if (i < at && GLOBAL_VALUES.has(arg)) {
161 i++
162 continue
163 }
164 if (i < at && carriesValue(arg)) continue
165 if (isBuilt(arg)) return true
166 }
167 return false
168}
169
170const GH_API_VALUES: ReadonlySet<string> = new Set([
171 '-f', '--raw-field', '-F', '--field', '-H', '--header', '-X', '--method', '--input', '-q', '--jq', '-t', '--template',
172 '--cache', '-p', '--preview', '--hostname',
173])
174
175function apiWordsOf(rest: readonly string[]): { methods: string[]; positionals: string[] } {
176 const methods: string[] = []
177 const positionals: string[] = []
178 for (let i = 0; i < rest.length; i++) {
179 const arg = rest[i] ?? ''
180 if (arg === '--') {
181 positionals.push(...rest.slice(i + 1))
182 break
183 }
184 const cluster = /^-[A-Za-z]*X(.*)$/.exec(arg)
185 if (arg === '--method') methods.push(rest[++i] ?? '')
186 else if (arg.startsWith('--method=')) methods.push(arg.slice('--method='.length))
187 else if (cluster && !arg.startsWith('--')) methods.push(cluster[1] === '' ? (rest[++i] ?? '') : (cluster[1] ?? '').replace(/^=/, ''))
188 else if (GH_API_VALUES.has(arg)) i++
189 else if (!arg.startsWith('-')) positionals.push(arg)
190 }
191 return { methods, positionals }
192}
193
194function builtMerge(rest: readonly string[]): boolean {
195 const { methods, positionals } = apiWordsOf(rest)
196 if (!positionals.some(isBuilt)) return false
197 const isBuiltFlag = positionals.length > 1
198 return isBuiltFlag || methods.some(m => isBuilt(m) || m.toUpperCase() === 'PUT')
199}
200
201export const MERGE_MUTATION = /mergePullRequest|enablePullRequestAutoMerge|mergeBranch/i
202
203export function isUnreadGraphql(s: Statement, rest: readonly string[]): boolean {
204 if (!rest.some(word => /graphql/i.test(word))) return false
205 const isStdin = (word: string, next: string | undefined) => (word === '--input' && next === '-') || word === '--input=-' || /(^|=)@-$/.test(word)
206 const isFile = (word: string, next: string | undefined) =>
207 (word === '--input' && next !== '-') || (/^--input=/.test(word) && word !== '--input=-') || /(^|=)@(?!-$)/.test(word)
208 if (rest.some((word, i) => isFile(word, rest[i + 1]))) return true
209 const expanding = expandingOf(s)
210 if (s.words.some((word, at) => at > s.nameAt && (expanding === undefined ? /[$`]/.test(word) : expanding.includes(at)))) return true
211 return rest.some((word, i) => isStdin(word, rest[i + 1])) && s.heredocs.length === 0
212}
213
214const isForceArg = (arg: string): boolean => /^--(?:forc|m|de|pru)/i.test(arg) || /^-[A-Za-z0-9]*[fd]/.test(arg) || /^[+:]\S/.test(arg)
215
216const SED_FLAGS = /^[gIipM0-9]*$/
217const PERL_FLAGS = /^[gimsxonrcadlu]*$/
218const PERL_RUNS_CODE = /\(\?\??\{|\(\*\{|`/
219const PERL_SAFE_REPLACEMENT = /^(?:[^$@]|\$(?:\d+|&))*$/
220const PERL_PATTERN_VARIABLE = /[$@][A-Za-z_{:#$[]/
221const unescaped = (text: string): string => text.replace(/\\[\s\S]/g, '')
222
223function substitutionsOnly(script: string, program: 'sed' | 'perl'): boolean {
224 let i = 0
225 let count = 0
226 const skip = () => {
227 while (i < script.length && /[\s;]/.test(script[i] ?? '')) i++
228 }
229 const part = (delimiter: string): string | undefined => {
230 let text = ''
231 while (i < script.length) {
232 const c = script[i] ?? ''
233 if (c === '\\') {
234 text += c + (script[i + 1] ?? '')
235 i += 2
236 continue
237 }
238 i++
239 if (c === delimiter) return text
240 text += c
241 }
242 return undefined
243 }
244 skip()
245 while (i < script.length) {
246 const command = program === 'perl' && script.startsWith('tr', i) ? 'tr' : (script[i] ?? '')
247 if (command !== 's' && command !== 'y' && command !== 'tr') return false
248 i += command.length
249 const delimiter = script[i] ?? ''
250 if (delimiter === '' || /[A-Za-z0-9\s\\(){}[\]<>]/.test(delimiter)) return false
251 i++
252 const pattern = part(delimiter)
253 const replacement = pattern === undefined ? undefined : part(delimiter)
254 if (pattern === undefined || replacement === undefined) return false
255 const flags = /^[A-Za-z]*/.exec(script.slice(i))?.[0] ?? ''
256 i += flags.length
257 if (!(program === 'sed' ? SED_FLAGS : PERL_FLAGS).test(flags)) return false
258 if (program === 'perl' && command === 's' && PERL_RUNS_CODE.test(pattern + replacement)) return false
259 if (program === 'perl' && command === 's' && !PERL_SAFE_REPLACEMENT.test(unescaped(replacement))) return false
260 if (program === 'perl' && command === 's' && PERL_PATTERN_VARIABLE.test(unescaped(pattern))) return false
261 count++
262 skip()
263 }
264 return count > 0
265}
266
267const SED_OPTION = /^(?:-[EnrsuzI]+|-i.*|--in-place(?:=.*)?|--regexp-extended|--quiet|--silent|--)$/
268const PERL_OPTION = /^(?:-[pinlaw0-9]*[eE]?|-i[^-]*|--)$/
269
270function isEditOnly(s: Statement): boolean {
271 if (s.name !== 'sed' && s.name !== 'perl') return false
272 const program = s.name
273 const scripts: string[] = []
274 let pending = false
275 for (let i = 0; i < s.args.length; i++) {
276 const arg = s.args[i] ?? ''
277 if (pending) {
278 scripts.push(arg)
279 pending = false
280 continue
281 }
282 if (program === 'sed' && (arg === '-e' || arg === '--expression')) pending = true
283 else if (program === 'sed' && arg.startsWith('--expression=')) scripts.push(arg.slice('--expression='.length))
284 else if (program === 'sed' && arg === '-i' && s.args[i + 1] === '') i++
285 else if (arg.startsWith('-')) {
286 if (!(program === 'sed' ? SED_OPTION : PERL_OPTION).test(arg)) return false
287 if (program === 'perl' && /[eE]$/.test(arg)) pending = true
288 } else if (program === 'sed' && scripts.length === 0 && !s.args.slice(0, i).some(a => a === '-e' || a.startsWith('--expression'))) {
289 scripts.push(arg)
290 }
291 }
292 return !pending && scripts.length > 0 && scripts.every(script => substitutionsOnly(script, program))
293}
294
295type Read = { ops: Op[]; isForce: boolean; isHidden: boolean; code: string[]; isUnread: boolean }
296
297function readGit(s: Statement): Read {
298 const read: Read = { ops: [], isForce: false, isHidden: false, code: [], isUnread: false }
299 const args = s.args
300 if (s.name === 'git-commit' || s.name === 'git-push') {
301 read.ops.push(s.name === 'git-commit' ? 'commit' : 'push')
302 read.isForce = s.name === 'git-push' && args.some(isForceArg)
303 return read
304 }
305 const at = s.subcommandAt
306 const config = configOf(args, at < 0 ? args.length : at)
307 read.code.push(...config.map(c => c.value))
308 if (decidesBuilt(s) || config.some(c => isBuilt(c.key))) read.isUnread = true
309 if (config.some(c => /^remote\..*\.(?:mirror|push)$/.test(c.key))) read.isForce = true
310 if (args.some(arg => arg.startsWith('--config-env'))) read.isUnread = true
311 if (at < 0) {
312 if (s.wrappers.includes('xargs')) read.isUnread = true
313 return read
314 }
315 let sub = (args[at] ?? '').toLowerCase()
316 let rest = args.slice(at + 1)
317 const alias = config.find(c => c.key === `alias.${sub}`)
318 if (alias !== undefined) {
319 read.isHidden = true
320 if (isBuilt(alias.value)) read.isUnread = true
321 if (alias.value.trimStart().startsWith('!')) {
322 read.code.push(alias.value)
323 return read
324 }
325 const words = alias.value.trim().split(/\s+/)
326 sub = (words[0] ?? '').toLowerCase()
327 rest = [...words.slice(1), ...rest]
328 }
329 if (sub === 'grep' && rest.some(arg => arg.startsWith('-O') || arg.startsWith('--open-files'))) {
330 read.code.push(...rest.map(arg => arg.replace(/^(?:-O|--open-files[a-z-]*=?)/, ' ')))
331 }
332 if (sub === 'commit' || sub === 'push') read.ops.push(sub)
333 if (sub === 'push' && rest.some(isForceArg)) read.isForce = true
334 return read
335}
336
337function readGh(s: Statement): Read {
338 const read: Read = { ops: [], isForce: false, isHidden: false, code: [], isUnread: false }
339 const at = s.subcommandAt
340 if (decidesBuilt(s)) read.isUnread = true
341 if (at < 0) return read
342 const sub = (s.args[at] ?? '').toLowerCase()
343 const rest = s.args.slice(at + 1)
344 if (sub === 'pr' && isBuilt(rest[0] ?? '')) read.isUnread = true
345 if (sub === 'pr' && rest.some(arg => arg.toLowerCase() === 'merge')) read.ops.push('merge')
346 const isLiteralMerge = sub === 'api' && rest.some(arg => /pulls\/[^\s/]+\/merge(?![A-Za-z0-9_/-])/i.test(arg) || /(?:^|\/)repos\/\S+\/merges(?:\?|$)/i.test(arg))
347 if (sub === 'api' && isUnreadGraphql(s, rest)) read.ops.push('merge')
348 if (sub === 'api' && [...rest, ...s.heredocs.map(h => h.body)].some(word => MERGE_MUTATION.test(word))) {
349 read.ops.push('merge')
350 read.isHidden = true
351 }
352 if (isLiteralMerge) read.ops.push('merge')
353 if (sub === 'api' && !isLiteralMerge && builtMerge(rest)) {
354 read.ops.push('merge')
355 read.isHidden = true
356 }
357 return read
358}
359
360function isPlain(s: Statement): boolean {
361 const named = s.words[s.nameAt] ?? ''
362 const escapedAt = new Set(s.escaped)
363 const lastRead = s.nameAt + 1 + Math.max(s.subcommandAt, 0)
364 for (let i = s.nameAt; i <= lastRead; i++) if (escapedAt.has(i)) return false
365 return s.assignments.length === 0 && s.wrappers.every(w => ASK_STRIPPED.has(w)) && s.source === 'line' && s.depth === 0 && named === s.name
366}
367
368export function findOps(parse: ShellParse, line: string): Found {
369 const found: Found = { ops: new Set(), isForce: false, isHidden: false }
370 const add = (ops: Iterable<Op>, isHidden: boolean) => {
371 for (const op of ops) {
372 found.ops.add(op)
373 if (isHidden) found.isHidden = true
374 }
375 }
376 const all: Op[] = ['commit', 'push', 'merge']
377 if (isReadOnlyPipeline(parse)) return found
378
379 const isUnread = parse.unknowns.length > 0 || parse.statements.some(s => !s.isPlaced)
380 if (isUnread && LOOSE.test(line)) {
381 add(all.filter(op => new RegExp(op, 'i').test(line)), true)
382 if (FORCE_TEXT.test(line.replace(/\\\n/g, '').replace(/["'\\]/g, ''))) found.isForce = true
383 }
384
385 const readerText: string[] = []
386 let hasRunner = false
387 const isSearchOnly = parse.statements.every(runsNothing)
388 for (const s of parse.statements) {
389 const heredocs = s.heredocs.filter(h => !h.feedsShell).map(h => h.body)
390 const code = (texts: readonly string[]) => {
391 const text = withoutComments(texts.join('\n'))
392 add(opsIn(text), true)
393 if (FORCE_TEXT.test(text)) found.isForce = true
394 }
395 if (s.nameAt < 0) {
396 readerText.push(...s.assignments, ...heredocs)
397 continue
398 }
399 if (s.name === 'git' || s.name === 'git-commit' || s.name === 'git-push' || s.name === 'gh') {
400 const read = s.name === 'gh' ? readGh(s) : readGit(s)
401 add(read.ops, read.isHidden || !isPlain(s))
402 if (read.isForce) found.isForce = true
403 if (read.isUnread) add(all, true)
404 if (read.code.length > 0) {
405 hasRunner = true
406 code(read.code)
407 }
408 readerText.push(...s.assignments, ...heredocs)
409 continue
410 }
411 if (BUILT_NAME.test(s.name) || s.escaped.includes(s.nameAt)) {
412 hasRunner = true
413 code([s.words.slice(s.nameAt).join(' '), ...heredocs])
414 if (LOOSE.test(s.words.join(' '))) add(all.filter(op => new RegExp(op, 'i').test(s.words.join(' '))), true)
415 continue
416 }
417 if (isReader(s)) {
418 readerText.push(...(SEARCHERS.has(s.name) && isSearchOnly ? [] : s.args), ...s.assignments, ...heredocs)
419 } else if (isPrintingSed(s)) {
420 hasRunner = true
421 readerText.push(...(isSearchOnly ? [] : s.args), ...s.assignments, ...heredocs)
422 } else {
423 hasRunner = true
424 code([...s.args, ...heredocs])
425 readerText.push(...s.assignments)
426 }
427 }
428 if (hasRunner) {
429 const text = withoutComments(readerText.join('\n'))
430 add(opsIn(text), false)
431 if (FORCE_TEXT.test(text)) found.isForce = true
432 }
433 return found
434}
435
436const READS =
437 'A command that only reads or quotes these words, such as git log --grep, a grep, rg or sed -n for them, or a heredoc of notes, is not refused here. The code of a program such as node -e or python3 -c is refused when it names them, even in a quote, because the guard cannot tell a quote there from a call. Read or count that text with grep or the Read tool. If any other read was refused, report it as a guard defect, and use the Read tool for the file meanwhile.'
438
439const refusal = (line: string, why: string): Refusal => ({ deny: `🛑 Blocked: ${line}\n\nCommit guard (workbench-core). ${why}` })
440
441export const FORCE_REFUSAL = refusal(
442 'a push that forces or deletes.',
443 'Pushes that force or delete remote refs are refused outright, and no approval changes that. Push without the force or delete, or ask Mike to do it.',
444)
445
446export const MERGE_REFUSAL = refusal(
447 'a sub-agent or the pipeline does not merge a pull request.',
448 `Merging is Mike's own step, after review. Report that the pull request is ready to merge, and stop. Do not look for another route to a merge. ${READS}`,
449)
450
451export const SUBAGENT_REFUSAL = refusal(
452 'a sub-agent does not commit or push.',
453 `Leave the working tree uncommitted. Report the diff and a proposed commit message to the session that dispatched you. Do not ask to commit. Do not look for another route to a commit or push. ${READS}`,
454)
455
456export const PLAIN_REFUSAL = refusal(
457 'run the commit, push, or merge as a plain line, so you are asked.',
458 'The permission rules that prompt Mike match a plain git or gh line, and they miss one behind a wrapper such as env or sudo, a leading NAME=value, bash -c, eval, a substitution, a path, an escape, or an alias, and one inside a program or a line the guard cannot read. Run it as git commit …, git push …, or gh pr merge …, with git -C <dir> for a directory and git -c <key>=<value> for configuration. Drop a variable prefix such as HUSKY=0. If the line only quotes these words in the code of a program such as node -e, the guard cannot tell that from a call either. Read or count that text with grep or the Read tool.',
459)
460
461export const BUILT_REFUSAL = refusal(
462 'a command name the guard cannot read, from a sub-agent or an unattended run.',
463 'The command this line runs is named by a variable or a substitution, or the guard cannot read the whole line: a wrapper option it cannot place, a quote, substitution, heredoc, array or case it cannot close, an escape it cannot decode, a script piped into a shell, or scripts nested past four levels. So the guard cannot tell whether it commits, pushes, or merges. Name the program in plain words, such as python3 script.py rather than "$PY" script.py, and write the line so every quote, substitution, heredoc, array and case closes plainly. Do not look for another spelling.',
464)
465
466export const FAILED_REFUSAL = refusal(
467 'a call the commit guard could not judge.',
468 'The guard failed while reading this command, so it refuses it rather than let a commit, push, or merge through unread. Report this to Mike as a guard defect. Do not try another spelling.',
469)
470
471const EVERY_UNKNOWN: Record<WorkbenchShellUnknown, true> = {
472 quote: true, substitution: true, heredoc: true, escape: true, wrapper: true, expansion: true, stdin: true, depth: true, compound: true,
473}
474export const HIDES_NAME = Object.keys(EVERY_UNKNOWN) as readonly WorkbenchShellUnknown[]
475const hasBuiltName = (parse: ShellParse): boolean =>
476 parse.unknowns.some(u => HIDES_NAME.includes(u)) || parse.statements.some(s => !s.isPlaced)
477
478export function commitVerdict(parse: ShellParse, line: string, caller: Caller): Refusal | undefined {
479 const found = findOps(parse, line)
480 const isUnwatched = caller.lane === 'sub-agent' || caller.lane === undefined || caller.isUnattended
481 if (found.isForce) return FORCE_REFUSAL
482 if (found.ops.has('merge') && (caller.lane !== 'main' || caller.isUnattended)) return MERGE_REFUSAL
483 const writes = found.ops.has('commit') || found.ops.has('push')
484 if (writes && caller.lane !== 'main' && caller.lane !== 'top-level-agent') return SUBAGENT_REFUSAL
485 if (found.ops.size > 0 && found.isHidden) return PLAIN_REFUSAL
486 if (isUnwatched && hasBuiltName(parse)) return BUILT_REFUSAL
487 return undefined
488}
489hooks/mods/commit-subject.ts 93 lines1import type { WorkbenchShellParse as ShellParse, WorkbenchShellStatement as Statement } from '../../types'
2
3export const TYPES: readonly string[] = ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'ci', 'chore']
4
5export const GITMOJI: readonly string[] = [
6 '🎨', '⚡️', '🔥', '🐛', '🚑️', '✨', '📝', '🚀', '💄', '🎉', '✅', '🔒️', '🔐', '🔖', '🚨', '🚧', '💚', '⬇️', '⬆️', '📌',
7 '👷', '📈', '♻️', '➕', '➖', '🔧', '🔨', '🌐', '✏️', '💩', '⏪️', '🔀', '📦️', '👽️', '🚚', '📄', '💥', '🍱', '♿️', '💡',
8 '🍻', '💬', '🗃️', '🔊', '🔇', '👥', '🚸', '🏗️', '📱', '🤡', '🥚', '🙈', '📸', '⚗️', '🔍️', '🏷️', '🌱', '🚩', '🥅', '💫',
9 '🗑️', '🛂', '🩹', '🧐', '⚰️', '🧪', '👔', '🩺', '🧱', '🧑💻', '💸', '🧵', '🦺', '✈️', '🦖',
10]
11
12const bare = (emoji: string): string => emoji.replace(/\uFE0F/g, '')
13const KNOWN: ReadonlySet<string> = new Set(GITMOJI.map(bare))
14
15const NOT_ON_LINE = /^(-F|--file|-C|-c|--reuse-message|--reedit-message|--fixup|--squash)(=|$)/
16const SHORT_VALUED = 'mFCct'
17const SHORT_ATTACHED = 'uS'
18
19type Message = { text: string } | 'not-judged'
20
21function messageOf(statement: Statement, parse: ShellParse): Message | undefined {
22 const args = statement.args
23 let message: string | undefined
24 for (let i = statement.subcommandAt + 1; i < args.length; i++) {
25 const arg = args[i] ?? ''
26 if (arg === '--') break
27 if (NOT_ON_LINE.test(arg)) return 'not-judged'
28 let value: string | undefined
29 if (arg === '--message' || arg === '--message=') value = args[++i]
30 else if (arg.startsWith('--message=')) value = arg.slice('--message='.length)
31 else if (/^-[^-]/.test(arg)) {
32 for (let c = 1; c < arg.length; c++) {
33 const flag = arg[c] ?? ''
34 if (SHORT_ATTACHED.includes(flag)) break
35 if (!SHORT_VALUED.includes(flag)) continue
36 if (flag === 'F' || flag === 'C' || flag === 'c') return 'not-judged'
37 const attached = arg.slice(c + 1)
38 const taken = attached === '' ? args[++i] : attached
39 if (flag === 'm') value = taken
40 break
41 }
42 }
43 if (value !== undefined && message === undefined) message = value
44 }
45 if (message === undefined) return undefined
46 if (message === '$_') {
47 const bodies = parse.statements.filter(s => s.source === 'substitution')
48 const only = bodies.length === 1 ? bodies[0] : undefined
49 if (only?.name === 'cat' && only.args.length === 0 && only.heredocs.length === 1) return { text: only.heredocs[0]?.body ?? '' }
50 return 'not-judged'
51 }
52 return message.includes('$') ? 'not-judged' : { text: message }
53}
54
55export function subjectFault(subject: string): string | undefined {
56 const head = /^([A-Za-z]+)(\([^)]*\))?(!)?:/.exec(subject)
57 if (head === null) return 'it does not start with a type and a colon'
58 if (head[2] !== undefined) return `it has a scope, ${head[2]}`
59 if (!TYPES.includes(head[1] ?? '')) return `"${head[1]}" is not a type`
60 const rest = subject.slice(head[0].length)
61 if (!rest.startsWith(' ') || rest.startsWith(' ')) return 'the colon is not followed by exactly one space'
62 const [emoji = '', ...words] = rest.slice(1).split(' ')
63 if (!KNOWN.has(bare(emoji))) return `"${emoji}" is not a gitmoji from the skill's list`
64 const description = words.join(' ')
65 if (!/[^.\s]/.test(description) || description.startsWith(' ')) return 'the gitmoji is not followed by one space and a description'
66 if (!description.endsWith('.')) return 'the description does not end with a period'
67 return undefined
68}
69
70export function subjectVerdict(parse: ShellParse): { deny: string } | undefined {
71 for (const statement of parse.statements) {
72 if (statement.name !== 'git' || statement.subcommandAt < 0 || statement.args[statement.subcommandAt] !== 'commit') continue
73 const message = messageOf(statement, parse)
74 if (message === undefined || message === 'not-judged') continue
75 const subject = message.text.split('\n').find(line => line.trim() !== '')?.replace(/\s+$/, '') ?? ''
76 const fault = subjectFault(subject)
77 if (fault !== undefined) return { deny: subjectDeny(subject, fault) }
78 }
79 return undefined
80}
81
82export function subjectDeny(subject: string, fault: string): string {
83 return [
84 `🛑 Blocked: a commit subject that breaks the git-commit format, because ${fault}.`,
85 '',
86 `Commit guard (workbench-core). The subject was: ${JSON.stringify(subject)}. ` +
87 'The expected shape is "<type>: <gitmoji> <Description>.", for example "feat: ✨ Add email validation endpoint.". ' +
88 `The type is one of ${TYPES.join(', ')}, with ! after it for a breaking change, and never a scope. ` +
89 'The gitmoji comes from the git-commit skill\'s references/gitmoji.md, and the description ends with a period. ' +
90 'Fix the message with the /workbench-dev-team:git-commit skill, and commit again.',
91 ].join('\n')
92}
93