opencode-model-router 2.3.0 → 2.4.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.
- package/CHANGELOG.md +149 -0
- package/README.md +56 -10
- package/package.json +1 -1
- package/src/commands/output.ts +21 -1
- package/src/compat/v2-hooks.ts +1322 -18
- package/src/escalate/ladder.ts +12 -0
- package/src/guard/enforce.ts +186 -22
- package/src/guard/guards.ts +132 -6
- package/src/guard/store.ts +5 -0
- package/src/index.ts +718 -29
- package/src/router/config.ts +247 -1
- package/src/router/dispatch-header.ts +46 -4
- package/src/router/git-tools.ts +1152 -0
- package/src/router/guard-profile.ts +100 -0
- package/src/router/plugin-agents.ts +433 -0
- package/src/router/prompts.ts +26 -1
- package/src/router/protocol.ts +133 -0
- package/src/router/read-only.ts +149 -0
- package/src/router/role-agents.ts +409 -0
- package/src/router/roles-config.ts +429 -0
- package/src/router/roles.ts +600 -0
- package/src/router/run-tools.ts +913 -0
- package/src/router/sensitive-paths.ts +101 -0
- package/src/router/sessions.ts +92 -0
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +193 -1
- package/src/routing/advisor/index.ts +13 -5
- package/src/routing/classify/index.ts +23 -5
- package/src/routing/classify/route-line.ts +67 -3
- package/src/routing/classify/rules.ts +80 -20
- package/src/routing/classify/types.ts +34 -4
- package/src/routing/commands/stats.ts +3 -0
- package/src/routing/engine/kernel.ts +163 -0
- package/src/routing/engine/ladders.ts +242 -1
- package/src/routing/engine/protocol-line.ts +17 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/types.ts +99 -1
- package/src/routing/outcomes/beta.ts +10 -4
- package/src/routing/outcomes/index.ts +44 -1
- package/src/routing/outcomes/ingest.ts +163 -15
- package/src/routing/outcomes/persist.ts +23 -1
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +273 -2
- package/src/routing/outcomes/store.ts +25 -5
- package/src/routing/outcomes/types.ts +145 -6
- package/src/routing/roles/authority.ts +495 -0
- package/src/routing/roles/binding.ts +543 -0
- package/src/routing/roles/policy.ts +416 -0
- package/src/routing/roles/work-root.ts +132 -0
- package/src/routing/wire/dispatch.ts +1306 -17
- package/src/routing/wire/hint.ts +14 -0
- package/src/routing/wire/runtime.ts +117 -28
- package/src/v2.ts +26 -1
- package/src/verify/checker.ts +249 -7
- package/src/verify/deterministic.ts +10 -1
- package/src/verify/dispatch.ts +63 -6
- package/src/verify/dod.ts +127 -10
- package/src/verify/gate.ts +75 -7
- package/src/verify/types.ts +12 -0
- package/src/verify/wiring.ts +55 -10
- package/tiers.json +13 -5
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Role dispatch policy (plan §2.2–§2.4, P1.2). Pure: no I/O, no clock, no module state.
|
|
3
|
+
*
|
|
4
|
+
* - `grantFor` (T1.2.1): the actions one dispatch may use, inside the role's max policy, with the
|
|
5
|
+
* separation rule (I4) and the work-root rule applied last so nothing can re-add what they remove.
|
|
6
|
+
* - `authorityFloor` (T1.2.1): the §2.3 table.
|
|
7
|
+
* - `tierBounds` (T1.2.2): the role range ∩ the authority floor ∩ `floorTier` ∩ the running rung, risk and
|
|
8
|
+
* scope raise-only, route-line pin lifted/clamped into the window.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { AuthorityAction, RoleKind, RoleSpec } from "../../router/roles";
|
|
12
|
+
import { DETECTIONS } from "../classify/types";
|
|
13
|
+
import type { ClassifyResult, ClassifyTrace, Detection, Need, Risk, RouteLine, Scope, TaskFacts } from "../classify/types";
|
|
14
|
+
|
|
15
|
+
export interface DispatchGrant {
|
|
16
|
+
actions: ReadonlySet<AuthorityAction>;
|
|
17
|
+
notes: readonly string[];
|
|
18
|
+
/**
|
|
19
|
+
* null → NO VALIDATED WORK ROOT (the binding is known; `root=` was absent or did not resolve to a worktree): no write
|
|
20
|
+
* and no run (`edit` and `router_run` withheld), no path outside the session directory. A fixed egress role
|
|
21
|
+
* (researcher) keeps its egress: it touches no file.
|
|
22
|
+
*
|
|
23
|
+
* It does NOT mean "unknown binding" (QA-P12-2-3): a child whose dispatch is unknown (P1.6 `bind` → `unknown`) gets the
|
|
24
|
+
* role max ∩ LOCAL — egress dropped too — and must never be granted through `grantFor(…, null)`.
|
|
25
|
+
*/
|
|
26
|
+
workRoot: string | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The classify shape a role dispatch is bounded from (`ClassifyResult` → `facts` and `trace.rules`/`trace.routeLine`):
|
|
31
|
+
* pass the classifier result itself, so the raise-only risk/scope of §2.3 cannot be lost by omitting an optional field.
|
|
32
|
+
*/
|
|
33
|
+
export interface ClassifiedDispatch {
|
|
34
|
+
readonly facts: ClassifyResult["facts"];
|
|
35
|
+
readonly trace: Pick<ClassifyTrace, "rules" | "routeLine">;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
declare const EFFECTIVE_DETECTION: unique symbol;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The EFFECTIVE detection of a dispatch (§2.1, A34): `deterministic` only when the router's own gate runs the acceptance
|
|
42
|
+
* checks for this dispatch, otherwise the weaker of the route-line claim and the prompt's `[acceptance]` block — never
|
|
43
|
+
* `ClassifyResult.detection` (a claim) as is. Built only with {@link effectiveDetection}: no other module may cast to it
|
|
44
|
+
* (a test scans `src` for the cast).
|
|
45
|
+
*/
|
|
46
|
+
export type EffectiveDetection = Detection & { readonly [EFFECTIVE_DETECTION]: true };
|
|
47
|
+
|
|
48
|
+
/** What A34 computes the effective detection from. */
|
|
49
|
+
export interface EffectiveDetectionInput {
|
|
50
|
+
/** The router's own gate (`src/verify/deterministic.ts`) will run this dispatch's acceptance checks. */
|
|
51
|
+
readonly routerGate: boolean;
|
|
52
|
+
/** The route line's `d=` claim (`ClassifyResult.detection`), or null. */
|
|
53
|
+
readonly claim: Detection | null;
|
|
54
|
+
/** The depth of the prompt's `[acceptance]` block, or null when it has none. */
|
|
55
|
+
readonly acceptance: Detection | null;
|
|
56
|
+
/**
|
|
57
|
+
* #84 QA-G-B-7: some verification of this dispatch will run at all (enforcement not off, not bypassed, `verify.require` not
|
|
58
|
+
* `never`, the requested cwd inside the root the gate verifies in; dispatch.ts `roleVerificationRuns`). `false` → `none`: nothing
|
|
59
|
+
* checks the work, so neither a claim nor an `[acceptance]` block counts. Absent: it will.
|
|
60
|
+
*/
|
|
61
|
+
readonly verifies?: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const DETECTION_STRENGTH: Readonly<Record<Detection, number>> = { none: 0, grader: 1, deterministic: 2 };
|
|
65
|
+
|
|
66
|
+
function strength(d: Detection | null): number {
|
|
67
|
+
return d !== null && Object.hasOwn(DETECTION_STRENGTH, d) ? DETECTION_STRENGTH[d] : 0; // absent or unknown → none
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A34 (QA-P12-2-1): `deterministic` only when the router's own gate runs the checks; otherwise the weaker of
|
|
72
|
+
* `claim ?? "none"` and `acceptance ?? "none"`, capped at `grader` (a claim alone is never deterministic). Absent or
|
|
73
|
+
* unknown values count as `none`. QA-G-B-7: `none` whenever no verification runs at all (`verifies: false`). (Same order
|
|
74
|
+
* as `engine/plan.weakerDetection`, restated here: importing the engine from the policy would close an import cycle.)
|
|
75
|
+
*/
|
|
76
|
+
export function effectiveDetection(input: EffectiveDetectionInput): EffectiveDetection {
|
|
77
|
+
if (input.verifies === false) return "none" as EffectiveDetection;
|
|
78
|
+
if (input.routerGate === true) return "deterministic" as EffectiveDetection;
|
|
79
|
+
const weaker = Math.min(strength(input.claim), strength(input.acceptance), DETECTION_STRENGTH.grader);
|
|
80
|
+
return DETECTIONS.find((d) => DETECTION_STRENGTH[d] === weaker)! as EffectiveDetection;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const BUILTIN_TIERS = ["fast", "medium", "heavy"] as const;
|
|
84
|
+
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
// Action classes (§2.2)
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
/** Canonical action order: grants are built in this order so logs and snapshots are stable. */
|
|
90
|
+
const ACTION_ORDER: readonly AuthorityAction[] = [
|
|
91
|
+
"read",
|
|
92
|
+
"glob",
|
|
93
|
+
"grep",
|
|
94
|
+
"router_git",
|
|
95
|
+
"router_run",
|
|
96
|
+
"edit",
|
|
97
|
+
"webfetch",
|
|
98
|
+
"websearch",
|
|
99
|
+
"context7",
|
|
100
|
+
"execute",
|
|
101
|
+
];
|
|
102
|
+
const KNOWN: ReadonlySet<string> = new Set<string>(ACTION_ORDER);
|
|
103
|
+
const LOCAL: ReadonlySet<AuthorityAction> = new Set<AuthorityAction>(["read", "glob", "grep", "router_git"]);
|
|
104
|
+
const EXEC: ReadonlySet<AuthorityAction> = new Set<AuthorityAction>(["router_run"]);
|
|
105
|
+
const WRITE: ReadonlySet<AuthorityAction> = new Set<AuthorityAction>(["edit"]);
|
|
106
|
+
const EGRESS: ReadonlySet<AuthorityAction> = new Set<AuthorityAction>(["webfetch", "websearch", "context7", "execute"]);
|
|
107
|
+
|
|
108
|
+
function hasAny(actions: ReadonlySet<AuthorityAction>, cls: ReadonlySet<AuthorityAction>): boolean {
|
|
109
|
+
for (const a of cls) if (actions.has(a)) return true;
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Static part of a dynamic role's grant (§2.2 table): `general` = local; `implementer` = local + write
|
|
115
|
+
* ("exec only when the task needs it"). Everything else of a dynamic role comes from needs or widening.
|
|
116
|
+
*/
|
|
117
|
+
function dynamicBase(kind: RoleKind): ReadonlySet<AuthorityAction> {
|
|
118
|
+
return kind === "implement" ? new Set<AuthorityAction>([...LOCAL, ...WRITE]) : LOCAL;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Notes a grant can carry (exact texts, shared with the runtime and the tests). */
|
|
122
|
+
export const GRANT_NOTES = {
|
|
123
|
+
shell: "raw shell is outside roles mode — dispatch a tier agent explicitly",
|
|
124
|
+
web: "web access is outside this role — use `researcher`",
|
|
125
|
+
edit: "edit is outside this role — use `implementer`",
|
|
126
|
+
externalDir: "paths outside the session directory need a work root (root=)",
|
|
127
|
+
noWorkRoot: "no valid work root: write and run withheld",
|
|
128
|
+
separation: "egress dropped: a grant never mixes local, exec or write actions with egress (separation rule)",
|
|
129
|
+
} as const;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The actions a dispatch may use (§2.2, §2.5).
|
|
133
|
+
*
|
|
134
|
+
* - max = `allow` minus `deny` (unknown action names dropped: configuration never widens authority).
|
|
135
|
+
* - fixed roles: the max; needs only add notes; `widened` is ignored (the ladder is for dynamic roles).
|
|
136
|
+
* - dynamic roles (any mode other than `fixed`, fail-closed): (base ∩ max) ∪ (needs-derived ∩ max) ∪
|
|
137
|
+
* (widened ∩ max), base per {@link dynamicBase}.
|
|
138
|
+
* - needs (classifier `needs`, plus `routeLine.needs` when the caller passes the route line separately;
|
|
139
|
+
* `classify()` already merges `needs=` into `facts.needs`, the union is idempotent):
|
|
140
|
+
* `edit` → edit (note when the result lacks it); `shell`/`network` → `router_run` + the raw-shell note;
|
|
141
|
+
* `web` → no action, note when the result has no egress; `external_dir` → satisfied by a non-null
|
|
142
|
+
* work root (P2.1 resolves and validates it), otherwise a note; unknown needs are ignored.
|
|
143
|
+
* - separation (I4): local/exec/write together with egress → egress dropped + note.
|
|
144
|
+
* - `workRoot` null = "no validated work root" for a KNOWN binding → local only: `edit` and `router_run` withheld
|
|
145
|
+
* + note (no write, no run); egress of a fixed egress role is kept. The work root is copied unchanged.
|
|
146
|
+
* Not for an unknown binding (QA-P12-2-3): that is the role max ∩ LOCAL (P1.6/P2.3), never `grantFor(…, null)`.
|
|
147
|
+
*/
|
|
148
|
+
export function grantFor(
|
|
149
|
+
role: RoleSpec,
|
|
150
|
+
facts: TaskFacts,
|
|
151
|
+
widened: readonly AuthorityAction[],
|
|
152
|
+
workRoot: string | null,
|
|
153
|
+
routeLine?: Pick<RouteLine, "needs"> | null,
|
|
154
|
+
): DispatchGrant {
|
|
155
|
+
const denied = new Set<string>(role.authority.deny);
|
|
156
|
+
const max = new Set<AuthorityAction>(role.authority.allow.filter((a) => KNOWN.has(a) && !denied.has(a)));
|
|
157
|
+
const needs = new Set<Need | string>([...facts.needs, ...(routeLine?.needs ?? [])]);
|
|
158
|
+
const wantsShell = needs.has("shell") || needs.has("network");
|
|
159
|
+
|
|
160
|
+
const actions = new Set<AuthorityAction>();
|
|
161
|
+
if (role.authority.mode === "fixed") {
|
|
162
|
+
for (const a of max) actions.add(a);
|
|
163
|
+
} else {
|
|
164
|
+
const derived: AuthorityAction[] = [...dynamicBase(role.kind)];
|
|
165
|
+
if (needs.has("edit")) derived.push("edit");
|
|
166
|
+
if (wantsShell) derived.push("router_run");
|
|
167
|
+
for (const a of [...derived, ...widened]) if (max.has(a)) actions.add(a);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const structural: string[] = [];
|
|
171
|
+
if (hasAny(actions, EGRESS) && (hasAny(actions, LOCAL) || hasAny(actions, EXEC) || hasAny(actions, WRITE))) {
|
|
172
|
+
for (const a of EGRESS) actions.delete(a);
|
|
173
|
+
structural.push(GRANT_NOTES.separation);
|
|
174
|
+
}
|
|
175
|
+
/** The role could edit: a missing edit is then the work root's doing (its note), not the role's. */
|
|
176
|
+
const roleEdits = actions.has("edit");
|
|
177
|
+
if (workRoot === null) {
|
|
178
|
+
// QA-P12-1-2: without a validated work root an edit would land in the session directory (the base checkout).
|
|
179
|
+
let withheld = false;
|
|
180
|
+
for (const a of [...WRITE, ...EXEC]) withheld = actions.delete(a) || withheld;
|
|
181
|
+
if (withheld) structural.push(GRANT_NOTES.noWorkRoot);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const notes: string[] = [];
|
|
185
|
+
if (wantsShell) notes.push(GRANT_NOTES.shell);
|
|
186
|
+
if (needs.has("web") && !hasAny(actions, EGRESS)) notes.push(GRANT_NOTES.web);
|
|
187
|
+
if (needs.has("edit") && !roleEdits) notes.push(GRANT_NOTES.edit);
|
|
188
|
+
if (needs.has("external_dir") && workRoot === null) notes.push(GRANT_NOTES.externalDir);
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
actions: new Set(ACTION_ORDER.filter((a) => actions.has(a))),
|
|
192
|
+
notes: [...notes, ...structural],
|
|
193
|
+
workRoot,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
// Tier floor (§2.3)
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
function tierIndex(tier: string): number {
|
|
202
|
+
return (BUILTIN_TIERS as readonly string[]).indexOf(tier);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function maxBuiltin(a: string, b: string): string {
|
|
206
|
+
return tierIndex(a) >= tierIndex(b) ? a : b;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Minimum tier for a grant (floor = max over every matching row of §2.3):
|
|
211
|
+
* - no write (local/egress/exec only): fast
|
|
212
|
+
* - write without exec: deterministic → fast if risk low and scope single, else medium;
|
|
213
|
+
* grader → medium; none → medium, heavy if risk high
|
|
214
|
+
* - write + exec: deterministic → medium; grader / none → heavy
|
|
215
|
+
* An unknown detection is treated as `none` (the strictest column).
|
|
216
|
+
*/
|
|
217
|
+
export function authorityFloor(grant: DispatchGrant, detection: Detection, risk: Risk, scope: Scope): string {
|
|
218
|
+
const write = hasAny(grant.actions, WRITE);
|
|
219
|
+
const exec = hasAny(grant.actions, EXEC);
|
|
220
|
+
let floor = "fast";
|
|
221
|
+
if (write && !exec) {
|
|
222
|
+
if (detection === "deterministic") floor = risk === "low" && scope === "single" ? "fast" : "medium";
|
|
223
|
+
else if (detection === "grader") floor = "medium";
|
|
224
|
+
else floor = risk === "high" ? "heavy" : "medium";
|
|
225
|
+
}
|
|
226
|
+
if (write && exec) {
|
|
227
|
+
floor = maxBuiltin(floor, detection === "deterministic" ? "medium" : "heavy");
|
|
228
|
+
}
|
|
229
|
+
return floor;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ---------------------------------------------------------------------------
|
|
233
|
+
// Tier window (§2.3, T1.2.2)
|
|
234
|
+
// ---------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
export interface TierBoundsOptions {
|
|
237
|
+
/** `enforcement.escalate.floorTier`, or null. */
|
|
238
|
+
floorTier: string | null;
|
|
239
|
+
/** The child's running tier on a resume (never move below it), or null. */
|
|
240
|
+
runningTier: string | null;
|
|
241
|
+
/** Route-line `tier=`, or null. */
|
|
242
|
+
pinTier: string | null;
|
|
243
|
+
/**
|
|
244
|
+
* Active tier order, cheapest first: `engine/ladders.roleTierOrder(cfg, session)`, the same order the role ladder is
|
|
245
|
+
* built on (QA-P12-1-5); empty → `fast`, `medium`, `heavy`.
|
|
246
|
+
*/
|
|
247
|
+
tiers: readonly string[];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Where the effective risk/scope of §2.3 come from besides `facts`. */
|
|
251
|
+
export interface EffectiveFactsSources {
|
|
252
|
+
/**
|
|
253
|
+
* The classifier's facts before the route line (`ClassifyResult.trace.rules`). `classify()` lets a route line
|
|
254
|
+
* override `scope` (tier-mode L3); these restore raise-only semantics.
|
|
255
|
+
*/
|
|
256
|
+
classifier?: Pick<TaskFacts, "risk" | "scope"> | null;
|
|
257
|
+
/** The route line (`ClassifyResult.trace.routeLine`): raises risk/scope, never lowers them. */
|
|
258
|
+
routeLine?: Pick<RouteLine, "risk" | "scope"> | null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export interface TierBounds {
|
|
262
|
+
floor: string;
|
|
263
|
+
ceiling: string;
|
|
264
|
+
pinned: string | null;
|
|
265
|
+
reasons: readonly string[];
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
type FloorSource = "role" | "authority" | "floorTier" | "running";
|
|
269
|
+
|
|
270
|
+
const RISK_ORDER: readonly string[] = ["low", "medium", "high"];
|
|
271
|
+
const SCOPE_ORDER: readonly string[] = ["single", "multi", "repo"];
|
|
272
|
+
|
|
273
|
+
/** Highest of `values` in `order`; values not in `order` are ignored; `base` when none is higher. */
|
|
274
|
+
function highest<T extends string>(order: readonly string[], base: T, values: ReadonlyArray<T | null | undefined>): T {
|
|
275
|
+
let out = base;
|
|
276
|
+
for (const v of values) if (v != null && order.indexOf(v) > order.indexOf(out)) out = v;
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Position of a floor-type tier on `order`. A built-in name missing from the order rounds UP to the
|
|
282
|
+
* cheapest present built-in tier at least as capable; with none, `fast` is vacuous (the cheapest tier) and
|
|
283
|
+
* anything else fails closed to the most capable tier. Any other unknown name fails closed to the top of
|
|
284
|
+
* the order (QA-P12-1-4: a floor is never dropped).
|
|
285
|
+
*/
|
|
286
|
+
function placeFloor(tier: string, order: readonly string[]): { index: number; exact: boolean; known: boolean } {
|
|
287
|
+
const at = order.indexOf(tier);
|
|
288
|
+
if (at >= 0) return { index: at, exact: true, known: true };
|
|
289
|
+
const rank = tierIndex(tier);
|
|
290
|
+
if (rank < 0) return { index: order.length - 1, exact: false, known: false };
|
|
291
|
+
const up = order.findIndex((t) => tierIndex(t) >= rank);
|
|
292
|
+
if (up >= 0) return { index: up, exact: false, known: true };
|
|
293
|
+
return { index: rank === 0 ? 0 : order.length - 1, exact: false, known: true };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Position of the role ceiling. A built-in name missing from the order rounds DOWN to the most capable
|
|
298
|
+
* present built-in tier not above it (none → the cheapest tier; the floor then wins). Any other unknown
|
|
299
|
+
* name → null (ignored: no ceiling below the top).
|
|
300
|
+
*/
|
|
301
|
+
function placeCeiling(tier: string, order: readonly string[]): { index: number; exact: boolean } | null {
|
|
302
|
+
const at = order.indexOf(tier);
|
|
303
|
+
if (at >= 0) return { index: at, exact: true };
|
|
304
|
+
const rank = tierIndex(tier);
|
|
305
|
+
if (rank < 0) return null;
|
|
306
|
+
let down = -1;
|
|
307
|
+
order.forEach((t, i) => {
|
|
308
|
+
const r = tierIndex(t);
|
|
309
|
+
if (r >= 0 && r <= rank) down = i;
|
|
310
|
+
});
|
|
311
|
+
return { index: Math.max(down, 0), exact: false };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* `facts` with the effective risk and scope of §2.3: max(`facts`, `sources.classifier`, `sources.routeLine`) — a route
|
|
316
|
+
* line raises them, never lowers them.
|
|
317
|
+
*/
|
|
318
|
+
export function effectiveFacts(facts: TaskFacts, sources: EffectiveFactsSources): TaskFacts {
|
|
319
|
+
const risk = highest<Risk>(RISK_ORDER, facts.risk, [sources.classifier?.risk, sources.routeLine?.risk]);
|
|
320
|
+
const scope = highest<Scope>(SCOPE_ORDER, facts.scope, [sources.classifier?.scope, sources.routeLine?.scope]);
|
|
321
|
+
return risk === facts.risk && scope === facts.scope ? facts : { ...facts, risk, scope };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** {@link effectiveFacts} of a classify result: `facts` raised by `trace.rules` and `trace.routeLine` (QA-P12-1-1). */
|
|
325
|
+
export function effectiveFactsOf(classified: ClassifiedDispatch): TaskFacts {
|
|
326
|
+
return effectiveFacts(classified.facts, { classifier: classified.trace.rules, routeLine: classified.trace.routeLine });
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Tier window of a dispatch (§2.3).
|
|
331
|
+
*
|
|
332
|
+
* - risk/scope = max(`classified.facts`, `classified.trace.rules`, `classified.trace.routeLine`)
|
|
333
|
+
* ({@link effectiveFactsOf}): a route line can raise them, never lower them.
|
|
334
|
+
* - `detection` is the EFFECTIVE detection ({@link effectiveDetection}), never `ClassifyResult.detection`.
|
|
335
|
+
* - floor = max(role floor, `authorityFloor(grant, detection, risk, scope)`, `floorTier`, `runningTier`).
|
|
336
|
+
* - ceiling = the role ceiling; when the floor is above it the floor wins and the ceiling is raised to the
|
|
337
|
+
* floor (the range is widened upward only).
|
|
338
|
+
* - pin (`tier=`): inside [floor, ceiling] → pinned; below → lifted to the floor; above → clamped to the
|
|
339
|
+
* ceiling; not on the tier order → ignored (`pinned` null).
|
|
340
|
+
* - Tier order = `opts.tiers` (empty → built-in). Built-in floor names missing from it round up, the ceiling
|
|
341
|
+
* rounds down (see {@link placeFloor}); any other unknown FLOOR name fails closed to the top of the order; an
|
|
342
|
+
* unknown ceiling or pin name is ignored.
|
|
343
|
+
*
|
|
344
|
+
* Reasons (deduplicated, in order of application):
|
|
345
|
+
* `floor:<source>` a source raised the floor (source = authority | floorTier | running);
|
|
346
|
+
* `round:<source>:<from>-><to>` a built-in name missing from the order was rounded (source adds role | ceiling);
|
|
347
|
+
* `unknown:<source>:<name>-><top>` an unknown floor name was placed at the top of the order (fail closed);
|
|
348
|
+
* `ignore:<source>:<name>` an unknown ceiling or pin name was ignored (source = ceiling | pin);
|
|
349
|
+
* `lift:authority` the authority floor (on a tie it is named first) lifted the pin or the ceiling;
|
|
350
|
+
* `lift:floor` any other floor source (role, floorTier, running) lifted the pin or the ceiling;
|
|
351
|
+
* `clamp:ceiling` a pin above the ceiling was clamped to it.
|
|
352
|
+
*/
|
|
353
|
+
export function tierBounds(
|
|
354
|
+
role: RoleSpec,
|
|
355
|
+
grant: DispatchGrant,
|
|
356
|
+
classified: ClassifiedDispatch,
|
|
357
|
+
detection: EffectiveDetection,
|
|
358
|
+
opts: TierBoundsOptions,
|
|
359
|
+
): TierBounds {
|
|
360
|
+
const listed = opts.tiers.filter((t, i) => typeof t === "string" && t !== "" && opts.tiers.indexOf(t) === i);
|
|
361
|
+
const order: readonly string[] = listed.length > 0 ? listed : BUILTIN_TIERS;
|
|
362
|
+
const reasons: string[] = [];
|
|
363
|
+
|
|
364
|
+
const { risk, scope } = effectiveFactsOf(classified);
|
|
365
|
+
const sources: Array<[FloorSource, string | null]> = [
|
|
366
|
+
["role", role.tierRange.floor],
|
|
367
|
+
["authority", authorityFloor(grant, detection, risk, scope)],
|
|
368
|
+
["floorTier", opts.floorTier],
|
|
369
|
+
["running", opts.runningTier],
|
|
370
|
+
];
|
|
371
|
+
|
|
372
|
+
let floor = 0;
|
|
373
|
+
let owner: FloorSource | null = null;
|
|
374
|
+
for (const [source, tier] of sources) {
|
|
375
|
+
if (tier === null) continue;
|
|
376
|
+
const placed = placeFloor(tier, order);
|
|
377
|
+
if (!placed.known) reasons.push(`unknown:${source}:${tier}->${order[placed.index]}`);
|
|
378
|
+
else if (!placed.exact) reasons.push(`round:${source}:${tier}->${order[placed.index]}`);
|
|
379
|
+
if (placed.index > floor || owner === null) {
|
|
380
|
+
if (placed.index > floor && source !== "role") reasons.push(`floor:${source}`);
|
|
381
|
+
floor = Math.max(floor, placed.index);
|
|
382
|
+
owner = source;
|
|
383
|
+
} else if (placed.index === floor && source === "authority") {
|
|
384
|
+
owner = source;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const lift = owner === "authority" ? "lift:authority" : "lift:floor";
|
|
388
|
+
|
|
389
|
+
let ceiling = order.length - 1;
|
|
390
|
+
const roleCeiling = placeCeiling(role.tierRange.ceiling, order);
|
|
391
|
+
if (roleCeiling === null) reasons.push(`ignore:ceiling:${role.tierRange.ceiling}`);
|
|
392
|
+
else {
|
|
393
|
+
if (!roleCeiling.exact) reasons.push(`round:ceiling:${role.tierRange.ceiling}->${order[roleCeiling.index]}`);
|
|
394
|
+
ceiling = roleCeiling.index;
|
|
395
|
+
}
|
|
396
|
+
if (ceiling < floor) {
|
|
397
|
+
ceiling = floor;
|
|
398
|
+
reasons.push(lift);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
let pinned: string | null = null;
|
|
402
|
+
const pin = opts.pinTier;
|
|
403
|
+
if (pin !== null) {
|
|
404
|
+
const at = order.indexOf(pin);
|
|
405
|
+
if (at < 0) reasons.push(`ignore:pin:${pin}`);
|
|
406
|
+
else if (at < floor) {
|
|
407
|
+
pinned = order[floor]!;
|
|
408
|
+
reasons.push(lift);
|
|
409
|
+
} else if (at > ceiling) {
|
|
410
|
+
pinned = order[ceiling]!;
|
|
411
|
+
reasons.push("clamp:ceiling");
|
|
412
|
+
} else pinned = pin;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
return { floor: order[floor]!, ceiling: order[ceiling]!, pinned, reasons: [...new Set(reasons)] };
|
|
416
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one work-root containment rule of a role dispatch (plan §2.2, P-11, P-13): a path a role session names is canonicalised
|
|
3
|
+
* by {@link canonicalAuthorityPath} and must lie in the work root by {@link insideWorkRoot}. P2.3 (authority, `compat/v2-hooks.ts`,
|
|
4
|
+
* which re-exports both) and P3.3 DF2-F1 (where the router verifies a role dispatch, {@link verificationScope}) use the same rule,
|
|
5
|
+
* so a directory the authority layer refuses is never one the verifier runs in.
|
|
6
|
+
*/
|
|
7
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
8
|
+
import { join, posix, win32 } from "node:path";
|
|
9
|
+
import { permissionMatches } from "../../router/read-only";
|
|
10
|
+
|
|
11
|
+
/** A win32 8.3 short-name segment (`PROGRA~1`, `MARQUI~1.TXT`): refused, never expanded (S11, P-11: fail closed). */
|
|
12
|
+
const SHORT_NAME_SEGMENT = /(?:^|[\\/])[^\\/~]{1,8}~\d+(?:\.[^\\/.]{0,3})?(?=[\\/]|$)/;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The canonical long form of a path a role session names (T2.3.1). The RAW path (a relative one joined to `base` as text) goes to
|
|
16
|
+
* `realpath` (`realpathSync.native`: links, junctions, case and 8.3 as on disk) WITHOUT lexical normalisation first, so a link is
|
|
17
|
+
* resolved before any `..` after it (QA-P23-A1: POSIX `<root>/link/../x` is where the filesystem says, not `<root>/x`). A path that
|
|
18
|
+
* does not exist is peeled to its longest existing ancestor, one component at a time, and only on a real "does not exist": an
|
|
19
|
+
* entry `lstat` sees but `realpath` cannot resolve is a dangling (or looping) link and refuses; a `..` left in the missing tail
|
|
20
|
+
* refuses. Undefined — the caller refuses — also for an empty path, leading or trailing whitespace (QA-G-A2-5: refused, never
|
|
21
|
+
* trimmed), a NUL, a wildcard, and on win32 an 8.3 spelling, a UNC/device
|
|
22
|
+
* path (`\\server\…`, `\\?\…`: no filesystem call may reach a remote host), a drive-relative path (`C:x`) or a rooted path without
|
|
23
|
+
* a drive (`\x`); and when anything fails to resolve for another reason than "does not exist".
|
|
24
|
+
*/
|
|
25
|
+
export function canonicalAuthorityPath(
|
|
26
|
+
path: string,
|
|
27
|
+
base: string,
|
|
28
|
+
opts: { platform?: NodeJS.Platform; realpath?: (path: string) => string; lstat?: (path: string) => unknown } = {},
|
|
29
|
+
): string | undefined {
|
|
30
|
+
const platform = opts.platform ?? process.platform;
|
|
31
|
+
const realpath = opts.realpath ?? ((p: string) => realpathSync.native(p));
|
|
32
|
+
const lstat = opts.lstat ?? ((p: string) => lstatSync(p));
|
|
33
|
+
// QA-G-A2-5: leading/trailing whitespace refuses; it is never trimmed (the host would not trim the path it acts on either).
|
|
34
|
+
const text = path;
|
|
35
|
+
if (text.trim() !== text || text === "" || text.includes("\0") || /[*?]/.test(text)) return undefined;
|
|
36
|
+
const api = platform === "win32" ? win32 : posix;
|
|
37
|
+
const unc = (value: string): boolean => /^[\\/]{2}/.test(value);
|
|
38
|
+
if (platform === "win32") {
|
|
39
|
+
if (SHORT_NAME_SEGMENT.test(text) || unc(text) || /^[A-Za-z]:(?![\\/])/.test(text) || /^[\\/](?![\\/])/.test(text)) return undefined;
|
|
40
|
+
if (!api.isAbsolute(text) && (SHORT_NAME_SEGMENT.test(base) || unc(base))) return undefined;
|
|
41
|
+
}
|
|
42
|
+
if (!api.isAbsolute(text) && !api.isAbsolute(base)) return undefined;
|
|
43
|
+
const sep = platform === "win32" ? "\\" : "/";
|
|
44
|
+
let head = api.isAbsolute(text) ? text : `${base.replace(/[\\/]+$/, "")}${sep}${text}`;
|
|
45
|
+
const tail: string[] = [];
|
|
46
|
+
const missing = (error: unknown): boolean => {
|
|
47
|
+
const code = (error as { code?: unknown } | null)?.code;
|
|
48
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
49
|
+
};
|
|
50
|
+
for (let depth = 0; depth < 4096; depth++) {
|
|
51
|
+
try {
|
|
52
|
+
const real = realpath(head);
|
|
53
|
+
if (tail.includes("..")) return undefined;
|
|
54
|
+
return tail.length === 0 ? real : api.join(real, ...tail);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (!missing(error)) return undefined;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
lstat(head);
|
|
60
|
+
return undefined; // the entry exists, yet does not resolve: a dangling or looping link
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (!missing(error)) return undefined;
|
|
63
|
+
}
|
|
64
|
+
const parent = api.dirname(head);
|
|
65
|
+
if (parent === head) return undefined;
|
|
66
|
+
const name = api.basename(head);
|
|
67
|
+
if (name !== "" && name !== ".") tail.unshift(name);
|
|
68
|
+
head = parent;
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* `target` (canonical) is the work root or inside it, with the matcher of the max policy's `external_directory` rules
|
|
75
|
+
* (`read-only.ts` `permissionMatches`: separators unified, win32 case folding) on the registration's `<root><sep>*` shape (P-11,
|
|
76
|
+
* P-13). A root carrying a wildcard never contains anything.
|
|
77
|
+
*/
|
|
78
|
+
export function insideWorkRoot(target: string, root: string): boolean {
|
|
79
|
+
if (root === "" || /[*?]/.test(root)) return false;
|
|
80
|
+
return permissionMatches(target, root) || permissionMatches(target, join(root, "*"));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* #84 P3.3 DF2-F1 (QA-P33F1-1 nit 3): the cwd a dispatch's verification is asked to use — the call's own `cwd` argument when it
|
|
85
|
+
* names one, else the `[acceptance]` block's `cwd:`. The dispatch-time detection and the after-hook's gate read it the same way.
|
|
86
|
+
*/
|
|
87
|
+
export function requestedVerificationCwd(argsCwd: unknown, blockCwd: string | undefined): string | undefined {
|
|
88
|
+
return requestedVerificationCwdSource(argsCwd, blockCwd) === "argument" ? (argsCwd as string) : blockCwd;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Fix-1 review nit: which input {@link requestedVerificationCwd} takes — `argument` (the call's `cwd`), `acceptance` (the block's
|
|
93
|
+
* `cwd:`), or undefined when neither names one. The gate names it in a refusal (`Delegation.cwdSource`).
|
|
94
|
+
*/
|
|
95
|
+
export function requestedVerificationCwdSource(argsCwd: unknown, blockCwd: string | undefined): "argument" | "acceptance" | undefined {
|
|
96
|
+
if (typeof argsCwd === "string" && argsCwd.trim() !== "") return "argument";
|
|
97
|
+
return blockCwd !== undefined ? "acceptance" : undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Where one dispatch is verified ({@link verificationScope}). */
|
|
101
|
+
export interface VerificationScope {
|
|
102
|
+
/** The directory the change capture, the change set, the checks and a deferral use; undefined = the router's own. */
|
|
103
|
+
readonly cwd: string | undefined;
|
|
104
|
+
/** The gate's `Delegation.cwd`: for a role dispatch the CHECKED canonical directory (also the checks' exec cwd). */
|
|
105
|
+
readonly requested: string | undefined;
|
|
106
|
+
/** The role dispatch's verification root (the gate's `Delegation.workRoot`); absent for every other dispatch. */
|
|
107
|
+
readonly workRoot?: string;
|
|
108
|
+
/** The requested cwd is outside `workRoot` (or cannot be resolved safely): the gate refuses it; no deferral; `cwd` = the root. */
|
|
109
|
+
readonly outside: boolean;
|
|
110
|
+
/** The refused cwd as written (the gate's `Delegation.refusedCwd`); only when `outside`. */
|
|
111
|
+
readonly refused?: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* #84 P3.3 DF2-F1: where a dispatch is verified. No root (a tier dispatch): the explicit `cwd`, exactly as before (I1). A role
|
|
116
|
+
* dispatch's verification root (its bound work root, else its canonical session directory: QA-P33F1-1-1, 1-3): no `cwd` → the root;
|
|
117
|
+
* a `cwd` (relative ones joined to the root) is canonicalised and contained by P2.3's rule ({@link canonicalAuthorityPath},
|
|
118
|
+
* {@link insideWorkRoot}: UNC/device/8.3 paths refused before any filesystem call, links resolved before `..`); inside → the
|
|
119
|
+
* canonical directory, which the checks then run in; anything else → `outside`, and every process stays in the root.
|
|
120
|
+
*/
|
|
121
|
+
export function verificationScope(
|
|
122
|
+
explicit: string | undefined,
|
|
123
|
+
root: string | null | undefined,
|
|
124
|
+
canonical: (path: string, base: string) => string | undefined = canonicalAuthorityPath,
|
|
125
|
+
): VerificationScope {
|
|
126
|
+
if (typeof root !== "string" || root === "") return { cwd: explicit, requested: explicit, outside: false };
|
|
127
|
+
const text = explicit?.trim() ? explicit.trim() : undefined;
|
|
128
|
+
if (text === undefined) return { cwd: root, requested: root, workRoot: root, outside: false };
|
|
129
|
+
const target = canonical(text, root);
|
|
130
|
+
if (target !== undefined && insideWorkRoot(target, root)) return { cwd: target, requested: target, workRoot: root, outside: false };
|
|
131
|
+
return { cwd: root, requested: undefined, workRoot: root, outside: true, refused: text };
|
|
132
|
+
}
|