@theoklitosbam7/verdict-kit 0.0.0-stage → 0.1.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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +625 -2
  3. package/config/routing/engineering.action-risk.consensus.v1.json +16 -0
  4. package/config/routing/engineering.task-route.cascade.v1.json +21 -0
  5. package/dist/action-policy.d.ts +104 -0
  6. package/dist/action-policy.js +173 -0
  7. package/dist/cache.d.ts +17 -0
  8. package/dist/cache.js +139 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +142 -0
  11. package/dist/concurrency.d.ts +12 -0
  12. package/dist/concurrency.js +110 -0
  13. package/dist/config.d.ts +61 -0
  14. package/dist/config.js +247 -0
  15. package/dist/decision.d.ts +75 -0
  16. package/dist/decision.js +278 -0
  17. package/dist/engine.d.ts +63 -0
  18. package/dist/engine.js +79 -0
  19. package/dist/errors.d.ts +6 -0
  20. package/dist/errors.js +19 -0
  21. package/dist/http.d.ts +18 -0
  22. package/dist/http.js +140 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +14 -0
  25. package/dist/package-info.d.ts +1 -0
  26. package/dist/package-info.js +5 -0
  27. package/dist/policy/evaluate.d.ts +7 -0
  28. package/dist/policy/evaluate.js +39 -0
  29. package/dist/policy/events.d.ts +32 -0
  30. package/dist/policy/events.js +31 -0
  31. package/dist/policy/payload.d.ts +6 -0
  32. package/dist/policy/payload.js +11 -0
  33. package/dist/policy/registry.d.ts +22 -0
  34. package/dist/policy/registry.js +89 -0
  35. package/dist/policy/schema.d.ts +198 -0
  36. package/dist/policy/schema.js +112 -0
  37. package/dist/policy/scope.d.ts +5 -0
  38. package/dist/policy/scope.js +120 -0
  39. package/dist/probability.d.ts +1 -0
  40. package/dist/probability.js +3 -0
  41. package/dist/providers/discovery.d.ts +10 -0
  42. package/dist/providers/discovery.js +113 -0
  43. package/dist/providers/index.d.ts +56 -0
  44. package/dist/providers/index.js +83 -0
  45. package/dist/providers/ollama.d.ts +12 -0
  46. package/dist/providers/ollama.js +93 -0
  47. package/dist/providers/opencode-go.d.ts +3 -0
  48. package/dist/providers/opencode-go.js +40 -0
  49. package/dist/providers/system-one.d.ts +21 -0
  50. package/dist/providers/system-one.js +44 -0
  51. package/dist/providers/typesafe.d.ts +3 -0
  52. package/dist/providers/typesafe.js +36 -0
  53. package/dist/public.d.ts +5 -0
  54. package/dist/public.js +5 -0
  55. package/dist/response.d.ts +6 -0
  56. package/dist/response.js +104 -0
  57. package/dist/routing/cascade.d.ts +112 -0
  58. package/dist/routing/cascade.js +220 -0
  59. package/dist/routing/consensus.d.ts +148 -0
  60. package/dist/routing/consensus.js +367 -0
  61. package/dist/routing/retry.d.ts +3 -0
  62. package/dist/routing/retry.js +47 -0
  63. package/dist/routing/router.d.ts +12 -0
  64. package/dist/routing/router.js +27 -0
  65. package/dist/schemas.d.ts +339 -0
  66. package/dist/schemas.js +283 -0
  67. package/dist/server.d.ts +42 -0
  68. package/dist/server.js +416 -0
  69. package/dist/telemetry/events.d.ts +15 -0
  70. package/dist/telemetry/events.js +87 -0
  71. package/dist/telemetry/sink.d.ts +7 -0
  72. package/dist/telemetry/sink.js +59 -0
  73. package/dist/templates/registry.d.ts +13 -0
  74. package/dist/templates/registry.js +100 -0
  75. package/dist/templates/schema.d.ts +115 -0
  76. package/dist/templates/schema.js +70 -0
  77. package/dist/types.d.ts +86 -0
  78. package/dist/types.js +2 -0
  79. package/package.json +77 -3
  80. package/policies/engineering-default.v1.json +36 -0
  81. package/policies/engineering-strict.v1.json +36 -0
  82. package/templates/engineering.action-risk.v1.json +32 -0
  83. package/templates/engineering.compatibility.v1.json +25 -0
  84. package/templates/engineering.pr-risk.v1.json +26 -0
  85. package/templates/engineering.security-sensitivity.v1.json +20 -0
  86. package/templates/engineering.task-route.v1.json +27 -0
  87. package/templates/engineering.test-depth.v1.json +26 -0
