@primitive.ai/prim 0.1.0-alpha.11 → 0.1.0-alpha.111

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.
Files changed (48) hide show
  1. package/README.md +450 -38
  2. package/SKILL.md +366 -0
  3. package/dist/chunk-2IRLFOEL.js +766 -0
  4. package/dist/chunk-2Q3OGSTV.js +164 -0
  5. package/dist/chunk-43ZKL27W.js +258 -0
  6. package/dist/chunk-4GLVJLEQ.js +55 -0
  7. package/dist/chunk-5BLGBSDM.js +233 -0
  8. package/dist/chunk-5LRKJTLA.js +155 -0
  9. package/dist/chunk-7VIMU2HR.js +209 -0
  10. package/dist/chunk-AOJ254C2.js +511 -0
  11. package/dist/chunk-CTRAJCPN.js +964 -0
  12. package/dist/chunk-EZXEWFDG.js +210 -0
  13. package/dist/chunk-GA2RXPJL.js +168 -0
  14. package/dist/chunk-HTRFPXMD.js +135 -0
  15. package/dist/chunk-IQZA65NV.js +1871 -0
  16. package/dist/chunk-JJI7FU24.js +439 -0
  17. package/dist/chunk-KGBMU76T.js +175 -0
  18. package/dist/chunk-KQ4WBK5R.js +262 -0
  19. package/dist/chunk-NH3VC7YO.js +264 -0
  20. package/dist/chunk-OYHYCK4K.js +13 -0
  21. package/dist/chunk-PO5QAYD7.js +1499 -0
  22. package/dist/chunk-UDBBJWQH.js +20383 -0
  23. package/dist/chunk-W4ZEPZLK.js +36 -0
  24. package/dist/chunk-XG7S3LIL.js +1372 -0
  25. package/dist/daemon/server.js +24051 -0
  26. package/dist/hook-runtime/daemon/server.js +24051 -0
  27. package/dist/hook-runtime/hooks/post-commit.js +21524 -0
  28. package/dist/hook-runtime/hooks/post-rewrite.js +21423 -0
  29. package/dist/hook-runtime/hooks/post-tool-use.js +28917 -0
  30. package/dist/hook-runtime/hooks/pre-commit.js +1657 -0
  31. package/dist/hook-runtime/hooks/pre-tool-use.js +28425 -0
  32. package/dist/hook-runtime/hooks/prim-hook.js +28977 -0
  33. package/dist/hook-runtime/hooks/session-end.js +1176 -0
  34. package/dist/hook-runtime/hooks/session-start.js +31553 -0
  35. package/dist/hook-runtime/index.js +59630 -0
  36. package/dist/hook-runtime/statusline-main.js +886 -0
  37. package/dist/hooks/post-commit.js +196 -0
  38. package/dist/hooks/post-rewrite.js +205 -0
  39. package/dist/hooks/post-tool-use.js +292 -0
  40. package/dist/hooks/pre-commit.js +15 -108
  41. package/dist/hooks/pre-tool-use.js +470 -0
  42. package/dist/hooks/prim-hook.js +242 -0
  43. package/dist/hooks/session-end.js +64 -0
  44. package/dist/hooks/session-start.js +309 -0
  45. package/dist/index.js +10651 -427
  46. package/dist/statusline-main.js +886 -0
  47. package/package.json +41 -16
  48. package/dist/chunk-3APLWTLB.js +0 -165
@@ -1,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- getClient
4
- } from "../chunk-3APLWTLB.js";
3
+ checkAffectedDecisions,
4
+ formatDecisionsWarning
5
+ } from "../chunk-2Q3OGSTV.js";
6
+ import "../chunk-2IRLFOEL.js";
7
+ import "../chunk-5LRKJTLA.js";
8
+ import "../chunk-XG7S3LIL.js";
5
9
 
6
10
  // src/hooks/pre-commit.ts
7
11
  import { execSync } from "child_process";
@@ -11,110 +15,19 @@ function getStagedFiles() {
11
15
  });
12
16
  return output.trim().split("\n").filter((f) => f.length > 0);
