@noppu-labs/opencode-permission-reviewer 2.4.2 → 3.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 (59) hide show
  1. package/CHANGELOG.md +174 -1
  2. package/LICENSE +21 -201
  3. package/LICENSE-APACHE +201 -0
  4. package/MIGRATION.md +2 -1
  5. package/NOTICE +14 -6
  6. package/README.md +109 -787
  7. package/SECURITY.md +41 -22
  8. package/dist/explain.d.ts +3 -4
  9. package/dist/explain.js +9708 -4298
  10. package/dist/index.d.ts +1096 -987
  11. package/dist/index.js +18646 -10575
  12. package/dist/rpc.d.ts +38 -38
  13. package/dist/rpc.js +30 -18
  14. package/dist/tui/config/jsonc.ts +71 -63
  15. package/dist/tui/config/layer-read.ts +120 -0
  16. package/dist/tui/config/loader.ts +73 -512
  17. package/dist/tui/config/risk-policy-clamp.ts +80 -0
  18. package/dist/tui/config/trust-boundary-keys.ts +102 -0
  19. package/dist/tui/config/trust-boundary.ts +148 -0
  20. package/dist/tui/config/trusted-degradation.ts +97 -0
  21. package/dist/tui/config-fields.ts +75 -0
  22. package/dist/tui/config-knobs.ts +119 -0
  23. package/dist/tui/config-policy-rules.ts +86 -0
  24. package/dist/tui/config-risk-policy.ts +59 -0
  25. package/dist/tui/config-rule-condition.ts +150 -0
  26. package/dist/tui/config.ts +72 -431
  27. package/dist/tui/descriptor-io.ts +42 -0
  28. package/dist/tui/failure-kind.ts +28 -0
  29. package/dist/tui/is-record.ts +13 -0
  30. package/dist/tui/opencode/event-normalizer.ts +41 -31
  31. package/dist/tui/reviewer-model.ts +87 -0
  32. package/dist/tui/system-one-routing.ts +110 -0
  33. package/dist/tui/tui.tsx +97 -99
  34. package/dist/tui/types.ts +206 -596
  35. package/dist/tui/ui/action-fit.ts +161 -0
  36. package/dist/tui/ui/action-spans.tsx +60 -0
  37. package/dist/tui/ui/attribution.ts +113 -0
  38. package/dist/tui/ui/components.tsx +69 -137
  39. package/dist/tui/ui/config-notices.ts +137 -0
  40. package/dist/tui/ui/fit-parts.ts +76 -0
  41. package/dist/tui/ui/manual-toast.ts +87 -0
  42. package/dist/tui/ui/review-connection.ts +32 -0
  43. package/dist/tui/ui/review-feed.ts +156 -0
  44. package/dist/tui/ui/review-overlay.tsx +111 -0
  45. package/dist/tui/ui/review-result.tsx +74 -0
  46. package/dist/tui/ui/review-store.ts +88 -0
  47. package/dist/tui/ui/review-theme.ts +70 -0
  48. package/dist/tui/ui/rpc.ts +5 -2
  49. package/dist/tui/ui/v1-host.ts +66 -0
  50. package/dist/tui/ui/v2.tsx +82 -220
  51. package/dist/tui/ui-protocol.ts +112 -124
  52. package/dist/tui/ui-state.ts +86 -64
  53. package/dist/tui/ui-status-extras.ts +165 -0
  54. package/dist/tui/ui-status-parse.ts +132 -0
  55. package/dist/tui/ui-text-elide.ts +89 -0
  56. package/package.json +24 -23
  57. package/rpc.js +2 -1
  58. package/server.js +2 -2
  59. package/tui.tsx +2 -1
