@cratis/pi 7.3.4 → 7.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package/corpus/harnesses/pi/extensions/cratis-hooks/index.ts +19 -2
- package/package/corpus/hooks/README.md +59 -3
- package/package/corpus/hooks/scripts/cratis-check-pr.mjs +397 -0
- package/package/corpus/hooks/scripts/cratis-guard-pr-body.sh +41 -0
- package/package/corpus/hooks/scripts/cratis-release-notes-reviewed.cjs +867 -0
- package/package/corpus/hooks/settings.template.json +4 -0
- package/package/corpus/prompts/ship-changes.prompt.md +7 -2
- package/package/corpus/rules/pull-requests.md +15 -5
- package/package/corpus/skills/cratis-release-notes/SKILL.md +10 -7
- package/package/corpus/skills/cratis-release-notes/verification.json +4 -1
- package/package.json +1 -1
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Claude PreToolUse (Write|Edit) → Pi `tool_call` → cratis-guard-writes.sh (exit 2 = block)
|
|
10
10
|
* Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-store-mutations.sh (exit 2 = block)
|
|
11
|
+
* Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-pr-body.sh (exit 2 = block)
|
|
11
12
|
* Claude PostToolUse (Write|Edit) → Pi `tool_result` → cratis-pattern-scan.sh (advisory context)
|
|
12
13
|
* Explicit Pi `cratis_quality_gate` tool → cratis-quality-gate.sh (exit 2 = failed)
|
|
13
14
|
*
|
|
@@ -99,6 +100,13 @@ function runScript(script: string, stdinJson: string, cwd: string, signal?: Abor
|
|
|
99
100
|
if (signal.aborted) kill();
|
|
100
101
|
else signal.addEventListener("abort", kill, { once: true });
|
|
101
102
|
}
|
|
103
|
+
// A script that exits before reading stdin (or doesn't read it at all) closes its end of the
|
|
104
|
+
// pipe first; the write then fails with EPIPE asynchronously, after this try/catch has already
|
|
105
|
+
// returned. Without a listener here that surfaces as an unhandled 'error' event and crashes the
|
|
106
|
+
// process, even though the exit code the close handler already captured is the real verdict.
|
|
107
|
+
proc.stdin?.on("error", () => {
|
|
108
|
+
/* the child may exit before (or without) reading stdin; its exit code is still the verdict */
|
|
109
|
+
});
|
|
102
110
|
try {
|
|
103
111
|
proc.stdin?.write(stdinJson);
|
|
104
112
|
proc.stdin?.end();
|
|
@@ -176,6 +184,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
176
184
|
const scriptsDir = fs.existsSync(managedScriptsDir) ? managedScriptsDir : path.join(bundledCorpusRoot, "hooks", "scripts");
|
|
177
185
|
const guardWrites = path.join(scriptsDir, "cratis-guard-writes.sh");
|
|
178
186
|
const guardStoreMutations = path.join(scriptsDir, "cratis-guard-store-mutations.sh");
|
|
187
|
+
const guardPrBody = path.join(scriptsDir, "cratis-guard-pr-body.sh");
|
|
179
188
|
const patternScan = path.join(scriptsDir, "cratis-pattern-scan.sh");
|
|
180
189
|
const qualityGate = path.join(scriptsDir, "cratis-quality-gate.sh");
|
|
181
190
|
|
|
@@ -201,9 +210,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
201
210
|
if (event.toolName === "bash") {
|
|
202
211
|
const command = (event as any).input?.command;
|
|
203
212
|
if (typeof command !== "string" || !command.trim()) return;
|
|
204
|
-
if (!isInstalled(guardStoreMutations)) return; // no guard installed in this repository - nothing to enforce
|
|
205
213
|
const payload = { cwd: ctx.cwd, tool_name: "Bash", tool_input: { command } };
|
|
206
|
-
|
|
214
|
+
if (isInstalled(guardStoreMutations)) {
|
|
215
|
+
const blocked = await runBlockingGuard(guardStoreMutations, "cratis-guard-store-mutations", "command", payload, ctx);
|
|
216
|
+
if (blocked) return blocked;
|
|
217
|
+
}
|
|
218
|
+
if (isInstalled(guardPrBody)) {
|
|
219
|
+
const run = await runScript(guardPrBody, JSON.stringify(payload), ctx.cwd, ctx.signal);
|
|
220
|
+
if (run.failed || run.code !== 0) return { block: true, reason: run.stderr.trim() || "cratis-guard-pr-body could not check this command." };
|
|
221
|
+
if (run.stderr.trim()) pi.sendMessage({ customType: "cratis-pr-body-warning", content: run.stderr.trim(), display: true });
|
|
222
|
+
}
|
|
223
|
+
return;
|
|
207
224
|
}
|
|
208
225
|
if (event.toolName !== "write" && event.toolName !== "edit") return;
|
|
209
226
|
const { filePath, content, newString } = writeTarget(event.toolName, (event as any).input);
|
|
@@ -11,6 +11,7 @@ Three layers:
|
|
|
11
11
|
| Pattern pass | `PostToolUse` on a write | `scripts/cratis-pattern-scan.sh` | zero tokens until a match | appends a one-line reminder to context, never blocks |
|
|
12
12
|
| Hard block | `PreToolUse` on a write | `scripts/cratis-guard-writes.sh` | zero | exits **2** — the write does not happen |
|
|
13
13
|
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-store-mutations.sh` | zero; parses only commands that mention `cratis` | exits **2** — the store-changing `cratis chronicle` command does not run |
|
|
14
|
+
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-pr-body.sh` | fetches shared rules only for `gh pr create/edit` | exits **2** for inline bodies, invalid notes or conflicting release labels; warns and allows when offline with no cache |
|
|
14
15
|
| 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 |
|
|
15
16
|
| Quality gate (Pi) | explicit `cratis_quality_gate` tool | same script | only at a requested verification checkpoint | error on failure; no turn-end hook |
|
|
16
17
|
|
|
@@ -34,7 +35,7 @@ they describe what a hook should do for tools that have no wiring yet.
|
|
|
34
35
|
|
|
35
36
|
> Hooks are the one surface with no folder adapter: Claude Code reads `.claude/settings.json`;
|
|
36
37
|
> the Pi harness bridges the same scripts to its own events through the `cratis-hooks`
|
|
37
|
-
> extension under `../harnesses/pi/extensions/` (its `bash` tool feeds the store-mutation
|
|
38
|
+
> extension under `../harnesses/pi/extensions/` (its `bash` tool feeds the store-mutation and PR-body guards, its
|
|
38
39
|
> `write` and `edit` tools the write guard); Copilot would read `.github/hooks/*.json`, and no
|
|
39
40
|
> Copilot wiring ships yet.
|
|
40
41
|
>
|
|
@@ -108,6 +109,60 @@ A person who has authorized a mutation sets `CRATIS_HOOKS_ALLOW_STORE_MUTATIONS=
|
|
|
108
109
|
environment the harness was started from. The hook reads its own environment, so an assignment
|
|
109
110
|
inside the command (`CRATIS_HOOKS_ALLOW_STORE_MUTATIONS=1 cratis …`) changes nothing.
|
|
110
111
|
|
|
112
|
+
### Pull-request bodies
|
|
113
|
+
|
|
114
|
+
The Bash guard is a no-op unless **both** target-repository opt-in conditions hold: the target is under
|
|
115
|
+
`github.com/Cratis/`, and its `.github/workflows` contains a reusable Cratis/Workflows
|
|
116
|
+
`verify-release-notes` or `verify-semver-label` caller (including the renamed
|
|
117
|
+
`verify-release-intent` caller). Installing the corpus or `@cratis/pi` alone does not opt in a
|
|
118
|
+
consumer or personal repository. This scope applies to both Claude Code and Pi; the direct checker
|
|
119
|
+
remains available explicitly in any repository. As in `gh`, an edit's PR URL takes priority over
|
|
120
|
+
`--repo` / `-R`, then literal leading or inherited `GH_REPO`, then the current directory's `origin`.
|
|
121
|
+
Cross-repository commands use the target's workflow
|
|
122
|
+
callers, not the checkout's; an unavailable remote opt-in lookup blocks rather than bypassing the guard.
|
|
123
|
+
|
|
124
|
+
In opted-in repositories, the Bash guard checks literal `gh pr create` and `gh pr edit` commands, also behind leading environment assignments, `env`, `command`, `rtk` or
|
|
125
|
+
following shell separators. Inline `--body` / `-b` is refused: write the body to
|
|
126
|
+
`.ai-work/pr-body.md` and use `--body-file` / `-F`. It applies `--label`, `--add-label` and
|
|
127
|
+
`--remove-label` to the current PR labels and requires exactly one release intent. A label-only
|
|
128
|
+
edit checks the current body too. Variables, aliases, shell functions, nested shell scripts and
|
|
129
|
+
script files are outside its scope; guarded option values must be literal paths or labels.
|
|
130
|
+
Shell comments and here-document payloads are not executable commands. If an earlier redirection
|
|
131
|
+
or `tee` in the same tool command writes the guarded body file, the command is blocked: **write the body
|
|
132
|
+
file first, then run `gh pr create/edit` in a separate command**. The guard reads files before
|
|
133
|
+
execution, so it cannot validate a body that the command has yet to write, even if an older file
|
|
134
|
+
already exists. Dependabot's generated description remains exempt (including GitHub CLI's
|
|
135
|
+
`app/dependabot` bot identity), but its release-intent label is still checked.
|
|
136
|
+
|
|
137
|
+
Run the same checker directly:
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
node .cratis/ai/hooks/scripts/cratis-check-pr.mjs --body-file .ai-work/pr-body.md --label patch
|
|
141
|
+
node .cratis/ai/hooks/scripts/cratis-check-pr.mjs --body-file .ai-work/pr-body.md --pr 123 --strict
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
The checker fetches both marked programs from Cratis/Workflows' `verify-release-notes.yml` at
|
|
145
|
+
the immutable commit SHA in the repository's own release-notes caller. If there is no such caller,
|
|
146
|
+
it uses the reviewed pin `40125b4fcae388e62ed9471edfffd0e991422f0a`. Floating callers such as `@main`
|
|
147
|
+
fetch the programs at that ref; if the fetch fails, they use the bundled programs from the reviewed
|
|
148
|
+
pin with a warning, so body validation is never silently skipped. Programs receive only the proposed PR
|
|
149
|
+
metadata and `PATH`, `HOME`, and `LANG`, not inherited credentials or Node runtime options.
|
|
150
|
+
The exact programs are cached by workflow blob SHA under
|
|
151
|
+
`${XDG_CACHE_HOME:-~/.cache}/cratis/release-notes/<ref>/<sha>.cjs`. Offline, the newest complete
|
|
152
|
+
cached copy for that same pin is used with a warning. With no cache it reports **unchecked** and
|
|
153
|
+
exits **3**; the hook passes through with that warning. Successful checks are silent in hook mode;
|
|
154
|
+
real warnings go to Pi's context or Claude Code's JSON `systemMessage` and `additionalContext`. Exit **0** means no violations; **1** means invalid notes or
|
|
155
|
+
release intent. `--strict` makes warnings (including a cached-rule fallback or an unavailable
|
|
156
|
+
diff comparison) fail too. `no-release` bodies may omit the change list (for example, a summary-only
|
|
157
|
+
internal change); other release-note contract violations still fail, rather than being exempted.
|
|
158
|
+
|
|
159
|
+
The drift program compares committed `HEAD` with `origin/<base>` (default: the repository's
|
|
160
|
+
default branch, normally `main`), so commit the intended changes and fetch the base before the
|
|
161
|
+
final check. Drift is advisory without `--strict`; re-read the note against the diff after
|
|
162
|
+
merging or rebasing main. The local checker requires Node and Git; fetching rules and live PR
|
|
163
|
+
labels also needs authenticated `gh`. Unrelated commands exit before checking for Node; when Node
|
|
164
|
+
is missing, relevant PR commands in locally opted-in repositories warn rather than claiming a pass.
|
|
165
|
+
|
|
111
166
|
**Flagged** (`PostToolUse`, exit 0 + context):
|
|
112
167
|
|
|
113
168
|
| Pattern id | Rule | Detects |
|
|
@@ -414,8 +469,9 @@ Each is an explicit, auditable opt-out — none of them is a default.
|
|
|
414
469
|
(macOS system bash) — no `mapfile`, no associative arrays, no GNU-only flags, `LC_ALL=C` on
|
|
415
470
|
every sort and compare.
|
|
416
471
|
- **Gate commands are an argv array**, executed directly. They never pass through a shell.
|
|
417
|
-
- **`jq` is the
|
|
418
|
-
|
|
472
|
+
- **`jq` is the dependency for the write, store-mutation, pattern and quality hooks.** They
|
|
473
|
+
degrade to a silent no-op when it is missing — a hook must never break a session. The
|
|
474
|
+
PR-body hook uses Node instead, and the checker uses Git and `gh` as described above.
|
|
419
475
|
- **Fail safe.** Malformed config, empty stdin, a missing file, a binary file, a file over 2 MB:
|
|
420
476
|
all exit 0 silently. The one deliberate exception is the store-mutation guard's command lists:
|
|
421
477
|
an unreadable shipped or local list is not an empty allowlist that happens to pass, so every `cratis chronicle`
|
|
@@ -0,0 +1,397 @@
|
|
|
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 { createHash } from 'node:crypto';
|
|
7
|
+
import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync } from 'node:fs';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
10
|
+
import { parseArgs } from 'node:util';
|
|
11
|
+
import { Script } from 'node:vm';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
|
|
14
|
+
const intents = ['major', 'minor', 'patch', 'no-release'];
|
|
15
|
+
const commandTimeout = 15_000;
|
|
16
|
+
const reviewedRulesRef = '40125b4fcae388e62ed9471edfffd0e991422f0a';
|
|
17
|
+
const hookMode = process.argv[2] === '--hook';
|
|
18
|
+
let claudeHook = false;
|
|
19
|
+
const hookWarnings = [];
|
|
20
|
+
const warningLine = line => /^(::warning\b|::notice title=Release notes (?:drift )?not checked|Warning:)/.test(line);
|
|
21
|
+
const warning = message => {
|
|
22
|
+
if (hookMode && claudeHook) hookWarnings.push(message);
|
|
23
|
+
else console.error(message);
|
|
24
|
+
};
|
|
25
|
+
const run = (command, args, options = {}) => spawnSync(command, args, {
|
|
26
|
+
encoding: 'utf8', timeout: commandTimeout, maxBuffer: 32 * 1024 * 1024, ...options,
|
|
27
|
+
});
|
|
28
|
+
const gh = args => {
|
|
29
|
+
const result = run('gh', args);
|
|
30
|
+
if (result.error || result.status !== 0) throw new Error(`gh ${args[0]} failed: ${result.stderr?.trim() || result.error?.message || result.status}`);
|
|
31
|
+
return result.stdout;
|
|
32
|
+
};
|
|
33
|
+
const git = (args, cwd = process.cwd()) => {
|
|
34
|
+
const result = run('git', args, { cwd });
|
|
35
|
+
return result.status === 0 ? result.stdout.trim() : '';
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
function workflowCallers(source) {
|
|
39
|
+
return [...source.matchAll(/^\s*uses:\s*['"]?Cratis\/Workflows\/\.github\/workflows\/(verify-(?:release-notes|semver-label|release-intent))\.yml@([^\s'"#]+)/gmi)]
|
|
40
|
+
.map(match => ({ name: match[1], ref: match[2] }));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function callers(cwd = process.cwd()) {
|
|
44
|
+
const root = git(['rev-parse', '--show-toplevel'], cwd);
|
|
45
|
+
if (!root) return [];
|
|
46
|
+
const directory = join(root, '.github/workflows');
|
|
47
|
+
try {
|
|
48
|
+
return readdirSync(directory).filter(name => /\.ya?ml$/.test(name)).flatMap(name => {
|
|
49
|
+
const source = readFileSync(join(directory, name), 'utf8');
|
|
50
|
+
return workflowCallers(source);
|
|
51
|
+
});
|
|
52
|
+
} catch { return []; }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function repositoryName(value) {
|
|
56
|
+
return value?.replace(/^(?:https?:\/\/github\.com\/|(?:ssh:\/\/)?git@github\.com[:/])/i, '')
|
|
57
|
+
.replace(/^github\.com\//i, '').replace(/\/$/, '').replace(/\.git$/i, '');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function originRepository(cwd) {
|
|
61
|
+
return repositoryName(git(['remote', 'get-url', 'origin'], cwd));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function targetCallers(repository, cwd) {
|
|
65
|
+
if (repository?.toLowerCase() === originRepository(cwd)?.toLowerCase()) return callers(cwd);
|
|
66
|
+
let files;
|
|
67
|
+
try { files = JSON.parse(gh(['api', `repos/${repository}/contents/.github/workflows`])); }
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (/HTTP 404/.test(error.message)) return [];
|
|
70
|
+
throw new Error(`Could not determine release-workflow opt-in for ${repository}: ${error.message}`);
|
|
71
|
+
}
|
|
72
|
+
return files.filter(file => file.type === 'file' && /\.ya?ml$/.test(file.name)).flatMap(file =>
|
|
73
|
+
workflowCallers(gh(['api', '-H', 'Accept: application/vnd.github.raw', `repos/${repository}/contents/${file.path}`])));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function optedIn(cwd) {
|
|
77
|
+
return /^Cratis\/[^/]+$/i.test(originRepository(cwd)) && callers(cwd).length > 0;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Fetch the actual inline programs, not a second implementation of the rules.
|
|
81
|
+
function programs(workflow) {
|
|
82
|
+
const found = new Map();
|
|
83
|
+
for (const match of workflow.matchAll(/^([ \t]*)node - <<'JS'\r?\n([\s\S]*?)^[ \t]*JS[ \t]*$/gm)) {
|
|
84
|
+
const source = match[2].split('\n').map(line => line.startsWith(match[1]) ? line.slice(match[1].length) : line).join('\n');
|
|
85
|
+
for (const name of ['release-notes', 'release-notes-drift']) {
|
|
86
|
+
if (source.split('\n').some(line => line.trim() === `// cratis:program ${name}`)) found.set(name, source);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (found.size !== 2) throw new Error('the workflow does not contain both marked release-note programs');
|
|
90
|
+
const bundle = '"use strict";\n' + [...found].map(([name, source]) => `if (process.argv[2] === ${JSON.stringify(name)}) {\n${source}\n}\n`).join('');
|
|
91
|
+
new Script(bundle); // Invalid or truncated downloads must not replace a usable cache.
|
|
92
|
+
return bundle;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function rules(warn, repositoryCallers) {
|
|
96
|
+
const ref = repositoryCallers.find(caller => caller.name === 'verify-release-notes')?.ref || reviewedRulesRef;
|
|
97
|
+
const floating = !/^[a-f0-9]{40}$/i.test(ref);
|
|
98
|
+
const cache = join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'cratis', 'release-notes', ref);
|
|
99
|
+
try {
|
|
100
|
+
const workflow = gh(['api', '-H', 'Accept: application/vnd.github.raw', `repos/Cratis/Workflows/contents/.github/workflows/verify-release-notes.yml?ref=${encodeURIComponent(ref)}`]);
|
|
101
|
+
const bundle = programs(workflow);
|
|
102
|
+
const bytes = Buffer.from(workflow);
|
|
103
|
+
const sha = createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
|
|
104
|
+
mkdirSync(cache, { recursive: true, mode: 0o700 });
|
|
105
|
+
const file = join(cache, `${sha}.cjs`);
|
|
106
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
107
|
+
writeFileSync(temporary, bundle, { mode: 0o600 });
|
|
108
|
+
renameSync(temporary, file);
|
|
109
|
+
return file;
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (floating) {
|
|
112
|
+
const bundled = fileURLToPath(new URL('./cratis-release-notes-reviewed.cjs', import.meta.url));
|
|
113
|
+
new Script(readFileSync(bundled, 'utf8'));
|
|
114
|
+
warn(`Could not fetch release-note rules at ${ref}; using bundled reviewed ${reviewedRulesRef}. ${error.message}`);
|
|
115
|
+
return bundled;
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
const cached = readdirSync(cache).filter(name => /^[a-f0-9]{40}\.cjs$/.test(name))
|
|
119
|
+
.map(name => ({ file: join(cache, name), modified: statSync(join(cache, name)).mtimeMs }))
|
|
120
|
+
.sort((a, b) => b.modified - a.modified);
|
|
121
|
+
for (const { file } of cached) {
|
|
122
|
+
try {
|
|
123
|
+
const source = readFileSync(file, 'utf8');
|
|
124
|
+
if (!source.includes('// cratis:program release-notes\n') || !source.includes('// cratis:program release-notes-drift\n')) continue;
|
|
125
|
+
new Script(source);
|
|
126
|
+
warn(`Could not fetch release-note rules; using cached ${file}. ${error.message}`);
|
|
127
|
+
return file;
|
|
128
|
+
} catch { /* Try the next complete cache entry. */ }
|
|
129
|
+
}
|
|
130
|
+
} catch { /* No cache available. */ }
|
|
131
|
+
warn(`unchecked: could not fetch release-note rules and nothing is cached. ${error.message}`);
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function check(argv, repositoryCallers) {
|
|
137
|
+
const { values } = parseArgs({ args: argv, options: {
|
|
138
|
+
'body-file': { type: 'string' }, label: { type: 'string', multiple: true },
|
|
139
|
+
'add-label': { type: 'string', multiple: true }, 'remove-label': { type: 'string', multiple: true },
|
|
140
|
+
pr: { type: 'string' }, base: { type: 'string' }, repo: { type: 'string' }, strict: { type: 'boolean' },
|
|
141
|
+
} });
|
|
142
|
+
let warned = false;
|
|
143
|
+
const warn = message => { warned = true; warning(`Warning: ${message}`); };
|
|
144
|
+
let pull;
|
|
145
|
+
// gh requires a selector when --repo is supplied; otherwise preserve current-branch lookup.
|
|
146
|
+
const repoArgs = values.pr && values.repo ? ['--repo', values.repo] : [];
|
|
147
|
+
if (values.pr !== undefined) {
|
|
148
|
+
pull = JSON.parse(gh(['pr', 'view', ...(values.pr ? [values.pr] : []), ...repoArgs,
|
|
149
|
+
'--json', 'labels,body,author,baseRefName']));
|
|
150
|
+
}
|
|
151
|
+
if (!values['body-file'] && !pull) throw new Error('--body-file is required when creating a pull request');
|
|
152
|
+
const split = labels => (labels || []).flatMap(label => label.split(',')).map(label => label.trim()).filter(Boolean);
|
|
153
|
+
const labels = new Set(values.label ? split(values.label) : (pull?.labels || []).map(label => label.name));
|
|
154
|
+
for (const label of split(values['remove-label'])) labels.delete(label);
|
|
155
|
+
for (const label of split(values['add-label'])) labels.add(label);
|
|
156
|
+
const intent = intents.filter(label => labels.has(label));
|
|
157
|
+
if (intent.length !== 1) throw new Error(`Exactly one release-intent label is required (major/minor/patch/no-release); found ${intent.join(', ') || 'none'}.`);
|
|
158
|
+
const body = values['body-file'] ? readFileSync(resolve(values['body-file']), 'utf8') : pull.body || '';
|
|
159
|
+
let repository = values.repo;
|
|
160
|
+
let defaultBranch = git(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']).replace(/^origin\//, '') || 'main';
|
|
161
|
+
try {
|
|
162
|
+
const metadata = JSON.parse(gh(['repo', 'view', ...(repository ? [repository] : []), '--json', 'nameWithOwner,defaultBranchRef']));
|
|
163
|
+
repository = metadata.nameWithOwner;
|
|
164
|
+
defaultBranch = metadata.defaultBranchRef?.name || defaultBranch;
|
|
165
|
+
} catch {
|
|
166
|
+
repository ||= git(['remote', 'get-url', 'origin']).replace(/^.*github\.com[:/]/, '').replace(/\.git$/, '') || 'Cratis/<Repository>';
|
|
167
|
+
}
|
|
168
|
+
let author = pull?.author?.login;
|
|
169
|
+
if (pull?.author?.is_bot && author?.startsWith('app/')) author = `${author.slice(4)}[bot]`;
|
|
170
|
+
if (!author) {
|
|
171
|
+
try { author = gh(['api', 'user', '--jq', '.login']).trim(); } catch { author = ''; }
|
|
172
|
+
}
|
|
173
|
+
// Match the reusable workflow's job-level Dependabot exemption as well as its body exemption.
|
|
174
|
+
// The release-intent check above still applies to bot-authored pull requests.
|
|
175
|
+
if (author === 'dependabot[bot]') return 0;
|
|
176
|
+
const base = values.base || pull?.baseRefName || defaultBranch;
|
|
177
|
+
const file = rules(warn, repositoryCallers || targetCallers(repository, process.cwd()));
|
|
178
|
+
if (!file) return 3;
|
|
179
|
+
const env = { PATH: process.env.PATH, HOME: homedir(), LANG: 'C.UTF-8',
|
|
180
|
+
PR_BODY: body, PR_LABELS: JSON.stringify([...labels]),
|
|
181
|
+
PR_AUTHOR: author, PR_BASE: base, DEFAULT_BRANCH: defaultBranch, GITHUB_REPOSITORY: repository,
|
|
182
|
+
BASE: base, REPOSITORY: repository };
|
|
183
|
+
for (const program of ['release-notes', 'release-notes-drift']) {
|
|
184
|
+
const result = run(process.execPath, [file, program], { env, timeout: 60_000 });
|
|
185
|
+
if (result.error || result.status !== 0) {
|
|
186
|
+
(hookMode ? process.stderr : process.stdout).write(result.stdout || '');
|
|
187
|
+
process.stderr.write(result.stderr || '');
|
|
188
|
+
if (result.error) console.error(result.error.message);
|
|
189
|
+
return 1;
|
|
190
|
+
}
|
|
191
|
+
// no-release may omit a change list, but other contract violations still block locally.
|
|
192
|
+
const output = (result.stdout || '') + (result.stderr || '');
|
|
193
|
+
if (intent[0] === 'no-release' && program === 'release-notes'
|
|
194
|
+
&& output.split('\n').some(line => /^::warning title=Release notes(?::|%3A) (?!No release notes::)/.test(line))) {
|
|
195
|
+
(hookMode ? process.stderr : process.stdout).write(result.stdout || '');
|
|
196
|
+
process.stderr.write(result.stderr || '');
|
|
197
|
+
return 1;
|
|
198
|
+
}
|
|
199
|
+
if (!hookMode) process.stdout.write(result.stdout || '');
|
|
200
|
+
for (const line of ((result.stdout || '') + (result.stderr || '')).split('\n').filter(warningLine)) {
|
|
201
|
+
warned = true;
|
|
202
|
+
if (hookMode) warning(line);
|
|
203
|
+
}
|
|
204
|
+
if (!hookMode) process.stderr.write(result.stderr || '');
|
|
205
|
+
}
|
|
206
|
+
return values.strict && warned ? 1 : 0;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// A deliberately bounded shell-text guard, not a shell interpreter. Quotes and escaped spaces are
|
|
210
|
+
// preserved; separators are recognized only outside quotes. Variables, aliases and script files
|
|
211
|
+
// are outside this guard's scope. Dynamic values of guarded options fail closed.
|
|
212
|
+
function commands(text) {
|
|
213
|
+
const result = [];
|
|
214
|
+
let words = [], writes = [], word = '', started = false, quote = '', redirect;
|
|
215
|
+
const heredocs = [];
|
|
216
|
+
const endWord = () => {
|
|
217
|
+
if (started) {
|
|
218
|
+
if (redirect?.heredoc) heredocs.push({ delimiter: word, tabs: redirect.tabs });
|
|
219
|
+
else if (redirect?.write && !(redirect.duplicate && /^(?:\d+|-)$/.test(word))) writes.push(word);
|
|
220
|
+
else if (!redirect) words.push(word);
|
|
221
|
+
redirect = undefined;
|
|
222
|
+
}
|
|
223
|
+
word = ''; started = false;
|
|
224
|
+
};
|
|
225
|
+
const endCommand = () => {
|
|
226
|
+
endWord();
|
|
227
|
+
if (words.length || writes.length) result.push({ words, writes });
|
|
228
|
+
words = []; writes = [];
|
|
229
|
+
};
|
|
230
|
+
for (let index = 0; index < text.length; index++) {
|
|
231
|
+
const char = text[index];
|
|
232
|
+
if (char === '\\' && quote !== "'") {
|
|
233
|
+
const next = text[++index];
|
|
234
|
+
if (next && next !== '\n') { word += next; started = true; }
|
|
235
|
+
} else if (quote) {
|
|
236
|
+
if (char === quote) quote = ''; else word += char;
|
|
237
|
+
} else if (char === '#' && !started) {
|
|
238
|
+
// Quotes inside comments have no shell meaning.
|
|
239
|
+
while (index + 1 < text.length && text[index + 1] !== '\n') index++;
|
|
240
|
+
} else if (char === '"' || char === "'") { quote = char; started = true;
|
|
241
|
+
} else if (char === '<' || char === '>') {
|
|
242
|
+
// A numeric word touching a redirect is a file descriptor, not an argument.
|
|
243
|
+
if (started && /^\d+$/.test(word)) { word = ''; started = false; }
|
|
244
|
+
endWord();
|
|
245
|
+
const operator = /^(?:<<<|<<-|<<|>>|<>|>&|<&|>\||[<>])/.exec(text.slice(index))[0];
|
|
246
|
+
redirect = { heredoc: operator === '<<' || operator === '<<-', tabs: operator === '<<-', duplicate: operator === '>&', write: operator.startsWith('>') || operator === '<>' };
|
|
247
|
+
index += operator.length - 1;
|
|
248
|
+
} else if (/[;&|\n]/.test(char)) {
|
|
249
|
+
endCommand();
|
|
250
|
+
if (char === '\n') {
|
|
251
|
+
// Here-document payloads are data; do not tokenize their quotes or gh examples.
|
|
252
|
+
for (const { delimiter, tabs } of heredocs.splice(0)) {
|
|
253
|
+
let found = false;
|
|
254
|
+
while (index + 1 < text.length) {
|
|
255
|
+
const start = index + 1;
|
|
256
|
+
const end = text.indexOf('\n', start);
|
|
257
|
+
const line = text.slice(start, end < 0 ? text.length : end);
|
|
258
|
+
index = end < 0 ? text.length - 1 : end;
|
|
259
|
+
if ((tabs ? line.replace(/^\t+/, '') : line) === delimiter) { found = true; break; }
|
|
260
|
+
}
|
|
261
|
+
if (!found) throw new Error('Unclosed heredoc in pull-request command; write the body file first in a separate command.');
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
} else if (/\s/.test(char)) endWord();
|
|
265
|
+
else { word += char; started = true; }
|
|
266
|
+
}
|
|
267
|
+
if (quote) throw new Error('Unclosed quote in pull-request command; use a simple gh command with --body-file.');
|
|
268
|
+
endCommand();
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function executableWords(words) {
|
|
273
|
+
const result = [...words];
|
|
274
|
+
let environmentRepository = process.env.GH_REPO;
|
|
275
|
+
while (result.length) {
|
|
276
|
+
if (/^[A-Za-z_][A-Za-z_0-9]*=/.test(result[0])) {
|
|
277
|
+
if (result[0].startsWith('GH_REPO=')) environmentRepository = result[0].slice('GH_REPO='.length);
|
|
278
|
+
result.shift();
|
|
279
|
+
} else if (['rtk', 'env', 'command', '--'].includes(result[0])) result.shift();
|
|
280
|
+
else break;
|
|
281
|
+
}
|
|
282
|
+
return { words: result, environmentRepository };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function effectiveRepository(words, cwd, environmentRepository) {
|
|
286
|
+
// gh selects an edit's PR URL before --repo, then GH_REPO, then the checkout origin.
|
|
287
|
+
let repository, target;
|
|
288
|
+
let explicitRepository = false;
|
|
289
|
+
for (let index = 3; index < words.length; index++) {
|
|
290
|
+
const compact = /^(-[bFlBRtarmpHT])(.+)$/.exec(words[index]);
|
|
291
|
+
const [option, ...attached] = compact ? [compact[1], compact[2]] : words[index].split('=');
|
|
292
|
+
if (option === '--repo' || option === '-R') {
|
|
293
|
+
explicitRepository = true;
|
|
294
|
+
repository = attached.length ? attached.join('=') : words[++index];
|
|
295
|
+
} else if (['--body', '-b', '--body-file', '-F', '--label', '-l', '--add-label', '--remove-label', '--base', '-B',
|
|
296
|
+
'--title', '-t', '--assignee', '-a', '--reviewer', '-r', '--milestone', '-m', '--project', '-p',
|
|
297
|
+
'--add-assignee', '--remove-assignee', '--add-reviewer', '--remove-reviewer', '--add-project', '--remove-project',
|
|
298
|
+
'--head', '-H', '--template', '-T', '--recover'].includes(option)) {
|
|
299
|
+
if (!attached.length) index++;
|
|
300
|
+
} else if (!option.startsWith('-') && words[2] === 'edit' && !target) target = words[index];
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
const url = new URL(target);
|
|
304
|
+
const pull = /^\/([^/]+)\/([^/]+)\/pull\/(\d+)/.exec(url.pathname);
|
|
305
|
+
if (['http:', 'https:'].includes(url.protocol) && url.hostname === 'github.com' && pull) return `${pull[1]}/${pull[2]}`;
|
|
306
|
+
} catch { /* A branch name or PR number is not a URL. */ }
|
|
307
|
+
if (explicitRepository) {
|
|
308
|
+
if (!repository || repository.startsWith('-') || /[$`]/.test(repository)) throw new Error('Use a literal value for --repo, not a shell expansion.');
|
|
309
|
+
return repositoryName(repository);
|
|
310
|
+
}
|
|
311
|
+
if (environmentRepository) {
|
|
312
|
+
if (/[$`]/.test(environmentRepository)) throw new Error('Use a literal value for GH_REPO, not a shell expansion.');
|
|
313
|
+
return repositoryName(environmentRepository);
|
|
314
|
+
}
|
|
315
|
+
return originRepository(cwd);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function hook() {
|
|
319
|
+
let payload;
|
|
320
|
+
try { payload = JSON.parse(readFileSync(0, 'utf8')); } catch { return 0; }
|
|
321
|
+
claudeHook = payload?.hook_event_name === 'PreToolUse';
|
|
322
|
+
const text = payload?.tool_input?.command;
|
|
323
|
+
if (typeof text !== 'string' || !/\bgh\s+pr\s+(create|edit)\b/.test(text.replace(/\\\r?\n/g, ''))) return 0;
|
|
324
|
+
// Match each simple command, never the same text inside an echo/grep argument.
|
|
325
|
+
let cwd = payload.cwd || process.cwd();
|
|
326
|
+
let knownDirectory = true;
|
|
327
|
+
let parsed;
|
|
328
|
+
try { parsed = commands(text); } catch (error) { if (!optedIn(cwd)) return 0; throw error; }
|
|
329
|
+
const written = new Set();
|
|
330
|
+
for (const command of parsed) {
|
|
331
|
+
const { words, environmentRepository } = executableWords(command.words);
|
|
332
|
+
const writes = [...command.writes];
|
|
333
|
+
if (words[0] === 'tee') writes.push(...words.slice(1).filter(word => !word.startsWith('-')));
|
|
334
|
+
if (knownDirectory) for (const file of writes) written.add(resolve(cwd, file));
|
|
335
|
+
if (words[0] === 'cd') {
|
|
336
|
+
const directory = words[1] === '--' ? words[2] : words[1];
|
|
337
|
+
if (!directory || /[$`~]/.test(directory)) knownDirectory = false;
|
|
338
|
+
else if (knownDirectory || isAbsolute(directory)) {
|
|
339
|
+
cwd = resolve(cwd, directory);
|
|
340
|
+
knownDirectory = true;
|
|
341
|
+
}
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
if (words[0] !== 'gh' || words[1] !== 'pr' || !['create', 'edit'].includes(words[2])) continue;
|
|
345
|
+
if (words.includes('--help') || words.includes('-h')) continue;
|
|
346
|
+
if (!knownDirectory) {
|
|
347
|
+
if (!optedIn(cwd)) return 0;
|
|
348
|
+
throw new Error('Use a literal directory before gh pr create/edit.');
|
|
349
|
+
}
|
|
350
|
+
const repository = effectiveRepository(words, cwd, environmentRepository);
|
|
351
|
+
if (!/^Cratis\/[^/]+$/i.test(repository)) continue;
|
|
352
|
+
const repositoryCallers = targetCallers(repository, cwd);
|
|
353
|
+
if (!repositoryCallers.length) continue;
|
|
354
|
+
const args = [];
|
|
355
|
+
let target = '', hasBody = false;
|
|
356
|
+
for (let index = 3; index < words.length; index++) {
|
|
357
|
+
const compact = /^(-[FlBRtarmpHT])(.+)$/.exec(words[index]);
|
|
358
|
+
const [option, ...attached] = compact ? [compact[1], compact[2]] : words[index].split('=');
|
|
359
|
+
if (option === '--body' || option === '-b' || /^-b./.test(option)) {
|
|
360
|
+
throw new Error('write the body to `.ai-work/pr-body.md` and use `--body-file`; inline --body/-b is blocked.');
|
|
361
|
+
}
|
|
362
|
+
const mapped = { '--body-file': '--body-file', '-F': '--body-file', '--label': '--label', '-l': '--label',
|
|
363
|
+
'--add-label': '--add-label', '--remove-label': '--remove-label', '--base': '--base', '-B': '--base', '--repo': '--repo', '-R': '--repo' }[option];
|
|
364
|
+
if (mapped) {
|
|
365
|
+
const value = attached.length ? attached.join('=') : words[++index];
|
|
366
|
+
if (!value || /[$`]/.test(value) || value === '-') throw new Error(`Use a literal value for ${option}, not stdin or a shell expansion.`);
|
|
367
|
+
if (mapped !== '--repo') args.push(mapped, value);
|
|
368
|
+
if (mapped === '--body-file') {
|
|
369
|
+
hasBody = true;
|
|
370
|
+
if (written.has(resolve(cwd, value))) throw new Error('write the body file first, then run gh pr create/edit in a separate command; an earlier redirection may change the submitted body.');
|
|
371
|
+
}
|
|
372
|
+
} else if (!option.startsWith('-') && words[2] === 'edit' && !target) {
|
|
373
|
+
target = words[index];
|
|
374
|
+
} else if (['--title', '-t', '--assignee', '-a', '--reviewer', '-r', '--milestone', '-m', '--project', '-p',
|
|
375
|
+
'--add-assignee', '--remove-assignee', '--add-reviewer', '--remove-reviewer', '--add-project', '--remove-project',
|
|
376
|
+
'--head', '-H', '--template', '-T', '--recover'].includes(option) && !attached.length) index++;
|
|
377
|
+
}
|
|
378
|
+
if (words[2] === 'create' && !hasBody) throw new Error('write the body to `.ai-work/pr-body.md` and use `--body-file` when creating a pull request.');
|
|
379
|
+
if (words[2] === 'edit') args.push('--pr', target);
|
|
380
|
+
// Use the same resolved target for opt-in, PR metadata and repository metadata.
|
|
381
|
+
args.push('--repo', repository);
|
|
382
|
+
process.chdir(cwd);
|
|
383
|
+
const code = check(args, repositoryCallers);
|
|
384
|
+
if (code !== 0 && code !== 3) throw new Error('The pull-request body or release intent failed cratis-check-pr. Fix the reported violations before retrying.');
|
|
385
|
+
}
|
|
386
|
+
return 0;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
try {
|
|
390
|
+
process.exitCode = hookMode ? hook() : check(process.argv.slice(2));
|
|
391
|
+
} catch (error) {
|
|
392
|
+
console.error(`${hookMode ? 'BLOCKED by cratis-guard-pr-body: ' : ''}${error.message}`);
|
|
393
|
+
process.exitCode = hookMode ? 2 : 1;
|
|
394
|
+
} finally {
|
|
395
|
+
if (claudeHook && hookWarnings.length) console.log(JSON.stringify({ systemMessage: hookWarnings.join('\n'),
|
|
396
|
+
hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: hookWarnings.join('\n') } }));
|
|
397
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
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
|
+
# PreToolUse (Bash): release-note bodies are checked before gh pr create/edit.
|
|
5
|
+
# Node reads the hook JSON and tokenizes literal shell arguments without executing them.
|
|
6
|
+
set -euo pipefail
|
|
7
|
+
# Read the inherited descriptor directly: Node uses a socket for stdin on Linux,
|
|
8
|
+
# and reopening it via /dev/stdin fails with ENXIO. EOF without a newline is normal.
|
|
9
|
+
payload=''
|
|
10
|
+
IFS= read -r -d '' payload || true
|
|
11
|
+
# This dependency-free prefilter runs even on Node-free machines. Normalize JSON-escaped
|
|
12
|
+
# line continuations before matching; Node still determines executable command identity.
|
|
13
|
+
command_text=${payload//\\n/ }
|
|
14
|
+
command_text=${command_text//\\t/ }
|
|
15
|
+
command_text=${command_text//\\r/ }
|
|
16
|
+
command_text=${command_text//\\/}
|
|
17
|
+
if [[ ! "$command_text" =~ gh[[:space:]]+pr[[:space:]]+(create|edit) ]]; then
|
|
18
|
+
exit 0
|
|
19
|
+
fi
|
|
20
|
+
if ! command -v node >/dev/null 2>&1; then
|
|
21
|
+
# No warning for unrelated repositories or installations without release workflows.
|
|
22
|
+
origin=$(git remote get-url origin 2>/dev/null || true)
|
|
23
|
+
if [[ ! "$origin" =~ ^(https?://github.com/|(ssh://)?git@github.com[:/])Cratis/ ]]; then
|
|
24
|
+
exit 0
|
|
25
|
+
fi
|
|
26
|
+
root=$(git rev-parse --show-toplevel 2>/dev/null || true)
|
|
27
|
+
if ! grep -Eq "^[[:space:]]*uses:[[:space:]]*['\"]?Cratis/Workflows/\\.github/workflows/verify-(release-notes|semver-label|release-intent)\\.yml@" "$root"/.github/workflows/*.yml "$root"/.github/workflows/*.yaml 2>/dev/null; then
|
|
28
|
+
exit 0
|
|
29
|
+
fi
|
|
30
|
+
# JSON makes fail-open warnings visible to Claude; stderr exposes the same warning to Pi.
|
|
31
|
+
printf '%s\n' '{"systemMessage":"Warning: unchecked pull-request body: node is unavailable.","hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"Warning: unchecked pull-request body: node is unavailable."}}'
|
|
32
|
+
printf 'Warning: unchecked pull-request body: node is unavailable.\n' >&2
|
|
33
|
+
exit 0
|
|
34
|
+
fi
|
|
35
|
+
status=0
|
|
36
|
+
node "$(dirname "${BASH_SOURCE[0]}")/cratis-check-pr.mjs" --hook <<< "$payload" || status=$?
|
|
37
|
+
# Unexpected runtime failures are not an allow verdict. Only the checker handles the
|
|
38
|
+
# documented offline/no-cache pass-through; its hook mode translates violations to 2.
|
|
39
|
+
if [ "$status" -ne 0 ]; then
|
|
40
|
+
exit 2
|
|
41
|
+
fi
|