opencode-model-router 2.9.1 → 2.11.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 +482 -0
- package/README.md +4 -2
- package/package.json +12 -5
- package/src/compat/background.ts +56 -19
- package/src/compat/child-history.ts +134 -0
- package/src/compat/child-report.ts +185 -0
- package/src/compat/child-session.ts +10 -0
- package/src/compat/session-lookup.ts +21 -0
- package/src/compat/v2-client.ts +124 -6
- package/src/compat/v2-hooks.ts +525 -203
- package/src/compat/v2-observations.ts +1 -0
- package/src/compat/v2-vocabulary.ts +14 -0
- package/src/executor/create.ts +47 -28
- package/src/executor/git.ts +226 -30
- package/src/executor/integrate/checks.ts +29 -11
- package/src/executor/integrate/land.ts +32 -2
- package/src/executor/integrate/queue.ts +95 -13
- package/src/executor/ledger.ts +16 -12
- package/src/executor/lfs-restore.ts +492 -0
- package/src/executor/paths.ts +7 -2
- package/src/executor/recovery.ts +2 -1
- package/src/executor/runtime.ts +1062 -243
- package/src/executor/slots/pool.ts +120 -19
- package/src/executor/slots/provision.ts +111 -23
- package/src/executor/slots/root.ts +81 -0
- package/src/executor/types.ts +28 -2
- package/src/executor/unattended.ts +6 -1
- package/src/executor/verify-trees.ts +507 -0
- package/src/guard/enforce.ts +2 -1
- package/src/guard/fingerprint.ts +9 -0
- package/src/guard/guards.ts +7 -1
- package/src/index.ts +191 -31
- package/src/router/answer-dedup.ts +198 -0
- package/src/router/common-dir.ts +241 -0
- package/src/router/config.ts +228 -40
- package/src/router/diff-handles.ts +322 -0
- package/src/router/diff-summary.ts +318 -0
- package/src/router/git-metadata-guard.ts +317 -0
- package/src/router/git-tools.ts +1136 -49
- package/src/router/read-only.ts +37 -13
- package/src/router/role-agents.ts +100 -36
- package/src/router/run-summary.ts +253 -0
- package/src/router/run-tools.ts +177 -25
- package/src/router/sessions.ts +23 -1
- package/src/router/tool-paths.ts +62 -4
- package/src/routing/classify/rules.ts +93 -14
- package/src/routing/roles/read-set.ts +10 -1
- package/src/routing/roles/work-root.ts +20 -3
- package/src/routing/wire/hint.ts +9 -2
- package/src/v2.ts +3 -1
- package/src/verify/exec.ts +454 -2
- package/src/verify/head.ts +6 -1
- package/src/verify/pending.ts +14 -1
- package/src/verify/plan-task.ts +86 -26
- package/src/verify/reference.ts +60 -7
- package/src/verify/runner.ts +14 -6
- package/src/verify/tree.ts +34 -10
- package/src/verify/types.ts +44 -0
- package/src/verify/wiring.ts +134 -22
package/src/router/run-tools.ts
CHANGED
|
@@ -59,17 +59,24 @@
|
|
|
59
59
|
* absolute, drive, UNC or URL path or a `..` segment, but a symlink or junction inside
|
|
60
60
|
* the work root, and the contents of an `@response` file, are repository content.
|
|
61
61
|
*/
|
|
62
|
-
import { lstatSync, realpathSync, statSync } from "node:fs";
|
|
62
|
+
import { lstatSync, realpathSync, statSync, unlinkSync } from "node:fs";
|
|
63
63
|
import { createRequire } from "node:module";
|
|
64
|
-
import { homedir } from "node:os";
|
|
64
|
+
import { homedir, tmpdir } from "node:os";
|
|
65
65
|
import { posix, win32 } from "node:path";
|
|
66
66
|
import { tool } from "@opencode-ai/plugin";
|
|
67
67
|
import { applySlotEnv, slotEnvFor, type SlotBin, type SlotEnv } from "../executor/slots/env";
|
|
68
68
|
import type { RunConfig } from "./roles";
|
|
69
|
+
import {
|
|
70
|
+
canonicalArgs, dedupeAnswer, forgetAnswer, forgetToolAnswers, FORCE_ARG_DESCRIPTION, RUN_UNCHANGED_NOTE, withoutRunDuration, type AnswerKey,
|
|
71
|
+
} from "./answer-dedup";
|
|
69
72
|
import {
|
|
70
73
|
checkWorkRootAnswer, dropPartialCredential, envLookup, errorMessage, firstOutside, isFullPath, readBoundedRegularFile as readBounded,
|
|
71
74
|
realFileOrUndefined, spawnBounded, stripUrlUserinfo, workRootGuards, type BoundedLabel, type BoundedResult, type WorkRootAnswer,
|
|
72
75
|
} from "./git-tools";
|
|
76
|
+
import {
|
|
77
|
+
newRunReportPath, parseVitestReport, renderFailureSummary, renderSummaryUnavailable, REPORTER_OPTION_RE, RUN_REPORT_MAX_BYTES, runReportPathAllowed,
|
|
78
|
+
vitestScriptRefusal,
|
|
79
|
+
} from "./run-summary";
|
|
73
80
|
|
|
74
81
|
export { isFullPath } from "./git-tools";
|
|
75
82
|
export type { WorkRootAnswer } from "./git-tools";
|
|
@@ -156,10 +163,26 @@ export interface RunToolDeps {
|
|
|
156
163
|
platform?: NodeJS.Platform;
|
|
157
164
|
/** Test seam: the environment the run inherits (hardened). Default: process.env at call time. */
|
|
158
165
|
env?: NodeJS.ProcessEnv;
|
|
166
|
+
/**
|
|
167
|
+
* #108 slice 4 (OpenCode v2, roles mode at start): declare `force`, and answer a run whose output (status line without its
|
|
168
|
+
* duration, then the output or summary) equals the previous identical run's with a stub (answer-dedup.ts). The run still
|
|
169
|
+
* executes and is recorded. Absent: schema and behaviour are unchanged.
|
|
170
|
+
*/
|
|
171
|
+
dedupe?: boolean;
|
|
159
172
|
}
|
|
160
173
|
|
|
161
174
|
export interface RunInput { script: string; args?: readonly string[]; cwd: string }
|
|
162
175
|
|
|
176
|
+
/** Options of {@link planRun} beyond the call itself. */
|
|
177
|
+
export interface RunPlanOptions {
|
|
178
|
+
/**
|
|
179
|
+
* #108 `summary: "failures"`: the vitest JSON report the run writes (absolute, router-named, in the OS temp directory). The
|
|
180
|
+
* entry must run a vitest npm script; `--reporter=json --outputFile=<path>` is appended to the script's arguments. Absent
|
|
181
|
+
* (every other caller, the plan executor's checks included): the plan is unchanged.
|
|
182
|
+
*/
|
|
183
|
+
failuresReport?: string;
|
|
184
|
+
}
|
|
185
|
+
|
|
163
186
|
/** A resolved, spawnable run. `executable` is absolute; argv never passes through a shell. */
|
|
164
187
|
export interface RunPlan {
|
|
165
188
|
kind: "script" | "command";
|
|
@@ -742,6 +765,35 @@ function pinnedProgram(program: string): "node" | "npm" | undefined {
|
|
|
742
765
|
return match ? match[1]!.toLowerCase() as "node" | "npm" : undefined;
|
|
743
766
|
}
|
|
744
767
|
|
|
768
|
+
/** Discoverability only: this does not validate or authorise a command or its arguments. */
|
|
769
|
+
function argumentCommands(config: RunConfig, script?: string) {
|
|
770
|
+
const sameScript = (argv: readonly string[]): boolean => {
|
|
771
|
+
const [program, command, name] = argv;
|
|
772
|
+
if (program === undefined || pinnedProgram(program) !== "npm") return false;
|
|
773
|
+
if (command === "run" || command === "run-script") return name === script && argv.slice(3).includes("--");
|
|
774
|
+
return script === "test" && command === "test" && argv.slice(2).includes("--");
|
|
775
|
+
};
|
|
776
|
+
return Object.entries(config.commands ?? {})
|
|
777
|
+
.filter(([, command]) => (command.args?.length ?? 0) > 0)
|
|
778
|
+
.sort(([, a], [, b]) => Number(sameScript(b.argv)) - Number(sameScript(a.argv)));
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function scriptArgumentsHint(config: RunConfig, script: string): string {
|
|
782
|
+
const commands = argumentCommands(config, script);
|
|
783
|
+
return commands.length === 0
|
|
784
|
+
? `declare a routing.run.commands entry with "args" for "${script}"`
|
|
785
|
+
: `use ${commands.map(([name, command]) => `script "${name}" (args: ${command.args!.join(", ")})`).join("; or ")}`;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/** Registration-time summary; execution still reads the current config on every call. */
|
|
789
|
+
function argumentCommandsDescription(config: RunConfig): string {
|
|
790
|
+
const commands = argumentCommands(config);
|
|
791
|
+
if (commands.length === 0) return "";
|
|
792
|
+
const bounded = (text: string, max: number) => text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
793
|
+
const entries = commands.slice(0, 5).map(([name, command]) => `${bounded(name, 64)} (args: ${bounded(command.args!.join(", "), 100)})`);
|
|
794
|
+
return ` Commands accepting arguments: ${entries.join("; ")}${commands.length > 5 ? "; …" : ""}.`;
|
|
795
|
+
}
|
|
796
|
+
|
|
745
797
|
/**
|
|
746
798
|
* The fixed npm argv of a `commands` entry (QA-P13-1-5): it starts with an allowed
|
|
747
799
|
* script-running command (exact name), `run`/`run-script` name a script of the work
|
|
@@ -767,6 +819,24 @@ function checkNpmArgv(fixed: readonly string[], scripts: Record<string, unknown>
|
|
|
767
819
|
}
|
|
768
820
|
}
|
|
769
821
|
|
|
822
|
+
/**
|
|
823
|
+
* #108: the arguments `summary: "failures"` appends to an npm run of `script` (undefined: the entry runs npm start, stop or
|
|
824
|
+
* restart, which name no single script). The script must be a vitest command ({@link vitestScriptRefusal}), and neither the
|
|
825
|
+
* entry's fixed arguments after `--` nor the caller's (`passed`) may set the reporter or output file. A `--` is added first
|
|
826
|
+
* when the argv has none, so npm hands the options to the script.
|
|
827
|
+
*/
|
|
828
|
+
function failuresReportArgs(report: string, scripts: Record<string, unknown>, script: string | undefined, name: string,
|
|
829
|
+
passed: readonly string[], separated: boolean): string[] {
|
|
830
|
+
const needs = 'summary "failures" needs a vitest npm script';
|
|
831
|
+
if (script === undefined) throw refuse(`${needs}; "${name}" does not run one package.json script`);
|
|
832
|
+
const why = vitestScriptRefusal(String(scripts[script]));
|
|
833
|
+
if (why !== undefined) throw refuse(`${needs}: script "${script}" ${why}`);
|
|
834
|
+
const set = passed.find(arg => REPORTER_OPTION_RE.test(arg));
|
|
835
|
+
if (set !== undefined) throw refuse(`summary "failures" sets vitest's reporter and output file itself; ${set} is not accepted with it`);
|
|
836
|
+
if (passed.includes("--")) throw refuse('summary "failures" does not accept a "--" argument (vitest would read the appended options as file filters)');
|
|
837
|
+
return [...(separated ? [] : ["--"]), "--reporter=json", `--outputFile=${report}`];
|
|
838
|
+
}
|
|
839
|
+
|
|
770
840
|
/**
|
|
771
841
|
* Resolve a call into a spawnable plan. `root` must come from authorizeCwd. Commands
|
|
772
842
|
* win over scripts of the same name. Package.json scripts take no caller arguments
|
|
@@ -774,9 +844,10 @@ function checkNpmArgv(fixed: readonly string[], scripts: Record<string, unknown>
|
|
|
774
844
|
* declaring `args`, e.g. `{ "argv": ["npm", "run", "test", "--"], "args": ["test/*"] }`.
|
|
775
845
|
* Caller arguments never name a path outside the work root, and an option-like one
|
|
776
846
|
* (`-`, `@`, `+`) needs a pattern with the same lead; a `node` entry takes option-like
|
|
777
|
-
* caller arguments only when its fixed argv starts with the script (QA-P13-1-1).
|
|
847
|
+
* caller arguments only when its fixed argv starts with the script (QA-P13-1-1). `options.failuresReport` (#108): see
|
|
848
|
+
* {@link RunPlanOptions}; any other entry is refused.
|
|
778
849
|
*/
|
|
779
|
-
export function planRun(input: RunInput, root: string, config: RunConfig, host: RunHost): RunPlan {
|
|
850
|
+
export function planRun(input: RunInput, root: string, config: RunConfig, host: RunHost, options: RunPlanOptions = {}): RunPlan {
|
|
780
851
|
const name = input.script;
|
|
781
852
|
if (typeof name !== "string" || !RUN_NAME_RE.test(name)) throw refuse("invalid entry name");
|
|
782
853
|
const args = validateRunArgs(input.args ?? []);
|
|
@@ -801,6 +872,9 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
|
|
|
801
872
|
});
|
|
802
873
|
const [program, ...fixed] = command.argv as string[];
|
|
803
874
|
const pinned = pinnedProgram(program!);
|
|
875
|
+
if (options.failuresReport !== undefined && pinned !== "npm") {
|
|
876
|
+
throw refuse(`summary "failures" needs a vitest npm script; "${name}" is not an npm entry`);
|
|
877
|
+
}
|
|
804
878
|
if (pinned === "node") {
|
|
805
879
|
if (args.some(arg => optionLead(arg) !== undefined) && (fixed.length === 0 || optionLead(fixed[0]!) !== undefined)) {
|
|
806
880
|
throw refuse(`option-like arguments to the node command "${name}" need a fixed script first in its argv`);
|
|
@@ -809,25 +883,32 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
|
|
|
809
883
|
argv = [...fixed, ...args];
|
|
810
884
|
} else if (pinned === "npm") {
|
|
811
885
|
refuseUncForShell(root, host.platform);
|
|
812
|
-
|
|
886
|
+
const scripts = packageScripts(root, host.platform);
|
|
887
|
+
checkNpmArgv(fixed, scripts, name);
|
|
813
888
|
// Caller options before `--` would be npm flags and could undo the hardening flags.
|
|
814
889
|
if (!fixed.includes("--") && args.some(arg => arg.startsWith("-"))) throw refuse(`option-like arguments to the npm command "${name}" need a "--" in its argv`);
|
|
890
|
+
const separator = fixed.indexOf("--");
|
|
891
|
+
const report = options.failuresReport === undefined ? [] : failuresReportArgs(options.failuresReport, scripts,
|
|
892
|
+
fixed[0] === "run" || fixed[0] === "run-script" ? fixed[1] : fixed[0] === "test" ? "test" : undefined, name,
|
|
893
|
+
[...(separator === -1 ? [] : fixed.slice(separator + 1)), ...args], separator !== -1);
|
|
815
894
|
const launch = npmLaunch(root, host, guarded());
|
|
816
895
|
executable = launch.node;
|
|
817
896
|
shell = launch.shell;
|
|
818
|
-
argv = [launch.cli, ...launch.flags, ...fixed, ...args];
|
|
897
|
+
argv = [launch.cli, ...launch.flags, ...fixed, ...args, ...report];
|
|
819
898
|
} else {
|
|
820
899
|
executable = slotToolExecutable(program!, slotEnv, host, guarded) ?? resolveCommandExecutable(program!, host, guarded());
|
|
821
900
|
argv = [...fixed, ...args];
|
|
822
901
|
}
|
|
823
902
|
} else if (scriptAllowed(config.scripts ?? [], name)) {
|
|
824
|
-
if (args.length > 0) throw refuse(`package.json scripts take no caller arguments;
|
|
903
|
+
if (args.length > 0) throw refuse(`package.json scripts take no caller arguments; ${scriptArgumentsHint(config, name)}`);
|
|
825
904
|
refuseUncForShell(root, host.platform);
|
|
826
|
-
|
|
905
|
+
const scripts = packageScripts(root, host.platform);
|
|
906
|
+
requireScript(scripts, name);
|
|
907
|
+
const report = options.failuresReport === undefined ? [] : failuresReportArgs(options.failuresReport, scripts, name, name, [], false);
|
|
827
908
|
const launch = npmLaunch(root, host, guarded());
|
|
828
909
|
executable = launch.node;
|
|
829
910
|
shell = launch.shell;
|
|
830
|
-
argv = [launch.cli, ...launch.flags, "run", name];
|
|
911
|
+
argv = [launch.cli, ...launch.flags, "run", name, ...report];
|
|
831
912
|
} else {
|
|
832
913
|
throw refuse(`"${name}" is not in routing.run.scripts or routing.run.commands`);
|
|
833
914
|
}
|
|
@@ -901,8 +982,11 @@ function statusLine(plan: RunPlan, result: BoundedResult, ms: number): string {
|
|
|
901
982
|
return `[router_run] ${what}: exit code: ${result.code ?? "none (killed by a signal)"}; duration ${duration}`;
|
|
902
983
|
}
|
|
903
984
|
|
|
904
|
-
/**
|
|
905
|
-
|
|
985
|
+
/**
|
|
986
|
+
* Spawn a plan (shell: false), bounded by time, abort and 64 KiB of output; never rejects on a timeout or abort. `text` is the
|
|
987
|
+
* tool's answer; `status` (its first line) and `output` (the bounded output) are its parts, for a summary (#108).
|
|
988
|
+
*/
|
|
989
|
+
export async function executeRunPlan(plan: RunPlan, signal?: AbortSignal): Promise<{ result: BoundedResult; text: string; ms: number; status: string; output: string }> {
|
|
906
990
|
const started = performance.now();
|
|
907
991
|
const result = await spawnBounded(plan.executable, plan.argv, plan.cwd, {
|
|
908
992
|
env: plan.env, timeoutMs: plan.timeoutMs, signal, maxBytes: RUN_HEAD_BYTES, tailBytes: RUN_TAIL_BYTES,
|
|
@@ -910,7 +994,34 @@ export async function executeRunPlan(plan: RunPlan, signal?: AbortSignal): Promi
|
|
|
910
994
|
});
|
|
911
995
|
const ms = performance.now() - started;
|
|
912
996
|
const output = renderRunOutput(result);
|
|
913
|
-
|
|
997
|
+
const status = statusLine(plan, result, ms);
|
|
998
|
+
return { result, ms, status, output, text: `${status}\n${output}${output.endsWith("\n") || output === "" ? "" : "\n"}` };
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** #108: a `summary: "failures"` report: its path and the OS temp directory read once for it (`os.tmpdir()` at the call). */
|
|
1002
|
+
interface RunReport { readonly path: string; readonly tmp: string }
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* #108: the answer of a `summary: "failures"` run: the report (only when the guard admits its path; its size is checked before
|
|
1006
|
+
* it is read, at most {@link RUN_REPORT_MAX_BYTES}) summarized, or why it could not be, with the output's last lines. The caller
|
|
1007
|
+
* deletes the report.
|
|
1008
|
+
*/
|
|
1009
|
+
function failuresAnswer(report: RunReport, cwd: string, run: { result: BoundedResult; status: string; output: string }): string {
|
|
1010
|
+
let text: string | undefined;
|
|
1011
|
+
let reason = "vitest wrote no report (it did not start, was stopped, or failed before reporting)";
|
|
1012
|
+
if (!runReportPathAllowed(report.path, report.tmp)) reason = "the report path was rejected";
|
|
1013
|
+
else {
|
|
1014
|
+
try {
|
|
1015
|
+
const size = statSync(report.path, { throwIfNoEntry: false })?.size;
|
|
1016
|
+
if (size !== undefined && size > RUN_REPORT_MAX_BYTES) reason = `the vitest report is larger than ${RUN_REPORT_MAX_BYTES / (1024 * 1024)} MiB`;
|
|
1017
|
+
else if (size !== undefined) text = readBounded(report.path, Math.max(1, size), "the vitest report");
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
reason = errorMessage(error);
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
const parsed = text === undefined ? undefined : parseVitestReport(text, cwd);
|
|
1023
|
+
if (parsed !== undefined) return renderFailureSummary(run.status, parsed, run.result.failure === undefined ? run.result.code : null, run.output);
|
|
1024
|
+
return renderSummaryUnavailable(run.status, text === undefined ? reason : "the vitest report is not a vitest JSON report", run.output);
|
|
914
1025
|
}
|
|
915
1026
|
|
|
916
1027
|
/**
|
|
@@ -920,23 +1031,36 @@ export async function executeRunPlan(plan: RunPlan, signal?: AbortSignal): Promi
|
|
|
920
1031
|
* is a normal result.
|
|
921
1032
|
*/
|
|
922
1033
|
export function routerRunTool(deps: RunToolDeps) {
|
|
923
|
-
const
|
|
1034
|
+
const shape = {
|
|
924
1035
|
script: tool.schema.string().min(1).max(200),
|
|
925
1036
|
args: tool.schema.array(tool.schema.string().max(200)).max(RUN_MAX_ARGS).optional(),
|
|
926
1037
|
cwd: tool.schema.string().min(1).max(4096),
|
|
927
|
-
|
|
1038
|
+
summary: tool.schema.enum(["failures"]).optional(),
|
|
1039
|
+
};
|
|
1040
|
+
// #108 slice 4: `force` is accepted only where it is declared (answers deduplicated).
|
|
1041
|
+
const inputSchema = deps.dedupe === true
|
|
1042
|
+
? tool.schema.object({ ...shape, force: tool.schema.boolean().optional() }).strict()
|
|
1043
|
+
: tool.schema.object(shape).strict();
|
|
928
1044
|
return tool({
|
|
929
1045
|
description: "Run one allowlisted package.json script or configured command in this dispatch's work root and report its exit code. "
|
|
930
1046
|
+ "No shell is spawned by the tool; arguments are accepted only when the entry declares them, each 1-200 characters of [A-Za-z0-9_./:=@+-], never a path outside the work root. "
|
|
931
1047
|
+ "cwd must be the dispatch's work root. Output (stdout and stderr) is bounded to 64 KiB; URL credentials in it are redacted (best effort, not a secret scanner) "
|
|
932
1048
|
+ "and credential-like environment variables are not passed to the run; agents and credential stores (ssh-agent, git credential helpers, "
|
|
933
|
-
+ "cloud CLI caches in the home directory) stay reachable to scripts. The run is time-limited."
|
|
1049
|
+
+ "cloud CLI caches in the home directory) stay reachable to scripts. The run is time-limited."
|
|
1050
|
+
+ " With summary \"failures\" (vitest npm scripts only) the answer is the test counts and the failing tests grouped by file, within 4 KiB."
|
|
1051
|
+
+ argumentCommandsDescription(deps.config()),
|
|
934
1052
|
args: {
|
|
935
1053
|
script: tool.schema.string().describe("Entry name: a script listed in routing.run.scripts (e.g. test, typecheck) or a routing.run.commands entry"),
|
|
936
1054
|
args: tool.schema.array(tool.schema.string()).optional().describe("Arguments, only for command entries that declare them"),
|
|
937
1055
|
cwd: tool.schema.string().describe("Absolute path of the dispatch's work root"),
|
|
1056
|
+
summary: tool.schema.enum(["failures"]).optional()
|
|
1057
|
+
.describe("failures: for an entry running a vitest npm script, return the counts and each failing test (first error block) instead of the raw output"),
|
|
1058
|
+
...(deps.dedupe === true ? { force: tool.schema.boolean().optional().describe(FORCE_ARG_DESCRIPTION) } : {}),
|
|
938
1059
|
},
|
|
939
1060
|
async execute(input, context) {
|
|
1061
|
+
// #108 slice 4: the call's dedup key, once known; an error answer forgets it, a refusal before it is known forgets the
|
|
1062
|
+
// session's router_run entries.
|
|
1063
|
+
let dedupKey: AnswerKey | undefined;
|
|
940
1064
|
try {
|
|
941
1065
|
const platform = deps.platform ?? process.platform;
|
|
942
1066
|
// Authority first (P-10, I9, QA-P13-2-8): nothing else is looked at for an unbound session.
|
|
@@ -945,18 +1069,46 @@ export function routerRunTool(deps: RunToolDeps) {
|
|
|
945
1069
|
if (answer.root === null) throw refuse("this session has no bound work root (I9); router_run only runs in a dispatch's work root");
|
|
946
1070
|
const root = authorizeCwd(answer.root, (input as { cwd?: unknown } | undefined)?.cwd, platform);
|
|
947
1071
|
const parsed = inputSchema.parse(input);
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
1072
|
+
if (deps.dedupe === true) {
|
|
1073
|
+
// `cwd` names `root` (authorizeCwd), whose real path is in the key already; however it was spelled, it is the same call.
|
|
1074
|
+
dedupKey = { sessionID: context.sessionID, tool: RUN_TOOL_NAME, via: { kind: "workRoot" }, root, args: canonicalArgs(parsed, { args: [] }, ["cwd"]) };
|
|
1075
|
+
}
|
|
1076
|
+
// #108: opt-in; the report path is router-named in the OS temp directory (read once) and deleted once the run settles. A path
|
|
1077
|
+
// the guard would not admit (a relative TEMP/TMPDIR) is refused before planning, so no report can land in the work root.
|
|
1078
|
+
let report: RunReport | undefined;
|
|
1079
|
+
if (parsed.summary === "failures") {
|
|
1080
|
+
const tmp = tmpdir();
|
|
1081
|
+
report = { path: newRunReportPath(tmp), tmp };
|
|
1082
|
+
if (!runReportPathAllowed(report.path, tmp)) {
|
|
1083
|
+
throw refuse(`summary "failures" needs an absolute OS temp directory for its report (it is "${tmp}"; check TEMP, TMP or TMPDIR)`);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
try {
|
|
1087
|
+
const plan = planRun(parsed, root, deps.config(), {
|
|
1088
|
+
platform, env: deps.env ?? process.env,
|
|
1089
|
+
...(deps.nodeExecPath !== undefined ? { nodeExecPath: deps.nodeExecPath } : {}),
|
|
1090
|
+
}, report === undefined ? {} : { failuresReport: report.path });
|
|
1091
|
+
const at = Date.now();
|
|
1092
|
+
const run = await executeRunPlan(plan, context.abort);
|
|
1093
|
+
const exitCode = run.result.failure === undefined ? run.result.code : null;
|
|
1094
|
+
try { deps.recordRun?.({ sessionID: context.sessionID, script: plan.name, exitCode, at }); } catch (error) {
|
|
1095
|
+
console.warn(`[model-router] router_run: could not record the run (${errorMessage(error)})`);
|
|
1096
|
+
}
|
|
1097
|
+
const text = report === undefined ? run.text : failuresAnswer(report, plan.cwd, run);
|
|
1098
|
+
// #108 slice 4: compared without the status line's duration; the stub keeps this run's status line. An answer given after
|
|
1099
|
+
// the call was aborted may never reach the model: it is not stored.
|
|
1100
|
+
return dedupKey === undefined ? text : dedupeAnswer(dedupKey, text, {
|
|
1101
|
+
force: "force" in parsed && parsed.force === true, compared: withoutRunDuration(text), stub: () => `${run.status}\n${RUN_UNCHANGED_NOTE}\n`,
|
|
1102
|
+
aborted: context.abort?.aborted === true,
|
|
1103
|
+
});
|
|
1104
|
+
} finally {
|
|
1105
|
+
if (report !== undefined && runReportPathAllowed(report.path, report.tmp)) {
|
|
1106
|
+
try { unlinkSync(report.path); } catch { /* missing (no report written) or already gone */ }
|
|
1107
|
+
}
|
|
957
1108
|
}
|
|
958
|
-
return text;
|
|
959
1109
|
} catch (error) {
|
|
1110
|
+
if (dedupKey !== undefined) forgetAnswer(dedupKey);
|
|
1111
|
+
else if (deps.dedupe === true) forgetToolAnswers(context.sessionID, RUN_TOOL_NAME);
|
|
960
1112
|
const prefix = error instanceof RunRefused ? "refused: " : "";
|
|
961
1113
|
return `[router_run] error: ${prefix}${stripUrlUserinfo(errorMessage(error))}`;
|
|
962
1114
|
}
|
package/src/router/sessions.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash, randomBytes } from "node:crypto";
|
|
2
2
|
import type { RouterConfig } from "./config";
|
|
3
3
|
import { fingerprintToolCall } from "../guard/fingerprint";
|
|
4
|
+
import { isWellFormedExpansion } from "./diff-handles";
|
|
4
5
|
import { DEFAULT_IDLE_TTL_MS } from "./idle-sweep";
|
|
5
6
|
import type { DecisionFacts, LadderStepKind } from "../routing/outcomes/types";
|
|
6
7
|
import type { ChangedFile } from "../verify/dispatch";
|
|
@@ -159,6 +160,15 @@ export function buildCapBanner(
|
|
|
159
160
|
/** Tools that count against the read-only cap. Keep narrow — editing tools should never count. */
|
|
160
161
|
export const READ_ONLY_TOOLS = new Set(["grep", "read", "glob", "ls"]);
|
|
161
162
|
|
|
163
|
+
/**
|
|
164
|
+
* #108 slice 5: a `router_git_show` call that expands a `gd_` handle, with well-formed arguments (`isWellFormedExpansion`: a
|
|
165
|
+
* malformed handle, `lines` or `side` is refused before git runs, so it is not a read). For a role session it is a read
|
|
166
|
+
* (read-only cap, guard clauses 4 and 5, trajectory); every other router_git_* call, and any call outside a role session, is not.
|
|
167
|
+
*/
|
|
168
|
+
export function isHandleExpansion(tool: string, args: unknown): boolean {
|
|
169
|
+
return tool === "router_git_show" && typeof args === "object" && args !== null && isWellFormedExpansion(args as Record<string, unknown>);
|
|
170
|
+
}
|
|
171
|
+
|
|
162
172
|
// ---------------------------------------------------------------------------
|
|
163
173
|
// Trivial classifier
|
|
164
174
|
// ---------------------------------------------------------------------------
|
|
@@ -569,10 +579,13 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
|
569
579
|
* Called from the tool.execute.after hook. Appends a cap/redundancy banner
|
|
570
580
|
* to the tool output for tracked subagent sessions running read-only tools.
|
|
571
581
|
* Mutates outputRef.output in place (same as the inlined hook logic).
|
|
582
|
+
* `roleExpansionReads` (#108 slice 5, set by the caller for a role session only): a handle expansion
|
|
583
|
+
* ({@link isHandleExpansion}) counts as a read too.
|
|
572
584
|
*/
|
|
573
585
|
recordToolCall(
|
|
574
586
|
input: { sessionID: string; tool: string; args: unknown },
|
|
575
587
|
outputRef: Record<string, unknown>,
|
|
588
|
+
opts: { roleExpansionReads?: boolean } = {},
|
|
576
589
|
): void {
|
|
577
590
|
const state = subagentCapState.get(input.sessionID);
|
|
578
591
|
if (!state) return; // not a tracked subagent session
|
|
@@ -581,7 +594,7 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
|
581
594
|
// removed it. Tracked sessions still refresh here, because the read-only
|
|
582
595
|
// filter below runs later.
|
|
583
596
|
touch(input.sessionID);
|
|
584
|
-
if (!READ_ONLY_TOOLS.has(input.tool)) return;
|
|
597
|
+
if (!READ_ONLY_TOOLS.has(input.tool) && !(opts.roleExpansionReads === true && isHandleExpansion(input.tool, input.args))) return;
|
|
585
598
|
|
|
586
599
|
const fp = fingerprintToolCall(input.tool, input.args);
|
|
587
600
|
const previousCall = state.seen.get(fp);
|
|
@@ -989,6 +1002,15 @@ export function runnerDescription(agent: string | undefined): string {
|
|
|
989
1002
|
return agent ? `Router ${agent} delegation` : RUNNER_VERIFICATION_DESCRIPTION;
|
|
990
1003
|
}
|
|
991
1004
|
|
|
1005
|
+
/**
|
|
1006
|
+
* #174: whether `description` has the shape {@link runnerDescription} gives. A shape only: an orchestrator may give its own
|
|
1007
|
+
* dispatch the same text, so a caller treats it as a fallback signal, never as proof that the child is the runner's.
|
|
1008
|
+
*/
|
|
1009
|
+
export function isRunnerDescription(description: string): boolean {
|
|
1010
|
+
// An agent name is one word (`[\w.-]+`): a longer title such as "Router fix the parser delegation" is never the runner's.
|
|
1011
|
+
return /^Router (?:[\w.-]+ delegation|result verification)$/.test(description);
|
|
1012
|
+
}
|
|
1013
|
+
|
|
992
1014
|
interface RunnerMark {
|
|
993
1015
|
/** Unique per announcement: a withdrawal removes exactly its own mark (QA-INT-3). */
|
|
994
1016
|
readonly id: number;
|
package/src/router/tool-paths.ts
CHANGED
|
@@ -71,7 +71,38 @@ export function applyPatchHeaderPaths(args: unknown): string[] {
|
|
|
71
71
|
*/
|
|
72
72
|
function hostPatchPaths(a: Record<string, unknown>): string[] | undefined {
|
|
73
73
|
const text = PATCH_KEYS.map(key => a[key]).find(value => typeof value === "string");
|
|
74
|
-
|
|
74
|
+
return typeof text === "string" ? patchTextPaths(text) : undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The paths of every patch text key of `a` (the git metadata guard's widest reading: a host that took another key than the first
|
|
79
|
+
* string would write those): the host's own text ({@link hostPatchPaths}) must be readable, another key's text adds its paths when
|
|
80
|
+
* it is and is ignored when it has no header. Undefined when the host's own text is unreadable, or (#161, fail closed) another
|
|
81
|
+
* key's text has a header line but cannot be read.
|
|
82
|
+
*/
|
|
83
|
+
function everyPatchTextPaths(a: Record<string, unknown>): string[] | undefined {
|
|
84
|
+
const host = hostPatchPaths(a);
|
|
85
|
+
if (host === undefined) return undefined;
|
|
86
|
+
const texts = PATCH_KEYS.map(key => a[key]).filter((value): value is string => typeof value === "string");
|
|
87
|
+
const paths = [...host];
|
|
88
|
+
for (const text of texts) {
|
|
89
|
+
const own = patchTextPaths(text);
|
|
90
|
+
if (own === undefined && hasPatchHeader(text)) return undefined;
|
|
91
|
+
paths.push(...(own ?? []));
|
|
92
|
+
}
|
|
93
|
+
return paths;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Whether a patch text has a header line as {@link patchTextPaths} reads them (leading blanks allowed). */
|
|
97
|
+
function hasPatchHeader(text: string): boolean {
|
|
98
|
+
return text.split(/\r?\n/).some(raw => {
|
|
99
|
+
const line = raw.trimStart();
|
|
100
|
+
return HOST_PATCH_HEADERS.some(prefix => line.startsWith(prefix));
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The header paths of one patch text; undefined when a header names no path or there is none. */
|
|
105
|
+
function patchTextPaths(text: string): string[] | undefined {
|
|
75
106
|
const paths: string[] = [];
|
|
76
107
|
for (const raw of text.split(/\r?\n/)) {
|
|
77
108
|
const line = raw.trimStart();
|
|
@@ -198,18 +229,45 @@ function none(): ToolTargets {
|
|
|
198
229
|
return { access: "none", paths: [], roots: [] };
|
|
199
230
|
}
|
|
200
231
|
|
|
201
|
-
|
|
232
|
+
/**
|
|
233
|
+
* The paths a write-class call names, as written, and whether its targets are known: false only for a patch whose text cannot
|
|
234
|
+
* be read ({@link hostPatchPaths}), whose header paths are then missing.
|
|
235
|
+
*/
|
|
236
|
+
function rawWriteTargets(tool: string, a: Record<string, unknown>, everyPatchText = false): { texts: (string | undefined)[]; known: boolean } {
|
|
202
237
|
if (tool === "patch" || tool === "apply_patch") {
|
|
203
238
|
// An unreadable patch has unknown targets: a write of nothing the caller can name. The host also honours the
|
|
204
239
|
// path arguments `filePath`, `path` and `file_path` of a patch call (`toolCallPaths` in src/compat/v2-hooks.ts).
|
|
240
|
+
const headers = everyPatchText ? everyPatchTextPaths(a) : hostPatchPaths(a);
|
|
205
241
|
const keyed = HOST_PATCH_PATH_KEYS.map(key => nonEmpty(a[key]));
|
|
206
|
-
return {
|
|
242
|
+
return { texts: [...(headers ?? []), ...keyed], known: headers !== undefined };
|
|
207
243
|
}
|
|
208
244
|
const raw = pathArgs(a);
|
|
209
245
|
if (tool === "multiedit" && Array.isArray(a.edits)) {
|
|
210
246
|
for (const edit of a.edits) raw.push(...pathArgs(record(edit)));
|
|
211
247
|
}
|
|
212
|
-
return {
|
|
248
|
+
return { texts: raw, known: true };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function writeTargets(tool: string, a: Record<string, unknown>, cwd: string): ToolTargets {
|
|
252
|
+
return { access: "write", paths: resolved(rawWriteTargets(tool, a).texts, cwd), roots: [] };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The files a write-class call ({@link WRITE_CLASS}) names, as written (not resolved: a link must be resolved before any `..`
|
|
257
|
+
* after it), deduped, in the order {@link toolTargets} reads them — and for a patch also the headers of every other patch text key
|
|
258
|
+
* (a superset of the lease targets: {@link toolTargets} reads only the text the host takes). Undefined when its targets are
|
|
259
|
+
* unknown — a `patch` / `apply_patch` whose (host's) text has no header, a header without a path, or no text at all, or whose
|
|
260
|
+
* other patch text key has a header without a path — so the caller fails closed. Empty for any other tool. Never throws.
|
|
261
|
+
*/
|
|
262
|
+
export function writeTargetTexts(tool: string, args: unknown): string[] | undefined {
|
|
263
|
+
const name = typeof tool === "string" ? tool.toLowerCase() : "";
|
|
264
|
+
if (!WRITE_CLASS.has(name)) return [];
|
|
265
|
+
try {
|
|
266
|
+
const { texts, known } = rawWriteTargets(name, record(args), true);
|
|
267
|
+
return known ? dedupe(texts.filter((text): text is string => text !== undefined)) : undefined;
|
|
268
|
+
} catch {
|
|
269
|
+
return undefined; // arguments that cannot be read: unknown targets
|
|
270
|
+
}
|
|
213
271
|
}
|
|
214
272
|
|
|
215
273
|
/**
|
|
@@ -102,22 +102,100 @@ const COMPILED_RULES: readonly CompiledRule[] = (() => {
|
|
|
102
102
|
});
|
|
103
103
|
})();
|
|
104
104
|
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
// Term labels (#194, #200): what a decision row may log for a vocabulary match
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* #194 (R2-6), #200: what a decision row may log for one vocabulary term, derived once from the term's source. The label
|
|
111
|
+
* tables of the high-risk terms ({@link highRiskTermOf}) and of the needs table (`trace.needTerms`) are both built with
|
|
112
|
+
* {@link termLabelOf}. Only a single-token term names a word: a closed one (`\bbilling\b`) its matched word, an open one
|
|
113
|
+
* (`\bdeploy\w*`, `\b(?:en|de)crypt\w*`) only one of its literal stems (`deploy`, `encrypt`), never the rest of the prompt's
|
|
114
|
+
* word. A term with a gap or a separator ({@link hasGap}) can span the prompt's own words, also joined by hyphens
|
|
115
|
+
* (`npm-acme-internal-publish`, `remote-acme-push`): it logs its table id.
|
|
116
|
+
*/
|
|
117
|
+
type TermLabel = { readonly kind: "id" } | { readonly kind: "word" } | { readonly kind: "stems"; readonly stems: readonly string[] };
|
|
118
|
+
/** `\b`, an optional `(?:a|b)` of lower-case literals, lower-case literals, `\w*`: nothing else. */
|
|
119
|
+
const OPEN_TERM_SHAPE = /^\\b(?:\(\?:([a-z]+(?:\|[a-z]+)*)\))?([a-z]+)\\w\*$/;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* True when a regex source has a gap or a separator, a part that can match the prompt's own text between or around its fixed
|
|
123
|
+
* words: `\s` (in or out of a class), any negated class (`[^\n]`), or, outside a class, a blank, an unescaped `.`, `*`, `+`
|
|
124
|
+
* or `{` (a `{m,n}` quantifier). Escapes other than `\s` and the rest of a class are single characters. A lookahead counts
|
|
125
|
+
* too: a gap anywhere in the source makes the whole term an id.
|
|
126
|
+
*/
|
|
127
|
+
function hasGap(source: string): boolean {
|
|
128
|
+
let inClass = false;
|
|
129
|
+
for (let i = 0; i < source.length; i++) {
|
|
130
|
+
const c = source[i];
|
|
131
|
+
if (c === "\\") {
|
|
132
|
+
if (source[i + 1] === "s") return true;
|
|
133
|
+
i++;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (inClass) {
|
|
137
|
+
if (c === "]") inClass = false;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (c === "[") {
|
|
141
|
+
if (source[i + 1] === "^") return true;
|
|
142
|
+
inClass = true;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (c === " " || c === "." || c === "*" || c === "+" || c === "{") return true;
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The {@link TermLabel} of one term source: an open term's stems first (its `\w*` is no gap), else id or word by {@link hasGap}. */
|
|
151
|
+
function termLabelOf(source: string): TermLabel {
|
|
152
|
+
const open = OPEN_TERM_SHAPE.exec(source);
|
|
153
|
+
if (open !== null) return { kind: "stems", stems: (open[1]?.split("|") ?? [""]).map((prefix) => prefix + (open[2] ?? "")) };
|
|
154
|
+
return hasGap(source) ? { kind: "id" } : { kind: "word" };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* How one match of term `index` is logged: the matched word (lower-cased) or the matched stem when its {@link TermLabel}
|
|
159
|
+
* allows one and `word` accepts it, else `term-<index>`.
|
|
160
|
+
*/
|
|
161
|
+
function matchLabel(label: TermLabel | undefined, text: string, index: number, word: RegExp): string {
|
|
162
|
+
const matched = text.toLowerCase();
|
|
163
|
+
const named = label === undefined || label.kind === "id" ? ""
|
|
164
|
+
: label.kind === "word" ? matched : label.stems.find((stem) => matched.startsWith(stem)) ?? "";
|
|
165
|
+
return word.test(named) ? named : `term-${index}`;
|
|
166
|
+
}
|
|
167
|
+
|
|
105
168
|
interface CompiledNeed {
|
|
106
169
|
readonly need: Need;
|
|
107
170
|
readonly implies: readonly Need[];
|
|
108
171
|
readonly res: readonly RegExp[];
|
|
172
|
+
/** #200, one per term: the load-time label table of this need ({@link termLabelOf}). */
|
|
173
|
+
readonly labels: readonly TermLabel[];
|
|
109
174
|
}
|
|
110
175
|
|
|
111
176
|
const COMPILED_NEEDS: readonly CompiledNeed[] = NEED_RULES.map((rule) => ({
|
|
112
177
|
need: rule.need,
|
|
113
178
|
implies: rule.implies ?? [],
|
|
114
179
|
res: rule.terms.map(globalCopy),
|
|
180
|
+
labels: rule.terms.map((re) => termLabelOf(re.source)),
|
|
115
181
|
}));
|
|
116
182
|
|
|
183
|
+
/**
|
|
184
|
+
* #200: the ids of the needs-table terms whose matches are logged as `term-<n>` whatever they matched (their source has a gap),
|
|
185
|
+
* as `<need>:term-<n>` in table order. For tests and docs; scanning reads {@link COMPILED_NEEDS}.
|
|
186
|
+
*/
|
|
187
|
+
export const GAPPED_NEED_TERMS: readonly string[] = COMPILED_NEEDS.flatMap((rule) =>
|
|
188
|
+
rule.labels.flatMap((label, index) => (label.kind === "id" ? [`${rule.need}:term-${index}`] : [])),
|
|
189
|
+
);
|
|
190
|
+
|
|
117
191
|
const HIGH_RISK_RES: readonly RegExp[] = [
|
|
118
192
|
...HIGH_RISK_TERMS.map(globalCopy),
|
|
119
193
|
...HIGH_RISK_CASE_SENSITIVE_TERMS.map((re) => new RegExp(re.source, "g")),
|
|
120
194
|
];
|
|
195
|
+
/** #194 (R2-6): what {@link highRiskTermOf} may log for each high-risk term ({@link termLabelOf}). */
|
|
196
|
+
const HIGH_RISK_LABELS: readonly TermLabel[] = HIGH_RISK_RES.map((re) => termLabelOf(re.source));
|
|
197
|
+
/** A logged high-risk word: lower-case letters and hyphens, at most 40 characters. */
|
|
198
|
+
const RISK_WORD = /^[a-z-]{1,40}$/;
|
|
121
199
|
const MEDIUM_RISK_RES: readonly RegExp[] = MEDIUM_RISK_TERMS.map(globalCopy);
|
|
122
200
|
const REPO_SCOPE_RES: readonly RegExp[] = REPO_SCOPE_TERMS.map(globalCopy);
|
|
123
201
|
const ABS_PATH_RES: readonly RegExp[] = [WINDOWS_ABS_PATH_RE, POSIX_ABS_PATH_RE].map(globalCopy);
|
|
@@ -444,23 +522,24 @@ function externalPath(needsText: string, cwd: string): string | null {
|
|
|
444
522
|
}
|
|
445
523
|
|
|
446
524
|
/**
|
|
447
|
-
* One need R9 found in a text, and why — never text of the prompt itself (D14, QA-G-B-2-2): the
|
|
448
|
-
*
|
|
449
|
-
* `
|
|
525
|
+
* One need R9 found in a text, and why — never text of the prompt itself (D14, QA-G-B-2-2): `url` for a URL; the term's id in
|
|
526
|
+
* the needs table (`term-<n>`) when the term's source has a gap (#200, the {@link termLabelOf} rule of the high-risk terms:
|
|
527
|
+
* `\s`, `[^\n]`, `.`, `*`, `+`, `{m,n}`; e.g. `run the tests`, `remote … push`), whatever it matched; else the matched
|
|
528
|
+
* vocabulary word (lower-cased, a single word, e.g. `update`), or `term-<n>` when the match is not one; `path` for an absolute
|
|
529
|
+
* path outside cwd; `implied-by-<need>`.
|
|
450
530
|
*/
|
|
451
531
|
export interface NeedMatch {
|
|
452
532
|
readonly need: Need;
|
|
453
533
|
readonly term: string;
|
|
454
534
|
}
|
|
455
535
|
|
|
456
|
-
/** A matched vocabulary word: letters
|
|
457
|
-
const VOCABULARY_WORD = /^[a-z][a-z
|
|
536
|
+
/** A matched vocabulary word: one word of letters and hyphens, short. Anything else (blanks, a URL, a path, a file name, `&&`) is not. */
|
|
537
|
+
const VOCABULARY_WORD = /^[a-z][a-z-]{0,39}$/;
|
|
458
538
|
|
|
459
|
-
/** QA-G-B-2-2: how a term match is named in a {@link NeedMatch} (see there). */
|
|
460
|
-
function termLabel(
|
|
461
|
-
if (need === "web" && /^https?:\/\//i.test(hit.text)) return "url";
|
|
462
|
-
|
|
463
|
-
return VOCABULARY_WORD.test(word) ? word : `term-${hit.index}`;
|
|
539
|
+
/** QA-G-B-2-2, #200: how a term match is named in a {@link NeedMatch} (see there). */
|
|
540
|
+
function termLabel(rule: CompiledNeed, hit: { readonly index: number; readonly text: string }): string {
|
|
541
|
+
if (rule.need === "web" && /^https?:\/\//i.test(hit.text)) return "url";
|
|
542
|
+
return matchLabel(rule.labels[hit.index], hit.text, hit.index, VOCABULARY_WORD);
|
|
464
543
|
}
|
|
465
544
|
|
|
466
545
|
/**
|
|
@@ -474,7 +553,7 @@ function scanNeeds(needsText: string, cwd: string | null, matches?: NeedMatch[])
|
|
|
474
553
|
const hit = firstHit(rule.res, rule.need === "external_dir" ? needsText : pathFreeText, true);
|
|
475
554
|
if (hit === null) continue;
|
|
476
555
|
needs.add(rule.need);
|
|
477
|
-
matches?.push({ need: rule.need, term: termLabel(rule
|
|
556
|
+
matches?.push({ need: rule.need, term: termLabel(rule, hit) });
|
|
478
557
|
for (const implied of rule.implies) {
|
|
479
558
|
needs.add(implied);
|
|
480
559
|
matches?.push({ need: implied, term: `implied-by-${rule.need}` });
|
|
@@ -672,7 +751,7 @@ export function highRiskTermOf(text: string): string | undefined {
|
|
|
672
751
|
const { riskText, prohibitionText } = splitSections(prepareBody(raw));
|
|
673
752
|
const hit = firstHit(HIGH_RISK_RES, riskText, false) ?? firstHit(HIGH_RISK_RES, prohibitionText, true);
|
|
674
753
|
if (hit === null) return undefined;
|
|
675
|
-
|
|
676
|
-
//
|
|
677
|
-
return
|
|
754
|
+
// Multiword/command regexes can span arbitrary arguments, and credential names can be private: log only a table id for
|
|
755
|
+
// those (#194: decided by the term's shape, HIGH_RISK_LABELS). An open term logs its stem, never the prompt's word.
|
|
756
|
+
return matchLabel(HIGH_RISK_LABELS[hit.index], hit.text, hit.index, RISK_WORD);
|
|
678
757
|
}
|