13
17
  }
14
- function getStagedDiff(files) {
15
- return execSync(`git diff --cached -- ${files.map((f) => `"${f}"`).join(" ")}`, {
16
- encoding: "utf-8"
17
- });
18
- }
19
- function matchPattern(filePath, pattern) {
20
- const regexStr = pattern.replaceAll("**", "\xA7GLOBSTAR\xA7").replaceAll("*", "[^/]*").replaceAll("\xA7GLOBSTAR\xA7", ".*");
21
- const regex = new RegExp(`^${regexStr}$`);
22
- return regex.test(filePath);
23
- }
24
- function findAffectedContexts(stagedFiles, specs) {
25
- const affected = /* @__PURE__ */ new Map();
26
- for (const file of stagedFiles) {
27
- for (const spec of specs) {
28
- for (const pattern of spec.filePatterns) {
29
- if (matchPattern(file, pattern)) {
30
- const existing = affected.get(spec._id);
31
- if (existing) {
32
- existing.matchedFiles.push(file);
33
- } else {
34
- affected.set(spec._id, {
35
- contextId: spec._id,
36
- matchedFiles: [file]
37
- });
38
- }
39
- break;
40
- }
41
- }
42
- }
43
- }
44
- return affected;
45
- }
46
- var HOOK_TIMEOUT_MS = 1e4;
47
- var defaultDeps = {
48
- getClient,
49
- getStagedFiles,
50
- getStagedDiff
51
- };
52
- async function syncAffectedSpecs(deps = defaultDeps) {
53
- const stagedFiles = deps.getStagedFiles();
18
+ async function runDecisionsCheck() {
19
+ const stagedFiles = getStagedFiles();
54
20
  if (stagedFiles.length === 0) {
55
- return [];
21
+ return { decisions: [], truncated: false };
56
22
  }
57
- const client = deps.getClient();
58
- let mappings = [];
59
- try {
60
- mappings = await client.get("/api/cli/specs/mappings", {
61
- signal: AbortSignal.timeout(HOOK_TIMEOUT_MS)
62
- });
63
- } catch {
64
- return [];
65
- }
66
- if (mappings.length === 0) {
67
- return [];
68
- }
69
- const affectedContexts = findAffectedContexts(stagedFiles, mappings);
70
- if (affectedContexts.size === 0) {
71
- return [];
72
- }
73
- console.log(`[prim] ${String(affectedContexts.size)} spec(s) affected by staged changes:`);
74
- const synced = [];
75
- for (const [contextId, affected] of affectedContexts) {
76
- try {
77
- const ctx = await client.get(`/api/cli/contexts/${contextId}`, {
78
- signal: AbortSignal.timeout(HOOK_TIMEOUT_MS)
79
- });
80
- if (!ctx._id) {
81
- console.log(` [skip] ${contextId} \u2014 not found`);
82
- continue;
83
- }
84
- if (!ctx.isSpecDocument) {
85
- console.log(` [skip] ${contextId} \u2014 not a spec document`);
86
- continue;
87
- }
88
- const diffContent = deps.getStagedDiff(affected.matchedFiles);
89
- if (!diffContent) {
90
- console.log(` [skip] ${contextId} \u2014 no diff content`);
91
- continue;
92
- }
93
- const response = await client.post(
94
- `/api/cli/contexts/${contextId}/sync-diff`,
95
- { diffContent, affectedFiles: affected.matchedFiles },
96
- { signal: AbortSignal.timeout(HOOK_TIMEOUT_MS) }
97
- );
98
- const name = ctx.name ?? "(unnamed)";
99
- if (response.truncated && response.sizeChars && response.limitChars) {
100
- const sizeKiB = Math.round(response.sizeChars / 1024);
101
- const limitKiB = Math.round(response.limitChars / 1024);
102
- console.log(
103
- ` [synced] ${contextId} \u2014 ${name} (truncated: ${String(sizeKiB)} KiB \u2192 ${String(limitKiB)} KiB analyzed)`
104
- );
105
- } else {
106
- console.log(` [synced] ${contextId} \u2014 ${name}`);
107
- }
108
- synced.push(contextId);
109
- } catch (error) {
110
- const message = error instanceof Error ? error.message : String(error);
111
- console.error(` [error] ${contextId} \u2014 ${message}`);
112
- }
113
- }
114
- return synced;
23
+ return checkAffectedDecisions(stagedFiles);
115
24
  }
116
25
  async function main() {
117
- await syncAffectedSpecs();
26
+ const decisionsResult = await runDecisionsCheck();
27
+ const warning = formatDecisionsWarning(decisionsResult);
28
+ if (warning) {
29
+ console.error(warning);
30
+ }
118
31
  process.exit(0);
119
32
  }
120
33
  if (!process.env.VITEST) {
@@ -123,9 +36,3 @@ if (!process.env.VITEST) {
123
36
  process.exit(0);
124
37
  });
125
38
  }
