@cratis/pi 7.146.0 → 7.147.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,6 +17,7 @@ Three layers:
17
17
  | Cleanup of delivered work | `PostToolUse` on `Bash` (`gh pr merge`, `git pull/merge/worktree`) and `SessionStart` (Pi: `tool_result` and `session_start`) | `scripts/cratis-cleanup-worktrees.sh --hook` | zero when the command is unrelated | never blocks; removes delivered worktrees and branches, reports what it kept |
18
18
  | Quality gate (Claude) | `Stop` | `scripts/cratis-quality-gate.sh` | one build/test run, only when relevant files changed | exits **2** — the turn does not end |
19
19
  | Quality gate (Pi) | explicit `cratis_quality_gate` tool | same script | only at a requested verification checkpoint | error on failure; no turn-end hook |
20
+ | Handoff checker | not wired: run by the skill | `scripts/cratis-check-handoff.mjs` | local files and git only | errors fail; warnings are advisory unless `--strict` |
20
21
 
21
22
  For false positives, a literal-prefix trailing `*`, including literal directory components, can be
22
23
  resolved in a known, readable cwd and parent directory. A single reader may stand alone or appear in
@@ -504,6 +505,26 @@ build (with `-p:CratisProxiesOutputPath=` per `general.md`, so the proxy generat
504
505
  re-run and touch already-correct generated files), frontend lint / compile / compile-specs /
505
506
  test.
506
507
 
508
+ ## Handoff checker
509
+
510
+ The `cratis-session-handoff` skill runs the harness-neutral validator before ending:
511
+
512
+ ```bash
513
+ node .cratis/ai/hooks/scripts/cratis-check-handoff.mjs .ai-work/<task>/handoff.md
514
+ ```
515
+
516
+ It checks the fixed template, paths, watch actions, branch/HEAD and state-note freshness.
517
+ With no path it selects the newest `.ai-work/*/handoff*.md`. Use `--repo <dir>` or
518
+ `--state-note <path>` to override those inputs, `--json` for one report object, and
519
+ `--strict` to promote warnings to errors. Exit **0** means no errors, **1** means
520
+ validation failed, and **2** means invalid arguments or an unreadable/non-handoff input.
521
+ Git checks degrade to explicit skips offline or outside a repository; no network is used.
522
+
523
+ This is not an agent-stop hook: a hook cannot reliably choose the active handoff,
524
+ a moved-HEAD warning must not trap a deliberately ending session, and Pi has no
525
+ turn-end hook. Follow-up: consider Stop wiring when a handoff newer than the last
526
+ commit can be identified without guessing; keep the standalone command portable.
527
+
507
528
  ## The package drift guards
508
529
 
509
530
  Three scripts sit outside the three layers and are not bound to a hook event: run
