@hasna/hooks 0.12.19 → 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 +129 -3
- package/bin/hooks/scratch-lifecycle.js +501 -0
- package/bin/hooks-mcp.js +5199 -3025
- package/bin/index.js +6207 -3610
- package/bin/native-safety-worker.cjs +1 -1
- package/bin/serve.js +15 -1
- package/dist/index.js +5534 -3359
- package/dist/lib/claude-skills-coordination.d.ts +1 -1
- package/dist/lib/codex-safety-check.d.ts +4 -0
- 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
|
@@ -13,7 +13,7 @@ export declare class ClaudeSettingsRefusal extends Error {
|
|
|
13
13
|
* as any file type. A lookup error other than ENOENT/ENOTDIR counts as present.
|
|
14
14
|
* Returns the evidence found; an empty list means Skills is genuinely absent. */
|
|
15
15
|
export declare function claudeSkillsUsage(before: string | null, home: string): string[];
|
|
16
|
-
/** Every location the bundled Skills package (@hasna/skills 0.10.
|
|
16
|
+
/** Every location the bundled Skills package (@hasna/skills 0.10.71, `getDataRoot`)
|
|
17
17
|
* considers for `agent-policy.json`, in its resolution order, with the outcome
|
|
18
18
|
* at each. Only called after Skills found no policy at the selected location. */
|
|
19
19
|
export declare function skillsPolicyLocations(dataDir?: string): string[];
|
|
@@ -3,6 +3,10 @@ import { verifyNativeSafetyCommand } from "../native-safety.js";
|
|
|
3
3
|
/** Exact `codex --version` outputs whose app-server protocol was measured
|
|
4
4
|
* against the real native binary. Anything else refuses as native_unsupported. */
|
|
5
5
|
export declare const SUPPORTED_CODEX_SAFETY_VERSIONS: readonly ["codex-cli 0.153.0", "codex-cli 0.154.0", "codex-cli 0.154.0-alpha.6.1", "codex-cli 0.155.0", "codex-cli 0.155.1", "codex-cli 0.156.1", "codex-cli 0.157.0", "codex-cli 0.157.1", "codex-cli 0.158.0", "codex-cli 0.159.0", "codex-cli 0.159.2", "codex-cli 0.159.3", "codex-cli 0.160.0", "codex-cli 0.160.1", "codex-cli 0.161.0", "codex-cli 0.162.0", "codex-cli 0.162.1"];
|
|
6
|
+
/** Hard sanity bound on the native Codex executable, which is read whole into
|
|
7
|
+
* memory for the header check and SHA-256 pin. Not a platform contract: the
|
|
8
|
+
* measured 0.162.1 binaries are 246.6 MB (darwin-arm64) to 294.4 MB (linux-x64). */
|
|
9
|
+
export declare const CODEX_EXECUTABLE_MAX_BYTES = 512000000;
|
|
6
10
|
export type CodexSafetyCode = "native_unavailable" | "native_unsafe_executable" | "native_executable_required" | "native_unsupported" | "native_failed" | "native_discovery_failed" | "hooks_disabled" | "guard_missing" | "guard_ambiguous" | "guard_definition_invalid" | "guard_disabled" | "guard_untrusted" | "guard_changed" | "guard_failed";
|
|
7
11
|
export declare class CodexSafetyError extends Error {
|
|
8
12
|
readonly code: CodexSafetyCode;
|
package/dist/lib/hook-env.d.ts
CHANGED
|
@@ -35,8 +35,9 @@
|
|
|
35
35
|
* fleet credential env AFTER the deny list ran. The interpreter-injection
|
|
36
36
|
* set below strips every variable that makes a child interpreter run or
|
|
37
37
|
* source code the hook did not ask for (sourcing vectors, interpreter option
|
|
38
|
-
* lists, module/startup injection,
|
|
39
|
-
* redirection, gconv/locale module injection). Exact
|
|
38
|
+
* lists, module/startup injection, Bun runtime configuration, dynamic-loader
|
|
39
|
+
* preloads, TLS-trust redirection, gconv/locale module injection). Exact
|
|
40
|
+
* case-sensitive names and prefixes:
|
|
40
41
|
* POSIX interpreters read these literals, and a differently-cased variant is
|
|
41
42
|
* an inert, unrelated variable.
|
|
42
43
|
*
|
package/dist/lib/run.d.ts
CHANGED
|
@@ -42,4 +42,13 @@ export declare class HookTimeoutError extends Error {
|
|
|
42
42
|
readonly timeoutMs: number;
|
|
43
43
|
constructor(timeoutMs: number);
|
|
44
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Bun flags for a hook child (HO-00087). The child keeps the harness's working
|
|
47
|
+
* directory, because hooks read process.cwd() as the project they guard, and
|
|
48
|
+
* Bun reads bunfig.toml (whose `preload` runs code) and .env from that
|
|
49
|
+
* directory by default. These flags stop both, and stop macros and auto-install.
|
|
50
|
+
* BUN_OPTIONS still applies through them, so buildHookEnv strips every BUN_*
|
|
51
|
+
* name as well.
|
|
52
|
+
*/
|
|
53
|
+
export declare const BUN_ISOLATION_FLAGS: readonly ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install"];
|
|
45
54
|
export declare function executeVerifiedScript(options: VerifiedRunOptions): Promise<VerifiedRunResult>;
|
package/dist/serve.d.ts
CHANGED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Scratch lifecycle
|
|
2
|
+
|
|
3
|
+
Keep lifecycle metadata on every session scratch tree, so a weekly census can tell
|
|
4
|
+
which trees are still wanted. A session scratch tree is
|
|
5
|
+
`~/.hasna/scratchpad/scratch/<session-id>/`. The metadata lives in that tree's own
|
|
6
|
+
Scratchpad manifest (`meta.json`, schema `hasna.scratchpad.session.v1`), under
|
|
7
|
+
`links.lifecycle`. There is no second manifest file.
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"schema": "hasna.scratch.lifecycle.v1",
|
|
12
|
+
"owner": { "harness": "claude", "sessionId": "<id>", "station": "<Scratchpad root stationId>", "agent": null },
|
|
13
|
+
"disposal": "disposed-on-close",
|
|
14
|
+
"until": null,
|
|
15
|
+
"untilEvent": null,
|
|
16
|
+
"setBy": "hooks/scratch-lifecycle@0.1.0",
|
|
17
|
+
"closedAt": null,
|
|
18
|
+
"closeReason": null
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`owner.station` is the Scratchpad root's own `stationId` (from `.scratchpad/root.json`,
|
|
23
|
+
read only when it is a regular file under 64 KiB), or `null` when it is not a plain
|
|
24
|
+
label. The hook never guesses a station. A root created without `HASNA_STATION` records
|
|
25
|
+
the hostname, and the hook then records that. The manifest's own
|
|
26
|
+
`purpose` and `createdAt` record the purpose and creation time. For a
|
|
27
|
+
tree that existed before Scratchpad recorded it, `createdAt` is when it was adopted.
|
|
28
|
+
`disposal` is one of `disposed-on-close`, `retain-until` (with `until`, an ISO-8601
|
|
29
|
+
time, or `untilEvent`) and `no-delete`. A `no-delete` tree should also be pinned
|
|
30
|
+
(`pinned: true` with a `pinReason`), so Scratchpad's own collection skips it.
|
|
31
|
+
|
|
32
|
+
## Events
|
|
33
|
+
|
|
34
|
+
Install for Claude Code or Codex: `hooks install scratch-lifecycle` or
|
|
35
|
+
`hooks install scratch-lifecycle --target codex`. The registration runs
|
|
36
|
+
`hooks run scratch-lifecycle --target <harness>` on both events.
|
|
37
|
+
|
|
38
|
+
- **SessionStart** (`startup`, `resume`, `clear`, `fork`; `compact` is skipped):
|
|
39
|
+
- `scratchpad --session <id> workspace` creates the session, or adopts a tree that
|
|
40
|
+
was created without Scratchpad;
|
|
41
|
+
- when no lifecycle is recorded, the default above is written;
|
|
42
|
+
- a recorded lifecycle is never replaced;
|
|
43
|
+
- a tree that was closed is reopened (`closedAt` and `closeReason` cleared). When its
|
|
44
|
+
disposal is `disposed-on-close`, the agent is told in its session context, so it
|
|
45
|
+
can clean up or record a longer retention. A tree that is never resumed is left to
|
|
46
|
+
the census.
|
|
47
|
+
- **SessionEnd**, only when the tree and its manifest already exist: `closedAt` and
|
|
48
|
+
`closeReason` are recorded. It never calls `workspace`, so it cannot recreate a tree
|
|
49
|
+
that was moved to Trash or renew its lifetime.
|
|
50
|
+
- On a station without a Scratchpad root (`~/.hasna/scratchpad/.scratchpad/root.json`),
|
|
51
|
+
the hook does nothing: the root's station identity belongs to the station's own setup.
|
|
52
|
+
|
|
53
|
+
## Guarantees
|
|
54
|
+
|
|
55
|
+
- Every write goes through the `scratchpad` CLI with `--expected-revision`. One
|
|
56
|
+
conflict gets one re-read and one retry. The hook writes the complete merged
|
|
57
|
+
`links` object, because a `links.<key>` patch replaces all of `links`.
|
|
58
|
+
- A lifecycle whose schema or disposal the hook does not recognise is left
|
|
59
|
+
untouched at both events, and so is one whose `closedAt` is neither null nor an
|
|
60
|
+
ISO-8601 UTC time.
|
|
61
|
+
- The manifest can be written by any process of the same user, so the session-context
|
|
62
|
+
text is built only from values the hook builds or validates: its own path, the
|
|
63
|
+
grammar-checked session ID and an ISO-8601 close time. The CLI's reported path must
|
|
64
|
+
equal the hook's own.
|
|
65
|
+
- A `links` patch over 64 KiB, counted as the bounded supervisor JSON-encodes it, is
|
|
66
|
+
reported (`links_too_large`), never truncated.
|
|
67
|
+
- Nothing is deleted, and no existing process is signalled. Each CLI call runs under
|
|
68
|
+
the package's bounded supervisor, which ends only its own new process group. Disposal
|
|
69
|
+
stays with the owner's `trash put` and the census's reconciliation.
|
|
70
|
+
- Each CLI call gets at most 4 s, and all calls of one event share a 10 s budget, under
|
|
71
|
+
the 15 s registration timeout.
|
|
72
|
+
- The CLI child runs with this hook's Bun, an explicit environment (`HOME`, `PATH`,
|
|
73
|
+
`LANG=C.UTF-8`, `TZ=UTC`), HOME as its working directory and Bun's `--config=/dev/null
|
|
74
|
+
--no-env-file --no-macros --no-install`, so the harness project's configuration never
|
|
75
|
+
runs in it. The hook process itself is started by `hooks run`.
|
|
76
|
+
- The CLI path is resolved one component at a time, as the kernel does. Every symlink
|
|
77
|
+
met on the way, file or directory link (at most 16), must sit in a directory owned by
|
|
78
|
+
the current user or root and not writable by group or others. The resolved file must
|
|
79
|
+
be a `.js` script inside HOME, and it and every directory from it up to HOME must be
|
|
80
|
+
owned by the current user and not writable by group or others.
|
|
81
|
+
- Every failure is fail-open: the hook prints `{}` and one stderr line with a fixed
|
|
82
|
+
reason code, and never blocks the session.
|
|
83
|
+
- `HOOKS_SCRATCH_LIFECYCLE_DISABLED=1` turns the hook off.
|
|
84
|
+
|
|
85
|
+
Not covered:
|
|
86
|
+
- Gemini has no session events in this package's installer, and Sumi does not use `hooks run`.
|
|
87
|
+
- A Scratchpad root moved with `HASNA_SCRATCHPAD_DIR` is not followed, because the hook
|
|
88
|
+
environment never carries `HASNA_*` variables.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "scratch-lifecycle",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Record owner, purpose and disposal for each session scratch tree in its Scratchpad manifest",
|
|
5
|
+
"events": ["SessionStart", "SessionEnd"],
|
|
6
|
+
"nativeTargetDispatch": true,
|
|
7
|
+
"script": "src/hook.ts",
|
|
8
|
+
"script_kind": "file",
|
|
9
|
+
"timeout_ms": 15000
|
|
10
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "hook-scratch-lifecycle",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Keep lifecycle metadata on every session scratch tree in its Scratchpad manifest",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/hook.ts",
|
|
7
|
+
"private": true,
|
|
8
|
+
"scripts": { "typecheck": "tsc --noEmit" },
|
|
9
|
+
"author": "Hasna",
|
|
10
|
+
"license": "Apache-2.0"
|
|
11
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { delimiter, dirname, join, sep } from "node:path";
|
|
5
|
+
import { runReadinessProcess } from "../../../src/lib/readiness-process";
|
|
6
|
+
import { handleEvent, HOOK_NAME, type CliResult, type Harness } from "./lifecycle";
|
|
7
|
+
|
|
8
|
+
const CALL_TIMEOUT_MS = 4000;
|
|
9
|
+
/** All CLI calls of one invocation share this budget, which stays under the 15 s registration timeout. */
|
|
10
|
+
const TOTAL_BUDGET_MS = 10_000;
|
|
11
|
+
const MIN_CALL_MS = 1000;
|
|
12
|
+
const STATION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
13
|
+
const MAX_ROOT_BYTES = 64 * 1024;
|
|
14
|
+
const MAX_OUTPUT_BYTES = 256 * 1024;
|
|
15
|
+
const MAX_INPUT_BYTES = 256 * 1024;
|
|
16
|
+
|
|
17
|
+
/** Only reads this newly invoked hook's stdin; no parent session/process is controlled. */
|
|
18
|
+
export function readHookInput(stream: NodeJS.ReadableStream = process.stdin): Promise<unknown> {
|
|
19
|
+
return new Promise((resolve) => {
|
|
20
|
+
const chunks: Buffer[] = [];
|
|
21
|
+
let size = 0, done = false;
|
|
22
|
+
const finish = (value?: unknown) => {
|
|
23
|
+
if (done) return; done = true; clearTimeout(timer);
|
|
24
|
+
stream.removeListener("data", onData); stream.removeListener("end", onEnd); stream.removeListener("error", onError);
|
|
25
|
+
stream.pause(); resolve(value);
|
|
26
|
+
};
|
|
27
|
+
const onData = (chunk: Buffer | string) => {
|
|
28
|
+
const bytes = Buffer.from(chunk);
|
|
29
|
+
size += bytes.length;
|
|
30
|
+
if (size > MAX_INPUT_BYTES) return finish();
|
|
31
|
+
chunks.push(bytes);
|
|
32
|
+
};
|
|
33
|
+
const onEnd = () => { try { finish(JSON.parse(Buffer.concat(chunks).toString("utf8"))); } catch { finish(); } };
|
|
34
|
+
const onError = () => finish();
|
|
35
|
+
const timer = setTimeout(() => finish(), 1000);
|
|
36
|
+
stream.on("data", onData); stream.on("end", onEnd); stream.on("error", onError);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Owned by this user and writable by nobody else. */
|
|
41
|
+
function owned(path: string, uid: number): boolean {
|
|
42
|
+
const stat = statSync(path);
|
|
43
|
+
return stat.uid === uid && (stat.mode & 0o022) === 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Owned by this user or root, and writable by nobody else. */
|
|
47
|
+
function safeDirectory(path: string, uid: number): boolean {
|
|
48
|
+
const stat = statSync(path);
|
|
49
|
+
return (stat.uid === uid || stat.uid === 0) && (stat.mode & 0o022) === 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Resolve an absolute path one component at a time, as the kernel does. Every
|
|
54
|
+
* symlink met on the way, a file link or a directory link, decides where the path
|
|
55
|
+
* leads, so the directory holding it must be safe. `..` applies to the directory
|
|
56
|
+
* already resolved, never to the link's text. At most 16 links are followed.
|
|
57
|
+
*/
|
|
58
|
+
function resolveTrusted(path: string, uid: number): string | undefined {
|
|
59
|
+
if (!path.startsWith(sep)) return undefined;
|
|
60
|
+
let pending: string[] = path.split(sep).filter(Boolean), current: string = sep, links = 0;
|
|
61
|
+
while (pending.length > 0) {
|
|
62
|
+
const part = pending.shift()!;
|
|
63
|
+
if (part === ".") continue;
|
|
64
|
+
if (part === "..") { current = dirname(current); continue; }
|
|
65
|
+
const next = join(current, part);
|
|
66
|
+
if (!lstatSync(next).isSymbolicLink()) { current = next; continue; }
|
|
67
|
+
if (++links > 16 || !safeDirectory(current, uid)) return undefined;
|
|
68
|
+
const target = readlinkSync(next);
|
|
69
|
+
if (target.startsWith(sep)) current = sep;
|
|
70
|
+
pending = [...target.split(sep).filter(Boolean), ...pending];
|
|
71
|
+
}
|
|
72
|
+
return current;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The installed Scratchpad CLI script: the first `scratchpad` on PATH or in the usual
|
|
77
|
+
* user bin directories that meets every check below.
|
|
78
|
+
* - Every symlink met while resolving it sits in a directory owned by this user or
|
|
79
|
+
* root and writable by nobody else, since those directories decide which file runs.
|
|
80
|
+
* - Its real file is a `.js` script inside HOME.
|
|
81
|
+
* - The file and every directory from it up to HOME are this user's alone.
|
|
82
|
+
*/
|
|
83
|
+
export function resolveScratchpadScript(path: string | undefined, home: string, uid: number): string | undefined {
|
|
84
|
+
let root: string;
|
|
85
|
+
try { root = realpathSync(home); } catch { return undefined; }
|
|
86
|
+
const dirs = [...(path ?? "").split(delimiter).filter((dir) => dir.startsWith("/")), join(home, ".bun", "bin"), join(home, ".local", "bin")];
|
|
87
|
+
for (const dir of dirs) {
|
|
88
|
+
const candidate = join(dir, "scratchpad");
|
|
89
|
+
try {
|
|
90
|
+
if (!existsSync(candidate)) continue;
|
|
91
|
+
const real = resolveTrusted(candidate, uid);
|
|
92
|
+
if (!real || !real.endsWith(".js") || !real.startsWith(root + sep) || !statSync(real).isFile()) continue;
|
|
93
|
+
let ok = owned(real, uid);
|
|
94
|
+
for (let current = dirname(real); ok && current !== root; current = dirname(current)) ok = owned(current, uid);
|
|
95
|
+
if (ok) return real;
|
|
96
|
+
} catch { continue; }
|
|
97
|
+
}
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Run the CLI with this hook's own Bun under the reviewed bounded supervisor. The
|
|
103
|
+
* child gets an explicit environment and Bun's isolation flags, so no project
|
|
104
|
+
* bunfig, `.env` or BUN_OPTIONS preload from the harness working directory runs.
|
|
105
|
+
*/
|
|
106
|
+
export function scratchpadRunner(script: string, home: string): (args: string[], timeoutMs: number) => Promise<CliResult> {
|
|
107
|
+
const childEnv: NodeJS.ProcessEnv = {
|
|
108
|
+
HOME: home,
|
|
109
|
+
PATH: [dirname(process.execPath), "/usr/bin", "/bin"].join(delimiter),
|
|
110
|
+
LANG: "C.UTF-8",
|
|
111
|
+
TZ: "UTC",
|
|
112
|
+
};
|
|
113
|
+
return async (args, timeoutMs) => {
|
|
114
|
+
const result = await runReadinessProcess(process.execPath, ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", script, ...args], {
|
|
115
|
+
cwd: home, env: childEnv, timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES,
|
|
116
|
+
});
|
|
117
|
+
return { status: result.status, stdout: result.stdout, error: result.error };
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Share one time budget across every CLI call of an invocation. Each call gets at
|
|
123
|
+
* most CALL_TIMEOUT_MS; once less than MIN_CALL_MS is left, no further call starts.
|
|
124
|
+
*/
|
|
125
|
+
export function withBudget(run: (args: string[], timeoutMs: number) => Promise<CliResult>, budgetMs: number, clock: () => number = () => performance.now()): (args: string[]) => Promise<CliResult> {
|
|
126
|
+
const deadline = clock() + budgetMs;
|
|
127
|
+
return async (args) => {
|
|
128
|
+
const remaining = deadline - clock();
|
|
129
|
+
if (remaining < MIN_CALL_MS) return { status: null, stdout: "", error: { code: "ETIMEDOUT" } };
|
|
130
|
+
return run(args, Math.min(CALL_TIMEOUT_MS, remaining));
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The Scratchpad root's own station identity, when it is a plain label. */
|
|
135
|
+
export function rootStation(rootFile: string): string | null {
|
|
136
|
+
try {
|
|
137
|
+
// A regular file of bounded size only: a FIFO or a device in its place must not stall the hook.
|
|
138
|
+
const stat = lstatSync(rootFile);
|
|
139
|
+
if (!stat.isFile() || stat.size > MAX_ROOT_BYTES) return null;
|
|
140
|
+
const value = JSON.parse(readFileSync(rootFile, "utf8")) as { stationId?: unknown };
|
|
141
|
+
return typeof value.stationId === "string" && STATION_ID.test(value.stationId) ? value.stationId : null;
|
|
142
|
+
} catch { return null; }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface HookIo {
|
|
146
|
+
input: NodeJS.ReadableStream;
|
|
147
|
+
stdout(text: string): void;
|
|
148
|
+
stderr(text: string): void;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const processIo: HookIo = {
|
|
152
|
+
input: process.stdin,
|
|
153
|
+
stdout: (text) => { process.stdout.write(text); },
|
|
154
|
+
stderr: (text) => { process.stderr.write(text); },
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
export async function main(argv = process.argv.slice(2), env = process.env, io: HookIo = processIo): Promise<void> {
|
|
158
|
+
let output: Record<string, unknown> = {}, reason = "invalid_configuration";
|
|
159
|
+
try {
|
|
160
|
+
const harness = argv.length === 2 && argv[0] === "--harness" && (argv[1] === "claude" || argv[1] === "codex") ? argv[1] as Harness : undefined;
|
|
161
|
+
if (env.HOOKS_SCRATCH_LIFECYCLE_DISABLED === "1") reason = "disabled";
|
|
162
|
+
else if (harness) {
|
|
163
|
+
const home = env.HOME || homedir();
|
|
164
|
+
const raw = await readHookInput(io.input);
|
|
165
|
+
const scratchRoot = join(home, ".hasna", "scratchpad", "scratch");
|
|
166
|
+
const rootFile = join(home, ".hasna", "scratchpad", ".scratchpad", "root.json");
|
|
167
|
+
// Resolved on the first CLI call, so skipped and invalid events never look for it.
|
|
168
|
+
let runner: ((args: string[]) => Promise<CliResult>) | undefined, unavailable: string | undefined;
|
|
169
|
+
const run = async (args: string[]): Promise<CliResult> => {
|
|
170
|
+
if (!runner) {
|
|
171
|
+
// Never create a Scratchpad root: its station identity belongs to the station's own setup.
|
|
172
|
+
if (!existsSync(rootFile)) unavailable = "scratchpad_root_absent";
|
|
173
|
+
const script = unavailable ? undefined : resolveScratchpadScript(env.PATH, home, process.getuid?.() ?? -1);
|
|
174
|
+
if (!script) { unavailable ??= "scratchpad_not_installed"; return { status: null, stdout: "", error: { code: "ENOENT" } }; }
|
|
175
|
+
runner = withBudget(scratchpadRunner(script, home), TOTAL_BUDGET_MS);
|
|
176
|
+
}
|
|
177
|
+
return runner(args);
|
|
178
|
+
};
|
|
179
|
+
const result = await handleEvent(raw, harness, {
|
|
180
|
+
run,
|
|
181
|
+
treeExists: (sessionId) => existsSync(join(scratchRoot, sessionId)),
|
|
182
|
+
scratchRoot,
|
|
183
|
+
station: rootStation(rootFile),
|
|
184
|
+
now: () => new Date(),
|
|
185
|
+
});
|
|
186
|
+
output = result.output; reason = unavailable ?? result.reason;
|
|
187
|
+
}
|
|
188
|
+
} catch { reason = "lifecycle_unavailable"; }
|
|
189
|
+
// Fixed machine reasons only. Never expose session content, CLI output or paths.
|
|
190
|
+
io.stderr(JSON.stringify({ hook: HOOK_NAME, reason: /^[a-z_]{1,64}$/.test(reason) ? reason : "lifecycle_unavailable" }) + "\n");
|
|
191
|
+
io.stdout(JSON.stringify(output) + "\n");
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (import.meta.main) await main();
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scratch-tree lifecycle metadata, kept in the session's own Scratchpad manifest.
|
|
3
|
+
*
|
|
4
|
+
* Every session scratch tree (`~/.hasna/scratchpad/scratch/<session-id>/`) carries
|
|
5
|
+
* `links.lifecycle` in its Scratchpad `meta.json` (hasna.scratchpad.session.v1). The
|
|
6
|
+
* hook writes it through the `scratchpad` CLI, never by editing the manifest file:
|
|
7
|
+
*
|
|
8
|
+
* - SessionStart (not `compact`): create or adopt the session with `workspace`, then
|
|
9
|
+
* write the default lifecycle when none is recorded. A tree that was closed is
|
|
10
|
+
* reopened; a reopened `disposed-on-close` tree is surfaced to the agent.
|
|
11
|
+
* - SessionEnd: record `closedAt` and `closeReason` in an existing manifest. It never
|
|
12
|
+
* calls `workspace`, so it cannot recreate a tree that was moved to Trash.
|
|
13
|
+
*
|
|
14
|
+
* `scratchpad meta --set links.<key>=…` replaces the whole `links` object, so the
|
|
15
|
+
* hook always writes the complete merged `links` under `--expected-revision`.
|
|
16
|
+
* The manifest is writable by any process of the same user, so only values this
|
|
17
|
+
* hook validates or builds itself reach the agent's context. Nothing is deleted,
|
|
18
|
+
* no existing process is signalled, and every failure is fail-open.
|
|
19
|
+
*/
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
|
|
22
|
+
export type Harness = "claude" | "codex";
|
|
23
|
+
export type Disposal = "disposed-on-close" | "retain-until" | "no-delete";
|
|
24
|
+
|
|
25
|
+
export const LIFECYCLE_SCHEMA = "hasna.scratch.lifecycle.v1";
|
|
26
|
+
export const HOOK_NAME = "scratch-lifecycle";
|
|
27
|
+
export const HOOK_VERSION = "0.1.0";
|
|
28
|
+
|
|
29
|
+
/** Scratchpad's session-ID grammar; it also keeps the ID a single path segment. */
|
|
30
|
+
const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
31
|
+
/** Scratchpad stores a UUID session ID in lower case, so the hook does too. */
|
|
32
|
+
const 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}$/;
|
|
33
|
+
/** The only close-time shape that counts as closed, and the only one ever shown to an agent. */
|
|
34
|
+
const CLOSED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
|
|
35
|
+
const START_SOURCES = new Set(["startup", "resume", "clear", "fork"]);
|
|
36
|
+
const REASON = /^[a-z_]{1,32}$/;
|
|
37
|
+
/**
|
|
38
|
+
* Bound on the `links=…` argument as the bounded supervisor carries it (JSON-encoded,
|
|
39
|
+
* so quotes and backslashes count twice). Well under the per-argument limit; a larger
|
|
40
|
+
* `links` object is reported, never truncated.
|
|
41
|
+
*/
|
|
42
|
+
const MAX_LINKS_ARG_BYTES = 64 * 1024;
|
|
43
|
+
|
|
44
|
+
export interface Lifecycle {
|
|
45
|
+
schema: typeof LIFECYCLE_SCHEMA;
|
|
46
|
+
owner: { harness: Harness; sessionId: string; station: string | null; agent: string | null };
|
|
47
|
+
disposal: Disposal;
|
|
48
|
+
until: string | null;
|
|
49
|
+
untilEvent: string | null;
|
|
50
|
+
setBy: string;
|
|
51
|
+
closedAt: string | null;
|
|
52
|
+
closeReason: string | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface CliResult {
|
|
56
|
+
status: number | null;
|
|
57
|
+
stdout: string;
|
|
58
|
+
error?: { code?: string };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface LifecycleDeps {
|
|
62
|
+
/** Runs `scratchpad <args>` with a hard bound; never throws. */
|
|
63
|
+
run(args: string[]): Promise<CliResult>;
|
|
64
|
+
/** Whether the session's scratch tree already exists (SessionEnd never creates one). */
|
|
65
|
+
treeExists(sessionId: string): boolean;
|
|
66
|
+
/** The scratch root the CLI must report; the hook builds every path it shows from it. */
|
|
67
|
+
scratchRoot: string;
|
|
68
|
+
/** The Scratchpad root's own station identity, or null; never a hostname guess. */
|
|
69
|
+
station: string | null;
|
|
70
|
+
now(): Date;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface Outcome {
|
|
74
|
+
output: Record<string, unknown>;
|
|
75
|
+
reason: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface Session {
|
|
79
|
+
revision: number;
|
|
80
|
+
links: Record<string, unknown>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
84
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A lifecycle this hook can safely update; anything else is left untouched. */
|
|
88
|
+
export function isLifecycle(value: unknown): value is Lifecycle {
|
|
89
|
+
if (!isRecord(value) || value.schema !== LIFECYCLE_SCHEMA) return false;
|
|
90
|
+
if (value.closedAt !== undefined && value.closedAt !== null && (typeof value.closedAt !== "string" || !CLOSED_AT.test(value.closedAt))) return false;
|
|
91
|
+
return value.disposal === "disposed-on-close" || value.disposal === "retain-until" || value.disposal === "no-delete";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function defaultLifecycle(harness: Harness, sessionId: string, station: string | null): Lifecycle {
|
|
95
|
+
return {
|
|
96
|
+
schema: LIFECYCLE_SCHEMA,
|
|
97
|
+
owner: { harness, sessionId, station, agent: null },
|
|
98
|
+
disposal: "disposed-on-close",
|
|
99
|
+
until: null,
|
|
100
|
+
untilEvent: null,
|
|
101
|
+
setBy: `hooks/${HOOK_NAME}@${HOOK_VERSION}`,
|
|
102
|
+
closedAt: null,
|
|
103
|
+
closeReason: null,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function parseJson(text: string): unknown {
|
|
108
|
+
try { return JSON.parse(text); } catch { return undefined; }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Create or adopt the session; its path must be exactly the one the hook expects. */
|
|
112
|
+
async function ensureSession(sessionId: string, harness: Harness, deps: LifecycleDeps): Promise<string | undefined> {
|
|
113
|
+
const purpose = `${harness} session ${sessionId}: purpose not declared`;
|
|
114
|
+
const result = await deps.run(["--session", sessionId, "--json", "workspace", "--purpose", purpose]);
|
|
115
|
+
const value = parseJson(result.stdout);
|
|
116
|
+
if (result.status !== 0 || !isRecord(value) || value.ok !== true || value.sessionId !== sessionId) return "scratchpad_unavailable";
|
|
117
|
+
return value.path === join(deps.scratchRoot, sessionId) ? undefined : "scratchpad_path_mismatch";
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function readSession(sessionId: string, deps: LifecycleDeps): Promise<Session | undefined> {
|
|
121
|
+
const result = await deps.run(["--local", "--session", sessionId, "--json", "meta"]);
|
|
122
|
+
const value = parseJson(result.stdout);
|
|
123
|
+
if (result.status !== 0 || !isRecord(value) || !isRecord(value.manifest)) return undefined;
|
|
124
|
+
const manifest = value.manifest;
|
|
125
|
+
const revision = value.revision ?? manifest.revision;
|
|
126
|
+
if (manifest.sessionId !== sessionId || !Number.isSafeInteger(revision) || (revision as number) < 1) return undefined;
|
|
127
|
+
return { revision: revision as number, links: isRecord(manifest.links) ? manifest.links : {} };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
type WriteResult = "applied" | "conflict" | "failed" | "too_large";
|
|
131
|
+
|
|
132
|
+
async function writeLinks(sessionId: string, session: Session, lifecycle: Lifecycle, deps: LifecycleDeps): Promise<WriteResult> {
|
|
133
|
+
const patch = `links=${JSON.stringify({ ...session.links, lifecycle })}`;
|
|
134
|
+
if (Buffer.byteLength(JSON.stringify(patch)) > MAX_LINKS_ARG_BYTES) return "too_large";
|
|
135
|
+
const result = await deps.run([
|
|
136
|
+
"--local", "--session", sessionId, "--json", "meta",
|
|
137
|
+
"--set", patch,
|
|
138
|
+
"--expected-revision", String(session.revision),
|
|
139
|
+
]);
|
|
140
|
+
const value = parseJson(result.stdout);
|
|
141
|
+
if (result.status === 0 && isRecord(value) && value.ok === true && value.applied === true) return "applied";
|
|
142
|
+
if (isRecord(value) && isRecord(value.error) && value.error.code === "CONFLICT") return "conflict";
|
|
143
|
+
return "failed";
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Read the manifest, compute the next lifecycle and write it under the observed
|
|
148
|
+
* revision. A concurrent write gets one re-read and one retry, never a blind overwrite.
|
|
149
|
+
*/
|
|
150
|
+
async function update(
|
|
151
|
+
sessionId: string,
|
|
152
|
+
deps: LifecycleDeps,
|
|
153
|
+
next: (session: Session) => { lifecycle?: Lifecycle; reason: string; context?: string },
|
|
154
|
+
): Promise<{ reason: string; context?: string }> {
|
|
155
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
156
|
+
const session = await readSession(sessionId, deps);
|
|
157
|
+
if (!session) return { reason: "scratchpad_unavailable" };
|
|
158
|
+
const plan = next(session);
|
|
159
|
+
if (!plan.lifecycle) return plan;
|
|
160
|
+
const written = await writeLinks(sessionId, session, plan.lifecycle, deps);
|
|
161
|
+
if (written === "applied") return plan;
|
|
162
|
+
if (written === "too_large") return { reason: "links_too_large" };
|
|
163
|
+
if (written === "failed") return { reason: "scratchpad_refused" };
|
|
164
|
+
}
|
|
165
|
+
return { reason: "scratchpad_conflict" };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Built only from the hook's own path, a grammar-checked session ID and a validated time. */
|
|
169
|
+
function reopenedContext(path: string, sessionId: string, closedAt: string): string {
|
|
170
|
+
return `Scratch tree ${path} (session ${sessionId}) was closed at ${closedAt} with disposal disposed-on-close, and this session reopened it. `
|
|
171
|
+
+ "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.";
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export async function handleEvent(raw: unknown, harness: Harness, deps: LifecycleDeps): Promise<Outcome> {
|
|
175
|
+
if (!isRecord(raw)) return { output: {}, reason: "invalid_input" };
|
|
176
|
+
const event = raw.hook_event_name;
|
|
177
|
+
const given = raw.session_id;
|
|
178
|
+
if (typeof given !== "string" || !SESSION_ID.test(given) || given.endsWith(".")) return { output: {}, reason: "invalid_input" };
|
|
179
|
+
const sessionId = UUID.test(given) ? given.toLowerCase() : given;
|
|
180
|
+
|
|
181
|
+
if (event === "SessionStart") {
|
|
182
|
+
const source = typeof raw.source === "string" ? raw.source : "startup";
|
|
183
|
+
if (source === "compact") return { output: {}, reason: "skipped_compact" };
|
|
184
|
+
if (!START_SOURCES.has(source)) return { output: {}, reason: "invalid_input" };
|
|
185
|
+
const failure = await ensureSession(sessionId, harness, deps);
|
|
186
|
+
if (failure) return { output: {}, reason: failure };
|
|
187
|
+
const path = join(deps.scratchRoot, sessionId);
|
|
188
|
+
const result = await update(sessionId, deps, (session) => {
|
|
189
|
+
const current = session.links.lifecycle;
|
|
190
|
+
if (current === undefined) return { lifecycle: defaultLifecycle(harness, sessionId, deps.station), reason: "lifecycle_written" };
|
|
191
|
+
// isLifecycle also refuses any close time other than an ISO-8601 UTC time.
|
|
192
|
+
if (!isLifecycle(current)) return { reason: "lifecycle_foreign" };
|
|
193
|
+
// Only a recorded close time means closed; an agent-written lifecycle may omit it.
|
|
194
|
+
if (typeof current.closedAt !== "string") return { reason: "lifecycle_present" };
|
|
195
|
+
const context = current.disposal === "disposed-on-close" ? reopenedContext(path, sessionId, current.closedAt) : undefined;
|
|
196
|
+
return { lifecycle: { ...current, closedAt: null, closeReason: null }, reason: "lifecycle_reopened", context };
|
|
197
|
+
});
|
|
198
|
+
const output = result.context && result.reason === "lifecycle_reopened"
|
|
199
|
+
? { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: result.context } }
|
|
200
|
+
: {};
|
|
201
|
+
return { output, reason: result.reason };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (event === "SessionEnd") {
|
|
205
|
+
if (!deps.treeExists(sessionId)) return { output: {}, reason: "no_scratch_tree" };
|
|
206
|
+
const closeReason = typeof raw.reason === "string" && REASON.test(raw.reason) ? raw.reason : "other";
|
|
207
|
+
const closedAt = deps.now().toISOString();
|
|
208
|
+
const result = await update(sessionId, deps, (session) => {
|
|
209
|
+
const current = session.links.lifecycle;
|
|
210
|
+
if (current !== undefined && !isLifecycle(current)) return { reason: "lifecycle_foreign" };
|
|
211
|
+
const base = current ?? defaultLifecycle(harness, sessionId, deps.station);
|
|
212
|
+
return { lifecycle: { ...base, closedAt, closeReason }, reason: "lifecycle_closed" };
|
|
213
|
+
});
|
|
214
|
+
return { output: {}, reason: result.reason };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return { output: {}, reason: "invalid_input" };
|
|
218
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hasna/hooks",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.21",
|
|
4
4
|
"description": "Open source hooks library for AI coding agents - Install safety, quality, and automation hooks with a single command",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -62,6 +62,12 @@
|
|
|
62
62
|
},
|
|
63
63
|
"keywords": [
|
|
64
64
|
"claude-code",
|
|
65
|
+
"codex",
|
|
66
|
+
"opencode",
|
|
67
|
+
"sumi",
|
|
68
|
+
"ai-agents",
|
|
69
|
+
"agent-safety",
|
|
70
|
+
"mcp",
|
|
65
71
|
"hooks",
|
|
66
72
|
"cli",
|
|
67
73
|
"typescript",
|
|
@@ -81,7 +87,7 @@
|
|
|
81
87
|
"@hasna/contracts": "~1.2.1"
|
|
82
88
|
},
|
|
83
89
|
"dependencies": {
|
|
84
|
-
"@hasna/skills": "0.10.
|
|
90
|
+
"@hasna/skills": "0.10.71",
|
|
85
91
|
"@hasna/events": "^0.1.16",
|
|
86
92
|
"@hasna/secrets": "0.4.2",
|
|
87
93
|
"@modelcontextprotocol/sdk": "1.31.0",
|
|
@@ -38,6 +38,18 @@ for (const meta of entries) {
|
|
|
38
38
|
assert.equal(sdk.exitCode, 0, sdk.stderr);
|
|
39
39
|
assert.deepEqual(sdk.output, {});
|
|
40
40
|
}
|
|
41
|
+
// A compact SessionStart runs the whole bundle but never reaches the Scratchpad
|
|
42
|
+
// CLI, so the proof writes nothing and needs no Scratchpad install.
|
|
43
|
+
if (meta.name === "scratch-lifecycle") {
|
|
44
|
+
const input = JSON.stringify({ hook_event_name: "SessionStart", session_id: "packed-probe", source: "compact" });
|
|
45
|
+
const result = spawnSync(process.execPath, [expected, "--harness", "codex"], {
|
|
46
|
+
cwd: ${JSON.stringify(consumerDir)}, encoding: "utf8", input, timeout: 5000,
|
|
47
|
+
env: { PATH: process.env.PATH, HOME: process.env.HOME }
|
|
48
|
+
});
|
|
49
|
+
assert.equal(result.status, 0, result.stderr);
|
|
50
|
+
assert.deepEqual(JSON.parse(result.stdout), {});
|
|
51
|
+
assert.deepEqual(JSON.parse(result.stderr), { hook: "scratch-lifecycle", reason: "skipped_compact" });
|
|
52
|
+
}
|
|
41
53
|
// A broken published bundle must fail closed even while its historical raw
|
|
42
54
|
// hook source is still packed. Only this synthetic extracted copy is moved.
|
|
43
55
|
const missing = expected + ".fixture-missing";
|