@hasna/hooks 0.12.22 → 0.13.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/README.md +36 -0
- package/bin/hooks/scratch-lifecycle.js +5 -5
- package/bin/hooks/stop-review.js +23 -8
- package/bin/hooks-mcp.js +1901 -1213
- package/bin/index.js +3355 -1978
- package/bin/native-safety-entry.js +37 -37
- package/bin/native-safety-worker.cjs +37 -37
- package/bin/serve.js +125 -121
- package/dist/index.js +2304 -1548
- package/dist/lib/claude-skills-coordination.d.ts +1 -1
- package/dist/lib/installer.d.ts +44 -5
- package/dist/lib/manifest.d.ts +21 -0
- package/dist/lib/native-safety.d.ts +24 -0
- package/dist/lib/native-target.d.ts +11 -2
- package/dist/lib/registry.d.ts +12 -0
- package/dist/lib/sumi-stop-plugin.d.ts +4 -0
- package/dist/lib/target-adapters.d.ts +151 -0
- package/dist/lib/targets.d.ts +99 -0
- package/dist/native-readiness.js +11 -11
- package/dist/native-safety.js +183 -24
- package/dist/opencode-stop-plugin.js +17 -7
- package/dist/sdk/index.js +60 -16
- package/dist/storage.js +34 -34
- package/dist/sumi-stop-plugin.js +29 -10
- package/hooks/hook-announce-stop/src/hook.ts +91 -15
- package/hooks/hook-stop-review/README.md +7 -0
- package/hooks/hook-stop-review/src/policy.ts +21 -4
- package/hooks/hook-stop-review/src/runtime.ts +4 -3
- package/hooks/hook-stop-review/src/types.ts +6 -0
- package/hooks/hook-trash-guard/src/hook.ts +108 -12
- package/package.json +2 -2
|
@@ -109,26 +109,102 @@ function postToSpace(summary: string): void {
|
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
+
interface TodoTaskRef {
|
|
113
|
+
id?: unknown;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The tasks an `--format json` list page carries, or null when the payload is
|
|
118
|
+
* not that envelope.
|
|
119
|
+
*
|
|
120
|
+
* `--json` writes a bare array whose completeness is stated on stderr, and a
|
|
121
|
+
* byte-limited page is refused outright: non-zero exit, error document on
|
|
122
|
+
* stdout, no rows. The envelope spelling carries its own page facts, so this
|
|
123
|
+
* reads `tasks` from the document and reports anything else as unreadable
|
|
124
|
+
* rather than as "no tasks".
|
|
125
|
+
*/
|
|
126
|
+
export function tasksFromListEnvelope(raw: string): TodoTaskRef[] | null {
|
|
127
|
+
let payload: unknown;
|
|
128
|
+
try {
|
|
129
|
+
payload = JSON.parse(raw);
|
|
130
|
+
} catch {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
|
|
134
|
+
const tasks = (payload as { tasks?: unknown }).tasks;
|
|
135
|
+
if (!Array.isArray(tasks)) return null;
|
|
136
|
+
return tasks.filter((task): task is TodoTaskRef => Boolean(task) && typeof task === "object");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The reason a failed `todos` call gave, taken from its own error document on
|
|
141
|
+
* stdout first, then from the first line of its stderr message, then from the
|
|
142
|
+
* error itself. Never throws: a hook must not fail while describing a failure.
|
|
143
|
+
*/
|
|
144
|
+
export function failureReason(error: unknown): string {
|
|
145
|
+
if (error && typeof error === "object") {
|
|
146
|
+
const record = error as { stdout?: unknown; stderr?: unknown; message?: unknown };
|
|
147
|
+
for (const stream of [record.stdout, record.stderr]) {
|
|
148
|
+
if (typeof stream !== "string") continue;
|
|
149
|
+
const text = stream.trim();
|
|
150
|
+
if (!text) continue;
|
|
151
|
+
let parsed: unknown;
|
|
152
|
+
try {
|
|
153
|
+
parsed = JSON.parse(text);
|
|
154
|
+
} catch {
|
|
155
|
+
parsed = undefined;
|
|
156
|
+
}
|
|
157
|
+
if (parsed && typeof parsed === "object") {
|
|
158
|
+
const reason = (parsed as { error?: unknown }).error;
|
|
159
|
+
if (typeof reason === "string" && reason.trim()) return reason.trim();
|
|
160
|
+
// A JSON document without an error reason says nothing useful here.
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
const firstLine = text.split("\n")[0]?.trim();
|
|
164
|
+
if (firstLine) return firstLine;
|
|
165
|
+
}
|
|
166
|
+
if (typeof record.message === "string" && record.message.trim()) {
|
|
167
|
+
return record.message.trim().split("\n")[0]!.trim();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return "unknown error";
|
|
171
|
+
}
|
|
172
|
+
|
|
112
173
|
function updateInProgressTasks(sessionId: string): void {
|
|
174
|
+
// `--format json` is the spelling that carries its page facts. `--json`
|
|
175
|
+
// refuses a byte-limited page instead of writing a shortened array, so its
|
|
176
|
+
// exit status must never be read as "no tasks" — it is said out loud once.
|
|
177
|
+
let output: string;
|
|
113
178
|
try {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
`todos list --status in_progress --json`,
|
|
179
|
+
output = execSync(
|
|
180
|
+
`todos list --status in_progress --format json`,
|
|
117
181
|
{ encoding: "utf-8", timeout: 10_000, stdio: ["pipe", "pipe", "pipe"] }
|
|
118
182
|
);
|
|
119
|
-
|
|
120
|
-
|
|
183
|
+
} catch (error) {
|
|
184
|
+
console.error(
|
|
185
|
+
`[hook-announce-stop] Could not list in-progress tasks (${failureReason(error)}); no task notes were added`
|
|
186
|
+
);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
121
189
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
190
|
+
const tasks = tasksFromListEnvelope(output.trim());
|
|
191
|
+
if (tasks === null) {
|
|
192
|
+
console.error(
|
|
193
|
+
"[hook-announce-stop] Could not read the in-progress task list: the output was not a task-list envelope; no task notes were added"
|
|
194
|
+
);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (tasks.length === 0) return;
|
|
198
|
+
|
|
199
|
+
for (const task of tasks.slice(0, 10)) {
|
|
200
|
+
if (typeof task.id !== "string" || !task.id) continue;
|
|
201
|
+
try {
|
|
202
|
+
execSync(
|
|
203
|
+
`todos comment ${task.id} "Session ${sessionId.slice(0, 8)} ended — task may need to be resumed"`,
|
|
204
|
+
{ encoding: "utf-8", timeout: 5_000, stdio: ["pipe", "pipe", "pipe"] }
|
|
205
|
+
);
|
|
206
|
+
} catch {}
|
|
207
|
+
}
|
|
132
208
|
}
|
|
133
209
|
|
|
134
210
|
export function run(): void {
|
|
@@ -75,6 +75,13 @@ receive a terminal assessment; an actionable result at that cap returns
|
|
|
75
75
|
`continuation_limit` and can never request another continuation.
|
|
76
76
|
Only an actual active goal in the captured snapshot is eligible for a
|
|
77
77
|
`complete` or `blocked` settlement certificate; other results certify `none`.
|
|
78
|
+
Sumi may additionally request a recommendation for its own agent-created pause
|
|
79
|
+
only when the session capability, goal snapshot and runtime snapshot all carry
|
|
80
|
+
the exact `parent_final_cas` admission and the paused goal carries native
|
|
81
|
+
`statusSource`, `pauseReason` and `activationEpoch` facts. The recommendation
|
|
82
|
+
never reactivates the goal: Sumi must recheck its current input, holds, limits
|
|
83
|
+
and goal epoch and commit any same-goal continuation itself. A legacy, missing,
|
|
84
|
+
changed or non-Sumi capability keeps the ordinary paused-goal refusal.
|
|
78
85
|
Certification requires confidence and winning probability at least 0.9 and
|
|
79
86
|
actionable probability at most 0.1. Completion additionally requires boundary
|
|
80
87
|
probability at most 0.1; blocked settlement requires at least 0.9. Allowing a
|
|
@@ -11,6 +11,14 @@ const stopReasons = ["end_turn", "user_stop", "cancelled", "error", "approval_wa
|
|
|
11
11
|
const MIN_CERTAINTY = 0.9;
|
|
12
12
|
const MAX_NEGATIVE = 0.1;
|
|
13
13
|
|
|
14
|
+
function hasTruthfulSumiAgentPause(envelope: StopReviewEnvelope, admission?: ParentStopReviewAdmission): boolean {
|
|
15
|
+
const goal = envelope.goal;
|
|
16
|
+
return admission?.mode === "parent_final_cas" && admission.harness === "sumi" && goal?.status === "paused" &&
|
|
17
|
+
goal.statusSource === "agent" && goal.pauseReason === "agent" && Number.isSafeInteger(goal.activationEpoch) &&
|
|
18
|
+
(goal.activationEpoch as number) >= 0 && envelope.runtime.paused === true &&
|
|
19
|
+
envelope.runtime.agentPauseAdmission === "parent_final_cas";
|
|
20
|
+
}
|
|
21
|
+
|
|
14
22
|
export function isStopReviewEnvelope(value: unknown): value is StopReviewEnvelope {
|
|
15
23
|
if (!record(value) || value.schema !== "hooks.stop-review.v1" || !identifier(value.sessionId) ||
|
|
16
24
|
!identifier(value.turnId) || !identifier(value.inputRevision) || typeof value.capturedAt !== "string" ||
|
|
@@ -20,8 +28,16 @@ export function isStopReviewEnvelope(value: unknown): value is StopReviewEnvelop
|
|
|
20
28
|
if (!runtimeFlags.every((key) => typeof runtime[key] === "boolean") ||
|
|
21
29
|
!stopReasons.includes(runtime.stopReason as string) || !Number.isSafeInteger(runtime.continuationCount) ||
|
|
22
30
|
(runtime.continuationCount as number) < 0) return false;
|
|
31
|
+
if (runtime.agentPauseAdmission !== undefined && runtime.agentPauseAdmission !== "parent_final_cas") return false;
|
|
23
32
|
if (value.goal !== undefined && value.goal !== null && (!record(value.goal) || !identifier(value.goal.id) ||
|
|
24
33
|
!text(value.goal.objective) || !goalStatuses.includes(value.goal.status as string))) return false;
|
|
34
|
+
if (record(value.goal)) {
|
|
35
|
+
const pauseFacts = [value.goal.statusSource, value.goal.pauseReason, value.goal.activationEpoch];
|
|
36
|
+
const hasPauseFact = pauseFacts.some((fact) => fact !== undefined);
|
|
37
|
+
const exactPauseFacts = value.goal.status === "paused" && value.goal.statusSource === "agent" && value.goal.pauseReason === "agent" &&
|
|
38
|
+
Number.isSafeInteger(value.goal.activationEpoch) && (value.goal.activationEpoch as number) >= 0;
|
|
39
|
+
if (hasPauseFact !== (runtime.agentPauseAdmission !== undefined) || (hasPauseFact && !exactPauseFacts)) return false;
|
|
40
|
+
} else if (runtime.agentPauseAdmission !== undefined) return false;
|
|
25
41
|
if (value.goalAvailability !== undefined && !["known", "unavailable"].includes(value.goalAvailability as string)) return false;
|
|
26
42
|
return true;
|
|
27
43
|
}
|
|
@@ -42,18 +58,19 @@ export function isStopReviewInstruction(value: unknown): value is StopReviewInst
|
|
|
42
58
|
}
|
|
43
59
|
|
|
44
60
|
export function stopPolicyGate(envelope: StopReviewEnvelope, now: number, maxContinuations = 1,
|
|
45
|
-
options: { assessmentOnlyAtCap?: boolean } = {}): StopReviewReason | null {
|
|
61
|
+
options: { assessmentOnlyAtCap?: boolean; admission?: ParentStopReviewAdmission } = {}): StopReviewReason | null {
|
|
46
62
|
const runtime = envelope.runtime;
|
|
63
|
+
const agentPause = hasTruthfulSumiAgentPause(envelope, options.admission);
|
|
47
64
|
if (runtime.userRequestedStop || ["user_stop", "cancelled"].includes(runtime.stopReason)) return "user_stop";
|
|
48
65
|
if (runtime.terminal) return "terminal";
|
|
49
|
-
if (runtime.paused) return "paused";
|
|
66
|
+
if (runtime.paused && !agentPause) return "paused";
|
|
50
67
|
if (runtime.budgetExhausted || runtime.stopReason === "budget_limit") return "budget_limit";
|
|
51
68
|
if (runtime.usageLimited || runtime.stopReason === "usage_limit") return "usage_limit";
|
|
52
69
|
if (runtime.awaitingApproval || runtime.stopReason === "approval_wait") return "approval_wait";
|
|
53
70
|
if (!runtime.nativeContinuationAllowed) return "native_continuation_unavailable";
|
|
54
71
|
if (runtime.stopReason === "error") return "runtime_failure";
|
|
55
72
|
if (runtime.stopReason !== "end_turn" || (envelope.goal === undefined && envelope.goalAvailability !== "unavailable") || envelope.goal?.status === "unknown") return "unknown_runtime";
|
|
56
|
-
if (envelope.goal && envelope.goal.status !== "active") return "goal_not_active";
|
|
73
|
+
if (envelope.goal && envelope.goal.status !== "active" && !agentPause) return "goal_not_active";
|
|
57
74
|
if (runtime.stopHookActive || runtime.continuationCount > maxContinuations ||
|
|
58
75
|
(runtime.continuationCount === maxContinuations && !options.assessmentOnlyAtCap)) return "recursion_guard";
|
|
59
76
|
const age = now - Date.parse(envelope.capturedAt);
|
|
@@ -101,7 +118,7 @@ async function assessStop(input: unknown, options: StopReviewOptions | StopRecom
|
|
|
101
118
|
if (!Number.isInteger(max) || max < 1 || max > 3) return stop("invalid_configuration");
|
|
102
119
|
const now = options.now ?? Date.now;
|
|
103
120
|
const parentGuarded = admission?.mode === "parent_final_cas" && ["sumi", "opencode"].includes(admission.harness);
|
|
104
|
-
const gateOptions = { assessmentOnlyAtCap: parentGuarded };
|
|
121
|
+
const gateOptions = { assessmentOnlyAtCap: parentGuarded, admission };
|
|
105
122
|
const gate = stopPolicyGate(envelope, now(), max, gateOptions);
|
|
106
123
|
if (gate) return stop(gate);
|
|
107
124
|
if (!isStopReviewInstruction(options.instruction)) return stop("instruction_unavailable");
|
|
@@ -224,7 +224,7 @@ export async function runJevProviderChild(raw: unknown, env: NodeJS.ProcessEnv =
|
|
|
224
224
|
!["sumi", "opencode"].includes(raw.admission.harness as string) || Object.keys(raw.admission).sort().join(",") !== "harness,mode" ||
|
|
225
225
|
nativeTarget !== raw.admission.harness)) return { ok: false, reason: "invalid_configuration" };
|
|
226
226
|
const admission = raw.admission as ParentStopReviewAdmission | undefined;
|
|
227
|
-
const gate = stopPolicyGate(raw.envelope, Date.now(), 1, { assessmentOnlyAtCap: !!admission });
|
|
227
|
+
const gate = stopPolicyGate(raw.envelope, Date.now(), 1, { assessmentOnlyAtCap: !!admission, admission });
|
|
228
228
|
if (gate) return { ok: false, reason: gate };
|
|
229
229
|
const instruction = instructionFromContent(raw.instructionContent, config);
|
|
230
230
|
if (!instruction) return { ok: false, reason: "instruction_unavailable" };
|
|
@@ -288,7 +288,9 @@ async function reviewRuntimeEnvelope(raw: unknown, env: NodeJS.ProcessEnv, entry
|
|
|
288
288
|
const envelope = structuredClone(raw);
|
|
289
289
|
const base = { schema: "hooks.stop-review-result.v1" as const, sessionId: envelope.sessionId, turnId: envelope.turnId, inputRevision: envelope.inputRevision };
|
|
290
290
|
const unavailable = (reason: StopReviewResult["reason"]): StopReviewResult => ({ ...base, action: "unavailable", reason });
|
|
291
|
-
const
|
|
291
|
+
const admission: ParentStopReviewAdmission | undefined = isCurrent || !nativeTarget || !["sumi", "opencode"].includes(nativeTarget)
|
|
292
|
+
? undefined : { mode: "parent_final_cas", harness: nativeTarget as ParentStopReviewAdmission["harness"] };
|
|
293
|
+
const gate = stopPolicyGate(envelope, Date.now(), 1, { assessmentOnlyAtCap: !isCurrent, admission });
|
|
292
294
|
if (gate) return { ...base, action: "allow_stop", reason: gate };
|
|
293
295
|
const config = loadNativeRuntimeConfiguration(env);
|
|
294
296
|
if (!config) return unavailable("invalid_configuration");
|
|
@@ -299,7 +301,6 @@ async function reviewRuntimeEnvelope(raw: unknown, env: NodeJS.ProcessEnv, entry
|
|
|
299
301
|
if (!instruction) return unavailable("instruction_unavailable");
|
|
300
302
|
if (!await scanStopReviewContent(envelope, instruction, config, env)) return unavailable("content_scan_failed");
|
|
301
303
|
const requestHash = sha256(JSON.stringify(buildJevRequest(envelope, { model: config.model, instruction })));
|
|
302
|
-
const admission: ParentStopReviewAdmission | undefined = isCurrent ? undefined : { mode: "parent_final_cas", harness: nativeTarget as ParentStopReviewAdmission["harness"] };
|
|
303
304
|
const claimed = claimStopReviewTurn(envelope, env, requestHash, instruction.digest, admission, nativeTarget);
|
|
304
305
|
if (claimed !== "claimed") return unavailable(claimed === "already_claimed" ? "turn_already_reviewed" : "claim_unavailable");
|
|
305
306
|
const options = { model: config.model, instruction, externalContentApproved: true, timeoutMs: 8000,
|
|
@@ -12,6 +12,10 @@ export interface StopReviewEnvelope {
|
|
|
12
12
|
id: string;
|
|
13
13
|
objective: string;
|
|
14
14
|
status: "active" | "complete" | "paused" | "cancelled" | "blocked" | "budget_limited" | "usage_limited" | "unknown";
|
|
15
|
+
/** Native Sumi facts for its narrowly admitted own-agent pause. */
|
|
16
|
+
statusSource?: "agent";
|
|
17
|
+
pauseReason?: "agent";
|
|
18
|
+
activationEpoch?: number;
|
|
15
19
|
} | null;
|
|
16
20
|
/** A native adapter can establish that this harness has no goal API; transcript text cannot set this. */
|
|
17
21
|
goalAvailability?: "known" | "unavailable";
|
|
@@ -26,6 +30,8 @@ export interface StopReviewEnvelope {
|
|
|
26
30
|
nativeContinuationAllowed: boolean;
|
|
27
31
|
stopHookActive: boolean;
|
|
28
32
|
continuationCount: number;
|
|
33
|
+
/** Advertised only for Sumi's native same-goal final-CAS pause admission. */
|
|
34
|
+
agentPauseAdmission?: "parent_final_cas";
|
|
29
35
|
};
|
|
30
36
|
}
|
|
31
37
|
|
|
@@ -1189,42 +1189,138 @@ function isUnder(target: string, root: string): boolean {
|
|
|
1189
1189
|
return target === root || target.startsWith(`${root}${sep}`);
|
|
1190
1190
|
}
|
|
1191
1191
|
|
|
1192
|
+
/**
|
|
1193
|
+
* Session ids the Scratchpad app actually issues, which are mixed case:
|
|
1194
|
+
* `ses_ebbb3f564ffe7PDf32UBmlNI3v`, `01a0af51-8109-72f0-9eac-a3f677b46f08`.
|
|
1195
|
+
* The first version of this carve-out used `^[a-z0-9]…$` and therefore never
|
|
1196
|
+
* matched a real id, so the sanctioned scratch workspace stayed refused and the
|
|
1197
|
+
* cleanup rule that requires agents to clean their own scratch could not run
|
|
1198
|
+
* (Todos 264c4be0). The pattern still refuses dot/underscore/dash-leading names,
|
|
1199
|
+
* whitespace, over-long names and trailing dots.
|
|
1200
|
+
*
|
|
1201
|
+
* The pattern also admits a literal `.` inside a name (`a..`), which is safe
|
|
1202
|
+
* only because of where the value goes: `session` is tested and mentioned, never
|
|
1203
|
+
* joined into a path, and the path being classified has already been normalised
|
|
1204
|
+
* by `resolveLiteralTarget`, so a `..` *segment* cannot survive to this point.
|
|
1205
|
+
* If either of those changes — a second consumer that joins the segment, or a
|
|
1206
|
+
* caller that reaches this function without normalising — re-evaluate the
|
|
1207
|
+
* pattern, because it is not traversal-proof on its own.
|
|
1208
|
+
*/
|
|
1209
|
+
const SCRATCH_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
1210
|
+
|
|
1211
|
+
/**
|
|
1212
|
+
* Whether a session's own root directory (`…/scratch/<session-id>`) counts as
|
|
1213
|
+
* scratch. It does NOT today, and that is a decision rather than an oversight:
|
|
1214
|
+
* removing the root also removes `meta.json` and `.lock`, which this carve-out
|
|
1215
|
+
* treats as app control state. The instruction owner and cyber hold that
|
|
1216
|
+
* decision (Todos 264c4be0); this constant exists so landing it is a one-line
|
|
1217
|
+
* change with the tests already covering both behaviours — not so a caller can
|
|
1218
|
+
* flip it locally.
|
|
1219
|
+
*
|
|
1220
|
+
* Whoever sets it true should know the trade: removing the root removes its
|
|
1221
|
+
* children, so `meta.json` and `.lock` go with it. The "control state is
|
|
1222
|
+
* refused" guarantee is therefore bounded by the parent, not by the file.
|
|
1223
|
+
*/
|
|
1224
|
+
export const SCRATCH_SESSION_ROOT_IS_SCRATCH = false;
|
|
1225
|
+
|
|
1226
|
+
/**
|
|
1227
|
+
* Path segments are interpolated into an operator-visible refusal string, and a
|
|
1228
|
+
* reader pasting that line back into a shell is a real habit. Only echo a
|
|
1229
|
+
* segment that is plainly an identifier; describe anything else generically
|
|
1230
|
+
* rather than replaying quotes, backticks or control bytes into prose.
|
|
1231
|
+
*/
|
|
1232
|
+
const PLAIN_SEGMENT = /^[A-Za-z0-9._@+-]{1,128}$/;
|
|
1233
|
+
const PATH_MAX_RENDERED = 512;
|
|
1234
|
+
/**
|
|
1235
|
+
* Render a path for an operator-visible refusal so that pasting the line back
|
|
1236
|
+
* into a terminal does not execute anything in the name. Control bytes become
|
|
1237
|
+
* `?`, over-long paths are elided, and the result is single-quoted with
|
|
1238
|
+
* embedded quotes escaped as `'\\''` — the shell's own inert form. Backtick
|
|
1239
|
+
* quoting is *not* escaping: a pasted backtick runs command substitution.
|
|
1240
|
+
*
|
|
1241
|
+
* Applies to every operator-supplied path in a refusal. Compile-time constants
|
|
1242
|
+
* (`/etc`, `~/.ssh`) stay in prose backticks: they cannot carry a hostile byte,
|
|
1243
|
+
* and rendering them would imply they came from the command line.
|
|
1244
|
+
*/
|
|
1245
|
+
function renderPath(raw: string): string {
|
|
1246
|
+
const cleaned = raw.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?").slice(0, PATH_MAX_RENDERED);
|
|
1247
|
+
return `'${cleaned.replace(/'/g, `'\\''`)}'`;
|
|
1248
|
+
}
|
|
1249
|
+
function mention(raw: string): string {
|
|
1250
|
+
return PLAIN_SEGMENT.test(raw) ? `\`${raw}\`` : "a name that is not a plain identifier";
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1192
1253
|
/** Literal execution content only; this path shape does not confer task ownership. */
|
|
1193
|
-
function
|
|
1254
|
+
function scratchpadCarveOut(target: string, home: string): { content: true } | { content: false; reason: string } | null {
|
|
1194
1255
|
const prefix = `${join(home, ".hasna", "scratchpad", "scratch")}${sep}`;
|
|
1195
|
-
if (!target.startsWith(prefix)) return
|
|
1256
|
+
if (!target.startsWith(prefix)) return null;
|
|
1196
1257
|
const [session, firstChild] = target.slice(prefix.length).split(sep);
|
|
1197
|
-
if (!session
|
|
1258
|
+
if (!session) return { content: false, reason: "the scratch root itself holds every session, not one session's content" };
|
|
1259
|
+
if (session.endsWith(".") || !SCRATCH_SESSION_ID.test(session)) {
|
|
1260
|
+
return { content: false, reason: `${mention(session)} is not a session id this carve-out accepts (real ids are mixed case, e.g. \`ses_ebbb3f564ffe7PDf32UBmlNI3v\`)` };
|
|
1261
|
+
}
|
|
1262
|
+
if (!firstChild) {
|
|
1263
|
+
return SCRATCH_SESSION_ROOT_IS_SCRATCH
|
|
1264
|
+
? { content: true }
|
|
1265
|
+
: { content: false, reason: `${mention(session)} is a session root; removing it would also remove its \`meta.json\` and \`.lock\` control files, and whether the root itself is scratch is an open decision (Todos 264c4be0) — remove specific children instead` };
|
|
1266
|
+
}
|
|
1198
1267
|
// Session metadata and its mutation lock are app control state, not scratch.
|
|
1199
1268
|
const control = firstChild.normalize("NFKC").toLowerCase();
|
|
1200
|
-
|
|
1269
|
+
// The refusal below prints `control`, never the raw `firstChild`. That is what
|
|
1270
|
+
// makes this branch safe: it can only ever emit one of two ASCII constants,
|
|
1271
|
+
// because the equality test is the thing that guards the print. It is NOT safe
|
|
1272
|
+
// because something sanitised `firstChild` on the way in — `firstChild` may
|
|
1273
|
+
// contain any byte a filesystem allows. If a later edit prints the raw segment
|
|
1274
|
+
// here (to show what was typed, say), that argument no longer holds and the
|
|
1275
|
+
// value must go through `mention`/`renderPath` first.
|
|
1276
|
+
if (control === "meta.json" || control === ".lock") {
|
|
1277
|
+
return { content: false, reason: `\`${control}\` is session control state, not scratch` };
|
|
1278
|
+
}
|
|
1279
|
+
return { content: true };
|
|
1201
1280
|
}
|
|
1202
1281
|
|
|
1282
|
+
|
|
1203
1283
|
/**
|
|
1204
1284
|
* Why `target` belongs to the protected class that is refused rather than
|
|
1205
1285
|
* redirected, or null when it is an ordinary path. Matches both directions:
|
|
1206
1286
|
* the target itself (`rm -rf /etc`) and any ancestor of a protected root
|
|
1207
1287
|
* (`rm -rf /home`).
|
|
1288
|
+
*
|
|
1289
|
+
* This function does NOT normalise `target`. Every current caller passes a path
|
|
1290
|
+
* already produced by `resolveLiteralTarget`, which collapses `.` and `..`
|
|
1291
|
+
* lexically; a future caller that hands over an unnormalised path would let a
|
|
1292
|
+
* literal `..` segment through the scratchpad carve-out, so normalise first.
|
|
1208
1293
|
*/
|
|
1209
1294
|
export function protectedTargetReason(target: string, home: string): string | null {
|
|
1210
1295
|
if (target === home) {
|
|
1211
|
-
return
|
|
1296
|
+
return `${renderPath(target)} is the home directory itself, which is never deleted or trashed. Delete a specific file or directory inside it instead.`;
|
|
1212
1297
|
}
|
|
1213
1298
|
// Root mode, exactly as `pre-bash` evaluates it for a system root: the root
|
|
1214
1299
|
// itself, or any ancestor of it (`rm -rf /home` destroys every home under it).
|
|
1215
1300
|
for (const root of SYSTEM_PROTECTED_ROOTS) {
|
|
1216
1301
|
if (target !== root && !isUnder(root, target)) continue;
|
|
1217
1302
|
return root === "/"
|
|
1218
|
-
?
|
|
1219
|
-
:
|
|
1303
|
+
? `${renderPath(target)} is the filesystem root, which is never deleted.`
|
|
1304
|
+
: `${renderPath(target)} is the system root \`${root}\` (or an ancestor of it), which is never deleted or trashed.`;
|
|
1220
1305
|
}
|
|
1221
1306
|
for (const suffix of PROTECTED_HOME_TREES) {
|
|
1222
1307
|
const root = join(home, suffix);
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1308
|
+
const insideTree = isUnder(target, root);
|
|
1309
|
+
if (!insideTree && !isUnder(root, target)) continue;
|
|
1310
|
+
if (suffix === ".hasna" && insideTree) {
|
|
1311
|
+
const carveOut = scratchpadCarveOut(target, home);
|
|
1312
|
+
if (carveOut?.content === true) continue;
|
|
1313
|
+
// A refused scratchpad path must say which condition refused it, and a
|
|
1314
|
+
// path merely inside `~/.hasna` must not be described as the tree itself:
|
|
1315
|
+
// that sentence sends the reader to a protected root that is already fine
|
|
1316
|
+
// while the actual cause sits under it (Todos 264c4be0).
|
|
1317
|
+
if (carveOut && carveOut.content === false) {
|
|
1318
|
+
return `${renderPath(target)} is inside the protected \`~/${suffix}\` tree and is not sanctioned scratch, because ${carveOut.reason}. Nothing under \`~/${suffix}\` is deleted or trashed outside that one carve-out.`;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
return insideTree
|
|
1322
|
+
? `${renderPath(target)} is inside the protected \`~/${suffix}\` tree, which is never deleted or trashed. Delete a specific file inside it, and only when you are sure.`
|
|
1323
|
+
: `${renderPath(target)} contains the protected \`~/${suffix}\` tree, which is never deleted or trashed. Delete a specific file or directory inside it instead.`;
|
|
1228
1324
|
}
|
|
1229
1325
|
return null;
|
|
1230
1326
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hasna/hooks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
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": {
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"@hasna/contracts": "~1.2.1"
|
|
88
88
|
},
|
|
89
89
|
"dependencies": {
|
|
90
|
-
"@hasna/skills": "0.10.
|
|
90
|
+
"@hasna/skills": "0.10.78",
|
|
91
91
|
"@hasna/events": "^0.1.16",
|
|
92
92
|
"@hasna/secrets": "0.4.2",
|
|
93
93
|
"@modelcontextprotocol/sdk": "1.31.0",
|