pi-permission-classifier 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Layered config loader: global then project `config.json`, project overriding
3
+ * global, validated once against the zod source of truth.
4
+ *
5
+ * Fail-safe by construction: a malformed file is skipped with a recorded issue
6
+ * (never fatal), and an invalid merged config yields `{ config: undefined }` so
7
+ * the extension registers no link — a config error degrades to no
8
+ * auto-decision, never to a wrong one (more prompting, never less).
9
+ *
10
+ * The project layer is trust-gated: in an untrusted project it is not even
11
+ * read, so a project file cannot replace the rubric or pick the judge before
12
+ * the operator has trusted the directory. The caller passes the trust state
13
+ * at each load, so a reload after the trust dialog picks the layer up.
14
+ */
15
+
16
+ import {
17
+ closeSync,
18
+ existsSync,
19
+ fchmodSync,
20
+ fsyncSync,
21
+ openSync,
22
+ readFileSync,
23
+ renameSync,
24
+ realpathSync,
25
+ statSync,
26
+ unlinkSync,
27
+ writeSync,
28
+ } from "node:fs";
29
+ import { join } from "node:path";
30
+
31
+ import {
32
+ CLASSIFIER_EXTENSION_ID,
33
+ type ClassifierConfig,
34
+ classifierConfigSchema,
35
+ } from "./config-schema";
36
+
37
+ const CONFIG_FILE_NAME = "config.json";
38
+
39
+ /** A validation or read problem, tied to the file(s) that produced it. */
40
+ export interface ConfigIssue {
41
+ path: string;
42
+ message: string;
43
+ sourcePath?: string;
44
+ }
45
+
46
+ /**
47
+ * Render one issue as `<file> <path>: <message>`.
48
+ *
49
+ * Both user-facing surfaces use this single renderer: the `session_start`
50
+ * warnings in `src/extension.ts` and the command notifications in
51
+ * `src/command.ts`, so the same problem reads the same way in the log and in
52
+ * the TUI. An issue with no `sourcePath` prints `(merged)` in the file
53
+ * position. The output is printable ASCII.
54
+ */
55
+ export function formatConfigIssue(issue: ConfigIssue): string {
56
+ return `${issue.sourcePath ?? "(merged)"} ${issue.path}: ${issue.message}`;
57
+ }
58
+
59
+ /**
60
+ * Outcome of a config load: a validated config (or `undefined`) plus issues.
61
+ * `projectSetsJudge` reports whether the project layer sets `provider` or
62
+ * `model`, so a global judge write can warn that the project file shadows it.
63
+ */
64
+ export interface LoadConfigResult {
65
+ config: ClassifierConfig | undefined;
66
+ issues: ConfigIssue[];
67
+ projectSetsJudge: boolean;
68
+ }
69
+
70
+ /** Global scope: `<agentDir>/extensions/<id>/config.json`. */
71
+ export function getGlobalConfigPath(agentDir: string): string {
72
+ return join(
73
+ agentDir,
74
+ "extensions",
75
+ CLASSIFIER_EXTENSION_ID,
76
+ CONFIG_FILE_NAME,
77
+ );
78
+ }
79
+
80
+ /** Project scope: `<cwd>/.pi/extensions/<id>/config.json`. */
81
+ export function getProjectConfigPath(cwd: string): string {
82
+ return join(
83
+ cwd,
84
+ ".pi",
85
+ "extensions",
86
+ CLASSIFIER_EXTENSION_ID,
87
+ CONFIG_FILE_NAME,
88
+ );
89
+ }
90
+
91
+ /** Whether the global config file exists (the precondition for any write). */
92
+ export function globalConfigExists(agentDir: string): boolean {
93
+ return existsSync(getGlobalConfigPath(agentDir));
94
+ }
95
+
96
+ function isRecord(value: unknown): value is Record<string, unknown> {
97
+ return typeof value === "object" && value !== null && !Array.isArray(value);
98
+ }
99
+
100
+ function setsJudge(layer: Record<string, unknown> | undefined): boolean {
101
+ return layer !== undefined && ("provider" in layer || "model" in layer);
102
+ }
103
+
104
+ /**
105
+ * Fields the schema still accepts but nothing reads. A layer that sets one
106
+ * gets an issue naming the file, so the operator learns the field does
107
+ * nothing; the config itself still loads.
108
+ */
109
+ const IGNORED_FIELDS: Record<string, string> = {
110
+ surfaces:
111
+ "This field is ignored: every surface outside the path and external_directory families is judged.",
112
+ };
113
+
114
+ function reportIgnoredFields(
115
+ layer: Record<string, unknown> | undefined,
116
+ sourcePath: string,
117
+ issues: ConfigIssue[],
118
+ ): void {
119
+ if (layer === undefined) {
120
+ return;
121
+ }
122
+ for (const [field, message] of Object.entries(IGNORED_FIELDS)) {
123
+ if (field in layer) {
124
+ issues.push({ path: field, message, sourcePath });
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Read and JSON-parse a layer. Returns `undefined` when the file is absent;
131
+ * records an issue and returns `undefined` when it is present but malformed.
132
+ */
133
+ function readLayer(
134
+ path: string,
135
+ issues: ConfigIssue[],
136
+ ): Record<string, unknown> | undefined {
137
+ if (!existsSync(path)) {
138
+ return undefined;
139
+ }
140
+ try {
141
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf-8"));
142
+ if (!isRecord(parsed)) {
143
+ issues.push({
144
+ path: "$",
145
+ message: "Expected a JSON object.",
146
+ sourcePath: path,
147
+ });
148
+ return undefined;
149
+ }
150
+ return parsed;
151
+ } catch (error) {
152
+ const message = error instanceof Error ? error.message : String(error);
153
+ issues.push({
154
+ path: "$",
155
+ message: `Failed to read config: ${message}`,
156
+ sourcePath: path,
157
+ });
158
+ return undefined;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Load the merged, validated classifier config from the global and project
164
+ * scopes.
165
+ *
166
+ * Both scopes are supplied by the caller: the extension resolves `agentDir`
167
+ * from the SDK's `getAgentDir()` (which honors `PI_CODING_AGENT_DIR`) and `cwd`
168
+ * from the session context, so this module reads no process globals of its own.
169
+ * `projectTrusted` is the session's trust state at this load: when false the
170
+ * project file is skipped unread and the global layer alone applies, with
171
+ * `projectSetsJudge` false.
172
+ *
173
+ * When neither file exists, returns `{ config: undefined, issues: [] }` — the
174
+ * normal not-configured state, reported without noise. When a present config is
175
+ * invalid, returns `{ config: undefined }` with the validation issues, each
176
+ * naming the layer file(s) that fed the merge. A layer that sets an accepted
177
+ * but ignored field (`surfaces`) adds one issue naming that file while the
178
+ * config still loads.
179
+ */
180
+ export function loadClassifierConfig(options: {
181
+ cwd: string;
182
+ agentDir: string;
183
+ projectTrusted: boolean;
184
+ }): LoadConfigResult {
185
+ const { cwd, agentDir, projectTrusted } = options;
186
+ const issues: ConfigIssue[] = [];
187
+
188
+ const globalPath = getGlobalConfigPath(agentDir);
189
+ const projectPath = getProjectConfigPath(cwd);
190
+ const global = readLayer(globalPath, issues);
191
+ const project = projectTrusted ? readLayer(projectPath, issues) : undefined;
192
+ const projectSetsJudge = setsJudge(project);
193
+
194
+ if (global === undefined && project === undefined) {
195
+ return { config: undefined, issues, projectSetsJudge };
196
+ }
197
+
198
+ reportIgnoredFields(global, globalPath, issues);
199
+ reportIgnoredFields(project, projectPath, issues);
200
+
201
+ // Shallow merge: project scalars and arrays replace global wholesale.
202
+ const merged = { ...(global ?? {}), ...(project ?? {}) };
203
+
204
+ const parsed = classifierConfigSchema.safeParse(merged);
205
+ if (!parsed.success) {
206
+ const sourcePath = [
207
+ ...(global === undefined ? [] : [globalPath]),
208
+ ...(project === undefined ? [] : [projectPath]),
209
+ ].join(", ");
210
+ for (const issue of parsed.error.issues) {
211
+ issues.push({
212
+ path: issue.path.join(".") || "$",
213
+ message: issue.message,
214
+ sourcePath,
215
+ });
216
+ }
217
+ return { config: undefined, issues, projectSetsJudge };
218
+ }
219
+
220
+ return { config: parsed.data, issues, projectSetsJudge };
221
+ }
222
+
223
+ /**
224
+ * Rewrite only `provider` and `model` in the global config file, preserving
225
+ * every other field. When either argument is `undefined` both keys are
226
+ * removed (the session model judges); the command passes both or neither.
227
+ *
228
+ * The write is atomic and durable: the new content goes to a sibling temporary
229
+ * file that is fsynced before it is renamed over `config.json`, so neither a
230
+ * process crash (the rename is atomic) nor an OS crash or power loss (the bytes
231
+ * are already on disk) can leave a truncated config. Throws when the global
232
+ * file is absent or is not a JSON object; the existing file is never touched on
233
+ * failure.
234
+ *
235
+ * The rename replaces the inode, so the target is resolved with `realpathSync`
236
+ * first: a `config.json` that is a symlink (a dotfiles-managed agent dir) stays
237
+ * a symlink and its target is what gets rewritten. The replacement is created
238
+ * with the original file's mode, set exactly with `fchmodSync` so the process
239
+ * umask cannot silently tighten it.
240
+ */
241
+ export function writeGlobalJudge(
242
+ agentDir: string,
243
+ provider: string | undefined,
244
+ model: string | undefined,
245
+ ): void {
246
+ const path = getGlobalConfigPath(agentDir);
247
+ if (!existsSync(path)) {
248
+ throw new Error(`Global config file not found: ${path}`);
249
+ }
250
+ // Rename replaces the inode, so write through the resolved target: a linked
251
+ // config keeps its link and the link's target receives the new bytes.
252
+ const target = realpathSync(path);
253
+ const mode = statSync(target).mode & 0o777;
254
+ const parsed: unknown = JSON.parse(readFileSync(target, "utf-8"));
255
+ if (!isRecord(parsed)) {
256
+ throw new Error(`Global config is not a JSON object: ${path}`);
257
+ }
258
+
259
+ const { provider: _provider, model: _model, ...rest } = parsed;
260
+ const next: Record<string, unknown> =
261
+ provider === undefined || model === undefined
262
+ ? rest
263
+ : { ...rest, provider, model };
264
+
265
+ const tempPath = `${target}.${process.pid}.tmp`;
266
+ try {
267
+ const fd = openSync(tempPath, "w", mode);
268
+ try {
269
+ writeSync(fd, `${JSON.stringify(next, null, 2)}\n`, undefined, "utf-8");
270
+ // openSync's mode is masked by the umask; set it exactly instead.
271
+ fchmodSync(fd, mode);
272
+ fsyncSync(fd);
273
+ } finally {
274
+ closeSync(fd);
275
+ }
276
+ renameSync(tempPath, target);
277
+ } catch (error) {
278
+ try {
279
+ unlinkSync(tempPath);
280
+ } catch {
281
+ // Nothing to clean up.
282
+ }
283
+ throw error;
284
+ }
285
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The zod source of truth for the classifier extension config.
3
+ *
4
+ * The config carries the model mechanism (provider/model override,
5
+ * instructions, timeout, context budget); the chain policy half
6
+ * (`authorizerChain`, the delegation envelope) lives in
7
+ * `@gotgenes/pi-permission-system`.
8
+ */
9
+
10
+ import { z } from "zod";
11
+
12
+ /** Extension id — the `extensions/<id>/config.json` path segment. */
13
+ export const CLASSIFIER_EXTENSION_ID = "pi-permission-classifier";
14
+
15
+ /** Default per-review model-call budget, in milliseconds. */
16
+ export const DEFAULT_TIMEOUT_MS = 5000;
17
+
18
+ /**
19
+ * Default cap on the extracted full-command context, in UTF-8 bytes. An ask
20
+ * whose context exceeds the budget defers before any model call;
21
+ * context is never truncated to fit.
22
+ */
23
+ export const DEFAULT_CONTEXT_BUDGET_BYTES = 8192;
24
+
25
+ /**
26
+ * Operator-owned config for the auto-classifier reviewer. An absent config
27
+ * file means no registration (fail-safe); an empty object means the defaults
28
+ * below. `provider`/`model` come together or not at all — with neither, the
29
+ * session's active model judges.
30
+ */
31
+ export const classifierConfigSchema = z
32
+ .object({
33
+ provider: z.string().min(1).optional(),
34
+ model: z.string().min(1).optional(),
35
+ instructions: z.string().min(1).optional(),
36
+ // Accepted for backward compatibility and never read: the reviewer
37
+ // judges every surface outside the path and external_directory
38
+ // families. Kept so an
39
+ // older config file still parses.
40
+ surfaces: z.array(z.string().min(1)).optional(),
41
+ timeoutMs: z.number().int().positive().default(DEFAULT_TIMEOUT_MS),
42
+ contextBudgetBytes: z
43
+ .number()
44
+ .int()
45
+ .positive()
46
+ .default(DEFAULT_CONTEXT_BUDGET_BYTES),
47
+ })
48
+ .refine((config) => (config.provider === undefined) === (config.model === undefined), {
49
+ message: "provider and model must be set together or not at all",
50
+ });
51
+
52
+ export type ClassifierConfig = z.infer<typeof classifierConfigSchema>;
package/src/context.ts ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The scoped full-command read: the one place in the classifier that
3
+ * touches payload evidence.
4
+ *
5
+ * A bash gate that intercepts one unit of a larger command attaches the whole
6
+ * command as the payload's single "full command" evidence entry
7
+ * (agent-authored ask text, never a tool result). This module extracts exactly
8
+ * that entry — bash kind, designated label, non-empty string text — and
9
+ * measures it for the budget gate and the audit trail. Everything else — other
10
+ * kinds, other labels, malformed shapes — yields null, and nothing here
11
+ * throws: absence degrades to the value-only prompt.
12
+ */
13
+
14
+ import { createHash } from "node:crypto";
15
+
16
+ import type { PromptPayload } from "@gotgenes/pi-permission-system";
17
+
18
+ /** The upstream label on the enclosing-command evidence entry. */
19
+ const FULL_COMMAND_LABEL = "full command";
20
+
21
+ /** The extracted full command with its measured facts. */
22
+ export interface FullCommandContext {
23
+ /** The full command exactly as the payload carried it. */
24
+ readonly text: string;
25
+ /** UTF-8 byte length of the text, the budget-gate measure. */
26
+ readonly bytes: number;
27
+ /** First 12 lowercase hex chars of sha256(text), the audit correlator. */
28
+ readonly hash12: string;
29
+ }
30
+
31
+ /**
32
+ * Extract the full-command context from a bash-kind ask payload, or null.
33
+ *
34
+ * Null for any other payload kind, any other label, a non-string or empty
35
+ * text, and an absent or malformed evidence array. Never throws.
36
+ */
37
+ export function extractFullCommandContext(
38
+ payload: PromptPayload,
39
+ ): FullCommandContext | null {
40
+ try {
41
+ if (typeof payload !== "object" || payload === null) return null;
42
+ if (payload.kind !== "bash") return null;
43
+
44
+ const { evidence } = payload;
45
+ if (!Array.isArray(evidence)) return null;
46
+
47
+ const entry = evidence.find(
48
+ (candidate): boolean =>
49
+ typeof candidate === "object" &&
50
+ candidate !== null &&
51
+ candidate.label === FULL_COMMAND_LABEL,
52
+ );
53
+ if (entry === undefined) return null;
54
+
55
+ const { text } = entry;
56
+ if (typeof text !== "string" || text === "") return null;
57
+
58
+ return {
59
+ text,
60
+ bytes: Buffer.byteLength(text, "utf8"),
61
+ hash12: createHash("sha256").update(text, "utf8").digest("hex").slice(0, 12),
62
+ };
63
+ } catch {
64
+ return null;
65
+ }
66
+ }