@@ -0,0 +1,80 @@
1
+ import { DEFAULT_RISK_POLICY } from "../config-risk-policy.ts";
2
+ import { asObjectLike } from "../is-record.ts";
3
+
4
+ type FailureKnob = "onInvalidDecision" | "onReviewerFailure";
5
+
6
+ /** Ensure project riskPolicy can only tighten the trusted baseline. */
7
+ export function clampRiskPolicy(
8
+ project: Record<string, unknown>,
9
+ trusted: Record<string, unknown>,
10
+ ): Record<string, unknown> {
11
+ // Start from trusted so partial project objects cannot wipe failure knobs.
12
+ const out: Record<string, unknown> = {
13
+ ...trusted,
14
+ allow: clampAllowMatrix(project.allow, trusted.allow),
15
+ };
16
+ hardenFailureKnob(out, project, trusted, "onInvalidDecision");
17
+ hardenFailureKnob(out, project, trusted, "onReviewerFailure");
18
+ out.minimumConfidence = raisedMinimumConfidence(
19
+ project.minimumConfidence,
20
+ trusted.minimumConfidence,
21
+ );
22
+ return out;
23
+ }
24
+
25
+ function asArray(value: unknown): unknown[] {
26
+ return Array.isArray(value) ? (value as unknown[]) : [];
27
+ }
28
+
29
+ function clampAllowMatrix(
30
+ projectValue: unknown,
31
+ trustedValue: unknown,
32
+ ): Record<string, unknown> {
33
+ const projectAllow = asObjectLike(projectValue);
34
+ const trustedAllow = asObjectLike(trustedValue) ?? {};
35
+ const clampedAllow: Record<string, unknown> = {};
36
+ for (const risk of ["low", "medium", "high", "critical"] as const) {
37
+ const trustedCell = asArray(trustedAllow[risk]);
38
+ if (projectAllow === undefined) {
39
+ // Project omitted allow entirely: keep the trusted cells.
40
+ clampedAllow[risk] = trustedCell;
41
+ continue;
42
+ }
43
+ const projectCell = asArray(projectAllow[risk]);
44
+ // Intersection: project can only remove, never add. Missing project cell →
45
+ // empty intersection (most restrictive) when the project provided an allow
46
+ // object at all.
47
+ clampedAllow[risk] = trustedCell.filter((auth) =>
48
+ projectCell.includes(auth),
49
+ );
50
+ }
51
+ return clampedAllow;
52
+ }
53
+
54
+ /** Failure knobs: project may harden manual → deny only. */
55
+ function hardenFailureKnob(
56
+ out: Record<string, unknown>,
57
+ project: Record<string, unknown>,
58
+ trusted: Record<string, unknown>,
59
+ knob: FailureKnob,
60
+ ): void {
61
+ if (project[knob] === "deny" || trusted[knob] === "deny") {
62
+ out[knob] = "deny";
63
+ } else if (project[knob] === "manual" || project[knob] === undefined) {
64
+ out[knob] = trusted[knob] ?? "manual";
65
+ }
66
+ }
67
+
68
+ /** minimumConfidence: project can raise but not lower. */
69
+ function raisedMinimumConfidence(
70
+ projectValue: unknown,
71
+ trustedValue: unknown,
72
+ ): number {
73
+ const trustedMin =
74
+ typeof trustedValue === "number" && Number.isFinite(trustedValue)
75
+ ? trustedValue
76
+ : DEFAULT_RISK_POLICY.minimumConfidence;
77
+ if (typeof projectValue === "number" && Number.isFinite(projectValue))
78
+ return Math.max(trustedMin, projectValue);
79
+ return trustedMin;
80
+ }
@@ -0,0 +1,102 @@
1
+ /** Fields managed by the trust boundary. For these, the boundary's output is
2
+ * final: the project layer may only tighten them against the trusted
3
+ * baseline (which already includes inline), and a later inline value must not
4
+ * undo that tightening. For every other field the documented precedence
5
+ * applies and inline (trusted, most specific) wins over the project. The
6
+ * reviewer resource knobs (timeouts, context budgets) are the strictest
7
+ * case: the project cannot set them at all, in either direction. */
8
+ export const TRUST_BOUNDARY_KEYS: ReadonlySet<string> = new Set([
9
+ "confidenceThreshold",
10
+ "systemOneConfidenceThreshold",
11
+ "systemOneReasoningThreshold",
12
+ "audit",
13
+ "auditPath",
14
+ "model",
15
+ "escalationReviewer",
16
+ "policy",
17
+ "repositoryTrust",
18
+ "actorProfiles",
19
+ "enforcementMode",
20
+ "riskPolicy",
21
+ "escalationMode",
22
+ "systemOneEscalation",
23
+ "systemOneDenialReview",
24
+ "policyRules",
25
+ "variant",
26
+ "outputFormat",
27
+ "retainReviewSessions",
28
+ "timeoutMs",
29
+ "reviewBudgetMs",
30
+ "maxContextChars",
31
+ "maxPartChars",
32
+ "maxEnrichmentChars",
33
+ "maxIntentChars",
34
+ "transcriptMessages",
35
+ "intentMessages",
36
+ "historyMessages",
37
+ "maxSessionDepth",
38
+ "maxParentSessions",
39
+ "askDecisions",
40
+ "debug",
41
+ ]);
42
+
43
+ /** Keys the project layer can never set, in either direction.
44
+ *
45
+ * - configDegraded describes the state of TRUSTED sources; the project layer
46
+ * has no say in it (injecting fake degradation would only tighten, but the
47
+ * field must stay authoritative for the loader that computes it).
48
+ * - Reviewer resource knobs (timeouts and context budgets): how long a review
49
+ * may run and how much context (transcript, evidence, session chains) it may
50
+ * consume. They are not monotonic security fields: raising them means more
51
+ * conversation sent to the provider, more cost, and longer processing, so a
52
+ * repository may not move them in either direction. Wrong-typed values are
53
+ * dropped with them.
54
+ * - askDecisions: prior user answers are scoped-authorization evidence for the
55
+ * reviewer. Only trusted layers may decide whether the reviewer sees them; a
56
+ * repository can neither strip them nor inject them.
57
+ * - auditPath: only trusted global/inline config may choose the audit
58
+ * destination. A repository must never be able to redirect or silence the
59
+ * audit trail by pointing it at /dev/null or a path it controls.
60
+ * - model, escalationReviewer and policy: the reviewer destinations and the
61
+ * tenant policy text are trusted decisions. A repository must not choose where code/context is sent
62
+ * for review, nor rewrite the policy the reviewer enforces. The reasoning
63
+ * variant, the decision output format, and review-session retention are the
64
+ * same class of decision: a weaker variant, a looser output format, or
65
+ * silenced retention must not be selectable from a repository.
66
+ * - actorProfiles: name→profile mappings are a trust delegation (which agent
67
+ * gets which capability profile). Only trusted global/inline config may
68
+ * grant them; otherwise a repository could promote its own agent to a
69
+ * higher-privilege profile ("build" → "operator"). */
70
+ export const TRUSTED_ONLY_KEYS = [
71
+ "configDegraded",
72
+ "timeoutMs",
73
+ "reviewBudgetMs",
74
+ "maxContextChars",
75
+ "maxPartChars",
76
+ "maxEnrichmentChars",
77
+ "maxIntentChars",
78
+ "transcriptMessages",
79
+ "intentMessages",
80
+ "historyMessages",
81
+ "maxSessionDepth",
82
+ "maxParentSessions",
83
+ "askDecisions",
84
+ "auditPath",
85
+ "model",
86
+ "escalationReviewer",
87
+ "policy",
88
+ "variant",
89
+ "outputFormat",
90
+ "retainReviewSessions",
91
+ "debug",
92
+ "actorProfiles",
93
+ ] as const;
94
+
95
+ /** Numeric floors: project config can raise but not lower them. Confidence
96
+ * floors guard the decision gate and are monotonic hardening: a stricter
97
+ * threshold is always safer, so the project may add one. */
98
+ export const CONFIDENCE_FLOOR_KEYS = [
99
+ "confidenceThreshold",
100
+ "systemOneConfidenceThreshold",
101
+ "systemOneReasoningThreshold",
102
+ ] as const;
@@ -0,0 +1,148 @@
1
+ import { DEFAULT_CONFIG } from "../config.ts";
2
+ import { DEFAULT_RISK_POLICY } from "../config-risk-policy.ts";
3
+ import { isRecord } from "../is-record.ts";
4
+ import type { PolicyRule } from "../types.ts";
5
+ import { clampRiskPolicy } from "./risk-policy-clamp.ts";
6
+ import {
7
+ CONFIDENCE_FLOOR_KEYS,
8
+ TRUSTED_ONLY_KEYS,
9
+ } from "./trust-boundary-keys.ts";
10
+
11
+ /** Whether the key is present in the layer (a `null`/wrong-type value must be
12
+ * handled as a present-but-invalid override, never silently forwarded). */
13
+ function hasKey(object: Record<string, unknown>, key: string): boolean {
14
+ return Object.hasOwn(object, key);
15
+ }
16
+
17
+ /** Merge the trusted baseline with the untrusted project layer. Project config
18
+ * can only TIGHTEN security-sensitive fields, never weaken them. A project
19
+ * value of the wrong type (including `null`) is dropped so it can never fall
20
+ * through to `resolveConfig`'s defaults and reset a trusted restriction. */
21
+ export function mergeWithTrustBoundary(
22
+ trusted: Record<string, unknown>,
23
+ project: Record<string, unknown>,
24
+ ): Record<string, unknown> {
25
+ const clamped = { ...project };
26
+ for (const key of TRUSTED_ONLY_KEYS) delete clamped[key];
27
+ clampConfidenceFloors(clamped, trusted);
28
+ // audit: project can enable but not disable.
29
+ if (clamped.audit === false && trusted.audit !== false) delete clamped.audit;
30
+ // repositoryTrust: the project layer may only declare its own repository
31
+ // untrusted; it cannot grant "trusted" or reset a trusted "untrusted".
32
+ if (clamped.repositoryTrust !== "untrusted") delete clamped.repositoryTrust;
33
+ clampEnforcementMode(clamped, trusted);
34
+ clampProjectRiskPolicy(clamped, trusted);
35
+ clampEscalationMode(clamped, trusted);
36
+ clampSystemOneRouting(clamped);
37
+ combinePolicyRules(clamped, trusted);
38
+ return { ...trusted, ...clamped };
39
+ }
40
+
41
+ /** Non-numeric values (including null) are dropped so they cannot reset a
42
+ * trusted floor. */
43
+ function clampConfidenceFloors(
44
+ clamped: Record<string, unknown>,
45
+ trusted: Record<string, unknown>,
46
+ ): void {
47
+ for (const key of CONFIDENCE_FLOOR_KEYS) {
48
+ if (!hasKey(clamped, key)) continue;
49
+ const value = clamped[key];
50
+ if (typeof value !== "number" || !Number.isFinite(value)) {
51
+ delete clamped[key];
52
+ continue;
53
+ }
54
+ const floor =
55
+ typeof trusted[key] === "number"
56
+ ? (trusted[key] as number)
57
+ : DEFAULT_CONFIG[key];
58
+ if (value < floor) clamped[key] = floor;
59
+ }
60
+ }
61
+
62
+ /** enforcementMode: project cannot enable OR disable enforcement — only
63
+ * global/inline can. A project "enforce" is deleted (can't enable), and a
64
+ * project "observe" when the trusted baseline is "enforce" is also deleted
65
+ * (can't downgrade from a global enforcement setting). */
66
+ function clampEnforcementMode(
67
+ clamped: Record<string, unknown>,
68
+ trusted: Record<string, unknown>,
69
+ ): void {
70
+ if (clamped.enforcementMode === undefined) return;
71
+ if (
72
+ clamped.enforcementMode === "enforce" ||
73
+ trusted.enforcementMode === "enforce"
74
+ ) {
75
+ delete clamped.enforcementMode;
76
+ }
77
+ }
78
+
79
+ /** riskPolicy: project can narrow allow cells and harden failure knobs, never
80
+ * relax a trusted deny or widen an allow cell. A non-object value (including
81
+ * null) is ignored entirely so it cannot wipe the trusted matrix. */
82
+ function clampProjectRiskPolicy(
83
+ clamped: Record<string, unknown>,
84
+ trusted: Record<string, unknown>,
85
+ ): void {
86
+ if (!hasKey(clamped, "riskPolicy")) return;
87
+ if (!isRecord(clamped.riskPolicy)) {
88
+ delete clamped.riskPolicy;
89
+ return;
90
+ }
91
+ const trustedPolicy = isRecord(trusted.riskPolicy)
92
+ ? trusted.riskPolicy
93
+ : (DEFAULT_RISK_POLICY as unknown as Record<string, unknown>);
94
+ clamped.riskPolicy = clampRiskPolicy(clamped.riskPolicy, trustedPolicy);
95
+ }
96
+
97
+ /** escalationMode: project can only harden manual → deny, never relax deny →
98
+ * manual. Invalid values are dropped so they cannot override a trusted deny
99
+ * through resolveConfig's "anything but deny → manual" fallback. */
100
+ function clampEscalationMode(
101
+ clamped: Record<string, unknown>,
102
+ trusted: Record<string, unknown>,
103
+ ): void {
104
+ const mode = clamped.escalationMode;
105
+ if (mode === undefined) return;
106
+ const invalid = mode !== "manual" && mode !== "deny";
107
+ const relaxes = mode === "manual" && trusted.escalationMode === "deny";
108
+ if (invalid || relaxes) delete clamped.escalationMode;
109
+ }
110
+
111
+ /** systemOneEscalation and systemOneDenialReview: a repository may keep Jev's
112
+ * escalations and denials with the human ("standard", false) but can never
113
+ * turn either hand-off on. Any other value, including null, is dropped. */
114
+ function clampSystemOneRouting(clamped: Record<string, unknown>): void {
115
+ if (clamped.systemOneEscalation !== "standard") {
116
+ delete clamped.systemOneEscalation;
117
+ }
118
+ if (clamped.systemOneDenialReview !== false) {
119
+ delete clamped.systemOneDenialReview;
120
+ }
121
+ }
122
+
123
+ /** policyRules: the project layer ADDS rules (which can only tighten — its
124
+ * allow rules are filtered by the engine), it never erases trusted
125
+ * global/inline deny/manual rules. Combine instead of replace so a repo
126
+ * cannot weaken policy by declaring an empty or narrower rule set. Project
127
+ * rules are also re-tagged source:"project" so they cannot spoof
128
+ * source:"inline" to bypass the project-allow filter. */
129
+ function combinePolicyRules(
130
+ clamped: Record<string, unknown>,
131
+ trusted: Record<string, unknown>,
132
+ ): void {
133
+ if (Array.isArray(clamped.policyRules)) {
134
+ const projectRules = (
135
+ clamped.policyRules as Array<Record<string, unknown>>
136
+ ).map((rule) => ({
137
+ ...rule,
138
+ source: "project" as PolicyRule["source"],
139
+ }));
140
+ const trustedRules = Array.isArray(trusted.policyRules)
141
+ ? trusted.policyRules
142
+ : [];
143
+ clamped.policyRules = [...trustedRules, ...projectRules];
144
+ } else if (Array.isArray(trusted.policyRules)) {
145
+ // Project omitted policyRules entirely: preserve the trusted rules.
146
+ clamped.policyRules = trusted.policyRules;
147
+ }
148
+ }
@@ -0,0 +1,97 @@
1
+ import { countInvalidPolicyRules } from "../config-policy-rules.ts";
2
+ import { isValidEscalationReviewer } from "../reviewer-model.ts";
3
+ import type { ConfigLayer } from "./layer-read.ts";
4
+ import type { InlineOptionsTrust } from "./sources.ts";
5
+
6
+ /** Trusted mode fields and the values resolveConfig honors. A mistyped mode
7
+ * silently falls back to the less restrictive default in resolveConfig, so it
8
+ * gets the same fail-closed treatment as a dropped rule: visible degradation
9
+ * instead of a quiet downgrade. */
10
+ const MODE_FIELDS = [
11
+ ["enforcementMode", ["enforce", "observe"]],
12
+ ["escalationMode", ["manual", "deny"]],
13
+ ] as const;
14
+
15
+ function invalidEscalationReviewer(
16
+ raw: Record<string, unknown>,
17
+ layer: "global" | "inline",
18
+ ): string[] {
19
+ return raw.escalationReviewer !== undefined &&
20
+ !isValidEscalationReviewer(raw.escalationReviewer)
21
+ ? [`${layer} config escalationReviewer is invalid and was ignored`]
22
+ : [];
23
+ }
24
+
25
+ function invalidModes(
26
+ raw: Record<string, unknown>,
27
+ layer: "global" | "inline",
28
+ ): string[] {
29
+ const invalid: string[] = [];
30
+ for (const [key, valid] of MODE_FIELDS) {
31
+ const value = raw[key];
32
+ if (value !== undefined && !(valid as readonly unknown[]).includes(value)) {
33
+ invalid.push(
34
+ `${layer} config ${key} ${JSON.stringify(value)} is invalid and was ignored`,
35
+ );
36
+ }
37
+ }
38
+ return invalid;
39
+ }
40
+
41
+ function warnUntilFixed(entries: string[]): string[] {
42
+ for (const entry of entries) {
43
+ console.warn(
44
+ `permission-reviewer: ${entry}; automatic approval stays disabled until it is fixed`,
45
+ );
46
+ }
47
+ return entries;
48
+ }
49
+
50
+ /** A TRUSTED layer that exists but cannot be honored may have lost the very
51
+ * restrictions it was supposed to carry (deny rules, enforce mode, stricter
52
+ * thresholds). That must degrade the config — automatic approval stays off
53
+ * until the file is fixed — instead of quietly reactivating defaults. Each
54
+ * reason found in a readable global file is also warned about. */
55
+ export function globalLayerDegradation(layer: ConfigLayer): string[] {
56
+ if (layer.status === "malformed")
57
+ return ["global config file is malformed and was ignored"];
58
+ if (layer.status === "read-error")
59
+ return ["global config file exists but could not be read"];
60
+ if (layer.status !== "ok") return [];
61
+ const degraded = warnUntilFixed(
62
+ invalidEscalationReviewer(layer.raw, "global"),
63
+ );
64
+ const invalidRules = countInvalidPolicyRules(layer.raw.policyRules);
65
+ if (invalidRules > 0) {
66
+ degraded.push(
67
+ `${invalidRules} policy rule(s) from the global config were dropped by validation`,
68
+ );
69
+ console.warn(
70
+ `permission-reviewer: ${invalidRules} policy rule(s) in the global config are invalid and were dropped; automatic approval stays disabled until they are fixed`,
71
+ );
72
+ }
73
+ return [...degraded, ...warnUntilFixed(invalidModes(layer.raw, "global"))];
74
+ }
75
+
76
+ /** Same visibility for trusted inline options, without console.warn.
77
+ * resolveConfig still clamps each value to the safe default; this only
78
+ * records that the trusted input was lost. */
79
+ export function inlineDegradation(
80
+ inlineOptions: Record<string, unknown> | undefined,
81
+ inlineTrust: InlineOptionsTrust,
82
+ ): string[] {
83
+ if (inlineTrust !== "trusted") return [];
84
+ const invalidRules = countInvalidPolicyRules(inlineOptions?.policyRules);
85
+ const degraded =
86
+ invalidRules > 0
87
+ ? [
88
+ `${invalidRules} policy rule(s) from inline config were dropped by validation`,
89
+ ]
90
+ : [];
91
+ if (inlineOptions === undefined) return degraded;
92
+ return [
93
+ ...degraded,
94
+ ...invalidEscalationReviewer(inlineOptions, "inline"),
95
+ ...invalidModes(inlineOptions, "inline"),
96
+ ];
97
+ }
@@ -0,0 +1,75 @@
1
+ import { ACTOR_PROFILES } from "./config-rule-condition.ts";
2
+ import type {
3
+ ActorProfile,
4
+ EscalationMode,
5
+ RepositoryTrust,
6
+ ReviewerConfig,
7
+ } from "./types.ts";
8
+
9
+ /** Parse a trusted name→profile mapping. Invalid entries are dropped. */
10
+ export function resolveActorProfiles(
11
+ value: unknown,
12
+ ): Record<string, ActorProfile> {
13
+ if (typeof value !== "object" || value === null) return {};
14
+ const out: Record<string, ActorProfile> = {};
15
+ for (const [name, profile] of Object.entries(
16
+ value as Record<string, unknown>,
17
+ )) {
18
+ if (
19
+ typeof profile === "string" &&
20
+ ACTOR_PROFILES.has(profile as ActorProfile)
21
+ ) {
22
+ out[name] = profile as ActorProfile;
23
+ }
24
+ }
25
+ return out;
26
+ }
27
+
28
+ export function resolveEscalationMode(value: unknown): EscalationMode {
29
+ return value === "deny" ? "deny" : "manual";
30
+ }
31
+
32
+ /** An invalid value falls back to the default, which adds no hand-off to the
33
+ * escalation reviewer, so system-one-routing.ts reports it as a config
34
+ * warning, never degradation. */
35
+ export function systemOneRoutingFields(
36
+ source: Record<string, unknown>,
37
+ ): Pick<ReviewerConfig, "systemOneEscalation" | "systemOneDenialReview"> {
38
+ return {
39
+ systemOneEscalation:
40
+ source.systemOneEscalation === "reasoning-first"
41
+ ? "reasoning-first"
42
+ : "standard",
43
+ systemOneDenialReview: source.systemOneDenialReview === true,
44
+ };
45
+ }
46
+
47
+ export function resolveRepositoryTrust(value: unknown): RepositoryTrust {
48
+ if (value === "trusted") return "trusted";
49
+ if (value === "untrusted") return "untrusted";
50
+ return "unknown";
51
+ }
52
+
53
+ export function nonEmptyStringOr(value: unknown, fallback: string): string {
54
+ return typeof value === "string" && value.length > 0 ? value : fallback;
55
+ }
56
+
57
+ /** The trimmed string, or undefined when it is not a string or is blank. */
58
+ export function trimmedText(value: unknown): string | undefined {
59
+ return typeof value === "string" && value.trim().length > 0
60
+ ? value.trim()
61
+ : undefined;
62
+ }
63
+
64
+ export function isStringArray(value: unknown): value is string[] {
65
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
66
+ }
67
+
68
+ /** A single-key object for a present value and an empty one for an absent
69
+ * value, so an optional field keeps its place in the output key order. */
70
+ export function optional<K extends string, V>(
71
+ key: K,
72
+ value: V | undefined,
73
+ ): Partial<Record<K, V>> {
74
+ return value === undefined ? {} : ({ [key]: value } as Record<K, V>);
75
+ }
@@ -0,0 +1,119 @@
1
+ import type { ReviewerConfig } from "./types.ts";
2
+
3
+ export function boundedInteger(
4
+ value: unknown,
5
+ fallback: number,
6
+ min: number,
7
+ max: number,
8
+ ): number {
9
+ if (typeof value !== "number" || !Number.isInteger(value)) return fallback;
10
+ return Math.min(max, Math.max(min, value));
11
+ }
12
+
13
+ function boundedNumber(
14
+ value: unknown,
15
+ fallback: number,
16
+ min: number,
17
+ max: number,
18
+ ): number {
19
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
20
+ return Math.min(max, Math.max(min, value));
21
+ }
22
+
23
+ type NumericKey = {
24
+ [K in keyof ReviewerConfig]-?: ReviewerConfig[K] extends number ? K : never;
25
+ }[keyof ReviewerConfig];
26
+
27
+ type KnobBounds<K extends NumericKey> = Readonly<
28
+ Record<K, readonly [min: number, max: number]>
29
+ >;
30
+
31
+ /** The total review deadline: absent when the source omits it, otherwise an
32
+ * integer clamped to [5 s, 15 min], or 3 min when the value is not one. */
33
+ export function reviewBudgetKnob(
34
+ source: Record<string, unknown>,
35
+ ): Pick<ReviewerConfig, "reviewBudgetMs"> {
36
+ return source.reviewBudgetMs === undefined
37
+ ? {}
38
+ : {
39
+ reviewBudgetMs: boundedInteger(
40
+ source.reviewBudgetMs,
41
+ 180_000,
42
+ 5_000,
43
+ 900_000,
44
+ ),
45
+ };
46
+ }
47
+
48
+ export const REVIEW_TIMEOUT: KnobBounds<"timeoutMs"> = {
49
+ timeoutMs: [5_000, 600_000],
50
+ };
51
+
52
+ export const CONTEXT_BUDGETS: KnobBounds<
53
+ | "maxContextChars"
54
+ | "maxPartChars"
55
+ | "maxEnrichmentChars"
56
+ | "maxIntentChars"
57
+ | "transcriptMessages"
58
+ | "intentMessages"
59
+ | "historyMessages"
60
+ > = {
61
+ maxContextChars: [4_000, 200_000],
62
+ maxPartChars: [500, 50_000],
63
+ maxEnrichmentChars: [1_000, 100_000],
64
+ maxIntentChars: [1_000, 50_000],
65
+ transcriptMessages: [1, 100],
66
+ intentMessages: [1, 50],
67
+ historyMessages: [20, 500],
68
+ };
69
+
70
+ export const CONFIDENCE_FLOORS: KnobBounds<
71
+ | "confidenceThreshold"
72
+ | "systemOneConfidenceThreshold"
73
+ | "systemOneReasoningThreshold"
74
+ > = {
75
+ confidenceThreshold: [0.5, 1],
76
+ systemOneConfidenceThreshold: [0.3, 1],
77
+ systemOneReasoningThreshold: [0, 1],
78
+ };
79
+
80
+ export const LINEAGE_LIMITS: KnobBounds<
81
+ "maxSessionDepth" | "maxParentSessions"
82
+ > = {
83
+ maxSessionDepth: [1, 32],
84
+ maxParentSessions: [0, 32],
85
+ };
86
+
87
+ function clampKnobs<K extends NumericKey>(
88
+ source: Record<string, unknown>,
89
+ bounds: KnobBounds<K>,
90
+ defaults: ReviewerConfig,
91
+ clamp: typeof boundedInteger,
92
+ ): Record<K, number> {
93
+ const out = {} as Record<K, number>;
94
+ for (const key of Object.keys(bounds) as K[]) {
95
+ const [min, max] = bounds[key];
96
+ out[key] = clamp(source[key], defaults[key], min, max);
97
+ }
98
+ return out;
99
+ }
100
+
101
+ /** Each knob in table order, clamped to an integer in its bounds; a missing
102
+ * or non-integer value falls back to its default. */
103
+ export function integerKnobs<K extends NumericKey>(
104
+ source: Record<string, unknown>,
105
+ bounds: KnobBounds<K>,
106
+ defaults: ReviewerConfig,
107
+ ): Record<K, number> {
108
+ return clampKnobs(source, bounds, defaults, boundedInteger);
109
+ }
110
+
111
+ /** Each knob in table order, clamped to a finite number in its bounds; a
112
+ * missing or non-finite value falls back to its default. */
113
+ export function numberKnobs<K extends NumericKey>(
114
+ source: Record<string, unknown>,
115
+ bounds: KnobBounds<K>,
116
+ defaults: ReviewerConfig,
117
+ ): Record<K, number> {
118
+ return clampKnobs(source, bounds, defaults, boundedNumber);
119
+ }