brl-subagent 2.5.2 → 2.7.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/src/loader.ts ADDED
@@ -0,0 +1,178 @@
1
+ // Purpose: Shared markdown-tier loader — scan dirs for `.md`, parse frontmatter, validate, map to a typed record.
2
+ /**
3
+ * brl-subagent — Markdown tier loader
4
+ *
5
+ * Presets and task templates are both FILE-BACKED tiers: a directory of `.md`
6
+ * files with YAML frontmatter is listed, filtered to `.md`, read, parsed,
7
+ * validated, and normalised into a family-specific record. Before issue #380
8
+ * that pipeline was written four times (builtin presets, custom presets,
9
+ * custom templates, builtin templates) with only the record shape, the
10
+ * validator, and the log wording differing (D6 in the smell audit).
11
+ *
12
+ * This module owns the common steps once. The two families keep their own
13
+ * record types and mappers — `loadMarkdownRecords` is generic over the record
14
+ * and takes the family-specific mapping as `spec.map`, so presets stay presets
15
+ * and templates stay templates while the walk is single-source.
16
+ *
17
+ * Behaviour preserved from the four copies:
18
+ * - non-`.md` entries are ignored; a directory named `*.md` surfaces as a
19
+ * read failure (warn) instead of aborting the scan;
20
+ * - an unreadable directory is skipped (`onMissingDir` lets the builtin tiers
21
+ * log the info line, custom tiers stay silent);
22
+ * - a validation error warns once per error and skips the file;
23
+ * - a per-file read/parse/map throw warns and continues;
24
+ * - dedupe by name is opt-in (`dedupeByName`) and first-occurrence-wins,
25
+ * which is how PROJECT > USER precedence is enforced.
26
+ */
27
+
28
+ import * as fs from "node:fs";
29
+ import * as path from "node:path";
30
+ import type { Logger } from "./logging";
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Frontmatter parsing
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /**
37
+ * Parse YAML frontmatter from a markdown file.
38
+ * Returns metadata key-value pairs and the body content.
39
+ */
40
+ export function parseFrontmatter(content: string): { meta: Record<string, unknown>; body: string } {
41
+ const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
42
+ if (!match) return { meta: {}, body: content };
43
+
44
+ const meta: Record<string, unknown> = {};
45
+ const lines = match[1].split("\n");
46
+ let currentKey = "";
47
+ let currentArray: string[] | null = null;
48
+
49
+ for (const line of lines) {
50
+ // Array item: starts with "- "
51
+ if (line.match(/^\s+-\s+/)) {
52
+ if (currentArray !== null) {
53
+ currentArray.push(line.replace(/^\s+-\s+/, "").trim());
54
+ }
55
+ continue;
56
+ }
57
+
58
+ // End of array if we were in one
59
+ if (currentArray !== null) {
60
+ meta[currentKey] = currentArray;
61
+ currentArray = null;
62
+ }
63
+
64
+ // Key-value pair
65
+ const kvMatch = line.match(/^(\w+):\s*(.*)$/);
66
+ if (kvMatch) {
67
+ const key = kvMatch[1];
68
+ const value = kvMatch[2].trim();
69
+ // Check if next line starts an array
70
+ if (value === "") {
71
+ currentKey = key;
72
+ currentArray = [];
73
+ } else {
74
+ // Strip quotes if present
75
+ meta[key] = value.replace(/^["']|["']$/g, "");
76
+ }
77
+ }
78
+ }
79
+ // Close any pending array
80
+ if (currentArray !== null) {
81
+ meta[currentKey] = currentArray;
82
+ }
83
+
84
+ return { meta, body: match[2].trim() };
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // Tier loading
89
+ // ---------------------------------------------------------------------------
90
+
91
+ /** Log wording for one tier — the only part of the walk that is family-specific. */
92
+ export interface LoaderMessages {
93
+ /** Warn message for a file skipped by `validate` or `bodyError`. */
94
+ invalid: string;
95
+ /** Warn message for a file that threw while being read, parsed, or mapped. */
96
+ readFailed: string;
97
+ }
98
+
99
+ /** Everything one tier needs: where to scan, how to validate, how to build the record. */
100
+ export interface MarkdownTierSpec<T> {
101
+ /** Directories to scan, in precedence order (first occurrence of a name wins). */
102
+ dirs: readonly string[];
103
+ /** Frontmatter validator; a non-empty result skips the file (one warn per error). */
104
+ validate: (meta: Record<string, unknown>, fileName: string) => string[];
105
+ /** Family-specific record construction from validated frontmatter, body, and name. */
106
+ map: (meta: Record<string, unknown>, body: string, name: string) => T;
107
+ /** Log wording for this tier. */
108
+ messages: LoaderMessages;
109
+ /** Logger for the warn/info lines; omitted → silent. */
110
+ log?: Logger;
111
+ /** Skip a second occurrence of an already-seen name (PROJECT > USER precedence). */
112
+ dedupeByName?: boolean;
113
+ /** Extra skip check after `validate`; a returned error string warns and skips. */
114
+ bodyError?: (meta: Record<string, unknown>, body: string) => string | null;
115
+ /** Called when a directory cannot be read (missing dir). Custom tiers stay silent. */
116
+ onMissingDir?: (dir: string) => void;
117
+ }
118
+
119
+ /**
120
+ * Load every record of one markdown tier: walk `spec.dirs` in order, and for
121
+ * each `.md` file parse frontmatter, validate, check the optional body guard,
122
+ * dedupe by name when asked, then map into the family-specific record.
123
+ *
124
+ * Never throws for a bad file or a missing directory — those are warnings (or
125
+ * silence), matching the four hand-written loaders this replaces.
126
+ */
127
+ export function loadMarkdownRecords<T>(spec: MarkdownTierSpec<T>): T[] {
128
+ const records: T[] = [];
129
+ const seenNames = new Set<string>();
130
+
131
+ for (const dir of spec.dirs) {
132
+ let files: string[];
133
+ try {
134
+ files = fs.readdirSync(dir);
135
+ } catch {
136
+ // Directory doesn't exist or can't be read — no records from this tier.
137
+ spec.onMissingDir?.(dir);
138
+ continue;
139
+ }
140
+
141
+ for (const file of files) {
142
+ if (!file.endsWith(".md")) continue;
143
+
144
+ try {
145
+ const content = fs.readFileSync(path.join(dir, file), "utf-8");
146
+ const { meta, body } = parseFrontmatter(content);
147
+
148
+ const errors = spec.validate(meta, file);
149
+ if (errors.length > 0) {
150
+ for (const err of errors) {
151
+ spec.log?.warn(spec.messages.invalid, { file, error: err });
152
+ }
153
+ continue;
154
+ }
155
+
156
+ const bodyError = spec.bodyError?.(meta, body) ?? null;
157
+ if (bodyError !== null) {
158
+ spec.log?.warn(spec.messages.invalid, { file, error: bodyError });
159
+ continue;
160
+ }
161
+
162
+ // Both validators reject a missing/non-string name, so it is a string here.
163
+ const name = meta.name as string;
164
+ if (spec.dedupeByName) {
165
+ // First occurrence (highest-precedence dir) wins; later ones are skipped.
166
+ if (seenNames.has(name)) continue;
167
+ seenNames.add(name);
168
+ }
169
+
170
+ records.push(spec.map(meta, body, name));
171
+ } catch (err) {
172
+ spec.log?.warn(spec.messages.readFailed, { file, error: (err as Error).message });
173
+ }
174
+ }
175
+ }
176
+
177
+ return records;
178
+ }
@@ -0,0 +1,169 @@
1
+ // Purpose: The batch-mode prologue (cost → depth → resolve → targets → preflight → H1), one call per foreground batch handler.
2
+ /**
3
+ * Batch-mode prologue (issue #379, the D1 cluster).
4
+ *
5
+ * `runChainMode`, `runParallelMode` and `runGraphMode` open with the SAME six
6
+ * gates in the SAME order:
7
+ *
8
+ * [graph only: DAG validation] → cost → depth → resolve params
9
+ * → mode-level target validation → pre-flight → H1
10
+ *
11
+ * That sequence used to be copied into each handler (~110 lines × 3). This
12
+ * module owns it once. The per-mode differences are parameters, not forks:
13
+ *
14
+ * - `label` — the warning/log lead: "Chain" → "Chain delegation" (cost
15
+ * and depth logs), "Chain pre-flight check failed", "Chain
16
+ * pre-task validation warnings/failed";
17
+ * - `units` — the cost estimate's multiplier (IN2: the declared unit
18
+ * count for chain/parallel/graph — never a wave count);
19
+ * - `beforeCost` — graph's DAG validation, the ONE hook that must run before
20
+ * the cost gate (IN1 boundary: a malformed graph is rejected
21
+ * before the session spends anything).
22
+ *
23
+ * Deliberately NOT here:
24
+ *
25
+ * - the per-unit pre-pass (`validateUnitPrePass`, prelude.ts) — each handler
26
+ * CALLS it at its own position, because that position is part of the
27
+ * contract (IN8: chain/parallel before model resolution, graph after the
28
+ * circuit check and the topological sort);
29
+ * - the model tail (`resolveModeModel`, prelude.ts) — same reason: graph
30
+ * resolves the model before its per-node pass, chain/parallel after;
31
+ * - the single foreground path and the two background paths — they are a
32
+ * different gate sequence (design note §2.1; IN1/IN3/IN6), so forcing
33
+ * them through this skeleton would normalise their order.
34
+ *
35
+ * The gate functions are imported from `prelude.ts` (not re-implemented), so
36
+ * the existing suite's call-through wrappers still observe each gate at the
37
+ * same point in the sequence.
38
+ */
39
+
40
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
41
+ import type { ToolResult } from "./types";
42
+ import type { SessionState } from "./state";
43
+ import type { Logger } from "./logging";
44
+ import { resolveSubagentParams, type ResolveInputParams } from "./params";
45
+ import { getCurrentDepth } from "./sanitize";
46
+ import { preflightCheck } from "./preflight";
47
+ import {
48
+ depthLimitRejection,
49
+ gateSessionCost,
50
+ rejection,
51
+ runPreTaskValidation,
52
+ validateDelegationTargets,
53
+ } from "./prelude";
54
+
55
+ /** The params object the shared resolver consumes (`ResolveInputParams`,
56
+ * params.ts) — the same type the background and single paths pass. */
57
+ export interface ModePrologueInput {
58
+ /**
59
+ * `noJev` is carried alongside the resolution inputs rather than inside
60
+ * `ResolveInputParams`: resolution never reads it, but the mode-level H1
61
+ * gate forwards it as the call's stated bypass (issue #412).
62
+ */
63
+ params: ResolveInputParams & { noJev?: string };
64
+ state: SessionState;
65
+ ctx: ExtensionContext;
66
+ log: Logger;
67
+ /** Mode name, used as the warning/log lead: "Chain" | "Parallel" | "Graph". */
68
+ label: string;
69
+ /** Units this dispatch would spawn — the cost estimate's multiplier (IN2). */
70
+ units: number;
71
+ /**
72
+ * Mode-specific validation that MUST run before the cost gate. Graph uses
73
+ * it for `validateGraph`; chain/parallel pass nothing. Returns the
74
+ * rejection to surface, or `undefined` when the mode's precondition holds.
75
+ */
76
+ beforeCost?: () => ToolResult<undefined> | undefined;
77
+ }
78
+
79
+ /** The resolved dispatch the handlers build on (IN4: resolved exactly once). */
80
+ export type ModeGlobalParams = ReturnType<typeof resolveSubagentParams>;
81
+
82
+ export type ModePrologueOutcome =
83
+ | { ok: false; error: ToolResult<undefined> }
84
+ | {
85
+ ok: true;
86
+ globalParams: ModeGlobalParams;
87
+ resolvedCwd: string;
88
+ /** The depth the depth gate measured — every unit spawns at `+ 1`. */
89
+ currentDepth: number;
90
+ };
91
+
92
+ /**
93
+ * Run the batch-mode prologue. Returns the resolved params + validated cwd on
94
+ * success, or the first gate's rejection in the verbatim wording the suites
95
+ * pin. Gate order is the invariant (IN1/IN3/IN4/IN5/IN6/IN7): `beforeCost` →
96
+ * cost → depth → resolve → targets → preflight → H1.
97
+ */
98
+ export function runModePrologue(input: ModePrologueInput): ModePrologueOutcome {
99
+ const { params, state, ctx, log, label, units, beforeCost } = input;
100
+
101
+ // 0. Mode precondition (graph: DAG validation) — before the cost gate.
102
+ const preCost = beforeCost?.();
103
+ if (preCost) return { ok: false, error: preCost };
104
+
105
+ // 1. Session cost gate (R5) — the first gate of every batch mode.
106
+ const costError = gateSessionCost({
107
+ state,
108
+ ctx,
109
+ log,
110
+ units,
111
+ label: `${label} delegation`,
112
+ });
113
+ if (costError) return { ok: false, error: costError };
114
+
115
+ // 2. Recursion depth gate (IN3) — absent from the background paths by
116
+ // design (they spawn in-process SDK sessions, which do not stamp the
117
+ // depth env key); pinning the asymmetry, not "fixing" it here.
118
+ const currentDepth = getCurrentDepth();
119
+ if (currentDepth >= state.config.maxSubagentDepth) {
120
+ log.warn(`${label} delegation rejected: max depth reached`, {
121
+ currentDepth,
122
+ maxDepth: state.config.maxSubagentDepth,
123
+ });
124
+ return {
125
+ ok: false,
126
+ error: depthLimitRejection(currentDepth, state.config.maxSubagentDepth),
127
+ };
128
+ }
129
+
130
+ // 3. Resolve the global params exactly once (IN4).
131
+ const globalParams = resolveSubagentParams(params, state, ctx, log);
132
+
133
+ // 4. Mode-level target validation — cwd only. Every unit's own outputFile
134
+ // is validated by the per-unit pre-pass (IN5); the message bytes are
135
+ // identical to the inline spelling this replaced.
136
+ const targets = validateDelegationTargets({ ctx, effectiveCwd: globalParams.effectiveCwd });
137
+ if (!targets.ok) return { ok: false, error: targets.error };
138
+
139
+ // 5. Pre-flight checks — fail fast before consuming resources (IN6).
140
+ const pfResult = preflightCheck(targets.cwd);
141
+ if (!pfResult.ok) {
142
+ log.warn(`${label} pre-flight check failed`, { error: pfResult.error });
143
+ return { ok: false, error: rejection(`Pre-flight check failed: ${pfResult.error}`) };
144
+ }
145
+
146
+ // 6. H1 at mode entry — mode-level params only, never prefixed and never
147
+ // carrying `force` (IN7). Warnings are logged, not surfaced: the result
148
+ // warnings come from the per-unit passes.
149
+ const preTask = runPreTaskValidation({
150
+ log,
151
+ label,
152
+ preTask: {
153
+ task: globalParams.task,
154
+ toolOptions: globalParams.toolOptions,
155
+ thinkingLevel: globalParams.thinkingLevel,
156
+ gitMode: globalParams.resolvedGitMode,
157
+ outputFile: globalParams.outputFile,
158
+ // Issue #412: the project-local Jev-line check keys on the DISPATCH
159
+ // cwd (the project whose manifest opts in), and `noJev` is the
160
+ // call-level stated bypass — the mode-level task text is the caller's
161
+ // own, so it is checked and bypassable exactly like a single task.
162
+ cwd: targets.cwd,
163
+ noJev: params.noJev,
164
+ },
165
+ });
166
+ if (preTask.error) return { ok: false, error: preTask.error };
167
+
168
+ return { ok: true, globalParams, resolvedCwd: targets.cwd, currentDepth };
169
+ }
@@ -1,4 +1,4 @@
1
- // Purpose: Auth-aware model availability: distinguishes catalog presence from configured provider auth.
1
+ // Purpose: Model identity + auth-aware availability: parse a provider/model-id string and check catalog presence plus configured provider auth.
2
2
  /**
3
3
  * Auth-aware model availability check (issue #4).
4
4
  *
@@ -23,6 +23,18 @@ export interface ModelLike {
23
23
  id: string;
24
24
  }
25
25
 
26
+ /**
27
+ * Parse a `provider/model-id` string. Returns null on anything that is not
28
+ * exactly one non-empty provider and one non-empty id (no provider-only or
29
+ * trailing-slash values).
30
+ */
31
+ export function parseModelString(s: string): { provider: string; id: string } | null {
32
+ const trimmed = s.trim();
33
+ const idx = trimmed.indexOf("/");
34
+ if (idx <= 0 || idx === trimmed.length - 1) return null;
35
+ return { provider: trimmed.slice(0, idx), id: trimmed.slice(idx + 1) };
36
+ }
37
+
26
38
  export interface ProviderAuthStatusLike {
27
39
  configured?: boolean;
28
40
  source?: string;