@hasna/hooks 0.12.20 → 0.12.21
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/README.md +95 -3
- package/bin/hooks/scratch-lifecycle.js +501 -0
- package/bin/hooks-mcp.js +5199 -3025
- package/bin/index.js +5852 -3635
- package/bin/native-safety-worker.cjs +1 -1
- package/bin/serve.js +15 -1
- package/dist/index.js +5533 -3359
- package/dist/lib/claude-skills-coordination.d.ts +1 -1
- package/dist/lib/hook-env.d.ts +3 -2
- package/dist/lib/run.d.ts +9 -0
- package/dist/serve.d.ts +1 -1
- package/hooks/hook-scratch-lifecycle/README.md +88 -0
- package/hooks/hook-scratch-lifecycle/manifest.json +10 -0
- package/hooks/hook-scratch-lifecycle/package.json +11 -0
- package/hooks/hook-scratch-lifecycle/src/hook.ts +194 -0
- package/hooks/hook-scratch-lifecycle/src/lifecycle.ts +218 -0
- package/package.json +8 -2
- package/scripts/validate-bundled-hooks.ts +12 -0
- package/scripts/validate-package.ts +46 -1
package/README.md
CHANGED
|
@@ -5,12 +5,102 @@ Open source hooks library for AI coding agents - Install safety, quality, and au
|
|
|
5
5
|
[](https://www.npmjs.com/package/@hasna/hooks)
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
|
|
8
|
-
##
|
|
8
|
+
## What it does
|
|
9
|
+
|
|
10
|
+
`@hasna/hooks` installs hooks into AI coding agents. A hook is a small program the agent runs at a fixed point: before a shell command, after a file edit, or when a turn ends. Hooks block a mistake, check the work, or automate a step. One CLI installs, lists, updates and removes them.
|
|
11
|
+
|
|
12
|
+
- **Agents.** Claude Code (the default target) and Codex. Compatible OpenCode and Sumi builds are supported for the stop-review hook. Gemini CLI is an install target (`--target gemini`), but the bundled shell guards do not yet recognise Gemini's tool names (`run_shell_command` rather than `Bash`), so do not rely on them there yet. Codewith targets remain for existing setups, but Codewith is deprecated.
|
|
13
|
+
- **Catalog.** 57 bundled hooks in 10 categories, listed below. You can also install your own hooks from a local directory, a git URL or a manifest URL.
|
|
14
|
+
- **Safety core.** Guards that:
|
|
15
|
+
- block destructive git commands (gitguard);
|
|
16
|
+
- send `rm` to a recoverable trash store instead of deleting (trash-guard). It needs the
|
|
17
|
+
`trash` CLI from `@hasna/trash` on PATH; without it, trash-guard refuses the `rm`;
|
|
18
|
+
- protect repository checkouts (workspace-repos-guard);
|
|
19
|
+
- keep signed links out of agent transcripts (signed-link-guard).
|
|
20
|
+
|
|
21
|
+
scanoutput is detection only: it warns about a secret in tool output after the output is already in the transcript, and cannot prevent or redact it.
|
|
22
|
+
|
|
23
|
+
Each is installed as a hook. For Claude Code, Codex and Sumi, `hooks safety install trash-guard --target <codex|claude|sumi>` can also register trash-guard, workspace-repos-guard and signed-link-guard as one native safety entry; the other guards are not part of it. `--target` defaults to `codex`, so name the agent.
|
|
24
|
+
- **Interfaces.** The `hooks` CLI, an MCP server (`hooks-mcp`) and a self-hostable hook registry (`hooks-serve`).
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
The CLI runs on [Bun](https://bun.sh) 1.0 or later, so `bun` must be on PATH. Without a Hasna hooks registry credential, use local mode: the bundled catalog and a local store in `~/.hasna/hooks`. Set it in your shell profile, not only in the current shell. The agent runs each installed hook as `hooks run <name>`, and that command needs the same setting. Without it the hook exits with `REMOTE_API_CONFIG_MISSING` and does not guard anything.
|
|
9
29
|
|
|
10
30
|
```bash
|
|
31
|
+
bun --version # Bun 1.0 or later is required
|
|
11
32
|
npm install -g @hasna/hooks
|
|
33
|
+
echo 'export HASNA_HOOKS_LOCAL=1' >> ~/.zshrc # or ~/.bashrc; then open a new shell.
|
|
34
|
+
# Only without a registry credential: the opt-in takes precedence over Keychain and file credentials.
|
|
35
|
+
hooks list --all --verbose # browse the full catalog
|
|
36
|
+
hooks install gitguard --dry-run # preview what would be installed
|
|
37
|
+
hooks install gitguard # Claude Code picks it up live; restart if /hooks does not list it
|
|
38
|
+
hooks install gitguard --target codex # or Codex; then review and trust it in Codex's /hooks
|
|
39
|
+
hooks list --installed --target codex # what is installed for one agent
|
|
40
|
+
hooks doctor # check the Claude Code installation
|
|
41
|
+
echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git reset --hard"}}' \
|
|
42
|
+
| hooks run gitguard # a simulated command: prints a "block" decision, runs nothing
|
|
12
43
|
```
|
|
13
44
|
|
|
45
|
+
**Starting the commands.** The `hooks`, `hooks-mcp` and `hooks-serve` commands start through `#!/usr/bin/env -S bun --config=/dev/null --no-env-file --no-macros --no-install`. Started this way, they do not read the working directory's `bunfig.toml` or `.env`, so a project an agent works in cannot run code inside them. Starting them as commands needs GNU coreutils 8.30 or later, or the macOS/BSD `env`. That covers PATH, an npm or Bun bin link, `bun x` and `bunx`. The flags are verified with Bun 1.3.14, which silently ignores flags it does not know, so an older Bun may start the commands without one of these protections.
|
|
46
|
+
|
|
47
|
+
With BusyBox `env` (for example on Alpine) or older coreutils, start them through Bun with the same flags:
|
|
48
|
+
- `bun --config=/dev/null --no-env-file --no-macros --no-install <package>/bin/index.js` for `hooks`;
|
|
49
|
+
- the same with `bin/hooks-mcp.js` or `bin/serve.js` for the others;
|
|
50
|
+
- `<package>` is `$(npm root -g)/@hasna/hooks` for an npm global install.
|
|
51
|
+
|
|
52
|
+
Without the flags, Bun reads the working directory's `bunfig.toml` and `.env`. Agents run installed hooks as `hooks run <name>`. On such systems, put a `hooks` wrapper on PATH: a `#!/bin/sh` script that runs `exec bun --config=/dev/null --no-env-file --no-macros --no-install <package>/bin/index.js "$@"`. Otherwise every hook installed as `hooks run <name>` fails at each event and guards nothing. The native-safety guards are registered with a pinned runtime and do not go through this shebang. For MCP, use `"command": "bun"` with those flags and `<package>/bin/hooks-mcp.js` as its arguments.
|
|
53
|
+
|
|
54
|
+
## Prompt for your agent
|
|
55
|
+
|
|
56
|
+
Paste this to your coding agent and it sets the hooks up itself:
|
|
57
|
+
|
|
58
|
+
```text
|
|
59
|
+
Set up @hasna/hooks (https://www.npmjs.com/package/@hasna/hooks) for this coding agent.
|
|
60
|
+
1. Confirm `bun --version` prints 1.0 or later; if Bun is missing, ask me to install it from
|
|
61
|
+
https://bun.sh. Install the CLI with `npm install -g @hasna/hooks` and confirm
|
|
62
|
+
`hooks --version` runs. Then run `hooks list`. If it prints REMOTE_API_CONFIG_MISSING, no
|
|
63
|
+
registry credential is configured: add `export HASNA_HOOKS_LOCAL=1` to my shell profile, tell
|
|
64
|
+
me to restart you from a new shell so the hooks you run inherit it, and until that restart
|
|
65
|
+
prefix every `hooks` command below with `HASNA_HOOKS_LOCAL=1`.
|
|
66
|
+
2. Run `hooks list --all --verbose` and choose hooks that fit this project. Include gitguard
|
|
67
|
+
and protectfiles.
|
|
68
|
+
3. Preview with `hooks install <names> --dry-run`. Add `--target codex` if you are Codex.
|
|
69
|
+
Then run the same command without `--dry-run`. If you are Codex, ask me to review and
|
|
70
|
+
trust the new hooks in Codex's `/hooks` screen. If you are Claude Code, the new hooks normally
|
|
71
|
+
take effect at once; if `/hooks` does not list them after a few seconds, ask me to restart
|
|
72
|
+
this session. An overlapping-matcher warning when two chosen hooks watch the same tool needs
|
|
73
|
+
no action. A "Sumi native-safety binding was not provisioned" note appears when that binding
|
|
74
|
+
cannot be set up, for example without a verified Trash guard: ignore it if this machine does
|
|
75
|
+
not run Sumi, and otherwise show it to me.
|
|
76
|
+
4. Run `hooks list --installed --target <claude|codex>`. If you are Claude Code, also run
|
|
77
|
+
`hooks doctor`, which checks Claude Code settings only.
|
|
78
|
+
5. Check gitguard without running anything destructive: pipe a simulated command into it with
|
|
79
|
+
`echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git reset --hard"}}' | hooks run gitguard`
|
|
80
|
+
(from the restarted shell). It must print a "block" decision.
|
|
81
|
+
Done when the chosen hooks are listed as installed for this agent (and, for Claude Code,
|
|
82
|
+
`hooks doctor` reports them healthy; for Codex, I have trusted them in `/hooks`), and step 5
|
|
83
|
+
prints "block". Never test a guard by running the real destructive command.
|
|
84
|
+
Do not ask me for, or print, any credential.
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Hook catalog
|
|
88
|
+
|
|
89
|
+
Run `hooks list --all --verbose` for each hook's description, or `hooks info <name>` for one hook.
|
|
90
|
+
|
|
91
|
+
| Category | Hooks |
|
|
92
|
+
|---|---|
|
|
93
|
+
| Git safety | gitguard, branchprotect, checkpoint, worktree-guard, workspace-repos-guard, trash-guard, conflict-detect |
|
|
94
|
+
| Code quality | checktests, checklint, checkfiles, checkbugs, checkdocs, checktasks, stylescheck, typecheck-gate, affected-tests |
|
|
95
|
+
| Security | checksecurity, packageage, pre-bash, scanoutput, signed-link-guard, signed-link-output |
|
|
96
|
+
| Permissions | permissionguard, protectfiles, promptguard, prompt-guard |
|
|
97
|
+
| Context management | contextrefresh, precompact, knowledge-context, mementos-context |
|
|
98
|
+
| Workflow automation | autoformat, autostage, tddguard, failure-to-task |
|
|
99
|
+
| Environment | envsetup |
|
|
100
|
+
| Notifications | phonenotify, agentmessages, desktopnotify, slacknotify, soundnotify |
|
|
101
|
+
| Observability | sessionlog, commandlog, costwatch, errornotify, spiral-detector, scratch-lifecycle |
|
|
102
|
+
| Agent teams | taskgate, session-start, stop-review, stop-sync, filelock, announce-start, announce-stop, dm-inject, fleet-catchup, agent-rules-version-check, fleet-blockers-gate |
|
|
103
|
+
|
|
14
104
|
## CLI Usage
|
|
15
105
|
|
|
16
106
|
### Trash startup readiness
|
|
@@ -423,7 +513,9 @@ on errors. See [setup, scope and provider options](hooks/hook-mementos-context/R
|
|
|
423
513
|
Codex requires review and trust of the exact registration through `/hooks`.
|
|
424
514
|
Claude Code and Codewith also support this hook through their explicit targets.
|
|
425
515
|
|
|
426
|
-
## Codewith-native hooks
|
|
516
|
+
## Codewith-native hooks (deprecated)
|
|
517
|
+
|
|
518
|
+
Codewith is deprecated. These hooks remain for existing Codewith setups; do not choose Codewith for new work.
|
|
427
519
|
|
|
428
520
|
@hasna/hooks includes unprefixed Codewith-native hook names:
|
|
429
521
|
|
|
@@ -605,7 +697,7 @@ Local mode is answered BEFORE the resolver runs (so an unhosted run touches neit
|
|
|
605
697
|
|
|
606
698
|
**Hosted is a route, not just admission (owner ruling 2026-09-07).** Once a registry credential resolves — the env pair, the Keychain item, or the credentials file — the on-box SQLite store is refused for the whole process: `hooks log *`, `hooks storage *`, the MCP `hooks_log_*` / `storage_*` / `send_feedback` tools and the hook-event writer answer `REMOTE_COMMAND_UNSUPPORTED` (naming the opt-in) instead of reading or creating `~/.hasna/hooks/hooks.db`. Pins and trust keep working on the hosted route through `hooks.lock` alone; the SQLite `hooks` table is a local-mode mirror.
|
|
607
699
|
|
|
608
|
-
**`hooks run` decides its route like every other client verb.** Under the explicit opt-in it executes the hook and records the event in the on-box store (the child hook sees `HOOKS_LOCAL`); on the hosted route it executes the hook but refuses the event write loudly (one stderr line — the hosted registry has no event route); with nothing configured it
|
|
700
|
+
**`hooks run` decides its route like every other client verb.** Under the explicit opt-in it executes the hook and records the event in the on-box store (the child hook sees `HOOKS_LOCAL`); on the hosted route it executes the hook but refuses the event write loudly (one stderr line — the hosted registry has no event route); with nothing configured it prints a `REMOTE_API_CONFIG_MISSING` error naming the credential tiers and the opt-in, creates nothing, and exits non-zero. For a bundled hook whose only event is PreToolUse (including a credential that is present but refused) it exits 2 and adds a "Blocked:" line, so the agent refuses the tool call instead of running it; every other hook exits 1, which agents treat as a non-blocking error. The same exit 2 applies whenever `hooks run` cannot run such a guard and so decides nothing: a missing script, an unreadable script or trust record (such as a malformed `hooks.lock`), a script changed since it was trusted, invalid run options (including an unknown option or a missing option value), an invalid native target, or a failure to start such as a read-only install refusing the temporary copy. The `hook-` alias of a guard's name counts as the guard; a custom hook installed under a guard's name takes precedence and keeps exit 1. Bundled hooks have no `hooks run` timeout, so a hung guard is bounded by the agent's own hook timeout. Before 0.12.21 an unconfigured PreToolUse guard also exited 1, and the guarded command ran. Agents that wire `hooks run <name>` into their settings on an unconfigured machine therefore need either a registry credential or `HASNA_HOOKS_LOCAL=1` in the hook's environment.
|
|
609
701
|
|
|
610
702
|
Surfaces that never open the client store and are server/operator-only by design need neither setting: `serve` (`hooks-serve`), `cf`, `migrate`, `init`, `profile-export`/`profile-import`, `channels`, `events`, and `--help`/`--version`. `hooks mcp` and the `hooks-mcp` bin decide their authority themselves before any transport connects (below).
|
|
611
703
|
|
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// hooks/hook-scratch-lifecycle/src/hook.ts
|
|
5
|
+
import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, statSync } from "fs";
|
|
6
|
+
import { homedir } from "os";
|
|
7
|
+
import { delimiter, dirname, join as join2, sep } from "path";
|
|
8
|
+
|
|
9
|
+
// src/lib/readiness-process.ts
|
|
10
|
+
import { spawn } from "child_process";
|
|
11
|
+
var supervisor = String.raw`
|
|
12
|
+
const {spawn}=require("node:child_process");
|
|
13
|
+
const spec=JSON.parse(process.argv.at(-1));
|
|
14
|
+
// This runtime was created detached and is its group's live leader. Its
|
|
15
|
+
// independent timer and parent pipe remain effective if the observer exits
|
|
16
|
+
// or its event loop stops responding. Only this freshly created tree is hit.
|
|
17
|
+
const cleanup=()=>{try{process.kill(-process.pid,"SIGKILL")}catch{process.exit(1)}};
|
|
18
|
+
setTimeout(cleanup,spec.timeout);
|
|
19
|
+
process.stdin.once("end",cleanup);
|
|
20
|
+
process.stdin.once("error",cleanup);
|
|
21
|
+
process.stdin.on("data",cleanup);
|
|
22
|
+
process.stdin.resume();
|
|
23
|
+
for(const signal of ["SIGTERM","SIGINT","SIGHUP"])process.once(signal,cleanup);
|
|
24
|
+
let done=false, out=Buffer.alloc(0), err=Buffer.alloc(0);
|
|
25
|
+
function report(status,error){
|
|
26
|
+
if(done)return; done=true;
|
|
27
|
+
process.stdout.write(JSON.stringify({status,error,stdout:out.toString("utf8"),stderr:err.toString("utf8")})+"\n");
|
|
28
|
+
}
|
|
29
|
+
const child=spawn(spec.command,spec.args,{stdio:["ignore","pipe","pipe"],env:process.env});
|
|
30
|
+
for(const [stream,name] of [[child.stdout,"stdout"],[child.stderr,"stderr"]]){
|
|
31
|
+
stream.on("data",bytes=>{
|
|
32
|
+
if(done)return;
|
|
33
|
+
const before=name==="stdout"?out:err;
|
|
34
|
+
if(before.length+bytes.length>spec.maxBuffer){report(null,{code:"ENOBUFS"});return}
|
|
35
|
+
if(name==="stdout")out=Buffer.concat([out,bytes]);else err=Buffer.concat([err,bytes]);
|
|
36
|
+
});
|
|
37
|
+
stream.on("error",()=>report(null,{code:"ECHILD"}));
|
|
38
|
+
}
|
|
39
|
+
child.on("error",()=>report(null,{code:"ECHILD"}));
|
|
40
|
+
// A successful observation includes complete streams. A nested client that
|
|
41
|
+
// keeps them open after its parent exits is a failure requiring group cleanup.
|
|
42
|
+
child.on("exit",()=>setTimeout(()=>report(null,{code:"ECHILD"}),100));
|
|
43
|
+
child.on("close",(status,signal)=>report(status,signal?{code:"ECHILD"}:undefined));
|
|
44
|
+
`;
|
|
45
|
+
function runReadinessProcess(command, args, options) {
|
|
46
|
+
if (!["darwin", "linux"].includes(process.platform)) {
|
|
47
|
+
return Promise.resolve({ status: null, error: { code: "ENOTSUP" }, stdout: "", stderr: "" });
|
|
48
|
+
}
|
|
49
|
+
if (options.signal?.aborted) {
|
|
50
|
+
return Promise.resolve({ status: null, error: { code: "ABORT_ERR" }, stdout: "", stderr: "" });
|
|
51
|
+
}
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
const child = spawn(command, ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", "--eval", supervisor, "--", JSON.stringify({ command, args, maxBuffer: options.maxBuffer, timeout: options.timeout })], {
|
|
54
|
+
cwd: options.cwd,
|
|
55
|
+
env: options.env,
|
|
56
|
+
detached: true,
|
|
57
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
58
|
+
});
|
|
59
|
+
let status = null, error;
|
|
60
|
+
let stopping = false, exited = false, finished = false;
|
|
61
|
+
let stdout = "", stderr = "", control = "";
|
|
62
|
+
const maximumEnvelope = options.maxBuffer * 12 + 1024;
|
|
63
|
+
let cleanup;
|
|
64
|
+
const finish = () => {
|
|
65
|
+
if (finished)
|
|
66
|
+
return;
|
|
67
|
+
finished = true;
|
|
68
|
+
clearTimeout(deadline);
|
|
69
|
+
clearTimeout(cleanup);
|
|
70
|
+
options.signal?.removeEventListener("abort", abort);
|
|
71
|
+
child.stdin?.destroy();
|
|
72
|
+
child.stdout?.destroy();
|
|
73
|
+
child.stderr?.destroy();
|
|
74
|
+
resolve({ status, error, stdout, stderr });
|
|
75
|
+
};
|
|
76
|
+
const stop = (code) => {
|
|
77
|
+
if (code && !finished)
|
|
78
|
+
error ??= { code };
|
|
79
|
+
if (finished || stopping)
|
|
80
|
+
return;
|
|
81
|
+
stopping = true;
|
|
82
|
+
if (exited || !child.pid) {
|
|
83
|
+
error ??= { code: "ECHILD" };
|
|
84
|
+
} else {
|
|
85
|
+
try {
|
|
86
|
+
child.stdin.end();
|
|
87
|
+
} catch {
|
|
88
|
+
error = { code: "ECHILD" };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
cleanup = setTimeout(() => {
|
|
92
|
+
error = { code: "ECHILD" };
|
|
93
|
+
finish();
|
|
94
|
+
}, 1000);
|
|
95
|
+
};
|
|
96
|
+
const abort = () => stop("ABORT_ERR");
|
|
97
|
+
const deadline = setTimeout(() => stop("ETIMEDOUT"), options.timeout);
|
|
98
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
99
|
+
if (options.signal?.aborted)
|
|
100
|
+
abort();
|
|
101
|
+
child.stdin?.on("error", () => {
|
|
102
|
+
if (!stopping)
|
|
103
|
+
stop("ECHILD");
|
|
104
|
+
});
|
|
105
|
+
child.stdout?.on("data", (bytes) => {
|
|
106
|
+
if (stopping)
|
|
107
|
+
return;
|
|
108
|
+
control += bytes.toString("utf8");
|
|
109
|
+
if (Buffer.byteLength(control) > maximumEnvelope)
|
|
110
|
+
return stop("ENOBUFS");
|
|
111
|
+
if (!control.endsWith(`
|
|
112
|
+
`))
|
|
113
|
+
return;
|
|
114
|
+
try {
|
|
115
|
+
const value = JSON.parse(control);
|
|
116
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !["status", "error", "stdout", "stderr"].includes(key)) || !(value.status === null || Number.isInteger(value.status) && value.status >= 0 && value.status <= 255) || typeof value.stdout !== "string" || typeof value.stderr !== "string" || Buffer.byteLength(value.stdout) > options.maxBuffer || Buffer.byteLength(value.stderr) > options.maxBuffer || value.error !== undefined && (Object.keys(value.error).join() !== "code" || !["ENOBUFS", "ECHILD"].includes(value.error.code))) {
|
|
117
|
+
return stop("EPROTO");
|
|
118
|
+
}
|
|
119
|
+
status = value.status;
|
|
120
|
+
stdout = value.stdout;
|
|
121
|
+
stderr = value.stderr;
|
|
122
|
+
stop(value.error?.code);
|
|
123
|
+
} catch {
|
|
124
|
+
stop("EPROTO");
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
child.stdout?.on("error", () => stop("EPROTO"));
|
|
128
|
+
child.stderr?.on("data", () => stop("ECHILD"));
|
|
129
|
+
child.stderr?.on("error", () => stop("ECHILD"));
|
|
130
|
+
child.on("error", () => {
|
|
131
|
+
error = { code: "ECHILD" };
|
|
132
|
+
stop();
|
|
133
|
+
});
|
|
134
|
+
child.on("exit", () => {
|
|
135
|
+
exited = true;
|
|
136
|
+
if (!stopping)
|
|
137
|
+
stop("ECHILD");
|
|
138
|
+
});
|
|
139
|
+
child.on("close", () => {
|
|
140
|
+
if (!stopping)
|
|
141
|
+
error = { code: "ECHILD" };
|
|
142
|
+
finish();
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// hooks/hook-scratch-lifecycle/src/lifecycle.ts
|
|
148
|
+
import { join } from "path";
|
|
149
|
+
var LIFECYCLE_SCHEMA = "hasna.scratch.lifecycle.v1";
|
|
150
|
+
var HOOK_NAME = "scratch-lifecycle";
|
|
151
|
+
var HOOK_VERSION = "0.1.0";
|
|
152
|
+
var SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
153
|
+
var UUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
|
|
154
|
+
var CLOSED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
|
|
155
|
+
var START_SOURCES = new Set(["startup", "resume", "clear", "fork"]);
|
|
156
|
+
var REASON = /^[a-z_]{1,32}$/;
|
|
157
|
+
var MAX_LINKS_ARG_BYTES = 64 * 1024;
|
|
158
|
+
function isRecord(value) {
|
|
159
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
160
|
+
}
|
|
161
|
+
function isLifecycle(value) {
|
|
162
|
+
if (!isRecord(value) || value.schema !== LIFECYCLE_SCHEMA)
|
|
163
|
+
return false;
|
|
164
|
+
if (value.closedAt !== undefined && value.closedAt !== null && (typeof value.closedAt !== "string" || !CLOSED_AT.test(value.closedAt)))
|
|
165
|
+
return false;
|
|
166
|
+
return value.disposal === "disposed-on-close" || value.disposal === "retain-until" || value.disposal === "no-delete";
|
|
167
|
+
}
|
|
168
|
+
function defaultLifecycle(harness, sessionId, station) {
|
|
169
|
+
return {
|
|
170
|
+
schema: LIFECYCLE_SCHEMA,
|
|
171
|
+
owner: { harness, sessionId, station, agent: null },
|
|
172
|
+
disposal: "disposed-on-close",
|
|
173
|
+
until: null,
|
|
174
|
+
untilEvent: null,
|
|
175
|
+
setBy: `hooks/${HOOK_NAME}@${HOOK_VERSION}`,
|
|
176
|
+
closedAt: null,
|
|
177
|
+
closeReason: null
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
function parseJson(text) {
|
|
181
|
+
try {
|
|
182
|
+
return JSON.parse(text);
|
|
183
|
+
} catch {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async function ensureSession(sessionId, harness, deps) {
|
|
188
|
+
const purpose = `${harness} session ${sessionId}: purpose not declared`;
|
|
189
|
+
const result = await deps.run(["--session", sessionId, "--json", "workspace", "--purpose", purpose]);
|
|
190
|
+
const value = parseJson(result.stdout);
|
|
191
|
+
if (result.status !== 0 || !isRecord(value) || value.ok !== true || value.sessionId !== sessionId)
|
|
192
|
+
return "scratchpad_unavailable";
|
|
193
|
+
return value.path === join(deps.scratchRoot, sessionId) ? undefined : "scratchpad_path_mismatch";
|
|
194
|
+
}
|
|
195
|
+
async function readSession(sessionId, deps) {
|
|
196
|
+
const result = await deps.run(["--local", "--session", sessionId, "--json", "meta"]);
|
|
197
|
+
const value = parseJson(result.stdout);
|
|
198
|
+
if (result.status !== 0 || !isRecord(value) || !isRecord(value.manifest))
|
|
199
|
+
return;
|
|
200
|
+
const manifest = value.manifest;
|
|
201
|
+
const revision = value.revision ?? manifest.revision;
|
|
202
|
+
if (manifest.sessionId !== sessionId || !Number.isSafeInteger(revision) || revision < 1)
|
|
203
|
+
return;
|
|
204
|
+
return { revision, links: isRecord(manifest.links) ? manifest.links : {} };
|
|
205
|
+
}
|
|
206
|
+
async function writeLinks(sessionId, session, lifecycle, deps) {
|
|
207
|
+
const patch = `links=${JSON.stringify({ ...session.links, lifecycle })}`;
|
|
208
|
+
if (Buffer.byteLength(JSON.stringify(patch)) > MAX_LINKS_ARG_BYTES)
|
|
209
|
+
return "too_large";
|
|
210
|
+
const result = await deps.run([
|
|
211
|
+
"--local",
|
|
212
|
+
"--session",
|
|
213
|
+
sessionId,
|
|
214
|
+
"--json",
|
|
215
|
+
"meta",
|
|
216
|
+
"--set",
|
|
217
|
+
patch,
|
|
218
|
+
"--expected-revision",
|
|
219
|
+
String(session.revision)
|
|
220
|
+
]);
|
|
221
|
+
const value = parseJson(result.stdout);
|
|
222
|
+
if (result.status === 0 && isRecord(value) && value.ok === true && value.applied === true)
|
|
223
|
+
return "applied";
|
|
224
|
+
if (isRecord(value) && isRecord(value.error) && value.error.code === "CONFLICT")
|
|
225
|
+
return "conflict";
|
|
226
|
+
return "failed";
|
|
227
|
+
}
|
|
228
|
+
async function update(sessionId, deps, next) {
|
|
229
|
+
for (let attempt = 0;attempt < 2; attempt++) {
|
|
230
|
+
const session = await readSession(sessionId, deps);
|
|
231
|
+
if (!session)
|
|
232
|
+
return { reason: "scratchpad_unavailable" };
|
|
233
|
+
const plan = next(session);
|
|
234
|
+
if (!plan.lifecycle)
|
|
235
|
+
return plan;
|
|
236
|
+
const written = await writeLinks(sessionId, session, plan.lifecycle, deps);
|
|
237
|
+
if (written === "applied")
|
|
238
|
+
return plan;
|
|
239
|
+
if (written === "too_large")
|
|
240
|
+
return { reason: "links_too_large" };
|
|
241
|
+
if (written === "failed")
|
|
242
|
+
return { reason: "scratchpad_refused" };
|
|
243
|
+
}
|
|
244
|
+
return { reason: "scratchpad_conflict" };
|
|
245
|
+
}
|
|
246
|
+
function reopenedContext(path, sessionId, closedAt) {
|
|
247
|
+
return `Scratch tree ${path} (session ${sessionId}) was closed at ${closedAt} with disposal disposed-on-close, and this session reopened it. ` + "Before the session ends, move what is no longer needed to Trash (`trash put`), or record a longer retention as the scratch-tree lifecycle rule describes.";
|
|
248
|
+
}
|
|
249
|
+
async function handleEvent(raw, harness, deps) {
|
|
250
|
+
if (!isRecord(raw))
|
|
251
|
+
return { output: {}, reason: "invalid_input" };
|
|
252
|
+
const event = raw.hook_event_name;
|
|
253
|
+
const given = raw.session_id;
|
|
254
|
+
if (typeof given !== "string" || !SESSION_ID.test(given) || given.endsWith("."))
|
|
255
|
+
return { output: {}, reason: "invalid_input" };
|
|
256
|
+
const sessionId = UUID.test(given) ? given.toLowerCase() : given;
|
|
257
|
+
if (event === "SessionStart") {
|
|
258
|
+
const source = typeof raw.source === "string" ? raw.source : "startup";
|
|
259
|
+
if (source === "compact")
|
|
260
|
+
return { output: {}, reason: "skipped_compact" };
|
|
261
|
+
if (!START_SOURCES.has(source))
|
|
262
|
+
return { output: {}, reason: "invalid_input" };
|
|
263
|
+
const failure = await ensureSession(sessionId, harness, deps);
|
|
264
|
+
if (failure)
|
|
265
|
+
return { output: {}, reason: failure };
|
|
266
|
+
const path = join(deps.scratchRoot, sessionId);
|
|
267
|
+
const result = await update(sessionId, deps, (session) => {
|
|
268
|
+
const current = session.links.lifecycle;
|
|
269
|
+
if (current === undefined)
|
|
270
|
+
return { lifecycle: defaultLifecycle(harness, sessionId, deps.station), reason: "lifecycle_written" };
|
|
271
|
+
if (!isLifecycle(current))
|
|
272
|
+
return { reason: "lifecycle_foreign" };
|
|
273
|
+
if (typeof current.closedAt !== "string")
|
|
274
|
+
return { reason: "lifecycle_present" };
|
|
275
|
+
const context = current.disposal === "disposed-on-close" ? reopenedContext(path, sessionId, current.closedAt) : undefined;
|
|
276
|
+
return { lifecycle: { ...current, closedAt: null, closeReason: null }, reason: "lifecycle_reopened", context };
|
|
277
|
+
});
|
|
278
|
+
const output = result.context && result.reason === "lifecycle_reopened" ? { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: result.context } } : {};
|
|
279
|
+
return { output, reason: result.reason };
|
|
280
|
+
}
|
|
281
|
+
if (event === "SessionEnd") {
|
|
282
|
+
if (!deps.treeExists(sessionId))
|
|
283
|
+
return { output: {}, reason: "no_scratch_tree" };
|
|
284
|
+
const closeReason = typeof raw.reason === "string" && REASON.test(raw.reason) ? raw.reason : "other";
|
|
285
|
+
const closedAt = deps.now().toISOString();
|
|
286
|
+
const result = await update(sessionId, deps, (session) => {
|
|
287
|
+
const current = session.links.lifecycle;
|
|
288
|
+
if (current !== undefined && !isLifecycle(current))
|
|
289
|
+
return { reason: "lifecycle_foreign" };
|
|
290
|
+
const base = current ?? defaultLifecycle(harness, sessionId, deps.station);
|
|
291
|
+
return { lifecycle: { ...base, closedAt, closeReason }, reason: "lifecycle_closed" };
|
|
292
|
+
});
|
|
293
|
+
return { output: {}, reason: result.reason };
|
|
294
|
+
}
|
|
295
|
+
return { output: {}, reason: "invalid_input" };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// hooks/hook-scratch-lifecycle/src/hook.ts
|
|
299
|
+
var CALL_TIMEOUT_MS = 4000;
|
|
300
|
+
var TOTAL_BUDGET_MS = 1e4;
|
|
301
|
+
var MIN_CALL_MS = 1000;
|
|
302
|
+
var STATION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
303
|
+
var MAX_ROOT_BYTES = 64 * 1024;
|
|
304
|
+
var MAX_OUTPUT_BYTES = 256 * 1024;
|
|
305
|
+
var MAX_INPUT_BYTES = 256 * 1024;
|
|
306
|
+
function readHookInput(stream = process.stdin) {
|
|
307
|
+
return new Promise((resolve) => {
|
|
308
|
+
const chunks = [];
|
|
309
|
+
let size = 0, done = false;
|
|
310
|
+
const finish = (value) => {
|
|
311
|
+
if (done)
|
|
312
|
+
return;
|
|
313
|
+
done = true;
|
|
314
|
+
clearTimeout(timer);
|
|
315
|
+
stream.removeListener("data", onData);
|
|
316
|
+
stream.removeListener("end", onEnd);
|
|
317
|
+
stream.removeListener("error", onError);
|
|
318
|
+
stream.pause();
|
|
319
|
+
resolve(value);
|
|
320
|
+
};
|
|
321
|
+
const onData = (chunk) => {
|
|
322
|
+
const bytes = Buffer.from(chunk);
|
|
323
|
+
size += bytes.length;
|
|
324
|
+
if (size > MAX_INPUT_BYTES)
|
|
325
|
+
return finish();
|
|
326
|
+
chunks.push(bytes);
|
|
327
|
+
};
|
|
328
|
+
const onEnd = () => {
|
|
329
|
+
try {
|
|
330
|
+
finish(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
331
|
+
} catch {
|
|
332
|
+
finish();
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
const onError = () => finish();
|
|
336
|
+
const timer = setTimeout(() => finish(), 1000);
|
|
337
|
+
stream.on("data", onData);
|
|
338
|
+
stream.on("end", onEnd);
|
|
339
|
+
stream.on("error", onError);
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
function owned(path, uid) {
|
|
343
|
+
const stat = statSync(path);
|
|
344
|
+
return stat.uid === uid && (stat.mode & 18) === 0;
|
|
345
|
+
}
|
|
346
|
+
function safeDirectory(path, uid) {
|
|
347
|
+
const stat = statSync(path);
|
|
348
|
+
return (stat.uid === uid || stat.uid === 0) && (stat.mode & 18) === 0;
|
|
349
|
+
}
|
|
350
|
+
function resolveTrusted(path, uid) {
|
|
351
|
+
if (!path.startsWith(sep))
|
|
352
|
+
return;
|
|
353
|
+
let pending = path.split(sep).filter(Boolean), current = sep, links = 0;
|
|
354
|
+
while (pending.length > 0) {
|
|
355
|
+
const part = pending.shift();
|
|
356
|
+
if (part === ".")
|
|
357
|
+
continue;
|
|
358
|
+
if (part === "..") {
|
|
359
|
+
current = dirname(current);
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
const next = join2(current, part);
|
|
363
|
+
if (!lstatSync(next).isSymbolicLink()) {
|
|
364
|
+
current = next;
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (++links > 16 || !safeDirectory(current, uid))
|
|
368
|
+
return;
|
|
369
|
+
const target = readlinkSync(next);
|
|
370
|
+
if (target.startsWith(sep))
|
|
371
|
+
current = sep;
|
|
372
|
+
pending = [...target.split(sep).filter(Boolean), ...pending];
|
|
373
|
+
}
|
|
374
|
+
return current;
|
|
375
|
+
}
|
|
376
|
+
function resolveScratchpadScript(path, home, uid) {
|
|
377
|
+
let root;
|
|
378
|
+
try {
|
|
379
|
+
root = realpathSync(home);
|
|
380
|
+
} catch {
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
const dirs = [...(path ?? "").split(delimiter).filter((dir) => dir.startsWith("/")), join2(home, ".bun", "bin"), join2(home, ".local", "bin")];
|
|
384
|
+
for (const dir of dirs) {
|
|
385
|
+
const candidate = join2(dir, "scratchpad");
|
|
386
|
+
try {
|
|
387
|
+
if (!existsSync(candidate))
|
|
388
|
+
continue;
|
|
389
|
+
const real = resolveTrusted(candidate, uid);
|
|
390
|
+
if (!real || !real.endsWith(".js") || !real.startsWith(root + sep) || !statSync(real).isFile())
|
|
391
|
+
continue;
|
|
392
|
+
let ok = owned(real, uid);
|
|
393
|
+
for (let current = dirname(real);ok && current !== root; current = dirname(current))
|
|
394
|
+
ok = owned(current, uid);
|
|
395
|
+
if (ok)
|
|
396
|
+
return real;
|
|
397
|
+
} catch {
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
function scratchpadRunner(script, home) {
|
|
404
|
+
const childEnv = {
|
|
405
|
+
HOME: home,
|
|
406
|
+
PATH: [dirname(process.execPath), "/usr/bin", "/bin"].join(delimiter),
|
|
407
|
+
LANG: "C.UTF-8",
|
|
408
|
+
TZ: "UTC"
|
|
409
|
+
};
|
|
410
|
+
return async (args, timeoutMs) => {
|
|
411
|
+
const result = await runReadinessProcess(process.execPath, ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", script, ...args], {
|
|
412
|
+
cwd: home,
|
|
413
|
+
env: childEnv,
|
|
414
|
+
timeout: timeoutMs,
|
|
415
|
+
maxBuffer: MAX_OUTPUT_BYTES
|
|
416
|
+
});
|
|
417
|
+
return { status: result.status, stdout: result.stdout, error: result.error };
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function withBudget(run, budgetMs, clock = () => performance.now()) {
|
|
421
|
+
const deadline = clock() + budgetMs;
|
|
422
|
+
return async (args) => {
|
|
423
|
+
const remaining = deadline - clock();
|
|
424
|
+
if (remaining < MIN_CALL_MS)
|
|
425
|
+
return { status: null, stdout: "", error: { code: "ETIMEDOUT" } };
|
|
426
|
+
return run(args, Math.min(CALL_TIMEOUT_MS, remaining));
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
function rootStation(rootFile) {
|
|
430
|
+
try {
|
|
431
|
+
const stat = lstatSync(rootFile);
|
|
432
|
+
if (!stat.isFile() || stat.size > MAX_ROOT_BYTES)
|
|
433
|
+
return null;
|
|
434
|
+
const value = JSON.parse(readFileSync(rootFile, "utf8"));
|
|
435
|
+
return typeof value.stationId === "string" && STATION_ID.test(value.stationId) ? value.stationId : null;
|
|
436
|
+
} catch {
|
|
437
|
+
return null;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
var processIo = {
|
|
441
|
+
input: process.stdin,
|
|
442
|
+
stdout: (text) => {
|
|
443
|
+
process.stdout.write(text);
|
|
444
|
+
},
|
|
445
|
+
stderr: (text) => {
|
|
446
|
+
process.stderr.write(text);
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
async function main(argv = process.argv.slice(2), env = process.env, io = processIo) {
|
|
450
|
+
let output = {}, reason = "invalid_configuration";
|
|
451
|
+
try {
|
|
452
|
+
const harness = argv.length === 2 && argv[0] === "--harness" && (argv[1] === "claude" || argv[1] === "codex") ? argv[1] : undefined;
|
|
453
|
+
if (env.HOOKS_SCRATCH_LIFECYCLE_DISABLED === "1")
|
|
454
|
+
reason = "disabled";
|
|
455
|
+
else if (harness) {
|
|
456
|
+
const home = env.HOME || homedir();
|
|
457
|
+
const raw = await readHookInput(io.input);
|
|
458
|
+
const scratchRoot = join2(home, ".hasna", "scratchpad", "scratch");
|
|
459
|
+
const rootFile = join2(home, ".hasna", "scratchpad", ".scratchpad", "root.json");
|
|
460
|
+
let runner, unavailable;
|
|
461
|
+
const run = async (args) => {
|
|
462
|
+
if (!runner) {
|
|
463
|
+
if (!existsSync(rootFile))
|
|
464
|
+
unavailable = "scratchpad_root_absent";
|
|
465
|
+
const script = unavailable ? undefined : resolveScratchpadScript(env.PATH, home, process.getuid?.() ?? -1);
|
|
466
|
+
if (!script) {
|
|
467
|
+
unavailable ??= "scratchpad_not_installed";
|
|
468
|
+
return { status: null, stdout: "", error: { code: "ENOENT" } };
|
|
469
|
+
}
|
|
470
|
+
runner = withBudget(scratchpadRunner(script, home), TOTAL_BUDGET_MS);
|
|
471
|
+
}
|
|
472
|
+
return runner(args);
|
|
473
|
+
};
|
|
474
|
+
const result = await handleEvent(raw, harness, {
|
|
475
|
+
run,
|
|
476
|
+
treeExists: (sessionId) => existsSync(join2(scratchRoot, sessionId)),
|
|
477
|
+
scratchRoot,
|
|
478
|
+
station: rootStation(rootFile),
|
|
479
|
+
now: () => new Date
|
|
480
|
+
});
|
|
481
|
+
output = result.output;
|
|
482
|
+
reason = unavailable ?? result.reason;
|
|
483
|
+
}
|
|
484
|
+
} catch {
|
|
485
|
+
reason = "lifecycle_unavailable";
|
|
486
|
+
}
|
|
487
|
+
io.stderr(JSON.stringify({ hook: HOOK_NAME, reason: /^[a-z_]{1,64}$/.test(reason) ? reason : "lifecycle_unavailable" }) + `
|
|
488
|
+
`);
|
|
489
|
+
io.stdout(JSON.stringify(output) + `
|
|
490
|
+
`);
|
|
491
|
+
}
|
|
492
|
+
if (import.meta.main)
|
|
493
|
+
await main();
|
|
494
|
+
export {
|
|
495
|
+
withBudget,
|
|
496
|
+
scratchpadRunner,
|
|
497
|
+
rootStation,
|
|
498
|
+
resolveScratchpadScript,
|
|
499
|
+
readHookInput,
|
|
500
|
+
main
|
|
501
|
+
};
|