@@ -0,0 +1,39 @@
1
+ import { gate } from "../decision.js";
2
+ import { isProbability } from "../probability.js";
3
+ export function evaluatePolicyAnswers(answers, { definition, questions }, reducedContext) {
4
+ const result = gate(answers, definition.rules);
5
+ if (result.action === "block")
6
+ return { ...result, reasonCode: "policy_block" };
7
+ const missing = definition.required_answers.filter((name) => {
8
+ const answer = Object.hasOwn(answers, name) ? answers[name] : undefined;
9
+ const question = questions[name];
10
+ if (!answer || !question || answer.type !== question.type)
11
+ return true;
12
+ if (answer.type === "choice" && question.type === "choice") {
13
+ return !Object.hasOwn(question.criteria, answer.choice);
14
+ }
15
+ if (answer.type === "noul")
16
+ return !isProbability(answer.noul);
17
+ return answer.type === "score" && !Number.isFinite(answer.score);
18
+ });
19
+ if (missing.length) {
20
+ return {
21
+ action: "review",
22
+ reasonCode: "required_answer_invalid",
23
+ reasons: [
24
+ ...result.reasons,
25
+ ...missing.map((name) => `${name}: required answer is missing or invalid`),
26
+ ],
27
+ };
28
+ }
29
+ if (result.action === "review")
30
+ return { ...result, reasonCode: "policy_review" };
31
+ if (reducedContext) {
32
+ return {
33
+ action: "review",
34
+ reasonCode: "reduced_context",
35
+ reasons: ["The decision provider received limited action context"],
36
+ };
37
+ }
38
+ return { ...result, reasonCode: "policy_allow" };
39
+ }
@@ -0,0 +1,32 @@
1
+ import type { ActionPolicyResult } from "../action-policy.js";
2
+ import type { ConsensusPolicyResult } from "../routing/consensus.js";
3
+ export type PolicyAdapterMode = "disabled" | "observe" | "enforce";
4
+ export type PolicyAdapter = "codex" | "claude-code" | "pi";
5
+ export type PolicyTargetIdentity = {
6
+ provider: string;
7
+ model?: string;
8
+ };
9
+ export declare function readPolicyAdapterMode(value?: string): PolicyAdapterMode;
10
+ export declare function recordPolicyObservation(adapter: PolicyAdapter, { status, profile, reasonCode, action, consensus, members, }: Pick<ActionPolicyResult, "status" | "profile" | "action"> & {
11
+ reasonCode: string;
12
+ } & Partial<Pick<ConsensusPolicyResult, "consensus" | "members">>, target?: PolicyTargetIdentity): {
13
+ event: string;
14
+ adapter: PolicyAdapter;
15
+ status: "evaluated" | "failed" | "skipped";
16
+ profile: {
17
+ id: string;
18
+ version: number;
19
+ };
20
+ provider?: string | undefined;
21
+ model?: string | undefined;
22
+ consensus?: {
23
+ id: string;
24
+ version: number;
25
+ } | undefined;
26
+ members?: {
27
+ provider: string;
28
+ model: string;
29
+ }[] | undefined;
30
+ reasonCode: string;
31
+ outcome: "would_allow" | "would_block" | "would_review";
32
+ };
@@ -0,0 +1,31 @@
1
+ import { DecisionError } from "../errors.js";
2
+ export function readPolicyAdapterMode(value = "enforce") {
3
+ if (value === "disabled" || value === "observe" || value === "enforce")
4
+ return value;
5
+ throw new DecisionError("configuration", "DECISION_ACTION_POLICY_MODE must be disabled, observe, or enforce.");
6
+ }
7
+ export function recordPolicyObservation(adapter, { status, profile, reasonCode, action, consensus, members, }, target) {
8
+ const event = {
9
+ event: "decision_policy_observation",
10
+ adapter,
11
+ status,
12
+ profile: { id: profile.id, version: profile.version },
13
+ ...(target ? { provider: target.provider } : {}),
14
+ ...(target?.model !== undefined ? { model: target.model } : {}),
15
+ ...(consensus && members
16
+ ? {
17
+ consensus: { id: consensus.id, version: consensus.version },
18
+ members: members.flatMap(({ status, provider, model }) => status === "evaluated" ? [{ provider, model }] : []),
19
+ }
20
+ : {}),
21
+ reasonCode,
22
+ outcome: `would_${action}`,
23
+ };
24
+ try {
25
+ console.error(JSON.stringify(event));
26
+ }
27
+ catch {
28
+ // A diagnostic sink must not change the host decision.
29
+ }
30
+ return event;
31
+ }
@@ -0,0 +1,6 @@
1
+ import type { JsonValue } from "../types.js";
2
+ export declare function containsRecognizedSecret(value: unknown): boolean;
3
+ export declare function projectNonLocalAction(toolName: string, input: JsonValue): {
4
+ readonly tool_family: "file_edit";
5
+ readonly action: "sensitive_path_edit";
6
+ } | undefined;
@@ -0,0 +1,11 @@
1
+ import { isSensitiveEdit } from "./scope.js";
2
+ const RECOGNIZED_SECRET = /-----BEGIN [A-Z ]*PRIVATE KEY-----|\bBearer\s+[^\s"]+|\b(?:api[_-]?key|access[_-]?token|password|secret|token)\s*=\s*[^\s"]+|"(?:authorization|api[_-]?key|access[_-]?token|password|secret|token)"\s*:\s*"[^"]+/i;
3
+ export function containsRecognizedSecret(value) {
4
+ return RECOGNIZED_SECRET.test(JSON.stringify(value));
5
+ }
6
+ export function projectNonLocalAction(toolName, input) {
7
+ if (!isSensitiveEdit(toolName, input) || containsRecognizedSecret(input)) {
8
+ return undefined;
9
+ }
10
+ return { tool_family: "file_edit", action: "sensitive_path_edit" };
11
+ }
@@ -0,0 +1,22 @@
1
+ import { type TemplateRegistry } from "../templates/registry.js";
2
+ import type { DecisionQuestions } from "../types.js";
3
+ import { type PolicyProfile } from "./schema.js";
4
+ export declare function createPolicyRegistry(definitions: readonly unknown[], templates: TemplateRegistry): {
5
+ get(selection: string): {
6
+ definition: PolicyProfile;
7
+ questions: DecisionQuestions;
8
+ validateState: (state: unknown) => Promise<boolean>;
9
+ };
10
+ };
11
+ export type ResolvedPolicyProfile = ReturnType<ReturnType<typeof createPolicyRegistry>["get"]>;
12
+ export declare function loadPolicyProfile(selection?: string, templates?: {
13
+ get(identity: import("../templates/schema.js").TemplateIdentity): import("../templates/schema.js").TemplateDefinition;
14
+ list(): {
15
+ id: string;
16
+ version: number;
17
+ description: string;
18
+ uri: string;
19
+ }[];
20
+ validateState(identity: import("../templates/schema.js").TemplateIdentity, state: unknown): Promise<boolean>;
21
+ }): ResolvedPolicyProfile;
22
+ export declare function getPolicyProfile(): ResolvedPolicyProfile;
@@ -0,0 +1,89 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { DecisionError } from "../errors.js";
3
+ import { loadTemplateRegistry } from "../templates/registry.js";
4
+ import { policyProfileSchema } from "./schema.js";
5
+ const DEFAULT_PROFILE = "engineering-default@1";
6
+ function invalidReference(profile) {
7
+ return new DecisionError("configuration", `Invalid rule or template reference in policy profile ${profile}.`);
8
+ }
9
+ function validateRules(profile, key, questions) {
10
+ const { rules, required_answers: required } = profile;
11
+ const choiceRules = Object.entries(rules.choice ?? {});
12
+ const noulRules = Object.entries(rules.noul ?? {});
13
+ if (!choiceRules.length && !noulRules.length && rules.min_confidence === undefined) {
14
+ throw invalidReference(key);
15
+ }
16
+ if (required.some((name) => !Object.hasOwn(questions, name)))
17
+ throw invalidReference(key);
18
+ for (const [name, rule] of choiceRules) {
19
+ const question = Object.hasOwn(questions, name) ? questions[name] : undefined;
20
+ const labels = [...(rule.allow ?? []), ...(rule.review ?? []), ...(rule.block ?? [])];
21
+ if (!required.includes(name) ||
22
+ question?.type !== "choice" ||
23
+ labels.length === 0 ||
24
+ labels.some((label) => !Object.hasOwn(question.criteria, label))) {
25
+ throw invalidReference(key);
26
+ }
27
+ }
28
+ for (const [name, rule] of noulRules) {
29
+ if (!required.includes(name) ||
30
+ questions[name]?.type !== "noul" ||
31
+ (rule.review_above === undefined && rule.block_above === undefined)) {
32
+ throw invalidReference(key);
33
+ }
34
+ }
35
+ }
36
+ export function createPolicyRegistry(definitions, templates) {
37
+ const entries = new Map();
38
+ for (const raw of definitions) {
39
+ const parsed = policyProfileSchema.safeParse(raw);
40
+ if (!parsed.success)
41
+ throw new DecisionError("configuration", "Invalid policy profile definition.");
42
+ const definition = parsed.data;
43
+ const key = `${definition.id}@${definition.version}`;
44
+ if (entries.has(key))
45
+ throw new DecisionError("configuration", `Duplicate policy profile ${key}.`);
46
+ let questions;
47
+ try {
48
+ ({ questions } = templates.get(definition.template));
49
+ }
50
+ catch {
51
+ throw invalidReference(key);
52
+ }
53
+ validateRules(definition, key, questions);
54
+ entries.set(key, { definition, questions });
55
+ }
56
+ return {
57
+ get(selection) {
58
+ const entry = entries.get(selection);
59
+ if (!entry) {
60
+ throw new DecisionError("configuration", "DECISION_POLICY_PROFILE must name an installed profile and version.");
61
+ }
62
+ const copy = structuredClone(entry);
63
+ return {
64
+ ...copy,
65
+ validateState: (state) => templates.validateState(copy.definition.template, state),
66
+ };
67
+ },
68
+ };
69
+ }
70
+ const bundled = [
71
+ new URL("../../policies/engineering-default.v1.json", import.meta.url),
72
+ new URL("../../policies/engineering-strict.v1.json", import.meta.url),
73
+ ];
74
+ export function loadPolicyProfile(selection = DEFAULT_PROFILE, templates = loadTemplateRegistry()) {
75
+ const profiles = bundled.map((file) => {
76
+ try {
77
+ return JSON.parse(readFileSync(file, "utf8"));
78
+ }
79
+ catch {
80
+ throw new DecisionError("configuration", "Could not load a bundled policy profile.");
81
+ }
82
+ });
83
+ return createPolicyRegistry(profiles, templates).get(selection);
84
+ }
85
+ let processProfile;
86
+ export function getPolicyProfile() {
87
+ processProfile ??= loadPolicyProfile(process.env.DECISION_POLICY_PROFILE, loadTemplateRegistry(process.env.DECISION_TEMPLATE_DIR));
88
+ return processProfile;
89
+ }
@@ -0,0 +1,198 @@
1
+ import * as z from "zod/v4";
2
+ export declare const policyProfileSchema: z.ZodObject<{
3
+ id: z.ZodString;
4
+ version: z.ZodNumber;
5
+ template: z.ZodObject<{
6
+ id: z.ZodString;
7
+ version: z.ZodNumber;
8
+ }, z.core.$strict>;
9
+ required_answers: z.ZodArray<z.ZodString>;
10
+ scope: z.ZodEnum<{
11
+ all: "all";
12
+ consequential: "consequential";
13
+ strict: "strict";
14
+ }>;
15
+ failure_mode: z.ZodEnum<{
16
+ block: "block";
17
+ native: "native";
18
+ review: "review";
19
+ }>;
20
+ providers: z.ZodArray<z.ZodEnum<{
21
+ ollama: "ollama";
22
+ "opencode-go": "opencode-go";
23
+ typesafe: "typesafe";
24
+ }>>;
25
+ data: z.ZodEnum<{
26
+ local_only: "local_only";
27
+ reduced_non_local: "reduced_non_local";
28
+ }>;
29
+ rules: z.ZodObject<{
30
+ min_confidence: z.ZodOptional<z.ZodNumber>;
31
+ choice: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
32
+ allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
33
+ review: z.ZodOptional<z.ZodArray<z.ZodString>>;
34
+ block: z.ZodOptional<z.ZodArray<z.ZodString>>;
35
+ }, z.core.$strict>>>;
36
+ noul: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
37
+ block_above: z.ZodOptional<z.ZodNumber>;
38
+ review_above: z.ZodOptional<z.ZodNumber>;
39
+ }, z.core.$strict>>>;
40
+ }, z.core.$strict>;
41
+ }, z.core.$strict>;
42
+ export type PolicyProfile = z.infer<typeof policyProfileSchema>;
43
+ export declare const actionPolicyOutputSchema: z.ZodUnion<readonly [z.ZodDiscriminatedUnion<[z.ZodObject<{
44
+ action: z.ZodEnum<{
45
+ allow: "allow";
46
+ block: "block";
47
+ review: "review";
48
+ }>;
49
+ reasons: z.ZodArray<z.ZodString>;
50
+ status: z.ZodLiteral<"evaluated">;
51
+ profile: z.ZodObject<{
52
+ id: z.ZodString;
53
+ version: z.ZodNumber;
54
+ }, z.core.$strict>;
55
+ reasonCode: z.ZodEnum<{
56
+ policy_allow: "policy_allow";
57
+ policy_block: "policy_block";
58
+ policy_review: "policy_review";
59
+ reduced_context: "reduced_context";
60
+ required_answer_invalid: "required_answer_invalid";
61
+ }>;
62
+ evaluated: z.ZodLiteral<true>;
63
+ provider: z.ZodString;
64
+ model: z.ZodOptional<z.ZodString>;
65
+ answers: z.ZodRecord<z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
66
+ confidence: z.ZodOptional<z.ZodNumber>;
67
+ probabilities: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
68
+ legend: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
69
+ type: z.ZodLiteral<"choice">;
70
+ choice: z.ZodString;
71
+ }, z.core.$catchall<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>>>, z.ZodObject<{
72
+ confidence: z.ZodOptional<z.ZodNumber>;
73
+ probabilities: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
74
+ legend: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
75
+ type: z.ZodLiteral<"noul">;
76
+ noul: z.ZodNumber;
77
+ }, z.core.$catchall<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>>>, z.ZodObject<{
78
+ confidence: z.ZodOptional<z.ZodNumber>;
79
+ probabilities: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
80
+ legend: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
81
+ type: z.ZodLiteral<"score">;
82
+ score: z.ZodNumber;
83
+ }, z.core.$catchall<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>>>], "type">>;
84
+ }, z.core.$strip>, z.ZodDiscriminatedUnion<[z.ZodObject<{
85
+ reasons: z.ZodArray<z.ZodString>;
86
+ status: z.ZodLiteral<"skipped">;
87
+ profile: z.ZodObject<{
88
+ id: z.ZodString;
89
+ version: z.ZodNumber;
90
+ }, z.core.$strict>;
91
+ action: z.ZodLiteral<"allow">;
92
+ evaluated: z.ZodLiteral<false>;
93
+ reasonCode: z.ZodEnum<{
94
+ out_of_scope: "out_of_scope";
95
+ recursive_tool: "recursive_tool";
96
+ }>;
97
+ }, z.core.$strip>, z.ZodObject<{
98
+ reasons: z.ZodArray<z.ZodString>;
99
+ status: z.ZodLiteral<"skipped">;
100
+ profile: z.ZodObject<{
101
+ id: z.ZodString;
102
+ version: z.ZodNumber;
103
+ }, z.core.$strict>;
104
+ action: z.ZodLiteral<"review">;
105
+ evaluated: z.ZodLiteral<false>;
106
+ reasonCode: z.ZodEnum<{
107
+ local_context_required: "local_context_required";
108
+ policy_state_invalid: "policy_state_invalid";
109
+ provider_restricted: "provider_restricted";
110
+ }>;
111
+ }, z.core.$strip>], "action">, z.ZodObject<{
112
+ action: z.ZodEnum<{
113
+ allow: "allow";
114
+ block: "block";
115
+ review: "review";
116
+ }>;
117
+ reasons: z.ZodArray<z.ZodString>;
118
+ status: z.ZodLiteral<"failed">;
119
+ profile: z.ZodObject<{
120
+ id: z.ZodString;
121
+ version: z.ZodNumber;
122
+ }, z.core.$strict>;
123
+ evaluated: z.ZodLiteral<false>;
124
+ reasonCode: z.ZodEnum<{
125
+ cancelled: "cancelled";
126
+ configuration: "configuration";
127
+ http: "http";
128
+ internal: "internal";
129
+ invalid_request: "invalid_request";
130
+ invalid_response: "invalid_response";
131
+ output_limit: "output_limit";
132
+ overload: "overload";
133
+ timeout: "timeout";
134
+ transport: "transport";
135
+ }>;
136
+ }, z.core.$strip>], "status">, z.ZodObject<{
137
+ action: z.ZodEnum<{
138
+ allow: "allow";
139
+ block: "block";
140
+ review: "review";
141
+ }>;
142
+ reasons: z.ZodArray<z.ZodString>;
143
+ status: z.ZodEnum<{
144
+ evaluated: "evaluated";
145
+ skipped: "skipped";
146
+ }>;
147
+ profile: z.ZodObject<{
148
+ id: z.ZodString;
149
+ version: z.ZodNumber;
150
+ }, z.core.$strict>;
151
+ consensus: z.ZodObject<{
152
+ id: z.ZodString;
153
+ version: z.ZodNumber;
154
+ }, z.core.$strict>;
155
+ reasonCode: z.ZodEnum<{
156
+ consensus_allow: "consensus_allow";
157
+ consensus_block: "consensus_block";
158
+ consensus_disagreement: "consensus_disagreement";
159
+ consensus_no_quorum: "consensus_no_quorum";
160
+ consensus_review: "consensus_review";
161
+ out_of_scope: "out_of_scope";
162
+ recursive_tool: "recursive_tool";
163
+ }>;
164
+ members: z.ZodArray<z.ZodObject<{
165
+ provider: z.ZodString;
166
+ model: z.ZodString;
167
+ status: z.ZodEnum<{
168
+ budget: "budget";
169
+ evaluated: "evaluated";
170
+ failed: "failed";
171
+ skipped: "skipped";
172
+ }>;
173
+ action: z.ZodOptional<z.ZodEnum<{
174
+ allow: "allow";
175
+ block: "block";
176
+ review: "review";
177
+ }>>;
178
+ reasonCode: z.ZodOptional<z.ZodString>;
179
+ }, z.core.$strip>>;
180
+ }, z.core.$strip>, z.ZodObject<{
181
+ hookSpecificOutput: z.ZodUnion<readonly [z.ZodObject<{
182
+ hookEventName: z.ZodLiteral<"PreToolUse">;
183
+ permissionDecision: z.ZodLiteral<"deny">;
184
+ permissionDecisionReason: z.ZodString;
185
+ }, z.core.$strict>, z.ZodObject<{
186
+ hookEventName: z.ZodLiteral<"PreToolUse">;
187
+ additionalContext: z.ZodString;
188
+ }, z.core.$strict>]>;
189
+ }, z.core.$strict>, z.ZodObject<{
190
+ hookSpecificOutput: z.ZodObject<{
191
+ hookEventName: z.ZodLiteral<"PreToolUse">;
192
+ permissionDecision: z.ZodEnum<{
193
+ ask: "ask";
194
+ deny: "deny";
195
+ }>;
196
+ permissionDecisionReason: z.ZodString;
197
+ }, z.core.$strict>;
198
+ }, z.core.$strict>, z.ZodObject<{}, z.core.$strict>]>;
@@ -0,0 +1,112 @@
1
+ import * as z from "zod/v4";
2
+ import { providerIds } from "../config.js";
3
+ import { decisionErrorCodes } from "../errors.js";
4
+ import { choiceGateRuleSchema, decisionAnswersSchema, gateOutputSchema, gatePolicySchema, noulGateRuleSchema, } from "../schemas.js";
5
+ import { templateIdentitySchema } from "../templates/schema.js";
6
+ const answerName = z.string().min(1).max(128);
7
+ const rulesSchema = gatePolicySchema.strict().extend({
8
+ choice: z.record(answerName, choiceGateRuleSchema.strict()).optional(),
9
+ noul: z.record(answerName, noulGateRuleSchema.strict()).optional(),
10
+ });
11
+ export const policyProfileSchema = templateIdentitySchema
12
+ .extend({
13
+ template: templateIdentitySchema,
14
+ required_answers: z.array(answerName).min(1).max(50),
15
+ scope: z.enum(["consequential", "strict", "all"]),
16
+ failure_mode: z.enum(["native", "review", "block"]),
17
+ providers: z.array(z.enum(providerIds)).min(1).max(2),
18
+ data: z.enum(["reduced_non_local", "local_only"]),
19
+ rules: rulesSchema,
20
+ })
21
+ .refine(({ required_answers, providers }) => new Set(required_answers).size === required_answers.length &&
22
+ new Set(providers).size === providers.length);
23
+ const actionPolicyResultSchema = z.discriminatedUnion("status", [
24
+ gateOutputSchema.extend({
25
+ status: z.literal("evaluated"),
26
+ profile: templateIdentitySchema,
27
+ reasonCode: z.enum([
28
+ "policy_allow",
29
+ "policy_review",
30
+ "policy_block",
31
+ "required_answer_invalid",
32
+ "reduced_context",
33
+ ]),
34
+ evaluated: z.literal(true),
35
+ provider: z.string(),
36
+ model: z.string().optional(),
37
+ answers: decisionAnswersSchema,
38
+ }),
39
+ z.discriminatedUnion("action", [
40
+ gateOutputSchema.extend({
41
+ status: z.literal("skipped"),
42
+ profile: templateIdentitySchema,
43
+ action: z.literal("allow"),
44
+ evaluated: z.literal(false),
45
+ reasonCode: z.enum(["out_of_scope", "recursive_tool"]),
46
+ }),
47
+ gateOutputSchema.extend({
48
+ status: z.literal("skipped"),
49
+ profile: templateIdentitySchema,
50
+ action: z.literal("review"),
51
+ evaluated: z.literal(false),
52
+ reasonCode: z.enum(["local_context_required", "provider_restricted", "policy_state_invalid"]),
53
+ }),
54
+ ]),
55
+ gateOutputSchema.extend({
56
+ status: z.literal("failed"),
57
+ profile: templateIdentitySchema,
58
+ evaluated: z.literal(false),
59
+ reasonCode: z.enum([...decisionErrorCodes, "internal"]),
60
+ }),
61
+ ]);
62
+ const codexHookResultSchema = z.strictObject({
63
+ hookSpecificOutput: z.union([
64
+ z.strictObject({
65
+ hookEventName: z.literal("PreToolUse"),
66
+ permissionDecision: z.literal("deny"),
67
+ permissionDecisionReason: z.string(),
68
+ }),
69
+ z.strictObject({
70
+ hookEventName: z.literal("PreToolUse"),
71
+ additionalContext: z.string(),
72
+ }),
73
+ ]),
74
+ });
75
+ const claudeCodeHookResultSchema = z.strictObject({
76
+ hookSpecificOutput: z.strictObject({
77
+ hookEventName: z.literal("PreToolUse"),
78
+ permissionDecision: z.enum(["ask", "deny"]),
79
+ permissionDecisionReason: z.string(),
80
+ }),
81
+ });
82
+ // Returned when DECISION_ACTION_POLICY_CONSENSUS routes the call through a consensus profile.
83
+ const consensusPolicyResultSchema = gateOutputSchema.extend({
84
+ status: z.enum(["evaluated", "skipped"]),
85
+ profile: templateIdentitySchema,
86
+ consensus: templateIdentitySchema,
87
+ reasonCode: z.enum([
88
+ "out_of_scope",
89
+ "recursive_tool",
90
+ "consensus_allow",
91
+ "consensus_review",
92
+ "consensus_block",
93
+ "consensus_disagreement",
94
+ "consensus_no_quorum",
95
+ ]),
96
+ members: z.array(z.object({
97
+ provider: z.string(),
98
+ model: z.string(),
99
+ status: z.enum(["evaluated", "skipped", "failed", "budget"]),
100
+ action: z.enum(["allow", "review", "block"]).optional(),
101
+ reasonCode: z.string().optional(),
102
+ })),
103
+ });
104
+ export const actionPolicyOutputSchema = z
105
+ .union([
106
+ actionPolicyResultSchema,
107
+ consensusPolicyResultSchema,
108
+ codexHookResultSchema,
109
+ claudeCodeHookResultSchema,
110
+ z.strictObject({}),
111
+ ])
112
+ .meta({ type: "object" });
@@ -0,0 +1,5 @@
1
+ import type { JsonValue } from "../types.js";
2
+ export type ActionPolicyScope = "consequential" | "strict" | "all";
3
+ export declare function isSensitiveEdit(toolName: string, input: JsonValue): boolean;
4
+ export declare function isDecisionModelTool(toolName: string): boolean;
5
+ export declare function shouldEvaluateAction(toolName: string, toolInput: JsonValue, scope?: ActionPolicyScope): boolean;
@@ -0,0 +1,120 @@
1
+ import { posix } from "node:path";
2
+ const MUTATING_TOOL_NAME = /(?:^|__|_)(?:create|update|delete|remove|write|edit|execute|apply|deploy|merge|send|publish|archive|close|approve|destroy)(?:$|__|_)/i;
3
+ const CURL_MUTATING_OPTION = /\s(?:-[XdFT]|--(?:request|data(?:-raw|-binary|-urlencode)?|form(?:-string)?|upload-file|json)\b)/;
4
+ const CURL_MUTATING_METHOD = /(?:POST|PUT|PATCH|DELETE)\b/i;
5
+ const CONSEQUENTIAL_COMMAND = /(?:^|[\s;&|])(?:sudo\b|rm\b|rmdir\b|chmod\b|chown\b|kill\b|pkill\b|ssh\b|scp\b|rsync\b|terraform\s+(?:apply|destroy|import|state|taint)\b|kubectl\s+(?:apply|delete|patch|replace|scale|rollout|exec)\b|docker\s+(?:push|rm|rmi|system\s+prune)\b|(?:npm|pnpm|yarn)\s+publish\b)/i;
6
+ // PowerShell cmdlet and alias names are case-insensitive. Web cmdlets count only with a mutating -Method.
7
+ const CONSEQUENTIAL_POWERSHELL = /(?:^|[\s;&|])(?:(?:Remove-Item(?:Property)?|Clear-(?:Item|Content|Disk)|Stop-(?:Process|Service|Computer)|Restart-Computer|Format-Volume|Set-ExecutionPolicy|del|erase)\b|Invoke-(?:WebRequest|RestMethod)\b.*\s-Method\s+(?:POST|PUT|PATCH|DELETE)\b)/i;
8
+ const CONSEQUENTIAL_GIT = /(?:^|[\s;&|])git\s+(?:(?:(?:-[Cc]\s+|--(?:git-dir|work-tree|namespace|config-env)(?:=|\s+))(?:"[^"]*"|'[^']*'|[^\s;&|"']+)|--(?:no-pager|paginate|no-replace-objects|no-optional-locks|bare|(?:literal|glob|noglob|icase)-pathspecs))\s+)*(?:push\b|reset\s+--hard\b|clean\b|branch\s+-D\b|checkout\s+--(?:\s|$))/i;
9
+ // SQL often appears inside a quoted argument, such as psql -c 'DROP TABLE users;'.
10
+ const SQL_MUTATION = /\b(?:(?:DROP|TRUNCATE|ALTER)\s+(?:TABLE|DATABASE)|DELETE\s+FROM|INSERT\s+INTO|UPDATE\s+[^;\r\n]+?\s+SET)\b/i;
11
+ const SENSITIVE_EDIT = /(?:^|[\\/])(?:\.env(?:\.|$)|\.github[\\/]workflows[\\/]|Dockerfile|package\.json|pnpm-lock\.yaml|[^\\/]*(?:auth|security|permission|policy|secret)[^\\/]*|(?:infra|terraform|k8s|kubernetes|migrations?|schema)[\\/])/i;
12
+ function inputText(value) {
13
+ if (typeof value === "string")
14
+ return value;
15
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
16
+ const command = value.command ?? value.cmd;
17
+ if (typeof command === "string")
18
+ return command;
19
+ }
20
+ return JSON.stringify(value);
21
+ }
22
+ const PATCH_PATH = /^\*\*\* (?:(?:Add|Update|Delete) File|Move to): ([^\r\n]+)$/gm;
23
+ const EDIT_TOOL = /^(?:.*__)?(?:apply_patch|edit|write)$/i;
24
+ function editPaths(input) {
25
+ if (typeof input === "string") {
26
+ const paths = Array.from(input.matchAll(PATCH_PATH), (match) => match[1]);
27
+ return paths.length > 0 ? paths : [input];
28
+ }
29
+ if (typeof input !== "object" || input === null || Array.isArray(input))
30
+ return [];
31
+ const paths = [input.path, input.file_path, input.filePath].filter((value) => typeof value === "string");
32
+ const patch = input.command ?? input.patch;
33
+ if (typeof patch === "string") {
34
+ paths.push(...Array.from(patch.matchAll(PATCH_PATH), (match) => match[1]));
35
+ }
36
+ return paths;
37
+ }
38
+ export function isSensitiveEdit(toolName, input) {
39
+ return (EDIT_TOOL.test(toolName.trim()) &&
40
+ editPaths(input).some((path) => {
41
+ const normalized = path.trim().replaceAll("\\", "/");
42
+ return SENSITIVE_EDIT.test(normalized) || SENSITIVE_EDIT.test(posix.normalize(normalized));
43
+ }));
44
+ }
45
+ function isKnownRoutineCommand(input) {
46
+ if (typeof input === "object" && input !== null && !Array.isArray(input)) {
47
+ const keys = Object.keys(input);
48
+ if (keys.length !== 1 || (keys[0] !== "command" && keys[0] !== "cmd"))
49
+ return false;
50
+ }
51
+ else if (typeof input !== "string") {
52
+ return false;
53
+ }
54
+ const command = inputText(input).trim().replaceAll("\t", " ");
55
+ return /^(?:git +status(?: +--short)?|pwd)$/.test(command);
56
+ }
57
+ function isShellTool(name) {
58
+ return /^(?:.*__)?(?:bash|powershell|exec_command)$/.test(name);
59
+ }
60
+ function shellSegments(command) {
61
+ return command
62
+ .split(/(?:\r?\n|&&|\|\||;|(?<![|&])[|&](?![|&]))/)
63
+ .map((segment) => segment.trim())
64
+ .filter(Boolean);
65
+ }
66
+ function curlInvocations(segment) {
67
+ const starts = [...segment.matchAll(/\bcurl\b/gi)];
68
+ if (starts.length === 0)
69
+ return [];
70
+ return starts.map((match, index) => {
71
+ const start = match.index ?? 0;
72
+ const end = index + 1 < starts.length ? (starts[index + 1]?.index ?? segment.length) : segment.length;
73
+ return segment.slice(start, end);
74
+ });
75
+ }
76
+ function isMutatingCurlInvocation(invocation) {
77
+ if (!CURL_MUTATING_OPTION.test(invocation))
78
+ return false;
79
+ // Explicit safe methods stay out of the consequential set even when -X is present.
80
+ const methodMatch = invocation.match(/(?:^|[\s])(?:-X|--request)(?:\s+|=)?([A-Za-z]+)/i);
81
+ if (methodMatch) {
82
+ return CURL_MUTATING_METHOD.test(methodMatch[1] ?? "");
83
+ }
84
+ return true;
85
+ }
86
+ function isMutatingCurl(command) {
87
+ for (const segment of shellSegments(command)) {
88
+ for (const invocation of curlInvocations(segment)) {
89
+ if (isMutatingCurlInvocation(invocation))
90
+ return true;
91
+ }
92
+ }
93
+ return false;
94
+ }
95
+ function isConsequentialCommand(command) {
96
+ return (isMutatingCurl(command) ||
97
+ CONSEQUENTIAL_COMMAND.test(command) ||
98
+ CONSEQUENTIAL_POWERSHELL.test(command) ||
99
+ SQL_MUTATION.test(command) ||
100
+ CONSEQUENTIAL_GIT.test(command));
101
+ }
102
+ export function isDecisionModelTool(toolName) {
103
+ return /^(?:mcp__)?decision[-_]models(?:__|[.:/]|$)/i.test(toolName.trim());
104
+ }
105
+ export function shouldEvaluateAction(toolName, toolInput, scope = "consequential") {
106
+ if (isDecisionModelTool(toolName))
107
+ return false;
108
+ if (scope === "all")
109
+ return true;
110
+ const normalized = toolName.trim().toLowerCase();
111
+ if (scope === "strict") {
112
+ return !isShellTool(normalized) || !isKnownRoutineCommand(toolInput);
113
+ }
114
+ if (isShellTool(normalized)) {
115
+ return isConsequentialCommand(inputText(toolInput));
116
+ }
117
+ if (EDIT_TOOL.test(normalized))
118
+ return isSensitiveEdit(normalized, toolInput);
119
+ return MUTATING_TOOL_NAME.test(toolName);
120
+ }