126
- export {
127
- HOOK_TIMEOUT_MS,
128
- findAffectedContexts,
129
- matchPattern,
130
- syncAffectedSpecs
131
- };
@@ -0,0 +1,470 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ analyzeShellTargets,
4
+ buildCodexOutput,
5
+ buildCursorOutput,
6
+ buildHermesOutput,
7
+ buildHookOutput,
8
+ demoteForMode,
9
+ extractFileTargets,
10
+ failOpenCodex,
11
+ failOpenCursor,
12
+ failOpenHermes,
13
+ failOpenOutput,
14
+ observeDemoInvocation,
15
+ readHookMode
16
+ } from "../chunk-CTRAJCPN.js";
17
+ import {
18
+ appendCodexContext,
19
+ hasVisibleCodexMessage,
20
+ prepareCodexContext
21
+ } from "../chunk-AOJ254C2.js";
22
+ import "../chunk-5BLGBSDM.js";
23
+ import "../chunk-GA2RXPJL.js";
24
+ import {
25
+ DEFAULT_RULES,
26
+ scrub
27
+ } from "../chunk-KQ4WBK5R.js";
28
+ import {
29
+ boundedHealthError,
30
+ cachedCollectScopeAdmits
31
+ } from "../chunk-UDBBJWQH.js";
32
+ import {
33
+ HttpError,
34
+ getClient,
35
+ terminalSafeLine
36
+ } from "../chunk-2IRLFOEL.js";
37
+ import {
38
+ normalizeEnvelope,
39
+ parseAgent,
40
+ readHookStdin,
41
+ shouldSuppressImportedCursorHandler
42
+ } from "../chunk-NH3VC7YO.js";
43
+ import "../chunk-PO5QAYD7.js";
44
+ import "../chunk-5LRKJTLA.js";
45
+ import {
46
+ canonicalGitRoot,
47
+ canonicalRepositoryPath,
48
+ currentBranch,
49
+ githubRepositoryFullName,
50
+ isRepoActive,
51
+ packageVersion,
52
+ repoSyncId,
53
+ resolveAuthCredential
54
+ } from "../chunk-XG7S3LIL.js";
55
+
56
+ // src/hooks/approval-copy.ts
57
+ var MAX_EXCERPT_CHARS = 80;
58
+ var MAX_TITLE_CHARS = 140;
59
+ var MAX_PATH_CHARS = 120;
60
+ var MAX_VISIBLE_CONFLICTS = 3;
61
+ var SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;
62
+ function displayText(value, maxChars) {
63
+ const redacted = scrub(value, DEFAULT_RULES);
64
+ const clean = terminalSafeLine(typeof redacted === "string" ? redacted : "");
65
+ const characters = Array.from(clean);
66
+ return characters.length > maxChars ? `${characters.slice(0, maxChars - 1).join("")}\u2026` : clean;
67
+ }
68
+ function targetLabel(paths) {
69
+ const shown = paths.slice(0, 2).map((path) => `\u201C${displayText(path, MAX_PATH_CHARS)}\u201D`);
70
+ if (shown.length === 0) return "the requested change";
71
+ const remaining = paths.length - shown.length;
72
+ return `${shown.join(" and ")}${remaining > 0 ? ` and ${remaining} more file(s)` : ""}`;
73
+ }
74
+ function editPreview(toolName, toolInput, paths) {
75
+ const input = toolInput && typeof toolInput === "object" ? toolInput : {};
76
+ const targets = targetLabel(paths);
77
+ if (toolName === "Edit") {
78
+ const before = typeof input.old_string === "string" ? displayText(input.old_string, MAX_EXCERPT_CHARS) : "";
79
+ const after = typeof input.new_string === "string" ? displayText(input.new_string, MAX_EXCERPT_CHARS) : "";
80
+ return before && after ? `Edit ${targets}:
81
+ Current text: \u201C${before}\u201D
82
+ Proposed replacement: \u201C${after}\u201D` : `Edit ${targets}.`;
83
+ }
84
+ if (toolName === "Write" || toolName === "NotebookEdit") return `Write ${targets}.`;
85
+ if (toolName === "Bash" || toolName === "Shell") return `Run a command affecting ${targets}.`;
86
+ return `Change ${targets}.`;
87
+ }
88
+ function decisionLabel(conflict) {
89
+ const id = typeof conflict.shortId === "string" && SAFE_ID.test(conflict.shortId) ? `dec_${conflict.shortId}` : typeof conflict.decisionId === "string" && SAFE_ID.test(conflict.decisionId) ? conflict.decisionId : "unknown";
90
+ const title = typeof conflict.title === "string" ? displayText(conflict.title, MAX_TITLE_CHARS) : "";
91
+ return title ? `Decision ${id}: \u201C${title}\u201D.` : `Decision ${id}: details unavailable; inspect it before approving.`;
92
+ }
93
+ function incomplete(evidence) {
94
+ const coverage = evidence.evaluationCoverage;
95
+ return Array.isArray(coverage?.selectionOmissions) && coverage.selectionOmissions.length > 0 || Array.isArray(coverage?.evidenceOmissions) && coverage.evidenceOmissions.length > 0 || coverage?.status !== void 0 && coverage.status !== "completed" || ["candidate_set_truncated", "evidence_incomplete", "coverage_unverified"].includes(
96
+ evidence.reasonCode
97
+ );
98
+ }
99
+ function approvalSummary(evidence, preview) {
100
+ const lines = [preview];
101
+ if (evidence.conflicts.length > 0) {
102
+ lines.push("Primitive found a conflict with an existing decision.");
103
+ lines.push(...evidence.conflicts.slice(0, MAX_VISIBLE_CONFLICTS).map(decisionLabel));
104
+ const remaining = evidence.conflicts.length - MAX_VISIBLE_CONFLICTS;
105
+ if (remaining > 0) lines.push(`${remaining} more conflicting decision(s) need inspection.`);
106
+ } else {
107
+ lines.push(
108
+ displayText(evidence.message || "Primitive requires review before this change.", 180)
109
+ );
110
+ }
111
+ if (incomplete(evidence)) {
112
+ lines.push("Some potentially applicable decisions were not fully checked.");
113
+ }
114
+ return lines.filter(Boolean).join("\n");
115
+ }
116
+
117
+ // src/hooks/preflight-v3.ts
118
+ import { Buffer } from "buffer";
119
+ var PREFLIGHT_PROTOCOL_VERSION = 3;
120
+ var PREFLIGHT_TIMEOUT_MS = 12e3;
121
+ var MAX_PREFLIGHT_PATHS = 32;
122
+ var MAX_PROPOSAL_BYTES = 6144;
123
+ var MAX_CLIENT_VERSION_CHARS = 32;
124
+ var CLIENT_VERSION_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
125
+ var MAX_DECISION_DISCLOSURES = 16;
126
+ var DISCLOSED_DECISION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;
127
+ var DISCLOSED_DECISION_SHORT_ID_RE = /^[0-9a-f]{8}$/u;
128
+ function boundedClientVersion(raw) {
129
+ return typeof raw === "string" && raw.length <= MAX_CLIENT_VERSION_CHARS && CLIENT_VERSION_RE.test(raw) ? raw : "unknown";
130
+ }
131
+ function resolvePreflightTargets(args) {
132
+ let rawPaths;
133
+ let coverage = "complete";
134
+ let mutation = "present";
135
+ let definite = false;
136
+ const shellTool = (args.agent === "claude_code" || args.agent === "codex") && args.toolName === "Bash" || args.agent === "cursor" && args.toolName === "Shell";
137
+ if (shellTool) {
138
+ const command = typeof args.toolInput === "string" ? args.toolInput : args.toolInput && typeof args.toolInput === "object" ? args.toolInput.command : void 0;
139
+ if (typeof command !== "string") {
140
+ return { paths: [], coverage: "unverified", mutation: "present" };
141
+ }
142
+ const shell = analyzeShellTargets(command);
143
+ rawPaths = shell.paths;
144
+ coverage = shell.coverage;
145
+ mutation = shell.mutation;
146
+ definite = shell.definiteEdit === true;
147
+ } else {
148
+ const extracted = extractFileTargets(args.toolName, args.toolInput, args.agent);
149
+ if (!extracted) return { paths: [], coverage: "complete", mutation: "none" };
150
+ rawPaths = extracted.paths;
151
+ if (!extracted.complete) coverage = "unverified";
152
+ definite = true;
153
+ }
154
+ const root = canonicalGitRoot(args.cwd);
155
+ const paths = /* @__PURE__ */ new Set();
156
+ for (const rawPath of rawPaths) {
157
+ const canonical = canonicalRepositoryPath(rawPath, args.cwd, root);
158
+ if (canonical) paths.add(canonical);
159
+ else coverage = "unverified";
160
+ }
161
+ const bounded = [...paths];
162
+ if (bounded.length > MAX_PREFLIGHT_PATHS) coverage = "unverified";
163
+ const resolved = bounded.slice(0, MAX_PREFLIGHT_PATHS);
164
+ if (definite && resolved.length === 0 && mutation === "present") {
165
+ return { paths: resolved, coverage: "unverified", mutation, definite: true };
166
+ }
167
+ return { paths: resolved, coverage, mutation };
168
+ }
169
+ function truncateUtf8(value, maxBytes) {
170
+ const encoded = Buffer.from(value);
171
+ if (encoded.byteLength <= maxBytes) return value;
172
+ return encoded.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD$/u, "");
173
+ }
174
+ function proposalFor(toolInput) {
175
+ const redacted = scrub(toolInput, DEFAULT_RULES);
176
+ return truncateUtf8(JSON.stringify(redacted) ?? "", MAX_PROPOSAL_BYTES);
177
+ }
178
+ function parsePreflightResponse(value) {
179
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
180
+ const response = value;
181
+ const verdicts = /* @__PURE__ */ new Set(["allow", "warn", "ask", "block", "unavailable"]);
182
+ if (response.protocolVersion !== PREFLIGHT_PROTOCOL_VERSION || typeof response.verdict !== "string" || !verdicts.has(response.verdict) || typeof response.reasonCode !== "string" || typeof response.message !== "string" || !Array.isArray(response.conflicts) || !Array.isArray(response.bypassed)) {
183
+ return null;
184
+ }
185
+ if (response.checkId !== void 0 && (typeof response.checkId !== "string" || !DISCLOSED_DECISION_ID_RE.test(response.checkId)))
186
+ return null;
187
+ const disclosures = response.decisionDisclosures;
188
+ if (disclosures !== void 0) {
189
+ if (!Array.isArray(disclosures) || disclosures.length === 0 || disclosures.length > MAX_DECISION_DISCLOSURES) {
190
+ return null;
191
+ }
192
+ const seen = /* @__PURE__ */ new Set();
193
+ for (const value2 of disclosures) {
194
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return null;
195
+ const disclosure = value2;
196
+ if (Object.keys(disclosure).length !== 3 || !Object.hasOwn(disclosure, "decisionId") || !Object.hasOwn(disclosure, "shortId") || !Object.hasOwn(disclosure, "participation") || typeof disclosure.decisionId !== "string" || !DISCLOSED_DECISION_ID_RE.test(disclosure.decisionId) || typeof disclosure.shortId !== "string" || !DISCLOSED_DECISION_SHORT_ID_RE.test(disclosure.shortId) || disclosure.participation !== "candidate" && disclosure.participation !== "reconcile_bypass" || seen.has(disclosure.decisionId)) {
197
+ return null;
198
+ }
199
+ seen.add(disclosure.decisionId);
200
+ }
201
+ }
202
+ return response;
203
+ }
204
+ function decisionDisclosureContext(response) {
205
+ return response.decisionDisclosures?.map(({ decisionId }) => `[primitive] hidden Decision: prim decisions show ${decisionId}`).join("\n") ?? "";
206
+ }
207
+ async function requestPreflight(request, signal = AbortSignal.timeout(PREFLIGHT_TIMEOUT_MS)) {
208
+ const response = await getClient().post("/api/cli/decisions/conflict-check", request, {
209
+ signal,
210
+ quietRefresh: true
211
+ });
212
+ return parsePreflightResponse(response);
213
+ }
214
+ function resultForPreflight(response, preview = "Review the requested change.") {
215
+ const verdict = response.verdict === "block" ? "deny" : response.verdict;
216
+ const message = boundedHealthError(response.message) ?? "";
217
+ const unavailable = message || boundedHealthError(response.reasonCode);
218
+ const safe = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
219
+ const directives = response.conflicts.flatMap((value) => {
220
+ if (!value || typeof value !== "object") return [];
221
+ const { decisionId, shortId } = value;
222
+ const id = typeof shortId === "string" && safe.test(shortId) ? `dec_${shortId}` : typeof decisionId === "string" && safe.test(decisionId) ? decisionId : void 0;
223
+ if (!id) return [];
224
+ return [
225
+ `To reconcile, run: prim reconcile ${id}`,
226
+ ...response.checkId && safe.test(response.checkId) ? [
227
+ `Check: ${response.checkId}. After resolving, record the confirmed outcome: prim reconcile ${id} --check ${response.checkId} --outcome followed (retained Decision), or --outcome superseded (after replacing it). A bypass alone is not a resolution.`
228
+ ] : []
229
+ ];
230
+ });
231
+ const guidance = [message, ...new Set(directives)].filter(Boolean).join("\n");
232
+ const reason = response.conflicts.length > 0 || response.verdict === "ask" || response.verdict === "block" ? approvalSummary(
233
+ {
234
+ conflicts: response.conflicts,
235
+ message,
236
+ reasonCode: response.reasonCode,
237
+ evaluationCoverage: response.evaluationCoverage
238
+ },
239
+ preview
240
+ ) : message;
241
+ const disclosureContext = decisionDisclosureContext(response);
242
+ return {
243
+ verdict,
244
+ conflicts: response.conflicts,
245
+ reason,
246
+ additionalContext: [
247
+ disclosureContext,
248
+ ["warn", "ask", "block"].includes(response.verdict) ? guidance : ""
249
+ ].filter(Boolean).join("\n"),
250
+ truncated: false,
251
+ unavailable: response.verdict === "unavailable" ? unavailable : void 0
252
+ };
253
+ }
254
+ function unverifiedResult(message) {
255
+ return {
256
+ verdict: "unavailable",
257
+ conflicts: [],
258
+ reason: "",
259
+ additionalContext: "",
260
+ truncated: false,
261
+ unavailable: message
262
+ };
263
+ }
264
+
265
+ // src/hooks/pre-tool-use.ts
266
+ var STDIN_TIMEOUT_MS = 1e3;
267
+ var agent = parseAgent(process.argv);
268
+ async function emit(output) {
269
+ return await new Promise((resolve) => {
270
+ try {
271
+ process.stdout.write(`${JSON.stringify(output)}
272
+ `, (error) => resolve(!error));
273
+ } catch {
274
+ resolve(false);
275
+ }
276
+ });
277
+ }
278
+ async function emitWithAcknowledgment(output, acknowledge) {
279
+ const handedOff = await emit(output);
280
+ await acknowledge?.(handedOff);
281
+ }
282
+ function failOpen() {
283
+ if (agent === "hermes") return failOpenHermes();
284
+ if (agent === "cursor") return failOpenCursor();
285
+ return agent === "codex" ? failOpenCodex() : failOpenOutput();
286
+ }
287
+ function invocationId(envelope) {
288
+ const value = agent === "hermes" ? envelope.extra?.tool_call_id : envelope.tool_use_id;
289
+ return typeof value === "string" && value.length > 0 ? value : void 0;
290
+ }
291
+ function hermesAdvisory(result, aggregate) {
292
+ const parts = [];
293
+ if (aggregate === "warn") parts.push(result.reason);
294
+ if (result.verdict === "unavailable") {
295
+ parts.push(result.unavailable ?? result.reason);
296
+ }
297
+ if (result.additionalContext && result.additionalContext !== result.reason) {
298
+ parts.push(result.additionalContext);
299
+ }
300
+ const message = [...new Set(parts.filter(Boolean))].join("\n");
301
+ return message.startsWith("[primitive]") ? message : message ? `[primitive] ${message}` : "";
302
+ }
303
+ function preflightFailure(error) {
304
+ if (!(error instanceof HttpError && error.status === 401)) {
305
+ return "enforcement service unavailable; change was not verified";
306
+ }
307
+ if (resolveAuthCredential()?.source === "environment") {
308
+ return "PRIM_TOKEN was rejected; change was not verified";
309
+ }
310
+ return "authentication required; run `prim auth login`; change was not verified";
311
+ }
312
+ async function emitUnverified(message, envelope) {
313
+ const result = unverifiedResult(message);
314
+ if (agent === "hermes") {
315
+ process.stderr.write(`[primitive] ${message}
316
+ `);
317
+ await emit(failOpenHermes());
318
+ } else if (agent === "cursor") {
319
+ process.stderr.write(`[primitive] ${message}
320
+ `);
321
+ await emit(buildCursorOutput("allow", [result]));
322
+ } else {
323
+ let output = agent === "codex" ? buildCodexOutput("allow", [result]) : buildHookOutput("allow", [result]);
324
+ if (agent === "codex" && typeof envelope?.session_id === "string" && envelope.session_id) {
325
+ try {
326
+ const context = await prepareCodexContext({
327
+ cwd: envelope.cwd ?? process.cwd(),
328
+ sessionId: envelope.session_id,
329
+ includeDigest: false
330
+ });
331
+ output = appendCodexContext(output, context.context);
332
+ await emitWithAcknowledgment(output, context.acknowledge);
333
+ return;
334
+ } catch {
335
+ }
336
+ }
337
+ await emit(output);
338
+ }
339
+ }
340
+ async function main() {
341
+ let raw;
342
+ try {
343
+ raw = await readHookStdin(STDIN_TIMEOUT_MS);
344
+ } catch {
345
+ await emit(failOpen());
346
+ return;
347
+ }
348
+ let envelope;
349
+ try {
350
+ const incoming = JSON.parse(raw);
351
+ if (agent !== "cursor" && shouldSuppressImportedCursorHandler(incoming, "prim-pre-tool-use")) {
352
+ await emit(failOpenCursor());
353
+ return;
354
+ }
355
+ envelope = normalizeEnvelope(incoming, agent);
356
+ } catch {
357
+ await emit(failOpen());
358
+ return;
359
+ }
360
+ try {
361
+ if (observeDemoInvocation(envelope, agent, false).invocation) {
362
+ await emit(failOpen());
363
+ return;
364
+ }
365
+ } catch {
366
+ }
367
+ if (envelope.hook_event_name !== "PreToolUse") {
368
+ await emit(failOpen());
369
+ return;
370
+ }
371
+ const env = process.env;
372
+ const mode = readHookMode(env);
373
+ if (mode === "off") {
374
+ await emit(failOpen());
375
+ return;
376
+ }
377
+ const toolName = typeof envelope.tool_name === "string" ? envelope.tool_name : "";
378
+ const cwd = typeof envelope.cwd === "string" && envelope.cwd.length > 0 ? envelope.cwd : process.cwd();
379
+ const targets = resolvePreflightTargets({
380
+ toolName,
381
+ toolInput: envelope.tool_input,
382
+ agent,
383
+ cwd
384
+ });
385
+ if (targets.mutation === "none") {
386
+ await emit(failOpen());
387
+ return;
388
+ }
389
+ if (!isRepoActive(cwd)) {
390
+ await emit(failOpen());
391
+ return;
392
+ }
393
+ if (targets.paths.length === 0 && !targets.definite) {
394
+ await emit(failOpen());
395
+ return;
396
+ }
397
+ if (agent === "cursor" && targets.coverage === "unverified") {
398
+ await emitUnverified("tool targets were ambiguous or outside the active repository", envelope);
399
+ return;
400
+ }
401
+ const binding = repoSyncId(cwd);
402
+ const branch = currentBranch(cwd);
403
+ const sessionId = envelope.session_id;
404
+ const callId = invocationId(envelope);
405
+ if (!binding || typeof sessionId !== "string" || !sessionId || !callId) {
406
+ await emitUnverified(
407
+ "GitHub repo connection is required for repository-specific file attribution, Conflict Gate verification, and commit correlation; or tool invocation identity is unavailable",
408
+ envelope
409
+ );
410
+ return;
411
+ }
412
+ const collectScopeAdmits = cachedCollectScopeAdmits(cwd, {
413
+ repository: githubRepositoryFullName(cwd) ?? void 0,
414
+ branch,
415
+ agent,
416
+ paths: targets.paths,
417
+ pathsComplete: targets.coverage === "complete"
418
+ });
419
+ const request = {
420
+ protocolVersion: PREFLIGHT_PROTOCOL_VERSION,
421
+ agent,
422
+ clientMode: mode,
423
+ clientVersion: boundedClientVersion(packageVersion()),
424
+ sessionId,
425
+ invocationId: callId,
426
+ repoSyncId: binding,
427
+ paths: targets.paths,
428
+ coverage: targets.coverage,
429
+ ...branch === void 0 ? {} : { branch },
430
+ proposal: collectScopeAdmits ? proposalFor(envelope.tool_input) : ""
431
+ };
432
+ let result;
433
+ try {
434
+ const response = await requestPreflight(request);
435
+ if (!response) {
436
+ await emitUnverified("enforcement service returned an incompatible response", envelope);
437
+ return;
438
+ }
439
+ result = resultForPreflight(
440
+ response,
441
+ editPreview(toolName, envelope.tool_input, targets.paths)
442
+ );
443
+ } catch (error) {
444
+ await emitUnverified(preflightFailure(error), envelope);
445
+ return;
446
+ }
447
+ const aggregate = demoteForMode(
448
+ result.verdict === "unavailable" ? "allow" : result.verdict,
449
+ mode
450
+ );
451
+ if (agent === "hermes" && aggregate !== "deny" && aggregate !== "ask") {
452
+ const advisory = hermesAdvisory(result, aggregate);
453
+ if (advisory) process.stderr.write(`${advisory}
454
+ `);
455
+ }
456
+ let output = agent === "hermes" ? buildHermesOutput(aggregate, [result]) : agent === "cursor" ? buildCursorOutput(aggregate, [result]) : agent === "codex" ? buildCodexOutput(aggregate, [result]) : buildHookOutput(aggregate, [result]);
457
+ if (agent === "codex" && hasVisibleCodexMessage(output) && typeof sessionId === "string" && sessionId.length > 0) {
458
+ try {
459
+ const context = await prepareCodexContext({ cwd, sessionId, includeDigest: false });
460
+ output = appendCodexContext(output, context.context);
461
+ await emitWithAcknowledgment(output, context.acknowledge);
462
+ return;
463
+ } catch {
464
+ }
465
+ }
466
+ await emit(output);
467
+ }
468
+ main().catch(async () => {
469
+ await emit(failOpen());
470
+ });