pi-permission-classifier 0.6.0 → 0.7.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.
@@ -0,0 +1,444 @@
1
+ /**
2
+ * The target read: the one place the classifier works out which file an ask
3
+ * targets.
4
+ *
5
+ * A path-bearing tool gate (read, write, edit, and any third-party tool the
6
+ * engine treats the same way) fixes the file into the ask's access intent:
7
+ * `matchValues` carries the absolute lexical spelling first and the other
8
+ * spellings after it, and `boundaryValue` carries the symlink-resolved
9
+ * spelling. Two kinds of ask are refused. A bash command has no single target:
10
+ * its path gates do emit a canonical form
11
+ * (permission system `handlers/gates/bash-path.ts`,
12
+ * `handlers/gates/bash-external-directory.ts`), but it names the one most
13
+ * restrictive token of a command that may touch many files, so a command is
14
+ * refused by what marks it as one: the `command` field a local bash ask carries,
15
+ * or the bash payload kind, which is what survives when a subagent escalates its
16
+ * ask upward (`authority/forwarded-request-server.ts` builds forwarded details
17
+ * with no command field, and the payload kind rides through
18
+ * `presentation/forwarded-ask-payload.ts`). An MCP target, a skill name and a
19
+ * plain tool have no canonical form at all and leave `boundaryValue` null
20
+ * (`handlers/gates/helpers.ts`). Neither refusal guesses from spelling.
21
+ *
22
+ * This module turns those strings into the facts a judge can use: the target
23
+ * path, where it resolves, whether the file and its directory exist, and
24
+ * whether it sits inside the session's project directory or the temporary
25
+ * directory. The file and its directory are resolved separately because a
26
+ * create has no file to resolve yet, and the directory is what says the ask is
27
+ * a create in a real place rather than a path to nowhere.
28
+ *
29
+ * Nothing here reads file contents, and nothing here throws: the link runs
30
+ * inside the permission system's own call stack, where a raise costs the whole
31
+ * prompt. A filesystem question that fails leaves the fact out, and a target
32
+ * that cannot be recognized leaves no target block behind. The
33
+ * filesystem, the temporary directory and the session directory arrive through
34
+ * {@link TargetContextDeps}, so tests answer them without a disk.
35
+ */
36
+
37
+ import { realpathSync, statSync } from "node:fs";
38
+ import { dirname, isAbsolute, sep } from "node:path";
39
+ import { tmpdir } from "node:os";
40
+
41
+ import type { PromptPermissionDetails } from "@gotgenes/pi-permission-system";
42
+
43
+ /** What an inspection of the target found. */
44
+ export type TargetState =
45
+ /** The target is an existing file. */
46
+ | "file"
47
+ /** The target is an existing directory. */
48
+ | "directory"
49
+ /** The target does not exist and its directory does: an ordinary create. */
50
+ | "missing"
51
+ /** Neither the target nor its directory exists. */
52
+ | "missing-parent"
53
+ /** The filesystem could not say (a failed or unsupported stat). */
54
+ | "unknown";
55
+
56
+ /** Where the target sits, relative to the places the rubric names. */
57
+ export type TargetLocation =
58
+ /** Inside the session's project directory. */
59
+ | "project"
60
+ /** Inside the operating system's temporary directory. */
61
+ | "temp"
62
+ /** Inside neither. */
63
+ | "outside"
64
+ /** Not determinable, because the target could not be inspected. */
65
+ | "unknown";
66
+
67
+ /** Why the read produced no target. */
68
+ export type TargetOmission =
69
+ /** The ask carried no access intent at all. */
70
+ | "no-access-intent"
71
+ /** The ask is a bash command, which targets no single file. */
72
+ | "multi-path-command"
73
+ /**
74
+ * A forwarded ask that arrived with no payload, so nothing says whether the
75
+ * child ran a command or a file action. Its intent can still carry a
76
+ * canonical path, and naming one token as the target would claim more than
77
+ * this side knows.
78
+ */
79
+ | "undetermined-action"
80
+ /** `boundaryValue` is null or empty: an MCP, skill or plain-tool ask. */
81
+ | "no-canonical-path"
82
+ /** The spelling is not absolute, or carries a control character. */
83
+ | "unusable-path"
84
+ /** The block's path text exceeds {@link MAX_TARGET_BYTES}, so all of it is out. */
85
+ | "over-size-cap"
86
+ /** A seam threw; the ask proceeds with no target rather than failing. */
87
+ | "extraction-failed";
88
+
89
+ /**
90
+ * The path text one target block may render, in UTF-8 bytes: the budget is the
91
+ * sum of the spellings, not a limit on any one of them. A block over it goes
92
+ * out whole, because a path with no state or placement line says nothing, and
93
+ * half a path can read like a different file.
94
+ *
95
+ * This cap is separate from `contextBudgetBytes`, which bounds the extracted
96
+ * full-command context (src/context.ts:42). That text appears only for a bash
97
+ * ask and this one never does, so they cannot both be in one ask. Each text
98
+ * source keeps its own cap, as the guidance files do with theirs.
99
+ */
100
+ export const MAX_TARGET_BYTES = 512;
101
+
102
+ /** The facts about the file one ask targets. */
103
+ export interface TargetContext {
104
+ /** The absolute spelling the gate matched on, symlinks unfollowed. */
105
+ readonly path: string;
106
+ /**
107
+ * The symlink-resolved spelling the outside-project decision uses, when it
108
+ * differs from {@link path}. The gate supplies it, so nothing here resolves
109
+ * a path a second time.
110
+ */
111
+ readonly resolved: string | null;
112
+ /**
113
+ * A spelling relative to the working directory, when the gate carried one.
114
+ * The gate synthesizes such a spelling for every path inside the project, so
115
+ * this is an alternate way to write the same file rather than a report of what
116
+ * the model typed.
117
+ */
118
+ readonly relativeSpelling: string | null;
119
+ /** The containing directory, in the same lexical form as {@link path}. */
120
+ readonly directory: string;
121
+ /** What exists at the target, judged on the resolved spelling. */
122
+ readonly state: TargetState;
123
+ /** Which named place the target falls in. */
124
+ readonly location: TargetLocation;
125
+ }
126
+
127
+ /** The read's outcome: the facts, or the reason there are none. */
128
+ export type TargetReading =
129
+ | { readonly included: true; readonly target: TargetContext }
130
+ | { readonly included: false; readonly reason: TargetOmission };
131
+
132
+ /** What the {@link TargetContextDeps.stat} seam answers; null means cannot tell. */
133
+ export type TargetStatAnswer = "file" | "directory" | "missing" | null;
134
+
135
+ /** The seams this module reads, injected so tests answer them in memory. */
136
+ export interface TargetContextDeps {
137
+ /** The session's working directory, the project boundary. */
138
+ readonly getCwd: () => string;
139
+ /** The operating system's temporary directory, never a hardcoded `/tmp`. */
140
+ readonly getTempDirectory: () => string;
141
+ /** Symlink-resolved absolute form, or null when it cannot be resolved. */
142
+ readonly realpath: (path: string) => string | null;
143
+ /** What is at `path`; null when the filesystem cannot say. */
144
+ readonly stat: (path: string) => TargetStatAnswer;
145
+ }
146
+
147
+ /**
148
+ * Read the target of one ask.
149
+ *
150
+ * Recognition is the gate's own work: a path-bearing gate hands over a
151
+ * canonical spelling and every other gate hands over null, so nothing here
152
+ * guesses at whether a value is a path. The canonical form is absolute for
153
+ * every tool ask the engine resolves, including a create whose file does not
154
+ * exist yet and a relative spelling that escapes the project with `..`.
155
+ */
156
+ export function extractTargetContext(
157
+ details: PromptPermissionDetails,
158
+ deps: TargetContextDeps,
159
+ ): TargetReading {
160
+ try {
161
+ return readTarget(details, deps);
162
+ } catch {
163
+ // An injected seam rejected instead of returning null, or a details bag
164
+ // shaped unlike the wire contract. Absence is the only safe answer.
165
+ return { included: false, reason: "extraction-failed" };
166
+ }
167
+ }
168
+
169
+ /** The read itself, with the seams already trusted to answer or return null. */
170
+ function readTarget(
171
+ details: PromptPermissionDetails,
172
+ deps: TargetContextDeps,
173
+ ): TargetReading {
174
+ const intent = details?.accessIntent;
175
+ if (typeof intent !== "object" || intent === null) {
176
+ return { included: false, reason: "no-access-intent" };
177
+ }
178
+
179
+ // A command is refused before its canonical value is read. The bash path
180
+ // gates emit one for the single most restrictive token, but the command is
181
+ // already in the prompt in full, and naming one of its paths as the target
182
+ // would misstate an action that may touch many files. A local bash ask carries
183
+ // the command itself; a forwarded one carries neither the command nor a tool
184
+ // name, only its payload kind, which is the signal src/context.ts:42 reads.
185
+ const kind = details.payload?.kind;
186
+ if (isBashPayload(kind) || (typeof details.command === "string" && details.command !== "")) {
187
+ return { included: false, reason: "multi-path-command" };
188
+ }
189
+ // A forwarded ask that reached this node without its payload says nothing
190
+ // about what the child was doing, even when its intent carries a canonical
191
+ // path, so no target is claimed for it.
192
+ if (kind === "forwarded") {
193
+ return { included: false, reason: "undetermined-action" };
194
+ }
195
+
196
+ const canonical = intent.boundaryValue;
197
+ if (typeof canonical !== "string" || canonical === "") {
198
+ return { included: false, reason: "no-canonical-path" };
199
+ }
200
+ if (!isAbsolute(canonical) || hasUnrenderableCharacter(canonical)) {
201
+ return { included: false, reason: "unusable-path" };
202
+ }
203
+
204
+ const lexical = firstAbsolute(intent.matchValues) ?? canonical;
205
+ // Every spelling the block renders is screened, not only the one the gate
206
+ // decided with: under a symlink the resolved form can be clean while the
207
+ // lexical form still carries a character that renders as a different path.
208
+ if (lexical !== canonical && hasUnrenderableCharacter(lexical)) {
209
+ return { included: false, reason: "unusable-path" };
210
+ }
211
+ // The block renders the lexical form, the resolved form when a symlink leads
212
+ // somewhere else, and a working-directory spelling when the gate carried one.
213
+ // They are sized
214
+ // together, and before the filesystem is read, so an oversized block costs no
215
+ // stat.
216
+ const relative = relativeSpellingOf(intent.matchValues, lexical);
217
+ const spellings = canonical === lexical ? [lexical] : [lexical, canonical];
218
+ if (relative !== null) spellings.push(relative);
219
+ if (pathTextBytes(spellings) > MAX_TARGET_BYTES) {
220
+ return { included: false, reason: "over-size-cap" };
221
+ }
222
+
223
+ const state = stateOf(canonical, dirname(canonical), deps);
224
+ return {
225
+ included: true,
226
+ target: {
227
+ path: lexical,
228
+ resolved: canonical === lexical ? null : canonical,
229
+ relativeSpelling: relative,
230
+ directory: dirname(lexical),
231
+ state,
232
+ location:
233
+ state === "unknown"
234
+ ? "unknown"
235
+ : locationOf(canonical, dirname(canonical), state, deps),
236
+ },
237
+ };
238
+ }
239
+
240
+ /**
241
+ * Whether a payload kind describes a shell command. Both bash gates carry a
242
+ * canonical path for one token: the plain one reports kind `bash`, the
243
+ * outside-project one reports `bash_external_directory`.
244
+ */
245
+ function isBashPayload(kind: unknown): boolean {
246
+ return kind === "bash" || kind === "bash_external_directory";
247
+ }
248
+
249
+ /** The UTF-8 size of the path text a block would render. */
250
+ function pathTextBytes(spellings: readonly string[]): number {
251
+ return spellings.reduce((total, one) => total + Buffer.byteLength(one, "utf8"), 0);
252
+ }
253
+
254
+ /** The first absolute spelling the gate carried, or null. */
255
+ function firstAbsolute(matchValues: unknown): string | null {
256
+ if (!Array.isArray(matchValues)) return null;
257
+ for (const candidate of matchValues) {
258
+ if (typeof candidate === "string" && candidate !== "" && isAbsolute(candidate)) {
259
+ return candidate;
260
+ }
261
+ }
262
+ return null;
263
+ }
264
+
265
+ /** What exists at the target, with the directory consulted only for an absent file. */
266
+ function stateOf(path: string, directory: string, deps: TargetContextDeps): TargetState {
267
+ const found = deps.stat(path);
268
+ if (found === "file" || found === "directory") return found;
269
+ if (found === null) return "unknown";
270
+ const parent = deps.stat(directory);
271
+ if (parent === "directory") return "missing";
272
+ if (parent === "missing") return "missing-parent";
273
+ return "unknown";
274
+ }
275
+
276
+ /**
277
+ * A spelling relative to the working directory, when the gate carried one. The
278
+ * gate emits `[absolute, cwd-relative?, as-typed]`, and it synthesizes the
279
+ * cwd-relative form for any path inside the project, so the last non-absolute
280
+ * entry is the as-typed spelling when there was one and the synthesized alias
281
+ * otherwise. Both are true alternate spellings of the same file, which is all
282
+ * that is worth saying about it.
283
+ */
284
+ function relativeSpellingOf(matchValues: unknown, lexical: string): string | null {
285
+ if (!Array.isArray(matchValues)) return null;
286
+ let found: string | null = null;
287
+ for (const candidate of matchValues) {
288
+ if (typeof candidate !== "string" || candidate === "") continue;
289
+ if (candidate === lexical || isAbsolute(candidate)) continue;
290
+ if (hasUnrenderableCharacter(candidate)) continue;
291
+ found = candidate;
292
+ }
293
+ return found;
294
+ }
295
+
296
+ /**
297
+ * Which named place the target falls in. An existing file is placed by its own
298
+ * resolved path; an absent one by the nearest directory above it, which is the
299
+ * place the write would land in.
300
+ */
301
+ function locationOf(
302
+ path: string,
303
+ directory: string,
304
+ state: TargetState,
305
+ deps: TargetContextDeps,
306
+ ): TargetLocation {
307
+ const probe =
308
+ state === "file" || state === "directory"
309
+ ? (deps.realpath(path) ?? path)
310
+ : (deps.realpath(directory) ?? directory);
311
+ // Both directories are read through the guarded helper: a host that cannot
312
+ // say where its session is loses the placement line, not the path.
313
+ const cwd = readDirectory(deps.getCwd);
314
+ if (cwd === null) return "unknown";
315
+ if (contains(deps.realpath(cwd) ?? cwd, probe)) return "project";
316
+ const temp = readDirectory(deps.getTempDirectory);
317
+ if (temp !== null && contains(deps.realpath(temp) ?? temp, probe)) return "temp";
318
+ return "outside";
319
+ }
320
+
321
+ /** Whether `inner` is `outer` or sits below it. */
322
+ function contains(outer: string, inner: string): boolean {
323
+ const base = outer === "/" ? "/" : trimTrailingSeparator(outer);
324
+ const [a, b] = caseFold(base, inner);
325
+ if (b === a) return true;
326
+ return b.startsWith(a.endsWith(sep) ? a : a + sep);
327
+ }
328
+
329
+ /** Compare case-insensitively where the platform does. */
330
+ function caseFold(left: string, right: string): [string, string] {
331
+ return process.platform === "win32" ? [left.toLowerCase(), right.toLowerCase()] : [left, right];
332
+ }
333
+
334
+ /** Drop trailing separators, leaving the filesystem root itself intact. */
335
+ function trimTrailingSeparator(path: string): string {
336
+ let end = path.length;
337
+ while (end > 1 && (path[end - 1] === sep || path[end - 1] === "/")) end -= 1;
338
+ return path.slice(0, end);
339
+ }
340
+
341
+ /**
342
+ * Whether a path carries a character that cannot be shown as the plain line it
343
+ * will be rendered into. Besides the control characters and DEL, that means the
344
+ * bidi overrides and isolates, the zero-width characters and word joiners, and
345
+ * the byte-order mark: each can make a path display as a different path from the
346
+ * one being judged, in the prompt and in the log alike.
347
+ */
348
+ function hasUnrenderableCharacter(path: string): boolean {
349
+ // eslint-disable-next-line no-control-regex
350
+ return /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/.test(
351
+ path,
352
+ );
353
+ }
354
+
355
+ /**
356
+ * The seams to read with: the caller's when it brought its own (tests), the
357
+ * real ones otherwise. A host that gives no session directory leaves
358
+ * {@link TargetContext.location} unknown; the process working directory is not
359
+ * a substitute, because the session directory can move out from under it.
360
+ */
361
+ export function resolveTargetDeps(
362
+ seams: TargetContextDeps | undefined,
363
+ getCwd: (() => string) | undefined,
364
+ ): TargetContextDeps {
365
+ return seams ?? defaultTargetContextDeps(getCwd ?? (() => ""));
366
+ }
367
+
368
+ /**
369
+ * The session directory to name in a prompt, or null. A seam that throws or
370
+ * answers empty gives null: the prompt loses a line rather than the ask.
371
+ */
372
+ export function sessionCwdOf(deps: TargetContextDeps): string | null {
373
+ return readDirectory(deps.getCwd);
374
+ }
375
+
376
+ /** The temporary directory to name in a prompt, or null. */
377
+ export function tempDirectoryOf(deps: TargetContextDeps): string | null {
378
+ return readDirectory(deps.getTempDirectory);
379
+ }
380
+
381
+ /** Read one directory seam, answering null for a throw or an empty string. */
382
+ function readDirectory(read: () => string): string | null {
383
+ try {
384
+ const value = read();
385
+ return typeof value === "string" && value !== "" ? value : null;
386
+ } catch {
387
+ return null;
388
+ }
389
+ }
390
+
391
+ /**
392
+ * The production seams: the real filesystem, the real temporary directory, and
393
+ * a failure answered by null instead of a throw.
394
+ */
395
+ export function defaultTargetContextDeps(getCwd: () => string): TargetContextDeps {
396
+ // Every placement check resolves the session directory and the temporary
397
+ // directory, and neither moves within a session in a way the rubric cares
398
+ // about, so each is resolved once. A target path is still resolved per ask:
399
+ // a file or a link can be replaced between two asks.
400
+ let realCwd: string | null | undefined;
401
+ let realTemp: string | null | undefined;
402
+ const tempDirectory = () => tmpdir();
403
+
404
+ return {
405
+ getCwd,
406
+ getTempDirectory: tempDirectory,
407
+ realpath: (path) => {
408
+ if (path === readDirectory(getCwd)) {
409
+ realCwd ??= tryRealpath(path);
410
+ return realCwd;
411
+ }
412
+ if (path === tempDirectory()) {
413
+ realTemp ??= tryRealpath(path);
414
+ return realTemp;
415
+ }
416
+ return tryRealpath(path);
417
+ },
418
+ stat: (path) => {
419
+ try {
420
+ const info = statSync(path);
421
+ return info.isFile() ? "file" : info.isDirectory() ? "directory" : null;
422
+ } catch (error) {
423
+ return isMissing(error) ? "missing" : null;
424
+ }
425
+ },
426
+ };
427
+ }
428
+
429
+ /** Resolve a path's symlinks, answering null when the filesystem cannot. */
430
+ function tryRealpath(path: string): string | null {
431
+ try {
432
+ return realpathSync(path);
433
+ } catch {
434
+ return null;
435
+ }
436
+ }
437
+
438
+ /** A stat failure that means "nothing is here" rather than "cannot tell". */
439
+ function isMissing(error: unknown): boolean {
440
+ const code = (error as { code?: string } | null)?.code;
441
+ return code === "ENOENT" || code === "ENOTDIR";
442
+ }
443
+
444
+