Engineering workflow in one resumable DOSSIER.md: dependency-ordered tasks, invariants, drift detection, cross-repo state, a rolling status log, and scout +…

Wave-scoped engineering workflow. One resumable DOSSIER.md drives a wave of work — tasks, bugs, invariants, cross-repo state, evidence log — with in-session quality gates.
Docs live at the repository root, which is not shipped to the install path — these are absolute so they resolve from the plugin cache too:
Local to this plugin:
hooks/register.tsx 186 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3import type { DossierWave } from '../types'
4import { contractPaths, DATE_PREFIX, field } from '../engine/converge.ts'
5import { headerToken } from '../engine/ledger.ts'
6import { needsTree, ownerLine, progress, progressLine, taskRows } from '../engine/progress.ts'
7import { BUILTINS, bugGate, editGate, type Io, ledgerRoot, promptGate, sessionGate, skillGate, skillOf, stopGate, verifyGate } from './gates.ts'
8
9function ioOf($: EngineInterface): Io {
10 return {
11 isDir: async (path) => {
12 try {
13 return (await $.fs.stat(path)).kind === 'dir'
14 } catch {
15 return false
16 }
17 },
18 read: async (path) => String(await $.fs.read(path)),
19 exists: (path) => $.fs.exists(path),
20 list: async (path) => (await $.fs.list(path)).map((entry) => entry.name),
21 env: (name) => {
22 if (name === 'DOSSIER_MARKER_GUARD') return $.env.get('DOSSIER_MARKER_GUARD')
23 if (name === 'DOSSIER_INVARIANT_GUARD') return $.env.get('DOSSIER_INVARIANT_GUARD')
24 return $.env.get('DOSSIER_FAKEIMPL_CMD')
25 },
26 run: (argv, init) => $.process.run(argv, init),
27 cli: `${$.plugin.root}/cli/ds`,
28 }
29}
30
31const RESEND = 'Then send the whole reply again. In focus mode the operator sees only your last message.'
32
33const seen = new Set<string>()
34const stopped = new Set<string>()
35const verified = new Set<string>()
36const bugsSeen = new Set<string>()
37const PANE = 'dossier-tasks'
38const wave = atom({ plugin: 'dossier', key: 'wave' } as const, null)
39const GLYPH: Record<string, string> = { x: '✓', '~': '▸', '.': '·', '!': '‼', '?': '?' }
40
41async function readOr($: EngineInterface, path: string): Promise<string | undefined> {
42 try {
43 return String(await $.fs.read(path))
44 } catch {
45 return undefined
46 }
47}
48
49async function liveWave($: EngineInterface, cwd: string): Promise<DossierWave | null> {
50 const root = await ledgerRoot(ioOf($), cwd)
51 const dossiers = `${root}/.scratchpad/dossier`
52 let names: string[]
53 try {
54 names = (await $.fs.list(dossiers)).filter((entry) => entry.kind === 'dir').map((entry) => entry.name)
55 } catch {
56 return null
57 }
58 for (const name of names.sort().reverse()) {
59 const ledger = await readOr($, `${dossiers}/${name}/DOSSIER.md`)
60 if (ledger === undefined || headerToken(ledger) !== 'live') continue
61 let contract: string | undefined
62 for (const path of contractPaths([cwd, root], `${dossiers}/${name}`)) contract ??= await readOr($, path)
63 const milestone = contract ? field(contract, 'milestone') || undefined : undefined
64 return { slug: name.replace(DATE_PREFIX, ''), text: ledger, ...(milestone ? { milestone } : {}) }
65 }
66 return null
67}
68
69async function refresh($: EngineInterface, cwd: string): Promise<void> {
70 const next = await liveWave($, cwd)
71 await update($, wave, (previous) => (previous?.text === next?.text ? previous : next))
72 $.ui.status(next ? progressLine(next.slug, progress(next.text, next.milestone)) : undefined)
73}
74
75export const register: Register = (on) => {
76 on('session.start', async ($, e, next) => {
77 await $.command.register({ name: PANE, description: 'Show the live dossier tasks and their needs in a pane' })
78 await refresh($, e.cwd)
79 return next(e)
80 })
81
82 on('turn.complete', async ($, e, next) => {
83 await refresh($, await $.session.cwd())
84 return next(e)
85 })
86
87 on('command.run', { command: PANE }, async ($) => {
88 await refresh($, await $.session.cwd())
89 await $.ui.open({ id: PANE, title: 'Dossier tasks' })
90 return { text: 'Dossier tasks pane opened.' }
91 })
92
93 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
94 const { Box, Text } = $.ui.resolve(e)
95 const live = await read($, wave)
96 if (!live) return <Text dimColor>No live dossier wave.</Text>
97 const view = progress(live.text, live.milestone)
98 const width = Math.max(20, e.props.bodyColumns)
99 return (
100 <Box flexDirection="column">
101 <Text bold>{progressLine(live.slug, view)}</Text>
102 <Text dimColor>{ownerLine(view)}</Text>
103 {needsTree(taskRows(live.text)).map(({ row, depth, also }) => {
104 const head = `${' '.repeat(depth)}${GLYPH[row.state] ?? row.state} ${row.id}${row.who === 'H' ? ' [you]' : ''} `
105 const tail = also.length ? ` +${also.join(' +')}` : ''
106 const room = Math.max(4, width - head.length - tail.length)
107 const task = row.task.length > room ? `${row.task.slice(0, room - 1)}…` : row.task
108 return (
109 <Text key={row.id} dimColor={row.state === 'x'} bold={row.state === '~'}>
110 {`${head}${task}${tail}`}
111 </Text>
112 )
113 })}
114 </Box>
115 )
116 })
117
118 on('classic.PreToolUse', async ($, e, next) => {
119 const input = e as unknown as Record<string, unknown>
120 const context: string[] = []
121 if (input.tool === 'Skill') {
122 context.push((await skillGate(ioOf($), await ledgerRoot(ioOf($), await $.session.cwd()), skillOf(input), seen)) ?? '')
123 } else if (input.tool === 'Edit' || input.tool === 'Write') {
124 const root = await ledgerRoot(ioOf($), await $.session.cwd())
125 const verdict = await editGate(ioOf($), root, input)
126 if (verdict.deny) return { deny: verdict.deny }
127 context.push(verdict.context ?? '', (await verifyGate(ioOf($), root, input, verified)) ?? '')
128 }
129 const result = await next(e)
130 const added = context.filter(Boolean)
131 if (!added.length) return result
132 return { ...result, additionalContext: [...(result.additionalContext ?? []), ...added] }
133 })
134
135 on('classic.PostToolUse', async ($, e, next) => {
136 const result = await next(e)
137 if (e.tool_name !== 'Edit' && e.tool_name !== 'Write') return result
138 const input = (e.tool_input ?? {}) as Record<string, unknown>
139 const path = typeof input.file_path === 'string' ? input.file_path : ''
140 const context = path ? await bugGate(ioOf($), path, bugsSeen) : undefined
141 if (!context) return result
142 return { ...result, additionalContext: [...(result.additionalContext ?? []), context] }
143 })
144
145 on('classic.UserPromptExpansion', async ($, e, next) => {
146 const result = await next(e)
147 if (!BUILTINS.has(e.command_name) || !e.cwd) return result
148 const context = await skillGate(ioOf($), await ledgerRoot(ioOf($), e.cwd), e.command_name, seen)
149 if (!context) return result
150 return { ...result, additionalContext: [...(result.additionalContext ?? []), context] }
151 })
152
153 on('classic.SessionStart', async ($, e, next) => {
154 const result = await next(e)
155 const root = await ledgerRoot(ioOf($), e.cwd)
156 const verdict = await sessionGate(ioOf($), root, { source: e.source, session_title: e.session_title ?? '' })
157 if (verdict.toast) $.ui.toast(verdict.toast)
158 const away =
159 root === e.cwd ? [] : [`dossier ledger: ${root}/.scratchpad — this session works in ${e.cwd}; read and write the ledger by that absolute path.`]
160 const context = [...(verdict.context ? [verdict.context] : []), ...(verdict.context ? away : [])]
161 return {
162 ...result,
163 ...(context.length ? { additionalContext: [...(result.additionalContext ?? []), ...context] } : {}),
164 ...(verdict.title && !result.sessionTitle ? { sessionTitle: verdict.title } : {}),
165 }
166 })
167
168 on('classic.UserPromptSubmit', async ($, e, next) => {
169 const result = await next(e)
170 const context = await promptGate(ioOf($), await ledgerRoot(ioOf($), e.cwd), e.cwd)
171 if (!context) return result
172 return { ...result, additionalContext: [...(result.additionalContext ?? []), context] }
173 })
174
175 on('classic.Stop', async ($, e, next) => {
176 const result = await next(e)
177 if (!e.stop_hook_active) stopped.delete(e.session_id)
178 if (stopped.has(e.session_id)) return result
179 const gate = await stopGate(ioOf($), e.cwd)
180 if (!gate) return result
181 stopped.add(e.session_id)
182 const own = result.block?.includes(RESEND) ? gate : `${gate}\n${RESEND}`
183 return { ...result, block: [result.block, own].filter(Boolean).join('\n\n') }
184 })
185}
186engine/converge.ts 171 lines1import { CELL, splitLines, strip, unicodeRegex } from './text.ts'
2
3const ROW = unicodeRegex('^\\|(.+)\\|\\s*$')
4const EXPECT = unicodeRegex('^(?:exit\\s+\\d+|stdout:\\s*\\S[^\\n]*)$')
5const EXIT = unicodeRegex('^exit\\s+(\\d+)$')
6const DETAIL_MAX = 120
7const RUNTIME_SUFFIXES = new Set(['.py', '.sh', '.js', '.ts', '.go', '.rs', '.rb'])
8const DOC_SUFFIXES = new Set(['.md', '.json', '.txt', '.yml', '.yaml'])
9const TEST_DIRS = new Set(['test', 'tests', '__tests__', 'spec'])
10
11export const DATE_PREFIX = unicodeRegex('^\\d{4}-\\d{2}-\\d{2}-')
12
13export function contractPaths(repos: readonly string[], waveDir: string): string[] {
14 const name = waveDir.split('/').filter(Boolean).pop() ?? ''
15 const stems = [...new Set([name, name.replace(DATE_PREFIX, '')])]
16 return [...repos.flatMap((repo) => stems.map((stem) => `${repo}/.dossier/${stem}.md`)), `${waveDir}/CONTRACT.md`]
17}
18
19function rstrip(text: string): string {
20 return text.replace(unicodeRegex('\\s+$'), '')
21}
22
23export function cells(line: string): string[] {
24 const match = ROW.exec(rstrip(line))
25 if (!match) return []
26 return (match[1] ?? '').split(CELL).map((cell) => strip(cell.replaceAll('\\|', '|')))
27}
28
29export function shlexWords(text: string): string[] | undefined {
30 const words: string[] = []
31 let word = ''
32 let started = false
33 let quote = ''
34 for (let i = 0; i < text.length; i++) {
35 const char = text[i] ?? ''
36 if (quote === "'") {
37 if (char === "'") quote = ''
38 else word += char
39 continue
40 }
41 if (quote === '"') {
42 if (char === '"') quote = ''
43 else if (char === '\\' && (text[i + 1] === '"' || text[i + 1] === '\\')) word += text[++i]
44 else word += char
45 continue
46 }
47 if (char === '\\') {
48 if (i + 1 >= text.length) return undefined
49 word += text[++i]
50 started = true
51 } else if (char === "'" || char === '"') {
52 quote = char
53 started = true
54 } else if (/[ \t\r\n]/.test(char)) {
55 if (started) words.push(word)
56 word = ''
57 started = false
58 } else {
59 word += char
60 started = true
61 }
62 }
63 if (quote) return undefined
64 if (started) words.push(word)
65 return words
66}
67
68export function isCommand(text: string): boolean {
69 if (!(text.startsWith('`') && text.endsWith('`') && text.length > 2)) return false
70 return (shlexWords(text.slice(1, -1))?.length ?? 0) > 0
71}
72
73export function numberedRows(text: string): string[][] {
74 const at = text.indexOf('## done-when')
75 if (at < 0) return []
76 const body = text.slice(at + '## done-when'.length).split('\n## ')[0] ?? ''
77 return splitLines(body)
78 .map(cells)
79 .filter((row) => row.length > 0 && /^\p{Nd}+$/u.test(row[0] ?? ''))
80}
81
82export function field(text: string, name: string): string {
83 for (const line of splitLines(text)) {
84 const row = cells(line)
85 if (row.length >= 2 && (row[0] ?? '').toLowerCase() === name) return row[1] ?? ''
86 }
87 return ''
88}
89
90export function hasConsumer(text: string): boolean {
91 return splitLines(text).some((line) => {
92 const row = cells(line)
93 return row.length >= 2 && (row[0] ?? '').toLowerCase() === 'consumer' && Boolean(row[1])
94 })
95}
96
97export function readableExpect(expect: string): boolean {
98 return EXPECT.test(strip(expect))
99}
100
101export function met(expect: string, code: number, out: string): boolean {
102 const wanted = strip(expect)
103 if (wanted.startsWith('stdout:')) {
104 const text = strip(wanted.slice('stdout:'.length))
105 if (text === '(nothing)') return code === 0 && strip(out) === ''
106 return code === 0 && out.includes(text)
107 }
108 const exit = EXIT.exec(wanted)
109 return exit ? code === Number(exit[1]) : false
110}
111
112export function detail(stream: string): string {
113 for (const raw of splitLines(stream)) {
114 const line = strip(raw)
115 if (line) return [...line].slice(0, DETAIL_MAX).join('')
116 }
117 return ''
118}
119
120function escaped(point: number): string {
121 if (point < 0x100) return `\\x${point.toString(16).padStart(2, '0')}`
122 if (point < 0x10000) return `\\u${point.toString(16).padStart(4, '0')}`
123 return `\\U${point.toString(16).padStart(8, '0')}`
124}
125
126export function pyRepr(text: string): string {
127 const quote = text.includes("'") && !text.includes('"') ? '"' : "'"
128 let out = ''
129 for (const char of text) {
130 const point = char.codePointAt(0) ?? 0
131 if (char === '\\') out += '\\\\'
132 else if (char === quote) out += `\\${quote}`
133 else if (char === '\n') out += '\\n'
134 else if (char === '\r') out += '\\r'
135 else if (char === '\t') out += '\\t'
136 else if (char !== ' ' && /[\p{C}\p{Z}]/u.test(char)) out += escaped(point)
137 else out += char
138 }
139 return `${quote}${out}${quote}`
140}
141
142function suffixOf(name: string): string {
143 const at = name.lastIndexOf('.')
144 return at <= 0 || at === name.length - 1 ? '' : name.slice(at)
145}
146
147function isTest(path: string): boolean {
148 const parts = path.split('/').filter((part) => part !== '' && part !== '.')
149 const name = parts[parts.length - 1] ?? ''
150 const stem = name.slice(0, name.length - suffixOf(name).length)
151 return parts.some((part) => TEST_DIRS.has(part)) || name.startsWith('test_') || ['_test', '.test', '_spec', '.spec'].some((end) => stem.endsWith(end))
152}
153
154export function layerMix(numstat: string): string {
155 if (!strip(numstat)) return ''
156 let runtime = 0
157 let docs = 0
158 let tests = 0
159 for (const line of splitLines(numstat)) {
160 const parts = line.split('\t')
161 if (parts.length !== 3 || !/^\p{Nd}+$/u.test(parts[0] ?? '') || !/^\p{Nd}+$/u.test(parts[1] ?? '')) continue
162 const changed = Number(parts[0]) + Number(parts[1])
163 const path = parts[2] ?? ''
164 const suffix = suffixOf(path.split('/').pop() ?? '').toLowerCase()
165 if (isTest(path)) tests += changed
166 else if (RUNTIME_SUFFIXES.has(suffix)) runtime += changed
167 else if (DOC_SUFFIXES.has(suffix)) docs += changed
168 }
169 return ` lines since contract: runtime ${runtime} · tests ${tests} · docs ${docs}`
170}
171engine/ledger.ts 483 lines1import { cells } from './converge.ts'
2import { CELL, strip, unicodeRegex } from './text.ts'
3
4const SPACE = '[ \\t\\n\\r\\f\\v]'
5
6function section(tag: string, word: string): RegExp {
7 return new RegExp(`^## (§${tag}([^A-Za-z]|$)|${word}(${SPACE}|$))`)
8}
9
10export const SEC = {
11 any: /^## /,
12 goal: section('G', 'Goal'),
13 constraints: section('C', 'Constraints'),
14 interfaces: section('I', 'Interfaces'),
15 invariants: section('V', 'Invariants'),
16 tasks: section('T', 'Tasks'),
17 bugs: section('B', 'Bugs'),
18 repos: section('X', 'Repos'),
19 status: section('S', 'Status'),
20 closeout: section('Z', 'Closeout'),
21}
22
23export const Z = {
24 complete: new RegExp(`^${SPACE}*complete:${SPACE}+true`),
25 abandoned: new RegExp(`^${SPACE}*abandoned:${SPACE}+true`),
26 successor: new RegExp(`^${SPACE}*successor:${SPACE}+[a-z0-9][a-z0-9-]*(${SPACE}|$)`),
27 slug: /^[a-z0-9][a-z0-9-]*$/,
28}
29
30export const HEADER = unicodeRegex('^`\\d[^`]*`\\s+·\\s+`([^`]*)`(?:\\s+·\\s|\\s*$)')
31const TASK_ROW = /^\|[ \t\n\r\f\v]*T[0-9]+[ \t\n\r\f\v]*\|/
32const BUG_ROW = /^\|[ \t\n\r\f\v]*B[0-9]+[ \t\n\r\f\v]*\|/
33const RULE_ROW = /^[-|:+\s]*$/
34
35export type Result = { text: string } | { error: string }
36
37export function lines(text: string): string[] {
38 if (text === '') return []
39 const out = text.split('\n')
40 if (out[out.length - 1] === '') out.pop()
41 return out
42}
43
44export function unlines(rows: string[]): string {
45 return rows.map((row) => `${row}\n`).join('')
46}
47
48export function trim(text: string): string {
49 return text.replace(/^[ \t]+|[ \t]+$/g, '')
50}
51
52function closureLine(line: string): boolean {
53 return Z.complete.test(line) || Z.abandoned.test(line) || Z.successor.test(line)
54}
55
56function* inSection(rows: string[], pattern: RegExp): Generator<[number, string, boolean]> {
57 let inside = false
58 for (let i = 0; i < rows.length; i++) {
59 const row = rows[i] ?? ''
60 if (pattern.test(row)) {
61 inside = true
62 yield [i, row, false]
63 continue
64 }
65 if (SEC.any.test(row)) inside = false
66 yield [i, row, inside]
67 }
68}
69
70function columns(header: string, names: string[]): Record<string, number> {
71 const cells = header.split(CELL)
72 const found: Record<string, number> = {}
73 for (let i = 1; i < cells.length - 1; i++) {
74 const name = trim(cells[i] ?? '')
75 if (names.includes(name)) found[name] = i
76 }
77 return found
78}
79
80export function rowFlip(text: string, file: string, id: string, state: string, cite: string): Result {
81 const rows = lines(text)
82 let found = 0
83 let header = false
84 let colState = 0
85 let colCite = 0
86 let rowCells = 0
87 let current = ''
88 for (const [, row, inside] of inSection(rows, SEC.tasks)) {
89 if (SEC.tasks.test(row)) {
90 header = false
91 colState = 0
92 colCite = 0
93 continue
94 }
95 if (!inside || !row.startsWith('|')) continue
96 const cells = row.split(CELL)
97 if (!header) {
98 header = true
99 const named = columns(row, ['state', 'cite'])
100 colState = named.state ?? 0
101 colCite = named.cite ?? 0
102 continue
103 }
104 if (trim(cells[1] ?? '') === id) {
105 found++
106 rowCells = cells.length
107 current = colCite ? trim(cells[colCite] ?? '') : ''
108 }
109 }
110 if (!colState || !colCite) {
111 return { error: `Tasks header in ${file} names no state/cite column; refusing to edit by position` }
112 }
113 if (found === 1 && (colState >= rowCells - 1 || colCite >= rowCells - 1)) {
114 return { error: `row ${id} has ${rowCells - 2} cells, fewer than the header names; refusing to write past its end` }
115 }
116 if (found === 0) return { error: `row id ${id} not found in the Tasks section of ${file}` }
117 if (found > 1) return { error: `row id ${id} matches ${found} Tasks rows (ambiguous)` }
118 if (state === 'x') {
119 const effective = (cite || current).replace(/[ \t\n\r\f\v]/g, '')
120 if (effective === '' || effective === '—' || effective === '-') {
121 return {
122 error: `${id} -> x requires a cite (Vm.3); ds vm-checks reads "", "—" and "-" alike as empty, so pass a real cite or set the row cite first`,
123 }
124 }
125 }
126 const out: string[] = []
127 header = false
128 for (const [, row, inside] of inSection(rows, SEC.tasks)) {
129 if (SEC.tasks.test(row)) header = false
130 if (!inside || !row.startsWith('|')) {
131 out.push(row)
132 continue
133 }
134 if (!header) {
135 header = true
136 out.push(row)
137 continue
138 }
139 const cells = row.split(CELL)
140 if (trim(cells[1] ?? '') !== id) {
141 out.push(row)
142 continue
143 }
144 cells[colState] = ` ${state} `
145 if (cite !== '') cells[colCite] = ` ${cite.replaceAll('|', '\\|')} `
146 out.push(`|${cells.slice(1, -1).join('|')}|`)
147 }
148 return { text: unlines(out) }
149}
150
151export function sAppend(text: string, entry: string): string {
152 const out: string[] = []
153 let done = false
154 for (const row of lines(text)) {
155 if (!done && SEC.closeout.test(row)) {
156 out.push(entry, '')
157 done = true
158 }
159 out.push(row)
160 }
161 return done ? unlines(out) : `${unlines(out)}\n${entry}\n`
162}
163
164export function headerIndex(rows: readonly string[]): number {
165 const end = rows.findIndex((row) => row.startsWith('## '))
166 return rows.slice(0, end < 0 ? rows.length : end).findIndex((row) => HEADER.test(row))
167}
168
169export function headerState(text: string, state: string): string | undefined {
170 const rows = lines(text)
171 const at = headerIndex(rows)
172 if (at < 0) return undefined
173 const parts = (rows[at] ?? '').split('`')
174 parts[3] = state
175 rows[at] = parts.join('`')
176 return unlines(rows)
177}
178
179export function headerToken(text: string): string {
180 const rows = lines(text)
181 return strip(HEADER.exec(rows[headerIndex(rows)] ?? '')?.[1] ?? '')
182}
183
184function repoRows(text: string): Generator<[number, string, boolean]> {
185 return inSection(lines(text), SEC.repos)
186}
187
188export function hasRepo(text: string, label: string): boolean {
189 for (const [, row, inside] of repoRows(text)) {
190 if (inside && row.startsWith('|') && trim(row.split(CELL)[1] ?? '') === label) return true
191 }
192 return false
193}
194
195export function xRefresh(text: string, label: string, values: [string, string, string, string]): string {
196 const out: string[] = []
197 for (const [, row, inside] of repoRows(text)) {
198 if (!inside || !row.startsWith('|')) {
199 out.push(row)
200 continue
201 }
202 const cells = row.split(CELL)
203 if (trim(cells[1] ?? '') !== label) {
204 out.push(row)
205 continue
206 }
207 const width = cells.length
208 values.forEach((value, i) => {
209 cells[i + 2] = ` ${value} `
210 })
211 out.push(`|${cells.slice(1, width - 1).join('|')}|`)
212 }
213 return unlines(out)
214}
215
216export function zWrite(text: string, file: string, kind: string, value: string, summary: string, cites: string, stamp: string, after = ''): Result {
217 let body: string
218 if (kind === 'complete') body = 'complete: true'
219 else if (kind === 'successor') {
220 if (!Z.slug.test(value)) return { error: `successor takes a slug (${Z.slug.source}), got "${value}"` }
221 body = `successor: ${value}`
222 } else if (kind === 'abandoned') {
223 if (value === '') return { error: 'abandoned requires a reason' }
224 body = `abandoned: true\n\nreason: ${value}`
225 } else return { error: `invalid kind "${kind}" (complete|successor|abandoned)` }
226 const checks: [string, string][] = [
227 ['summary', `summary: ${summary}`],
228 ['key cites', `key cites: ${cites}`],
229 ]
230 if (kind === 'abandoned') checks.push(['reason', `reason: ${value}`])
231 if (after) checks.push(['after', `after: ${after}`])
232 for (const [label, rendered] of checks) {
233 if (lines(rendered).some(closureLine)) {
234 return { error: `${label} reads as a §Z closure key and would flip the INDEX §Z column; reword it` }
235 }
236 }
237 const rows = lines(text)
238 const at = rows.findIndex((row) => SEC.closeout.test(row))
239 if (at < 0) return { error: `no Closeout heading in ${file}` }
240 const head = unlines(rows.slice(0, at))
241 const carried = after ? `\n\nafter: ${after}` : ''
242 return { text: `${head}${rows[at]}\n\n${stamp} — closed\n\n${body}${carried}\n\nsummary: ${summary}\n\nkey cites: ${cites}\n` }
243}
244
245export function missingSections(text: string): string[] {
246 const rows = lines(text)
247 const missing: string[] = []
248 if (!rows.some((row) => row.startsWith('# '))) missing.push('title')
249 const required: [string, RegExp][] = [
250 ['Goal', SEC.goal],
251 ['Constraints', SEC.constraints],
252 ['Interfaces', SEC.interfaces],
253 ['Invariants', SEC.invariants],
254 ['Tasks', SEC.tasks],
255 ['Bugs', SEC.bugs],
256 ['Repos', SEC.repos],
257 ['Status', SEC.status],
258 ['Closeout', SEC.closeout],
259 ]
260 for (const [name, pattern] of required) if (!rows.some((row) => pattern.test(row))) missing.push(name)
261 return missing
262}
263
264function closeoutLines(text: string): string[] {
265 const rows = lines(text)
266 const at = rows.findIndex((row) => SEC.closeout.test(row))
267 return at < 0 ? [] : rows.slice(at)
268}
269
270export function zClosed(text: string): boolean {
271 return closeoutLines(text).some(closureLine)
272}
273
274export function zColumn(text: string): string {
275 const rows = closeoutLines(text)
276 if (rows.some((row) => Z.complete.test(row))) return 'complete'
277 if (rows.some((row) => Z.abandoned.test(row))) return 'abandoned'
278 const hit = rows.map((row) => Z.successor.exec(row)?.[0]).find((match) => match !== undefined)
279 if (hit === undefined) return '—'
280 return `→${hit.replace(/^.*successor:[ \t\n\r\f\v]*/, '').replace(/[ \t\n\r\f\v]+$/, '')}`
281}
282
283export const STAMP = '[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}(?::[0-9]{2})?'
284const STAMPED = new RegExp(`^${STAMP}`)
285const ENTRY = new RegExp(`^(?:${STAMP} )?(ds:[a-z]+) (\\S+) (.*)$`)
286const JOINED = new RegExp(` (?=${STAMP} ds:[a-z]+ )`)
287
288export type Cell = (name: string) => string
289
290export function namedRows(text: string, heading: RegExp): Cell[] {
291 const out: Cell[] = []
292 let inside = false
293 let names: string[] = []
294 for (const row of lines(text)) {
295 if (SEC.any.test(row)) {
296 inside = heading.test(row)
297 names = []
298 continue
299 }
300 const values = inside && !RULE_ROW.test(row) ? cells(row) : []
301 if (!values.length) continue
302 if (!names.length) {
303 names = values.map((name) => name.toLowerCase())
304 continue
305 }
306 const named = names
307 out.push((name) => values[named.indexOf(name)] ?? '')
308 }
309 return out
310}
311
312export function unpushedRepos(text: string): string[] {
313 const header = cells(sectionRows(text, SEC.repos).find((row) => cells(row).length) ?? '')
314 if (!header.some((name) => name.toLowerCase() === 'pushed')) return []
315 return namedRows(text, SEC.repos)
316 .filter((row) => row('pushed').toLowerCase() !== 'yes')
317 .map((row) => row('repo'))
318}
319
320export function indexNames(index: string, state: string): string[] {
321 const [names = [], ...body] = lines(index)
322 .map(cells)
323 .filter((row) => row.length)
324 const at = (name: string): number => names.indexOf(name)
325 return body.filter((row) => row[at('state')] === state).map((row) => `${row[at('date')]}-${row[at('slug')]}`)
326}
327
328export function sectionRows(text: string, heading: RegExp): string[] {
329 const out: string[] = []
330 let inside = false
331 for (const row of lines(text)) {
332 if (SEC.any.test(row)) inside = heading.test(row)
333 else if (inside) out.push(row)
334 }
335 return out
336}
337
338export function statusSection(text: string): string[] {
339 return sectionRows(text, SEC.status)
340}
341
342export function openOps(entries: string[]): Map<string, string> {
343 const open = new Map<string, string>()
344 const pending = new Map<string, string>()
345 for (const entry of entries.flatMap((line) => trim(line).split(JOINED))) {
346 const match = ENTRY.exec(entry)
347 if (!match) continue
348 const [, verb = '', target = '', rest = ''] = match
349 const key = `${verb} ${target}`
350 const events = rest.split(/;[ \t]*/).map((part) => part.trim().split(/[ \t]+/)[0] ?? '')
351 if (events.includes('START')) {
352 open.set(key, entry)
353 if (target === 'pending') pending.set(verb, key)
354 }
355 if (events.includes('DONE')) {
356 open.delete(key)
357 const parked = pending.get(verb)
358 if (parked !== undefined) {
359 open.delete(parked)
360 pending.delete(verb)
361 }
362 }
363 }
364 return open
365}
366
367export function vmFindings(file: string, text: string): string[] {
368 const out: string[] = []
369 const status: string[] = []
370 let sec = ''
371 let header = false
372 let colState = 0
373 let colCite = 0
374 for (const row of lines(text)) {
375 if (SEC.any.test(row)) {
376 if (SEC.status.test(row)) sec = 'S'
377 else if (SEC.tasks.test(row)) {
378 sec = 'T'
379 header = false
380 colState = 0
381 colCite = 0
382 } else sec = 'other'
383 continue
384 }
385 if (sec === 'S') {
386 const line = trim(row)
387 if (line === '' || line.startsWith('<!--')) continue
388 if (!STAMPED.test(line)) {
389 out.push(`WARN Vm.2 ${file}: Status line missing ISO timestamp: ${line}`)
390 }
391 status.push(line)
392 }
393 if (sec === 'T') {
394 if (!row.startsWith('|') || RULE_ROW.test(row)) continue
395 const cells = row.split(CELL)
396 if (!header) {
397 header = true
398 const named = columns(row, ['state', 'cite'])
399 colState = named.state ?? 0
400 colCite = named.cite ?? 0
401 if (!colState || !colCite) {
402 const missing = !colState && !colCite ? 'state or cite' : colState ? 'cite' : 'state'
403 out.push(`WARN Vm.3 ${file}: Tasks header names no ${missing} column, so its rows go unchecked`)
404 }
405 continue
406 }
407 if (!colState || !colCite) continue
408 const id = trim(cells[1] ?? '')
409 const state = trim(cells[colState] ?? '')
410 const cite = trim(cells[colCite] ?? '')
411 if (id === 'id' || id === '') continue
412 if (state === 'x' && (cite === '' || cite === '—' || cite === '-')) {
413 out.push(`CRITICAL Vm.3 ${file}: Tasks row ${id} state=x has empty cite`)
414 }
415 }
416 }
417 for (const key of openOps(status).keys()) out.push(`WARN Vm.6 ${file}: Status ${key} START without DONE`)
418 return out
419}
420
421export type IndexRow = { date: string; slug: string; state: string; row: string }
422
423function taskCount(rows: string[]): { done: number; total: number; noState: boolean } {
424 let header = false
425 let colState = 0
426 let done = 0
427 let total = 0
428 let noState = false
429 for (const [, row, inside] of inSection(rows, SEC.tasks)) {
430 if (SEC.tasks.test(row)) {
431 header = false
432 colState = 0
433 continue
434 }
435 if (!inside) continue
436 if (TASK_ROW.test(row)) total++
437 if (!row.startsWith('|') || RULE_ROW.test(row)) continue
438 if (!header) {
439 header = true
440 colState = columns(row, ['state']).state ?? 0
441 if (!colState) noState = true
442 continue
443 }
444 if (TASK_ROW.test(row) && colState && trim(row.split(CELL)[colState] ?? '') === 'x') done++
445 }
446 return { done, total, noState }
447}
448
449export function indexRow(dir: string, text: string, archived: boolean, mtime: string): IndexRow & { warning?: string } {
450 const chars = [...dir]
451 const date = chars.slice(0, 10).join('')
452 const slug = chars.slice(11).join('')
453 const rows = lines(text)
454 const token = headerToken(text)
455 const { done, total, noState } = taskCount(rows)
456 let bugs = 0
457 for (const [, row, inside] of inSection(rows, SEC.bugs)) if (inside && BUG_ROW.test(row)) bugs++
458 const z = zColumn(text)
459 const closed = z !== '—'
460 let state: string
461 if (archived) state = token === 'done' ? 'done' : 'drift!'
462 else if (closed) state = 'drift!'
463 else if (token === 'live' || token === 'paused') state = token
464 else state = 'drift!'
465 const row = `| ${date} | ${slug} | ${state} | ${done}/${total} | ${bugs} | ${mtime} | ${z} |`
466 return { date, slug, state, row, ...(noState ? { warning: 'Tasks header names no state column, so its rows count as not-done' } : {}) }
467}
468
469const RANK: Record<string, number> = { 'drift!': 0, live: 1, paused: 2 }
470
471function byCodeUnit(a: string, b: string): number {
472 return a < b ? -1 : a > b ? 1 : 0
473}
474
475export function renderIndex(rows: IndexRow[]): string {
476 const sorted = [...rows].sort((a, b) => byCodeUnit(b.date, a.date) || (RANK[a.state] ?? 3) - (RANK[b.state] ?? 3) || byCodeUnit(a.row, b.row))
477 let out = '# .scratchpad index\n\n| date | slug | state | T | B | mtime | §Z |\n|------|------|-------|---|---|-------|-----|\n'
478 out += sorted.map((row) => `${row.row}\n`).join('')
479 const drift = rows.filter((row) => row.state === 'drift!')
480 if (drift.length) out += `\n<!-- drift:${drift.length} slugs:${drift.map((row) => `${row.date}-${row.slug}`).join(' ')} -->\n`
481 return out
482}
483engine/progress.ts 158 lines1import { cells } from './converge.ts'
2import { splitLines } from './text.ts'
3
4export type Count = { done: number; total: number }
5
6export type Progress = {
7 all: Count
8 agent: Count
9 operator: Count
10 milestone?: Count & { id: string }
11 active: string[]
12 tail: string[]
13 next: string[]
14 waiting: string[]
15}
16
17export type Row = { id: string; state: string; who: string; task: string; needs: string[]; cite: string; verify: string }
18
19const TASK_ID = /^T\d+$/
20export const DELAYED = /^(T\d+)\+\d+d$/
21
22export function taskRows(text: string): Row[] {
23 const lines = splitLines(text)
24 const start = lines.findIndex((line) => /^##\s+(§T\b|Tasks\b)/.test(line))
25 if (start < 0) return []
26 const rows: Row[] = []
27 let names: string[] = []
28 for (const line of lines.slice(start + 1)) {
29 if (line.startsWith('## ')) break
30 const row = cells(line)
31 if (!row.length) continue
32 if (!names.length) {
33 names = row.map((name) => name.toLowerCase())
34 continue
35 }
36 const at = (name: string): string => row[names.indexOf(name)] ?? ''
37 if (!TASK_ID.test(at('id'))) continue
38 const needs = at('needs')
39 .split(',')
40 .map((need) => need.trim())
41 .filter((need) => need && need !== '—' && need !== '-')
42 rows.push({ id: at('id'), state: at('state'), who: at('who').toUpperCase(), task: at('task'), needs, cite: at('cite'), verify: at('verify') })
43 }
44 return rows
45}
46
47function count(rows: Row[]): Count {
48 return { done: rows.filter((row) => row.state === 'x').length, total: rows.length }
49}
50
51export function progress(text: string, milestone?: string): Progress {
52 const rows = taskRows(text)
53 const done = new Set(rows.filter((row) => row.state === 'x').map((row) => row.id))
54 const ready = (row: Row): boolean => row.state === '.' && row.needs.every((need) => !DELAYED.test(need) && done.has(need))
55 const view: Progress = {
56 all: count(rows),
57 agent: count(rows.filter((row) => row.who === 'A')),
58 operator: count(rows.filter((row) => row.who === 'H')),
59 active: rows.filter((row) => row.state === '~').map((row) => row.id),
60 tail: rows.flatMap((row) => (row.state === 'x' ? [] : row.needs.filter((need) => DELAYED.test(need)).map((need) => `${row.id} ${need}`))),
61 next: rows.filter((row) => row.who === 'A' && ready(row)).map((row) => row.id),
62 waiting: rows.filter((row) => row.who === 'H' && ready(row)).map((row) => row.id),
63 }
64 if (milestone !== undefined && rows.some((row) => row.id === milestone)) {
65 const after = downstream(rows, milestone)
66 view.milestone = { id: milestone, ...count(rows.filter((row) => !after.has(row.id))) }
67 }
68 return view
69}
70
71function downstream(rows: Row[], id: string): Set<string> {
72 const after = new Set<string>()
73 const reaches = (row: Row): boolean =>
74 row.needs.some((need) => {
75 const target = DELAYED.exec(need)?.[1] ?? need
76 return target === id || after.has(target)
77 })
78 let grew = true
79 while (grew) {
80 grew = false
81 for (const row of rows) {
82 if (after.has(row.id) || !reaches(row)) continue
83 after.add(row.id)
84 grew = true
85 }
86 }
87 return after
88}
89
90function percent({ done, total }: Count): string {
91 return `${total ? Math.floor((done * 100) / total) : 0}%`
92}
93
94export function progressLine(slug: string, view: Progress): string {
95 const head = `${slug} ${percent(view.all)} · ${view.all.done}/${view.all.total}`
96 if (view.all.total && view.all.done === view.all.total) return `${head} · ready to close`
97 const later = [...new Set(view.tail.map((entry) => entry.split(' ')[0] ?? ''))]
98 if (later.length && later.length === view.all.total - view.all.done) return `${head} · ready to close · carry ${later.join(' ')}`
99 const parts = [head]
100 if (view.next[0]) parts.push(`next ${view.next[0]}`)
101 if (view.waiting.length) parts.push(`waits on you: ${view.waiting.join(' ')}`)
102 if (!view.next.length && !view.waiting.length && view.active.length) parts.push(`in progress ${view.active.join(' ')}`)
103 return parts.join(' · ')
104}
105
106export type Branch = { row: Row; depth: number; also: string[] }
107
108export function needsTree(rows: readonly Row[]): Branch[] {
109 const ids = new Set(rows.map((row) => row.id))
110 const parents = (row: Row): string[] => row.needs.map((need) => DELAYED.exec(need)?.[1] ?? need).filter((id) => ids.has(id))
111 const out: Branch[] = []
112 const placed = new Set<string>()
113 const walk = (row: Row, depth: number): void => {
114 if (placed.has(row.id)) return
115 placed.add(row.id)
116 out.push({ row, depth, also: parents(row).slice(1) })
117 for (const child of rows) if (parents(child)[0] === row.id) walk(child, depth + 1)
118 }
119 for (const row of rows) if (!parents(row).length) walk(row, 0)
120 for (const row of rows) walk(row, 0)
121 return out
122}
123
124export function ownerLine(view: Progress): string {
125 const parts = [`Agent ${view.agent.done}/${view.agent.total}`, `You ${view.operator.done}/${view.operator.total}`]
126 if (view.milestone) parts.push(`Up to ${view.milestone.id} ${view.milestone.done}/${view.milestone.total}`)
127 if (view.active.length) parts.push(`in progress ${view.active.join(' ')}`)
128 if (view.tail.length) parts.push(`later ${view.tail.map((entry) => entry.replace(' ', ' (') + ')').join(', ')}`)
129 return parts.join(' · ')
130}
131
132export function progressTable(slug: string, view: Progress): string {
133 const rows: [string, Count][] = [
134 ['Agent', view.agent],
135 ['You', view.operator],
136 ]
137 if (view.milestone) rows.push([`Up to ${view.milestone.id}`, view.milestone])
138 const width = Math.max(5, ...rows.map(([label]) => label.length))
139 const out = [`${slug} · ${view.all.done} of ${view.all.total} done · ${percent(view.all)}`, '']
140 out.push(`${'Owner'.padEnd(width)} Done Total Share`)
141 for (const [label, value] of rows) {
142 out.push(`${label.padEnd(width)} ${String(value.done).padEnd(4)} ${String(value.total).padEnd(5)} ${percent(value)}`)
143 }
144 if (view.active.length) out.push('', `In progress, not counted: ${view.active.join(' ')}`)
145 if (view.tail.length) out.push(`After the milestone: ${view.tail.join(', ')}`)
146 return out.join('\n')
147}
148
149const LATER_DAYS = 30
150
151export function laterLine(slug: string, text: string, now: Date): string | undefined {
152 const after = /^after: (.+)$/m.exec(text)?.[1]
153 const closed = /^(\d{4}-\d{2}-\d{2}) \d{2}:\d{2} — closed$/m.exec(text)?.[1]
154 if (!after || !closed) return undefined
155 const age = (now.getTime() - Date.parse(`${closed}T00:00:00Z`)) / 86_400_000
156 return age <= LATER_DAYS ? `later: ${slug} · ${after} · closed ${closed}` : undefined
157}
158hooks/gates.ts 292 lines1import { cells } from '../engine/converge.ts'
2import { editOf, headerDenial, isDossierPath, markerDenial } from '../engine/guards.ts'
3import { indexNames, SEC } from '../engine/ledger.ts'
4import { byCodePoint } from '../engine/text.ts'
5
6export type Io = {
7 isDir: (path: string) => Promise<boolean>
8 read: (path: string) => Promise<string>
9 exists: (path: string) => Promise<boolean>
10 list: (path: string) => Promise<string[]>
11 env: (name: 'DOSSIER_MARKER_GUARD' | 'DOSSIER_INVARIANT_GUARD' | 'DOSSIER_FAKEIMPL_CMD') => Promise<string | undefined>
12 run: (argv: string[], init: { stdin: string; timeoutMs: number; cwd?: string }) => Promise<{ exitCode: number; stdout: string; stderr: string }>
13 cli?: string
14}
15
16export type Verdict = { deny?: string; context?: string }
17
18const INVARIANT_TIMEOUT_MS = 5000
19const VERIFY_TIMEOUT_MS = 10_000
20const VERIFY_FOOTER = '\nsilence a rule for this write: `# verify-skip: <ruleName>` anywhere in the content.'
21const SESSION_TIMEOUT_MS = 60_000
22const PROMPT_TIMEOUT_MS = 10_000
23const STOP_TIMEOUT_MS = 180_000
24const EXIT_NO_NODE = 69
25export const BUILTINS = new Set(['code-review', 'review', 'security-review', 'simplify'])
26const CLOSE = 'dossier:close'
27const GRILLING = new Set(['mattpocock-skills:grilling', 'grilling'])
28const EMPTY_CELL = new Set(['', '—', '-'])
29export const WHETSTONE = new Set([
30 'whetstone:doubt-pass',
31 'whetstone:flaky-test-audit',
32 'whetstone:merge-resolve',
33 'whetstone:skill-smith',
34 'whetstone:tdd-cycle',
35 'whetstone:tiger-style',
36])
37
38async function invariantGate(io: Io, root: string, filePath: string, chunks: string[]): Promise<Verdict> {
39 if ((await io.env('DOSSIER_INVARIANT_GUARD')) === 'off') return {}
40 if (!(await io.exists(`${root}/.scratchpad/dossier/.invariant-guards.json`))) return {}
41 try {
42 const argv = ['sh', io.cli ?? 'cli/ds', 'invariant-check', root]
43 const done = await io.run(argv, { stdin: JSON.stringify({ file_path: filePath, chunks }), timeoutMs: INVARIANT_TIMEOUT_MS })
44 const text = done.stdout.trim()
45 if (done.exitCode === 1 && text) return { deny: text }
46 if (done.exitCode === 0 && text) return { context: text }
47 } catch {
48 return {}
49 }
50 return {}
51}
52
53const PRIMARY = /^worktree (.+)$/m
54
55const roots = new Map<string, string>()
56
57async function gitOut(io: Io, args: string[]): Promise<string | undefined> {
58 try {
59 const done = await io.run(['git', ...args], { stdin: '', timeoutMs: 5000 })
60 return done.exitCode === 0 ? done.stdout : undefined
61 } catch {
62 return undefined
63 }
64}
65
66export async function ledgerRoot(io: Io, cwd: string): Promise<string> {
67 if (await io.isDir(`${cwd}/.scratchpad/dossier`)) return cwd
68 const known = roots.get(cwd)
69 if (known) return known
70 const top = (await gitOut(io, ['-C', cwd, 'rev-parse', '--show-toplevel']))?.trim()
71 const primary = PRIMARY.exec((await gitOut(io, ['-C', cwd, 'worktree', 'list', '--porcelain'])) ?? '')?.[1]
72 let root = cwd
73 for (const dir of [top, primary]) {
74 if (dir && (await io.isDir(`${dir}/.scratchpad/dossier`))) {
75 root = dir
76 break
77 }
78 }
79 roots.set(cwd, root)
80 return root
81}
82
83export async function editGate(io: Io, root: string, input: Record<string, unknown>): Promise<Verdict> {
84 const edit = editOf(input)
85 if (!edit) return {}
86 if (!(await io.isDir(`${root}/.scratchpad/dossier`))) return {}
87 const guarded = (await io.env('DOSSIER_MARKER_GUARD')) !== 'off'
88 const header = guarded ? headerDenial(edit) : undefined
89 if (header) return { deny: header }
90 if (isDossierPath(edit.filePath)) return {}
91 const marker = guarded ? markerDenial(edit) : undefined
92 if (marker) return { deny: marker }
93 return invariantGate(io, root, edit.filePath, edit.chunks)
94}
95
96export async function verifyGate(io: Io, root: string, input: Record<string, unknown>, fired: Set<string>): Promise<string | undefined> {
97 const edit = editOf(input)
98 const content = edit?.chunks[0]
99 if (!edit || !content || isDossierPath(edit.filePath)) return undefined
100 if (!(await io.isDir(`${root}/.scratchpad/dossier`))) return undefined
101 let done: { exitCode: number; stdout: string }
102 try {
103 const argv = ['sh', io.cli ?? 'cli/ds', 'verify-edit', root]
104 done = await io.run(argv, { stdin: JSON.stringify({ file_path: edit.filePath, content }), timeoutMs: VERIFY_TIMEOUT_MS })
105 } catch {
106 return undefined
107 }
108 if (done.exitCode !== 0 || !done.stdout.trim()) return undefined
109 let hits: unknown
110 try {
111 hits = JSON.parse(done.stdout)
112 } catch {
113 return undefined
114 }
115 if (!Array.isArray(hits)) return undefined
116 const lines: string[] = []
117 for (const hit of hits as { key?: unknown; line?: unknown }[]) {
118 if (typeof hit?.key !== 'string' || typeof hit.line !== 'string' || fired.has(hit.key)) continue
119 fired.add(hit.key)
120 lines.push(hit.line)
121 }
122 return lines.length ? `${lines.join('\n')}${VERIFY_FOOTER}` : undefined
123}
124
125async function inFlight(io: Io, root: string, live: string[]): Promise<string | undefined> {
126 const dossiers = `${root}/.scratchpad/dossier`
127 let names: string[]
128 try {
129 names = (await io.list(dossiers)).sort(byCodePoint)
130 } catch {
131 return undefined
132 }
133 for (const name of names) {
134 if (!live.includes(name)) continue
135 const lockPath = `${dossiers}/${name}/.ds-lock`
136 if (!(await io.exists(lockPath))) continue
137 let text: string
138 try {
139 text = await io.read(lockPath)
140 } catch {
141 return name
142 }
143 try {
144 const data: unknown = JSON.parse(text)
145 if (typeof data !== 'object' || data === null || Array.isArray(data)) return name
146 const lock = data as Record<string, unknown>
147 return `${name}: ${String(lock.skill ?? '?')} ${String(lock.target ?? '?')}`
148 } catch {
149 return name
150 }
151 }
152 return undefined
153}
154
155export async function bugGate(io: Io, filePath: string, seen: Set<string>): Promise<string | undefined> {
156 if (!filePath.endsWith('/DOSSIER.md') || !isDossierPath(filePath)) return undefined
157 let text: string
158 try {
159 text = await io.read(filePath)
160 } catch {
161 return undefined
162 }
163 let inside = false
164 let names: string[] = []
165 const bare: string[] = []
166 for (const line of text.split('\n')) {
167 if (line.startsWith('## ')) {
168 inside = SEC.bugs.test(line)
169 names = []
170 continue
171 }
172 const values = inside ? cells(line) : []
173 if (!values.length || /^-+$/.test(values[0] ?? '')) continue
174 if (!names.length) names = values.map((name) => name.toLowerCase())
175 else if (/^B\d+$/.test(values[0] ?? '') && ['invariant added', 'fix cite'].every((name) => EMPTY_CELL.has(values[names.indexOf(name)] ?? ''))) {
176 bare.push(values[0] ?? '')
177 }
178 }
179 const fresh = bare.filter((id) => !seen.has(`${filePath}#${id}`))
180 for (const id of fresh) seen.add(`${filePath}#${id}`)
181 if (!fresh.length) return undefined
182 return `${fresh.join(', ')} ${fresh.length > 1 ? 'have' : 'has'} no invariant yet — ds:backprop ${fresh[0]} registers one before the fix. Reminder only, never blocking.`
183}
184
185function reminder(name: string, paused: string[], live: string | undefined, flight: string | undefined): string | undefined {
186 if (GRILLING.has(name)) {
187 return (
188 'this repo keeps dossier waves — dossier:grill records each decision through ds grill-add, forks a decision on ' +
189 '"discuss more", and ds:new consumes its draft. Prefer it here. Reminder only, never blocking.'
190 )
191 }
192 if (name === CLOSE && paused.length) {
193 return (
194 `${paused.length} paused dossier(s) alongside this close: ${paused.join(', ')}. Decide each one ` +
195 'before the tree loses its current reader — resume it, or close it with ds:close --abandon ' +
196 '"<reason>". Reminder only, never blocking.'
197 )
198 }
199 if (BUILTINS.has(name) && flight) {
200 return (
201 `live dossier build in flight (${flight}) — fold /${name} findings into the ds:build step 6.5 ` +
202 'artifact trail and record the verdict in §S. Reminder only, never blocking.'
203 )
204 }
205 if (WHETSTONE.has(name) && live) {
206 return (
207 `live dossier (${live}) — after this skill's verdict, record the §S line this skill's own rule ` +
208 "calls for via dossier's cli/ds s-append (first live row = current; main thread writes, never " +
209 'subagents). Reminder only, never blocking.'
210 )
211 }
212 return undefined
213}
214
215export async function skillGate(io: Io, root: string, name: string, seen: Set<string>): Promise<string | undefined> {
216 if (!BUILTINS.has(name) && !WHETSTONE.has(name) && !GRILLING.has(name) && name !== CLOSE) return undefined
217 if (seen.has(name)) return undefined
218 let index: string
219 try {
220 index = await io.read(`${root}/.scratchpad/INDEX.md`)
221 } catch {
222 return undefined
223 }
224 const live = indexNames(index, 'live')
225 const paused = name === CLOSE ? indexNames(index, 'paused') : []
226 const flight = BUILTINS.has(name) && live.length ? await inFlight(io, root, live) : undefined
227 const text = reminder(name, paused, live[0], flight)
228 if (text) seen.add(name)
229 return text
230}
231
232export function skillOf(input: Record<string, unknown>): string {
233 return String(input.skill || input.name || '')
234}
235
236export type SessionVerdict = { context?: string; title?: string; toast?: string }
237
238function parsed(text: string): Record<string, unknown> {
239 try {
240 const value: unknown = JSON.parse(text)
241 return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {}
242 } catch {
243 return {}
244 }
245}
246
247function cliFailure(exitCode: number | undefined): string {
248 const why = exitCode === EXIT_NO_NODE ? 'needs Node.js 22.18+' : `failed${exitCode === undefined ? '' : ` (exit ${exitCode})`}`
249 return `dossier: cli/ds ${why}; stale locks, reconcile and INDEX.md were not refreshed.`
250}
251
252export async function sessionGate(io: Io, root: string, input: { source: string; session_title: string }): Promise<SessionVerdict> {
253 if (!(await io.isDir(`${root}/.scratchpad/dossier`))) return {}
254 let done: { exitCode: number; stdout: string }
255 try {
256 const argv = ['sh', io.cli ?? 'cli/ds', 'session-start']
257 done = await io.run(argv, { stdin: JSON.stringify(input), timeoutMs: SESSION_TIMEOUT_MS, cwd: root })
258 } catch {
259 return { context: cliFailure(undefined) }
260 }
261 if (done.exitCode !== 0) return { context: cliFailure(done.exitCode) }
262 const output = parsed(done.stdout)
263 const nested = output.hookSpecificOutput
264 const specific = typeof nested === 'object' && nested !== null ? (nested as Record<string, unknown>) : {}
265 const text = (value: unknown): string | undefined => (typeof value === 'string' && value ? value : undefined)
266 return { context: text(specific.additionalContext), title: text(specific.sessionTitle), toast: text(output.systemMessage) }
267}
268
269export async function promptGate(io: Io, root: string, from: string = root): Promise<string | undefined> {
270 if (!(await io.isDir(`${root}/.scratchpad/dossier`))) return undefined
271 try {
272 const argv = ['sh', io.cli ?? 'cli/ds', 'convergence-state']
273 const done = await io.run(argv, { stdin: JSON.stringify({ cwd: root, from }), timeoutMs: PROMPT_TIMEOUT_MS, cwd: root })
274 const text = done.stdout.trim()
275 return done.exitCode === 0 && text ? text : undefined
276 } catch {
277 return undefined
278 }
279}
280
281export async function stopGate(io: Io, root: string): Promise<string | undefined> {
282 if (!(await io.env('DOSSIER_FAKEIMPL_CMD'))?.trim()) return undefined
283 try {
284 const argv = ['sh', io.cli ?? 'cli/ds', 'fakeimpl']
285 const done = await io.run(argv, { stdin: '{}', timeoutMs: STOP_TIMEOUT_MS, cwd: root })
286 const output = parsed(done.stdout)
287 return done.exitCode === 0 && output.decision === 'block' && typeof output.reason === 'string' ? output.reason : undefined
288 } catch {
289 return undefined
290 }
291}
292engine/text.ts 63 lines1const WORD_SET = '\\p{L}\\p{N}_'
2const SPACE_SET = '\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000'
3const DIGIT_SET = '\\p{Nd}'
4const WORD = `[${WORD_SET}]`
5const BOUNDARY = `(?:(?<=${WORD})(?!${WORD})|(?<!${WORD})(?=${WORD}))`
6const LINE_BREAK = /\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/
7const EDGE_SPACE = new RegExp(`^[${SPACE_SET}]+|[${SPACE_SET}]+$`, 'gu')
8
9const IN_CLASS: Record<string, string> = { w: WORD_SET, s: SPACE_SET, d: DIGIT_SET }
10const OUTSIDE: Record<string, string> = {
11 w: WORD,
12 s: `[${SPACE_SET}]`,
13 d: `[${DIGIT_SET}]`,
14 b: BOUNDARY,
15 W: `[^${WORD_SET}]`,
16 S: `[^${SPACE_SET}]`,
17 D: `[^${DIGIT_SET}]`,
18 B: `(?:(?<=${WORD})(?=${WORD})|(?<!${WORD})(?!${WORD}))`,
19}
20
21export function unicodeRegex(source: string, flags = ''): RegExp {
22 let out = ''
23 let inClass = false
24 for (let i = 0; i < source.length; i++) {
25 const char = source[i] ?? ''
26 if (char === '\\') {
27 const next = source[i + 1] ?? ''
28 i++
29 const table = inClass ? IN_CLASS : OUTSIDE
30 out += table[next] ?? `\\${next}`
31 continue
32 }
33 if (char === '[' && !inClass) inClass = true
34 else if (char === ']' && inClass) inClass = false
35 out += char
36 }
37 return new RegExp(out, `${flags}u`)
38}
39
40export const CELL = /(?<!\\)\|/
41
42export function strip(text: string): string {
43 return text.replace(EDGE_SPACE, '')
44}
45
46export function splitLines(text: string): string[] {
47 if (!text) return []
48 const lines = text.split(LINE_BREAK)
49 if (lines[lines.length - 1] === '') lines.pop()
50 return lines
51}
52
53export function byCodePoint(a: string, b: string): number {
54 const left = [...a]
55 const right = [...b]
56 for (let i = 0; i < Math.min(left.length, right.length); i++) {
57 const x = left[i]?.codePointAt(0) ?? 0
58 const y = right[i]?.codePointAt(0) ?? 0
59 if (x !== y) return x - y
60 }
61 return left.length - right.length
62}
63engine/guards.ts 111 lines1import { compilePython, fnmatch } from './pyregex.ts'
2import { HEADER } from './ledger.ts'
3import { splitLines, strip, unicodeRegex } from './text.ts'
4
5const COMMENT_PREFIX = String.raw`^\s*(?://+|#+|--|/\*+|\*(?!/)|<!--|;)\s*`
6const MARKER_PATTERNS = [unicodeRegex(COMMENT_PREFIX + String.raw`.*\bPH\d+-[A-Z]\d+\b`), unicodeRegex(COMMENT_PREFIX + '.*§[VBTSXGZ]\\d+')]
7const CANONICAL_STATES = new Set(['live', 'done', 'paused'])
8
9export type Edit = { filePath: string; chunks: string[] }
10
11export type Guard = { id?: unknown; pattern?: unknown; message?: unknown; paths?: unknown }
12
13function posix(path: string): string {
14 const absolute = path.startsWith('/')
15 const parts = path.split('/').filter((part) => part !== '' && part !== '.')
16 const joined = parts.join('/')
17 return absolute ? `/${joined}` : joined || '.'
18}
19
20function baseName(path: string): string {
21 return posix(path).split('/').pop() ?? ''
22}
23
24export function editOf(input: Record<string, unknown>): Edit | undefined {
25 if (input.tool !== 'Edit' && input.tool !== 'Write') return undefined
26 const path = input.file_path || input.path
27 if (!path) return undefined
28 const text = input.tool === 'Write' ? input.content : input.new_string
29 if (typeof text !== 'string') return undefined
30 return { filePath: String(path), chunks: [text] }
31}
32
33export function isDossierPath(path: string): boolean {
34 return posix(path).includes('.scratchpad/') || baseName(path) === 'DOSSIER.md'
35}
36
37export function headerDenial({ filePath, chunks }: Edit): string | undefined {
38 if (baseName(filePath) !== 'DOSSIER.md') return undefined
39 for (const line of chunks.flatMap(splitLines)) {
40 const token = strip(HEADER.exec(line)?.[1] ?? '')
41 if (token && !CANONICAL_STATES.has(token)) {
42 return (
43 `dossier: refusing to write non-canonical header state '${token}'.\n` +
44 ' canonical header states: live | done | paused.\n' +
45 ' route header changes through cli/ds header-state ' +
46 '(ds:close flips done; ds:status pause/resume) — not a raw Edit/Write.'
47 )
48 }
49 }
50 return undefined
51}
52
53export function markerDenial({ filePath, chunks }: Edit): string | undefined {
54 const line = chunks.flatMap(splitLines).find((text) => MARKER_PATTERNS.some((pattern) => pattern.test(text)))
55 if (line === undefined) return undefined
56 return [
57 `dossier marker guard: '${filePath}' carries a dossier audit-id marker.`,
58 ` offending line: ${strip(line)}`,
59 '',
60 'Audit-id markers (`PH3-B7`) and §-cites (`§V26`) belong in the',
61 'DOSSIER.md §B/§V ledger + commit trailer, not source. Drop the',
62 'marker; keep any why-tail (workaround ref, invariant, upstream-bug',
63 'link). Bypass: DOSSIER_MARKER_GUARD=off.',
64 ].join('\n')
65}
66
67function inScope(path: string, paths: unknown): boolean {
68 if (!Array.isArray(paths) || paths.length === 0) return true
69 return paths.some((glob) => typeof glob === 'string' && fnmatch(posix(path), glob))
70}
71
72export function parseRegistry(text: string): Guard[] {
73 try {
74 const data: unknown = JSON.parse(text)
75 if (!Array.isArray(data)) return []
76 return data.filter((entry): entry is Guard => typeof entry === 'object' && entry !== null && !Array.isArray(entry))
77 } catch {
78 return []
79 }
80}
81
82export function invariantVerdict({ filePath, chunks }: Edit, registry: Guard[]): { deny?: string; skipped: string[] } {
83 const skipped: string[] = []
84 for (const entry of registry) {
85 if (typeof entry.pattern !== 'string' || !entry.pattern) continue
86 if (!inScope(filePath, entry.paths)) continue
87 const compiled = compilePython(entry.pattern)
88 if (!compiled) {
89 skipped.push(String(entry.id ?? '?'))
90 continue
91 }
92 if (chunks.some((chunk) => compiled.test(chunk))) {
93 const deny =
94 `dossier invariant guard: edit to '${filePath}' violates §V ${String(entry.id ?? '?')}.\n` +
95 ` pattern: ${entry.pattern}\n` +
96 ` ${String(entry.message ?? '')}\n` +
97 ' registered by ds:backprop (recurrence=high). Legit edit? set ' +
98 'DOSSIER_INVARIANT_GUARD=off and log the rationale in §S.'
99 return { deny, skipped }
100 }
101 }
102 return { skipped }
103}
104
105export function skippedAdvisory(skipped: string[]): string {
106 return (
107 `dossier invariant guard: §V ${skipped.join(', ')} not checked — the pattern has no ECMAScript ` +
108 'meaning. Re-register it in JS regex syntax in .scratchpad/dossier/.invariant-guards.json.'
109 )
110}
111engine/pyregex.ts 112 lines1import { unicodeRegex } from './text.ts'
2
3const LEADING_FLAGS = /^\(\?([a-zA-Z]+)\)/
4const FLAGS: Record<string, string> = { i: 'i', s: 's', m: 'm', u: '' }
5const NEGATED_IN_CLASS = new Set(['W', 'S', 'D'])
6
7function translate(source: string, flags: string): string | undefined {
8 const multiline = flags.includes('m')
9 const dotAll = flags.includes('s')
10 let out = ''
11 let inClass = false
12 for (let i = 0; i < source.length; i++) {
13 const char = source[i] ?? ''
14 if (char === '\\') {
15 const point = source.codePointAt(i + 1) ?? 0
16 const next = String.fromCodePoint(point)
17 i += next.length
18 if (inClass && NEGATED_IN_CLASS.has(next)) return undefined
19 if (next === 'A' && !inClass) out += '(?<![\\s\\S])'
20 else if (next === 'Z' && !inClass) out += '(?![\\s\\S])'
21 else if (/^[\p{L}\p{N}]$/u.test(next)) out += `\\${next}`
22 else out += `\\u{${point.toString(16)}}`
23 continue
24 }
25 if (inClass) {
26 if (char === ']') inClass = false
27 out += char
28 continue
29 }
30 if (char === '[') {
31 inClass = true
32 out += char
33 if (source[i + 1] === '^') out += source[++i]
34 if (source[i + 1] === ']') {
35 out += '\\]'
36 i++
37 }
38 continue
39 }
40 if (source.startsWith('(?P<', i)) {
41 out += '(?<'
42 i += 3
43 continue
44 }
45 const backref = /^\(\?P=(\w+)\)/.exec(source.slice(i))
46 if (backref) {
47 out += `\\k<${backref[1]}>`
48 i += backref[0].length - 1
49 continue
50 }
51 if (char === '.') out += dotAll ? '[\\s\\S]' : '[^\\n]'
52 else if (char === '^') out += multiline ? '(?<![^\\n])' : '^'
53 else if (char === '$') out += multiline ? '(?![^\\n])' : '(?=\\n?(?![\\s\\S]))'
54 else out += char
55 }
56 return out
57}
58
59export function compilePython(pattern: string): RegExp | undefined {
60 let flags = ''
61 let body = pattern
62 const leading = LEADING_FLAGS.exec(pattern)
63 if (leading) {
64 for (const flag of leading[1] ?? '') {
65 const js = FLAGS[flag]
66 if (js === undefined) return undefined
67 if (!flags.includes(js)) flags += js
68 }
69 body = pattern.slice(leading[0].length)
70 }
71 const source = translate(body, flags)
72 if (source === undefined) return undefined
73 try {
74 return unicodeRegex(source, flags.includes('i') ? 'i' : '')
75 } catch {
76 return undefined
77 }
78}
79
80function globClass(inner: string): string {
81 const negated = inner.startsWith('!')
82 const body = (negated ? inner.slice(1) : inner).replaceAll('\\', '\\\\').replaceAll(']', '\\]').replaceAll('[', '\\[')
83 if (negated) return `[^${body}]`
84 return body.startsWith('^') ? `[\\${body}]` : `[${body}]`
85}
86
87export function fnmatch(name: string, glob: string): boolean {
88 let out = ''
89 for (let i = 0; i < glob.length; i++) {
90 const char = glob[i] ?? ''
91 if (char === '*') out += '[\\s\\S]*'
92 else if (char === '?') out += '[\\s\\S]'
93 else if (char === '[') {
94 let j = i + 1
95 if (glob[j] === '!') j++
96 if (glob[j] === ']') j++
97 while (j < glob.length && glob[j] !== ']') j++
98 if (j >= glob.length) {
99 out += '\\['
100 continue
101 }
102 out += globClass(glob.slice(i + 1, j))
103 i = j
104 } else out += char.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
105 }
106 try {
107 return new RegExp(`^(?:${out})$`, 'u').test(name)
108 } catch {
109 return false
110 }
111}
112types/index.d.ts 8 lines1export type DossierWave = { slug: string; text: string; milestone?: string }
2
3declare module 'claude-code' {
4 interface PluginState {
5 dossier: { wave: DossierWave | null }
6 }
7}
8