@@ -0,0 +1,294 @@
1
+ #!/usr/bin/env node
2
+ // Copyright (c) Cratis. All rights reserved.
3
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
4
+
5
+ import { spawnSync } from 'node:child_process';
6
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
7
+ import { dirname, join, resolve } from 'node:path';
8
+ import { parseArgs } from 'node:util';
9
+
10
+ const headings = [
11
+ 'Goal', 'Repositories and worktrees', 'Verified facts (with evidence)',
12
+ 'Plans and hypotheses (not verified)', 'Watch and action', 'Finished, results not yet read',
13
+ 'Open questions carried forward', 'User constraints (verbatim)',
14
+ 'User instructions since the last handoff (verbatim)', 'Next commands', 'Files to read',
15
+ ];
16
+ const repositoryHeader = ['Path', 'Repository', 'Branch', 'HEAD (full SHA)', 'State', 'Ahead/behind'];
17
+ const watchHeader = ['Id', 'Target (immutable)', 'Action on completion', 'How to cancel'];
18
+ const clean = value => value.trim().replace(/^`(.*)`$/, '$1').trim();
19
+ const absent = value => !value || clean(value).toLowerCase() === 'none';
20
+
21
+ function git(directory, args) {
22
+ const result = spawnSync('git', ['-C', directory, ...args], { encoding: 'utf8', timeout: 15_000 });
23
+ return {
24
+ ok: result.status === 0,
25
+ output: result.stdout?.trim() || '',
26
+ reason: result.stderr?.trim() || result.error?.message || `git exited ${result.status}`,
27
+ status: result.status,
28
+ };
29
+ }
30
+
31
+ function argumentsFor(argv) {
32
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {
33
+ json: { type: 'boolean' }, strict: { type: 'boolean' },
34
+ repo: { type: 'string' }, 'state-note': { type: 'string' },
35
+ } });
36
+ if (positionals.length > 1) throw new Error('Expected at most one handoff path.');
37
+ return { ...values, path: positionals[0] };
38
+ }
39
+
40
+ function fallbackRoot(directory) {
41
+ let current = directory;
42
+ while (true) {
43
+ if (existsSync(join(current, '.ai-work'))) return current;
44
+ const parent = dirname(current);
45
+ if (parent === current) return directory;
46
+ current = parent;
47
+ }
48
+ }
49
+
50
+ function newestHandoff(root) {
51
+ const work = join(root, '.ai-work');
52
+ if (!existsSync(work)) throw new Error(`No handoff found under ${work}.`);
53
+ const candidates = readdirSync(work, { withFileTypes: true }).filter(entry => entry.isDirectory())
54
+ .flatMap(entry => readdirSync(join(work, entry.name))
55
+ .filter(name => /^handoff.*\.md$/.test(name)).map(name => join(work, entry.name, name)))
56
+ .filter(path => statSync(path).isFile())
57
+ .sort((left, right) => statSync(right).mtimeMs - statSync(left).mtimeMs || left.localeCompare(right));
58
+ if (!candidates.length) throw new Error(`No handoff found under ${work}/*/handoff*.md.`);
59
+ return candidates[0];
60
+ }
61
+
62
+ function input(options) {
63
+ const start = resolve(options.repo || process.cwd());
64
+ const discoveryRoot = git(start, ['rev-parse', '--show-toplevel']);
65
+ const searchRoot = options.repo ? start : discoveryRoot.output || fallbackRoot(start);
66
+ const handoff = options.path ? resolve(options.path) : newestHandoff(searchRoot);
67
+ const body = readFileSync(handoff, 'utf8');
68
+ if (!/^# Handoff:.*$/m.test(body)) throw new Error(`Not a handoff: ${handoff} (missing # Handoff: title).`);
69
+ const repository = git(options.repo ? start : dirname(handoff), ['rev-parse', '--show-toplevel']);
70
+ const repoRoot = options.repo ? start : repository.output || fallbackRoot(dirname(handoff));
71
+ return { handoff, body, repoRoot, hasGit: repository.ok };
72
+ }
73
+
74
+ function findings(options, document) {
75
+ const report = { ok: true, handoff: document.handoff, repoRoot: document.repoRoot, errors: [], warnings: [], skipped: [] };
76
+ const add = (severity, code, message, line) => {
77
+ if (options.strict && severity === 'warning') severity = 'error';
78
+ const finding = { severity, code, message, ...(line ? { line } : {}) };
79
+ report[severity === 'error' ? 'errors' : 'warnings'].push(finding);
80
+ };
81
+ return {
82
+ report,
83
+ error: (code, message, line) => add('error', code, message, line),
84
+ warning: (code, message, line) => add('warning', code, message, line),
85
+ skip: (check, reason) => report.skipped.push({ check, reason }),
86
+ };
87
+ }
88
+
89
+ function splitSections(body) {
90
+ const sections = new Map();
91
+ const order = [];
92
+ let section;
93
+ for (const [index, text] of body.split(/\r?\n/).entries()) {
94
+ if (text.startsWith('## ')) {
95
+ const name = text.slice(3);
96
+ order.push(name);
97
+ section = { line: index + 1, lines: [] };
98
+ sections.set(name, section);
99
+ } else if (section) section.lines.push({ text, line: index + 1 });
100
+ }
101
+ return { sections, order };
102
+ }
103
+
104
+ function checkSection(name, section, context) {
105
+ if (!section) context.error('section-missing', `Missing section: ${name}.`);
106
+ else if (!section.lines.some(item => item.text.trim())) context.warning('section-empty', `Write none in empty section: ${name}.`, section.line);
107
+ }
108
+
109
+ function sectionsOf(body, context) {
110
+ const { sections, order } = splitSections(body);
111
+ for (const name of headings) checkSection(name, sections.get(name), context);
112
+ const expected = headings.filter(name => sections.has(name));
113
+ if (order.join('\n') !== expected.join('\n')) context.error('section-order', 'Sections must use the template headings in order.');
114
+ return sections;
115
+ }
116
+
117
+ function cellsOf(text) {
118
+ return text.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(clean);
119
+ }
120
+
121
+ function tableRows(section, header, context) {
122
+ if (!section) return [];
123
+ const lines = section.lines.filter(item => item.text.trim().startsWith('|'));
124
+ const first = lines[0];
125
+ if (!first || JSON.stringify(cellsOf(first.text)) !== JSON.stringify(header)) {
126
+ context.error('table-header', `Expected table header: | ${header.join(' | ')} |.`, first?.line || section.line);
127
+ return [];
128
+ }
129
+ return lines.slice(1).filter(item => !/^\|?\s*:?-+/.test(item.text.trim()))
130
+ .map(item => ({ cells: cellsOf(item.text), line: item.line }));
131
+ }
132
+
133
+ function bullets(section) {
134
+ return (section?.lines || []).filter(item => /^\s*[-*+]\s+/.test(item.text))
135
+ .map(item => ({ text: item.text.replace(/^\s*[-*+]\s+/, '').trim(), line: item.line }));
136
+ }
137
+
138
+ function pathFrom(root, value) {
139
+ const path = clean(value);
140
+ if (absent(path) || path.startsWith('~')) return undefined;
141
+ return resolve(root, path);
142
+ }
143
+
144
+ function firstCodeSpan(text) {
145
+ return /`([^`]+)`/.exec(text)?.[1];
146
+ }
147
+
148
+ const looksLikePath = value => !/\s/.test(value) && (value.includes('/') || /\.[A-Za-z0-9]+$/.test(value));
149
+
150
+ function readPaths(sections, root, context) {
151
+ const paths = bullets(sections.get('Files to read'))
152
+ .map(item => ({ ...item, text: firstCodeSpan(item.text) ?? clean(item.text) }))
153
+ .filter(item => !absent(item.text));
154
+ for (const item of paths) {
155
+ const path = pathFrom(root, item.text);
156
+ if (!path || !existsSync(path)) context.error('files-to-read-missing', `Cannot resolve Files to read path: ${item.text}.`, item.line);
157
+ }
158
+ return paths;
159
+ }
160
+
161
+ function watchRows(rows, context) {
162
+ for (const { cells, line } of rows) {
163
+ const [id, target = '', action = '', cancel = ''] = cells;
164
+ if (absent(id)) continue;
165
+ if (absent(action)) context.error('watch-action-missing', `Watch ${id} needs an Action on completion.`, line);
166
+ if (absent(target) || /^(latest|the PR|current)$/i.test(target)) context.error('watch-target-mutable', `Watch ${id} needs an immutable target, not ${target || 'an empty cell'}.`, line);
167
+ if (absent(cancel)) context.warning('watch-cancel-missing', `Watch ${id} needs How to cancel.`, line);
168
+ }
169
+ }
170
+
171
+ function unreadResults(section, root, context) {
172
+ for (const item of bullets(section)) {
173
+ for (const match of item.text.matchAll(/`([^`]+)`/g)) {
174
+ if (!looksLikePath(match[1])) continue;
175
+ const path = pathFrom(root, match[1]);
176
+ if (!path || !existsSync(path)) context.warning('result-missing', `Unread result path does not exist: ${match[1]}.`, item.line);
177
+ }
178
+ }
179
+ }
180
+
181
+ function gitValue(directory, args, label, context) {
182
+ const result = git(directory, args);
183
+ if (!result.ok) context.skip(label, result.reason);
184
+ return result.ok ? result.output : undefined;
185
+ }
186
+
187
+ function compareBranch(repository, branch, context) {
188
+ const { directory, label, line } = repository;
189
+ const actual = gitValue(directory, ['branch', '--show-current'], `${label}: branch`, context);
190
+ if (actual !== undefined && actual !== branch) context.error('branch-mismatch', `${label}: branch is ${actual || '(detached)'}, recorded ${branch}.`, line);
191
+ }
192
+
193
+ function compareHead(repository, recorded, context) {
194
+ const { directory, label, line } = repository;
195
+ if (!/^[a-f\d]{40}$/i.test(recorded)) {
196
+ context.error('sha-malformed', `${label}: expected a full 40-character hexadecimal SHA, got ${recorded}.`, line);
197
+ return;
198
+ }
199
+ const actual = gitValue(directory, ['rev-parse', 'HEAD'], `${label}: HEAD`, context);
200
+ if (actual === undefined || actual === recorded.toLowerCase()) return;
201
+ const ancestry = git(directory, ['merge-base', '--is-ancestor', recorded, actual]);
202
+ if (ancestry.ok) context.warning('head-moved', `${label}: HEAD moved from ${recorded} to ${actual}.`, line);
203
+ else if (ancestry.status === 1 || /(?:not a valid|bad object|invalid|unknown revision)/i.test(ancestry.reason)) {
204
+ context.error('head-unrelated', `${label}: recorded HEAD ${recorded} is not an ancestor of ${actual}.`, line);
205
+ } else context.skip(`${label}: ancestry`, ancestry.reason);
206
+ }
207
+
208
+ function checkRepository(row, document, context) {
209
+ const [path, , branch = '', sha = ''] = row.cells;
210
+ if (absent(path)) return undefined;
211
+ const directory = pathFrom(document.repoRoot, path);
212
+ if (!directory || !existsSync(directory)) {
213
+ context.error('worktree-missing', `Cannot resolve worktree: ${path}.`, row.line);
214
+ context.skip(`repository ${path}`, `worktree-missing: ${path}`);
215
+ return undefined;
216
+ }
217
+ if (!document.hasGit) {
218
+ context.skip(`repository ${path}`, 'no-git-repository');
219
+ return undefined;
220
+ }
221
+ const repository = { directory, branch, sha, line: row.line, label: path };
222
+ compareBranch(repository, branch, context);
223
+ compareHead(repository, sha, context);
224
+ return repository;
225
+ }
226
+
227
+ function preconditions(body, first, context) {
228
+ if (!first) return;
229
+ const text = body.split(/^## /m)[0];
230
+ const branch = /\bbranch\s+`([^`]+)`/i.exec(text)?.[1];
231
+ const sha = /\bHEAD\s+`([^`]+)`/.exec(text)?.[1];
232
+ const repository = { ...first, label: 'preconditions', line: undefined };
233
+ if (branch && branch !== first.branch) compareBranch(repository, branch, context);
234
+ if (sha && sha !== first.sha) compareHead(repository, sha, context);
235
+ }
236
+
237
+ function stateNotePath(options, document, paths) {
238
+ const named = paths.find(item => /(^|\/)STATE\.md$/.test(item.text));
239
+ const sibling = join(dirname(document.handoff), 'STATE.md');
240
+ const value = options['state-note'] || named?.text || sibling;
241
+ return pathFrom(document.repoRoot, value);
242
+ }
243
+
244
+ function stateNote(note, first, document, context) {
245
+ if (!note || !existsSync(note)) {
246
+ context.skip('state-note', 'no-state-note');
247
+ return;
248
+ }
249
+ if (!first) {
250
+ context.skip('state-note', document.hasGit ? 'no-repository-row' : 'no-git-repository');
251
+ return;
252
+ }
253
+ const timestamp = gitValue(first.directory, ['log', '-1', '--format=%ct'], 'state-note: commit time', context);
254
+ if (timestamp !== undefined && statSync(note).mtimeMs < Number(timestamp) * 1000) {
255
+ context.warning('state-note-stale', `State note ${note} is older than the branch tip.`);
256
+ }
257
+ }
258
+
259
+ function validate(options, document) {
260
+ const context = findings(options, document);
261
+ const sections = sectionsOf(document.body, context);
262
+ const rows = tableRows(sections.get('Repositories and worktrees'), repositoryHeader, context);
263
+ const watches = tableRows(sections.get('Watch and action'), watchHeader, context);
264
+ const paths = readPaths(sections, document.repoRoot, context);
265
+ watchRows(watches, context);
266
+ unreadResults(sections.get('Finished, results not yet read'), document.repoRoot, context);
267
+ const checked = rows.map(row => checkRepository(row, document, context));
268
+ preconditions(document.body, checked[0], context);
269
+ stateNote(stateNotePath(options, document, paths), checked[0], document, context);
270
+ if (!document.hasGit) context.skip('git preconditions', 'no-git-repository');
271
+ context.report.ok = context.report.errors.length === 0;
272
+ return context.report;
273
+ }
274
+
275
+ function print(report, json) {
276
+ if (json) {
277
+ console.log(JSON.stringify(report));
278
+ return;
279
+ }
280
+ console.log(`handoff: ${report.handoff} (repo root: ${report.repoRoot})`);
281
+ for (const finding of [...report.errors, ...report.warnings]) console.log(`${finding.severity} ${finding.code}: ${finding.message}`);
282
+ for (const skipped of report.skipped) console.log(`skipped: ${skipped.check}: ${skipped.reason}`);
283
+ console.log(`handoff ${report.ok ? 'OK' : 'FAILED'} (${report.errors.length} errors, ${report.warnings.length} warnings, ${report.skipped.length} checks skipped)`);
284
+ }
285
+
286
+ try {
287
+ const options = argumentsFor(process.argv.slice(2));
288
+ const report = validate(options, input(options));
289
+ print(report, options.json);
290
+ process.exitCode = report.ok ? 0 : 1;
291
+ } catch (error) {
292
+ console.error(error.message);
293
+ process.exitCode = 2;
294
+ }
@@ -52,8 +52,11 @@ When the context is nearly full:
52
52
  3. Write the handoff from it. Read
53
53
  [references/handoff-template.md](references/handoff-template.md) for the
54
54
  fixed structure, the rules for filling it and a worked example.
55
- 4. Verify it: check every precondition against `git`, confirm each section is
56
- present, confirm every running job has a full watch row.
55
+ 4. Verify it: run `node .cratis/ai/hooks/scripts/cratis-check-handoff.mjs .ai-work/<task>/handoff.md`;
56
+ fix every error and either fix or acknowledge each warning (a moved HEAD means
57
+ update the table). Where the script is not installed, check by hand:
58
+ preconditions against `git`, each section present, every running job with a
59
+ full watch row.
57
60
  5. End the session, or reset it with your harness's compaction or new-session
58
61
  command, starting from the handoff.
59
62
 
@@ -102,4 +105,5 @@ resetting anything.
102
105
  A handoff is complete when every heading of the template is present in order,
103
106
  the repositories and watch tables use the exact header rows, every running job,
104
107
  CI watch and subagent has a row with an immutable target, and each user quote
105
- is verbatim.
108
+ is verbatim. Run `node .cratis/ai/hooks/scripts/cratis-check-handoff.mjs .ai-work/<task>/handoff.md`;
109
+ the checker exits 0. Fix or acknowledge its warnings before ending the session.
@@ -8,6 +8,8 @@
8
8
  { "kind": "skill-contains", "value": "never mid-atomic-step" },
9
9
  { "kind": "skill-contains", "value": "A stale handoff is not a lost one" },
10
10
  { "kind": "skill-contains", "value": "A truncated view is never gate evidence" },
11
- { "kind": "skill-contains", "value": "cratis-orchestration-lanes" }
11
+ { "kind": "skill-contains", "value": "cratis-orchestration-lanes" },
12
+ { "kind": "skill-contains", "value": "cratis-check-handoff.mjs" },
13
+ { "kind": "skill-contains", "value": "exits 0" }
12
14
  ]
13
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.146.0",
3
+ "version": "7.147.1",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [