@agent-corpus/policy-manager 0.1.0 → 0.2.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,113 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
+ import { canonical, git } from "./evidence.js";
6
+ export const strictProfile = {
7
+ mode: "strict",
8
+ cloudWrites: "human",
9
+ humanPatterns: [],
10
+ scratchRoots: [],
11
+ };
12
+ export function defaultProfilePath() {
13
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
14
+ return join(base, "agent-corpus", "policy-manager", "policy.json");
15
+ }
16
+ export class ProfileError extends Error {
17
+ }
18
+ function verifyLocation(path) {
19
+ if (!isAbsolute(path))
20
+ throw new ProfileError("Profile path must be absolute");
21
+ const stat = lstatSync(path);
22
+ if (!stat.isFile() || stat.isSymbolicLink())
23
+ throw new ProfileError("Profile must be a regular file");
24
+ // POSIX ownership and mode bits do not exist on Windows. There the trust boundary is the NTFS
25
+ // ACL of the user's profile directory, which Node cannot inspect, so only the file type,
26
+ // symlink and Git-checkout checks apply.
27
+ if (process.platform !== "win32") {
28
+ if (process.getuid && stat.uid !== process.getuid())
29
+ throw new ProfileError("Profile must be owned by the current user");
30
+ if ((stat.mode & 0o022) !== 0)
31
+ throw new ProfileError("Profile must not be group or world writable");
32
+ }
33
+ try {
34
+ git(dirname(canonical(path)), ["rev-parse", "--show-toplevel"]);
35
+ }
36
+ catch {
37
+ return; // not inside a Git checkout: an agent cannot rewrite it from a worktree
38
+ }
39
+ throw new ProfileError("Profile must live outside Git checkouts");
40
+ }
41
+ export function parseProfile(text) {
42
+ let raw;
43
+ try {
44
+ raw = JSON.parse(text);
45
+ }
46
+ catch {
47
+ throw new ProfileError("Profile is not valid JSON");
48
+ }
49
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
50
+ throw new ProfileError("Profile must be an object");
51
+ const value = raw;
52
+ const allowed = new Set([
53
+ "version",
54
+ "mode",
55
+ "cloudWrites",
56
+ "humanPatterns",
57
+ "scratchRoots",
58
+ "description",
59
+ ]);
60
+ for (const key of Object.keys(value))
61
+ if (!allowed.has(key))
62
+ throw new ProfileError(`Unknown profile key: ${key}`);
63
+ if (value.version !== 1)
64
+ throw new ProfileError("Unsupported profile version");
65
+ if (value.mode !== "strict" && value.mode !== "permissive")
66
+ throw new ProfileError("mode must be strict or permissive");
67
+ const cloudWrites = value.cloudWrites ?? "human";
68
+ if (cloudWrites !== "human" && cloudWrites !== "allow")
69
+ throw new ProfileError("cloudWrites must be human or allow");
70
+ const patterns = value.humanPatterns ?? [];
71
+ const roots = value.scratchRoots ?? [];
72
+ if (!Array.isArray(patterns) || patterns.some((p) => typeof p !== "string" || p.length > 300))
73
+ throw new ProfileError("humanPatterns must be short strings");
74
+ if (!Array.isArray(roots) || roots.some((r) => typeof r !== "string" || !isAbsolute(r)))
75
+ throw new ProfileError("scratchRoots must be absolute paths");
76
+ let humanPatterns;
77
+ try {
78
+ humanPatterns = patterns.map((p) => new RegExp(p));
79
+ }
80
+ catch {
81
+ throw new ProfileError("humanPatterns contains an invalid expression");
82
+ }
83
+ const scratchRoots = new Set();
84
+ for (const root of roots) {
85
+ try {
86
+ scratchRoots.add(canonical(root));
87
+ }
88
+ catch {
89
+ /* a missing scratch directory simply grants nothing */
90
+ }
91
+ }
92
+ return {
93
+ mode: value.mode,
94
+ cloudWrites,
95
+ humanPatterns,
96
+ scratchRoots: value.mode === "permissive" ? [...scratchRoots] : [],
97
+ digest: createHash("sha256").update(text).digest("hex"),
98
+ };
99
+ }
100
+ /** Loads the installed profile. A missing file means strict; an invalid one is an error. */
101
+ export function loadProfile(path = defaultProfilePath()) {
102
+ try {
103
+ lstatSync(path);
104
+ }
105
+ catch (error) {
106
+ if (error.code === "ENOENT")
107
+ return strictProfile;
108
+ throw new ProfileError("Profile is not readable");
109
+ }
110
+ verifyLocation(path);
111
+ return parseProfile(readFileSync(path, "utf8"));
112
+ }
113
+ //# sourceMappingURL=profile.js.map
@@ -0,0 +1,18 @@
1
+ import { type Profile } from "./profile.js";
2
+ export interface ReplayReport {
3
+ commands: number;
4
+ approved: number;
5
+ strictApproved: number;
6
+ reasons: Array<{
7
+ reason: string;
8
+ count: number;
9
+ examples: string[];
10
+ }>;
11
+ }
12
+ /**
13
+ * Replays the Bash commands recorded in Claude Code transcripts (`~/.claude/projects/**.jsonl`)
14
+ * through the evaluator and reports the approval rate with and without a profile. Commands are
15
+ * not executed. Output lists reasons and a first-line excerpt of examples, so keep reports local.
16
+ */
17
+ export declare function replayTranscripts(paths: string[], profile: Profile, files?: number): ReplayReport;
18
+ //# sourceMappingURL=replay.d.ts.map
package/dist/replay.js ADDED
@@ -0,0 +1,81 @@
1
+ import { readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { evaluate } from "./policy.js";
4
+ import { strictProfile } from "./profile.js";
5
+ function transcriptFiles(paths, limit) {
6
+ const files = [];
7
+ const visit = (path) => {
8
+ const stat = statSync(path);
9
+ if (stat.isDirectory())
10
+ for (const name of readdirSync(path))
11
+ visit(join(path, name));
12
+ else if (path.endsWith(".jsonl"))
13
+ files.push([path, stat.mtimeMs]);
14
+ };
15
+ for (const path of paths)
16
+ visit(path);
17
+ return files
18
+ .sort((a, b) => b[1] - a[1])
19
+ .slice(0, limit)
20
+ .map(([path]) => path);
21
+ }
22
+ /**
23
+ * Replays the Bash commands recorded in Claude Code transcripts (`~/.claude/projects/**.jsonl`)
24
+ * through the evaluator and reports the approval rate with and without a profile. Commands are
25
+ * not executed. Output lists reasons and a first-line excerpt of examples, so keep reports local.
26
+ */
27
+ export function replayTranscripts(paths, profile, files = 50) {
28
+ const seen = new Set();
29
+ const reasons = new Map();
30
+ const report = { commands: 0, approved: 0, strictApproved: 0, reasons: [] };
31
+ for (const file of transcriptFiles(paths, files))
32
+ for (const line of readFileSync(file, "utf8").split("\n")) {
33
+ if (!line.includes('"tool_use"'))
34
+ continue;
35
+ let entry;
36
+ try {
37
+ entry = JSON.parse(line);
38
+ }
39
+ catch {
40
+ continue;
41
+ }
42
+ const content = entry.message?.content;
43
+ if (!Array.isArray(content))
44
+ continue;
45
+ for (const item of content) {
46
+ const command = item.input?.command;
47
+ if (item.type !== "tool_use" || item.name !== "Bash" || typeof command !== "string")
48
+ continue;
49
+ const cwd = entry.cwd ?? process.cwd();
50
+ const key = `${cwd}\0${command}`;
51
+ if (seen.has(key))
52
+ continue;
53
+ seen.add(key);
54
+ const request = {
55
+ sessionId: "replay",
56
+ harness: "claude",
57
+ cwd,
58
+ tool: "Bash",
59
+ input: { command },
60
+ };
61
+ const decision = evaluate(request, undefined, profile);
62
+ report.commands++;
63
+ if (evaluate(request, undefined, strictProfile).decision === "approve")
64
+ report.strictApproved++;
65
+ if (decision.decision === "approve") {
66
+ report.approved++;
67
+ continue;
68
+ }
69
+ const bucket = reasons.get(decision.reason) ?? { count: 0, examples: [] };
70
+ bucket.count++;
71
+ if (bucket.examples.length < 3)
72
+ bucket.examples.push(command.split("\n")[0]?.slice(0, 100) ?? "");
73
+ reasons.set(decision.reason, bucket);
74
+ }
75
+ }
76
+ report.reasons = [...reasons]
77
+ .map(([reason, value]) => ({ reason, ...value }))
78
+ .sort((a, b) => b.count - a.count);
79
+ return report;
80
+ }
81
+ //# sourceMappingURL=replay.js.map
package/dist/service.d.ts CHANGED
@@ -8,6 +8,13 @@ interface Message {
8
8
  }
9
9
  export declare function serve(harness: string, sessionId: string): Promise<void>;
10
10
  export declare function send(harness: string, sessionId: string, message: Omit<Message, "token">): Promise<unknown>;
11
+ /**
12
+ * Stops a session's service. A session with no service (it never started, already ended, or the
13
+ * harness fired SessionEnd outside a real session such as `claude update`) is not an error:
14
+ * there is nothing left to stop, and no session directory is created for it. Unsafe directories
15
+ * and other failures still throw.
16
+ */
17
+ export declare function stop(harness: string, sessionId: string): Promise<"stopped" | "not-running">;
11
18
  export declare function start(harness: string, sessionId: string, cliPath: string): Promise<string>;
12
19
  export {};
13
20
  //# sourceMappingURL=service.d.ts.map
package/dist/service.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
- import { chmodSync } from "node:fs";
2
+ import { chmodSync, existsSync } from "node:fs";
3
3
  import { createConnection, createServer } from "node:net";
4
4
  import { join } from "node:path";
5
- import { audit, sessionDirectory, sessionToken } from "./audit.js";
5
+ import { audit, sessionDirectory, sessionDirectoryPath, sessionToken } from "./audit.js";
6
6
  import { hash } from "./policy.js";
7
+ import { loadProfile, strictProfile } from "./profile.js";
7
8
  import { PolicySession } from "./session.js";
8
9
  function endpoint(directory) {
9
10
  return process.platform === "win32"
@@ -12,7 +13,15 @@ function endpoint(directory) {
12
13
  }
13
14
  export async function serve(harness, sessionId) {
14
15
  const directory = sessionDirectory(harness, sessionId), token = sessionToken(directory);
15
- const session = new PolicySession(directory, harness, sessionId);
16
+ let profile = strictProfile;
17
+ let profileFailure = false;
18
+ try {
19
+ profile = loadProfile();
20
+ }
21
+ catch {
22
+ profileFailure = true; // an unreadable or untrusted profile must never loosen policy
23
+ }
24
+ const session = new PolicySession(directory, harness, sessionId, profile);
16
25
  const server = createServer((socket) => {
17
26
  socket.setTimeout(3000, () => socket.destroy());
18
27
  let data = "";
@@ -92,6 +101,16 @@ export async function serve(harness, sessionId) {
92
101
  });
93
102
  });
94
103
  audit(directory, { event: "session-start", harness, sessionHash: hash(sessionId) });
104
+ audit(directory, {
105
+ event: "profile",
106
+ mode: profile.mode,
107
+ status: profileFailure
108
+ ? "invalid-using-strict"
109
+ : profile.digest
110
+ ? "loaded"
111
+ : "none-using-strict",
112
+ ...(profile.digest ? { digest: profile.digest } : {}),
113
+ });
95
114
  }
96
115
  export function send(harness, sessionId, message) {
97
116
  const directory = sessionDirectory(harness, sessionId);
@@ -120,6 +139,26 @@ export function send(harness, sessionId, message) {
120
139
  });
121
140
  });
122
141
  }
142
+ /**
143
+ * Stops a session's service. A session with no service (it never started, already ended, or the
144
+ * harness fired SessionEnd outside a real session such as `claude update`) is not an error:
145
+ * there is nothing left to stop, and no session directory is created for it. Unsafe directories
146
+ * and other failures still throw.
147
+ */
148
+ export async function stop(harness, sessionId) {
149
+ if (!existsSync(sessionDirectoryPath(harness, sessionId)))
150
+ return "not-running";
151
+ try {
152
+ await send(harness, sessionId, { action: "stop" });
153
+ return "stopped";
154
+ }
155
+ catch (error) {
156
+ const code = error.code;
157
+ if (code === "ENOENT" || code === "ECONNREFUSED")
158
+ return "not-running";
159
+ throw error;
160
+ }
161
+ }
123
162
  export async function start(harness, sessionId, cliPath) {
124
163
  const directory = sessionDirectory(harness, sessionId);
125
164
  try {
package/dist/session.d.ts CHANGED
@@ -1,11 +1,13 @@
1
+ import { type Profile } from "./profile.js";
1
2
  import type { Classification, Decision, OutcomeReport, Request } from "./types.js";
2
3
  export declare class PolicySession {
3
4
  readonly directory: string;
4
5
  readonly harness: string;
5
6
  readonly sessionId: string;
7
+ readonly profile: Profile;
6
8
  private cache;
7
9
  private pending;
8
- constructor(directory: string, harness: string, sessionId: string);
10
+ constructor(directory: string, harness: string, sessionId: string, profile?: Profile);
9
11
  review(request: Request, ai?: Classification): Decision;
10
12
  record(report: OutcomeReport): void;
11
13
  classify(classification: Classification): Decision;
package/dist/session.js CHANGED
@@ -1,15 +1,18 @@
1
1
  import { audit, requestSummary } from "./audit.js";
2
2
  import { evaluate, hash } from "./policy.js";
3
+ import { strictProfile } from "./profile.js";
3
4
  export class PolicySession {
4
5
  directory;
5
6
  harness;
6
7
  sessionId;
8
+ profile;
7
9
  cache = new Map();
8
10
  pending = new Map();
9
- constructor(directory, harness, sessionId) {
11
+ constructor(directory, harness, sessionId, profile = strictProfile) {
10
12
  this.directory = directory;
11
13
  this.harness = harness;
12
14
  this.sessionId = sessionId;
15
+ this.profile = profile;
13
16
  }
14
17
  review(request, ai) {
15
18
  if (request.sessionId !== this.sessionId || request.harness !== this.harness)
@@ -38,7 +41,7 @@ export class PolicySession {
38
41
  });
39
42
  throw new Error("Malformed AI classification");
40
43
  }
41
- const key = hash([hash(request), "policy-v1"]);
44
+ const key = hash([hash(request), "policy-v1", this.profile.digest ?? this.profile.mode]);
42
45
  const entry = this.cache.get(key);
43
46
  const cachedAi = entry && entry.expires > Date.now() ? entry.ai : undefined;
44
47
  if (ai)
@@ -48,7 +51,7 @@ export class PolicySession {
48
51
  category: ai.category,
49
52
  confidence: ai.confidence,
50
53
  });
51
- const decision = evaluate(request, ai ?? cachedAi);
54
+ const decision = evaluate(request, ai ?? cachedAi, this.profile);
52
55
  if (decision.decision === "human")
53
56
  this.cache.delete(key);
54
57
  // Evaluation always precedes lookup. Filesystem evidence is never cached.
@@ -0,0 +1,13 @@
1
+ export interface Redirect {
2
+ fd: string;
3
+ op: ">" | ">>" | "<" | ">&";
4
+ target: string;
5
+ }
6
+ export interface SimpleCommand {
7
+ env: Array<[string, string]>;
8
+ argv: string[];
9
+ redirects: Redirect[];
10
+ }
11
+ export type Pipeline = SimpleCommand[];
12
+ export declare function parseShell(command: string): Pipeline[] | undefined;
13
+ //# sourceMappingURL=shell.d.ts.map
package/dist/shell.js ADDED
@@ -0,0 +1,158 @@
1
+ // Parses a bounded subset of POSIX shell: simple commands joined by `;`, newlines, `&&`, `||`
2
+ // and `|`, with quoting, leading VAR=value assignments and file redirections. Anything whose
3
+ // effects depend on expansion (`$`, backticks, subshells, braces, heredocs, background jobs,
4
+ // backslashes, comments, process substitution) is rejected so a caller can fall back to a human.
5
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
6
+ export function parseShell(command) {
7
+ if (!command || command.includes("\0") || command.includes("\r"))
8
+ return undefined;
9
+ const pipelines = [];
10
+ let pipeline = [];
11
+ let words = [];
12
+ let redirects = [];
13
+ let pendingRedirect;
14
+ let current = "";
15
+ let active = false;
16
+ let quoted = false;
17
+ let quote = "";
18
+ let dangling = false;
19
+ const endWord = () => {
20
+ if (!active)
21
+ return true;
22
+ const word = { text: current, quoted };
23
+ current = "";
24
+ active = false;
25
+ quoted = false;
26
+ if (pendingRedirect) {
27
+ redirects.push({ ...pendingRedirect, target: word.text });
28
+ pendingRedirect = undefined;
29
+ }
30
+ else {
31
+ words.push(word);
32
+ dangling = false;
33
+ }
34
+ return true;
35
+ };
36
+ const endSimple = () => {
37
+ if (pendingRedirect)
38
+ return false;
39
+ if (!words.length && !redirects.length)
40
+ return true;
41
+ const env = [];
42
+ let index = 0;
43
+ while (index < words.length) {
44
+ const word = words[index];
45
+ if (!word || word.quoted || !ASSIGNMENT.test(word.text))
46
+ break;
47
+ const eq = word.text.indexOf("=");
48
+ env.push([word.text.slice(0, eq), word.text.slice(eq + 1)]);
49
+ index++;
50
+ }
51
+ const argv = words.slice(index).map((word) => word.text);
52
+ if (!argv.length)
53
+ return false;
54
+ pipeline.push({ env, argv, redirects });
55
+ words = [];
56
+ redirects = [];
57
+ return true;
58
+ };
59
+ const endPipeline = (allowEmpty) => {
60
+ if (!endSimple())
61
+ return false;
62
+ if (!pipeline.length)
63
+ return allowEmpty;
64
+ pipelines.push(pipeline);
65
+ pipeline = [];
66
+ return true;
67
+ };
68
+ for (let i = 0; i < command.length; i++) {
69
+ const char = command[i];
70
+ if (quote) {
71
+ if (quote === '"' && /[$`\\]/.test(char))
72
+ return undefined;
73
+ if (char === quote)
74
+ quote = "";
75
+ else
76
+ current += char;
77
+ continue;
78
+ }
79
+ if (char === "'" || char === '"') {
80
+ quote = char;
81
+ active = true;
82
+ quoted = true;
83
+ continue;
84
+ }
85
+ if (/[`$(){}\\#!]/.test(char)) {
86
+ // `#` only starts a comment at a word boundary, but rejecting it everywhere is simpler.
87
+ return undefined;
88
+ }
89
+ if (char === " " || char === "\t") {
90
+ endWord();
91
+ continue;
92
+ }
93
+ if (char === "\n" || char === ";") {
94
+ endWord();
95
+ if (dangling || !endPipeline(true))
96
+ return undefined;
97
+ continue;
98
+ }
99
+ if (char === "&") {
100
+ if (command[i + 1] !== "&")
101
+ return undefined;
102
+ endWord();
103
+ if (!endPipeline(false))
104
+ return undefined;
105
+ dangling = true;
106
+ i++;
107
+ continue;
108
+ }
109
+ if (char === "|") {
110
+ endWord();
111
+ if (command[i + 1] === "|") {
112
+ if (!endPipeline(false))
113
+ return undefined;
114
+ i++;
115
+ }
116
+ else if (!words.length || !endSimple())
117
+ return undefined;
118
+ dangling = true;
119
+ continue;
120
+ }
121
+ if (char === ">" || char === "<") {
122
+ if (command[i + 1] === "(" || (char === "<" && command[i + 1] === "<"))
123
+ return undefined;
124
+ let fd = char === ">" ? "1" : "0";
125
+ if (active && !quoted && /^[0-9]$/.test(current)) {
126
+ fd = current;
127
+ current = "";
128
+ active = false;
129
+ }
130
+ else
131
+ endWord();
132
+ let op = char;
133
+ if (char === ">" && command[i + 1] === ">") {
134
+ op = ">>";
135
+ i++;
136
+ }
137
+ else if (char === ">" && command[i + 1] === "&") {
138
+ op = ">&";
139
+ i++;
140
+ }
141
+ else if (char === ">" && command[i + 1] === "|")
142
+ return undefined;
143
+ if (pendingRedirect)
144
+ return undefined;
145
+ pendingRedirect = { fd, op };
146
+ continue;
147
+ }
148
+ current += char;
149
+ active = true;
150
+ }
151
+ if (quote)
152
+ return undefined;
153
+ endWord();
154
+ if (dangling || !endPipeline(true))
155
+ return undefined;
156
+ return pipelines.length ? pipelines : undefined;
157
+ }
158
+ //# sourceMappingURL=shell.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-corpus/policy-manager",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Deterministic, session-scoped permission decisions with audit logs and bounded AI classification.",
5
5
  "keywords": [
6
6
  "coding-agent",