@yaag/runtime 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent-compaction.ts +1 -1
  3. package/src/agent/agent.ts +1 -1
  4. package/src/agent/define-agent.ts +7 -5
  5. package/src/agent/spawn-open.ts +2 -0
  6. package/src/ask/ask-exchange-events.ts +8 -3
  7. package/src/ask/ask-exchange.ts +6 -9
  8. package/src/catalog/agent-describe-fixture.ts +121 -0
  9. package/src/catalog/agent-describe.ts +210 -0
  10. package/src/catalog/catalog-entry.ts +39 -0
  11. package/src/catalog/catalog-fixture.ts +87 -0
  12. package/src/catalog/catalog-match.ts +77 -0
  13. package/src/catalog/catalog-result.ts +69 -0
  14. package/src/catalog/index.ts +57 -0
  15. package/src/catalog/load-catalog.ts +74 -0
  16. package/src/catalog/program-scan.ts +64 -0
  17. package/src/catalog/registry-paths.ts +26 -0
  18. package/src/catalog/registry-reader.ts +115 -0
  19. package/src/catalog/registry-schema.ts +119 -0
  20. package/src/config/config-paths.ts +14 -7
  21. package/src/config/index.ts +1 -0
  22. package/src/contract/agent-report.ts +42 -0
  23. package/src/contract/error-codes.ts +65 -0
  24. package/src/contract/handle.ts +132 -0
  25. package/src/contract/index.ts +34 -0
  26. package/src/contract/model-spec.ts +81 -0
  27. package/src/contract/spawn-options.ts +127 -0
  28. package/src/error-factories.ts +70 -0
  29. package/src/errors.ts +22 -118
  30. package/src/events.ts +13 -2
  31. package/src/index.ts +45 -0
  32. package/src/model/index.ts +1 -1
  33. package/src/model/model-resolution.ts +19 -71
  34. package/src/model/model-swap.ts +11 -2
  35. package/src/model/resolution-loop.ts +1 -1
  36. package/src/model/thinking-level.ts +5 -5
  37. package/src/public-api.ts +28 -0
  38. package/src/run/run-context.ts +4 -2
  39. package/src/summary/summary-agent.ts +8 -2
  40. package/src/summary/summary-model.ts +5 -1
  41. package/src/transport/live-transport.ts +2 -3
  42. package/src/transport/pi-state.ts +29 -9
  43. package/src/transport/transport.ts +10 -26
  44. package/src/types.ts +16 -243
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yaag/runtime",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -1,4 +1,4 @@
1
- import { agentError } from "../errors.ts";
1
+ import { agentError } from "../error-factories.ts";
2
2
  import type { EventSink } from "../events.ts";
3
3
  import type { AgentTransport, CompactionResult, Connection } from "../transport/index.ts";
4
4
  import { readCompaction } from "../transport/index.ts";
@@ -2,7 +2,7 @@ import type { Static, TSchema } from "typebox";
2
2
  import type { EffectiveAskOptions } from "../ask/index.ts";
3
3
  import { exchangeAsk } from "../ask/index.ts";
4
4
  import { ReportResultTool } from "../ask-contract/index.ts";
5
- import { agentError } from "../errors.ts";
5
+ import { agentError } from "../error-factories.ts";
6
6
  import type { EventSink } from "../events.ts";
7
7
  import type { ModelErrorHistory, ModelResolution } from "../model/index.ts";
8
8
  import type {
@@ -1,15 +1,17 @@
1
- import type { ModelSpec, ThinkingSpec } from "../model/index.ts";
2
- import type { AskOptions } from "../types.ts";
1
+ import type { AskOptions, ModelSpec, ThinkingSpec } from "../contract/index.ts";
3
2
 
4
- export type { ThinkingLevel } from "../types.ts";
3
+ export type { ThinkingLevel } from "../contract/index.ts";
5
4
 
6
5
  /** What `defineAgent` is given: the policy of one Agent, never its topology. */
7
6
  export interface AgentConfig {
8
7
  /** Stable identity, used in every Lifecycle Event and log line. */
9
8
  readonly name: string;
10
- /** System prompt text appended to pi's own, unless `overrideSystemPrompt`. */
9
+ /** Text added after pi's own system prompt, which stays, unless `overrideSystemPrompt`. */
11
10
  readonly prompt?: string;
12
- /** Replace pi's system prompt with `prompt` instead of appending to it. */
11
+ /**
12
+ * Replace pi's system prompt with `prompt` instead of appending to it, which
13
+ * removes pi's own documentation and tool guidance from the Agent.
14
+ */
13
15
  readonly overrideSystemPrompt?: boolean;
14
16
  /**
15
17
  * Model id handed to `pi --model`. Unset = pi's default. An array is an ordered
@@ -151,6 +151,7 @@ export async function openAgent(
151
151
  const resolvedCwd = opened.startup.worktree?.cwd ?? cwd;
152
152
  const branch = opened.startup.worktree?.branch;
153
153
  const sessionFile = opened.startup.sessionFile;
154
+ const thinking = opened.startup.thinking;
154
155
  const agent = new Agent({
155
156
  name,
156
157
  cwd: resolvedCwd,
@@ -176,6 +177,7 @@ export async function openAgent(
176
177
  cwd: resolvedCwd,
177
178
  ...(branch === undefined ? {} : { branch }),
178
179
  ...(sessionFile === undefined ? {} : { sessionFile }),
180
+ ...(thinking === undefined ? {} : { thinking }),
179
181
  ...(parent === undefined ? {} : { parent }),
180
182
  ...(request.fork === undefined ? {} : { origin: "fork" as const }),
181
183
  });
@@ -1,5 +1,5 @@
1
1
  import type { AgentActivity, AskOutputChannel, EventSink } from "../events.ts";
2
- import type { ModelFallback } from "../model/index.ts";
2
+ import type { ModelFallback, ThinkingLevel } from "../model/index.ts";
3
3
  import type { NodeSnapshot } from "../node/index.ts";
4
4
  import { agentAskPath, childPath } from "../node/index.ts";
5
5
  import { promptGist } from "../prompt/index.ts";
@@ -71,8 +71,13 @@ export class AskEvents {
71
71
  * Agent-scoped like `fallback`: the pattern side of the story stays in
72
72
  * `model_fallback`, and this carries pi's own `provider/id`.
73
73
  */
74
- model = (model: string): void => {
75
- this.#emit({ type: "agent_model", agent: this.#agent, model });
74
+ model = (change: { readonly model: string; readonly thinking?: ThinkingLevel }): void => {
75
+ this.#emit({
76
+ type: "agent_model",
77
+ agent: this.#agent,
78
+ model: change.model,
79
+ ...(change.thinking === undefined ? {} : { thinking: change.thinking }),
80
+ });
76
81
  };
77
82
 
78
83
  /** A `normal` cause is the absent default, so ordinary settlements stay lean. */
@@ -9,14 +9,8 @@ import {
9
9
  resolvePlaybackAskOutput,
10
10
  resolvePlaybackReportedResult,
11
11
  } from "../ask-contract/index.ts";
12
- import {
13
- type AskLimitOutcome,
14
- type AskStalledOutcome,
15
- agentError,
16
- askLimitError,
17
- askStalledError,
18
- isYaagError,
19
- } from "../errors.ts";
12
+ import { agentError, askLimitError, askStalledError } from "../error-factories.ts";
13
+ import { type AskLimitOutcome, type AskStalledOutcome, isYaagError } from "../errors.ts";
20
14
  import { retryOnModelFailure, swapModel } from "../model/index.ts";
21
15
  import { NodeTracker } from "../node/index.ts";
22
16
  import type { AskPlayback } from "../transport/index.ts";
@@ -114,7 +108,10 @@ class AskExchange {
114
108
  fallback.onSwapped(selection.model ?? swapped.model, swapped.model);
115
109
  // Only a swap that landed reports a model: a refused `set_model` throws
116
110
  // above and re-enters the loop, so the loop itself stays event-free.
117
- this.#events.model(swapped.model);
111
+ this.#events.model({
112
+ model: swapped.model,
113
+ ...(swapped.thinking === undefined ? {} : { thinking: swapped.thinking }),
114
+ });
118
115
  },
119
116
  });
120
117
  }
@@ -0,0 +1,121 @@
1
+ import {
2
+ type AgentDescribeRequest,
3
+ type AgentDescribeResult,
4
+ agentDescribeArgv,
5
+ describedAgent,
6
+ encodeAgentDescribe,
7
+ } from "./agent-describe.ts";
8
+
9
+ /** One recorded describe exchange with the CLI child (ADR-0047). */
10
+ export interface AgentDescribeTranscriptEntry {
11
+ /** Names the case, so a consumer test can pick one by intent. */
12
+ readonly label: "healthy" | "deviates" | "export-not-found" | "module-threw" | "not-a-definition";
13
+ readonly argv: readonly string[];
14
+ /** Always `0`: a finding is a payload, not a failure. */
15
+ readonly code: 0;
16
+ readonly stdout: string;
17
+ /** Always empty, for the same reason. */
18
+ readonly stderr: "";
19
+ }
20
+
21
+ const HEALTHY_FILE = "/repo/programs/agents/reviewer.ts";
22
+ const RENAMED_FILE = "/repo/programs/agents/renamed.ts";
23
+
24
+ function record(
25
+ label: AgentDescribeTranscriptEntry["label"],
26
+ request: AgentDescribeRequest,
27
+ result: AgentDescribeResult,
28
+ ): AgentDescribeTranscriptEntry {
29
+ return {
30
+ label,
31
+ argv: agentDescribeArgv(request),
32
+ code: 0,
33
+ stdout: encodeAgentDescribe(result),
34
+ stderr: "",
35
+ };
36
+ }
37
+
38
+ /**
39
+ * The recorded CLI-child transcript every describe consumer test asserts
40
+ * against. Each `argv` comes from `agentDescribeArgv` and each `stdout` from
41
+ * `encodeAgentDescribe`, so the fixture cannot state a wire form the real
42
+ * emitter does not produce. Only the payload objects are literals.
43
+ *
44
+ * This is a seam, not a verified reader: ticket 07 owns the test that
45
+ * pins the real loader's output against these payloads, the way
46
+ * `catalog-contract.test.ts` pins `CATALOG_FIXTURE` against `loadCatalog`.
47
+ */
48
+ export const AGENT_DESCRIBE_TRANSCRIPT: readonly AgentDescribeTranscriptEntry[] = deepFreeze([
49
+ record(
50
+ "healthy",
51
+ { file: HEALTHY_FILE, exportName: "reviewer", registeredName: "reviewer" },
52
+ describedAgent({
53
+ file: HEALTHY_FILE,
54
+ exportName: "reviewer",
55
+ declared: { name: "reviewer" },
56
+ registeredName: "reviewer",
57
+ }),
58
+ ),
59
+ record(
60
+ "deviates",
61
+ { file: RENAMED_FILE, exportName: "reviewer", registeredName: "reviewer" },
62
+ describedAgent({
63
+ file: RENAMED_FILE,
64
+ exportName: "reviewer",
65
+ declared: { name: "code-reviewer" },
66
+ registeredName: "reviewer",
67
+ }),
68
+ ),
69
+ record(
70
+ "export-not-found",
71
+ { file: "/repo/programs/agents/archivist.ts", exportName: "archivist" },
72
+ {
73
+ outcome: "finding",
74
+ file: "/repo/programs/agents/archivist.ts",
75
+ exportName: "archivist",
76
+ finding: {
77
+ code: "EXPORT_NOT_FOUND",
78
+ detail: 'the module exports no "archivist"',
79
+ },
80
+ },
81
+ ),
82
+ record(
83
+ "module-threw",
84
+ { file: "/repo/programs/agents/exploder.ts", exportName: "exploder" },
85
+ {
86
+ outcome: "finding",
87
+ file: "/repo/programs/agents/exploder.ts",
88
+ exportName: "exploder",
89
+ finding: {
90
+ code: "MODULE_IMPORT_THREW",
91
+ detail: "Cannot find module './missing.ts'",
92
+ },
93
+ },
94
+ ),
95
+ record(
96
+ "not-a-definition",
97
+ { file: "/repo/programs/agents/helpers.ts", exportName: "notAnAgent" },
98
+ {
99
+ outcome: "finding",
100
+ file: "/repo/programs/agents/helpers.ts",
101
+ exportName: "notAnAgent",
102
+ finding: {
103
+ code: "NOT_AN_AGENT_DEFINITION",
104
+ detail: "the export is not a value that defineAgent produced",
105
+ },
106
+ },
107
+ ),
108
+ ]);
109
+
110
+ /** Looks a recorded exchange up by the argv a fake child was called with. */
111
+ export function transcriptFor(argv: readonly string[]): AgentDescribeTranscriptEntry | undefined {
112
+ return AGENT_DESCRIBE_TRANSCRIPT.find(
113
+ (entry) => entry.argv.length === argv.length && entry.argv.every((arg, i) => arg === argv[i]),
114
+ );
115
+ }
116
+
117
+ function deepFreeze<T>(value: T): T {
118
+ if (typeof value !== "object" || value === null) return value;
119
+ for (const item of Object.values(value)) deepFreeze(item);
120
+ return Object.freeze(value);
121
+ }
@@ -0,0 +1,210 @@
1
+ /**
2
+ * The frozen contract for describing one registered Agent Definition
3
+ * (ADR-0047). It is pure: it builds argv, encodes one JSON line, and reads one
4
+ * JSON line back. It imports no Orchestration Program module and touches no
5
+ * file.
6
+ *
7
+ * **Process boundary.** Verification always runs in a CLI child (ADR-0005).
8
+ * The extension never imports a user module in its own process. A describe of
9
+ * a Definition is opt-in and on demand; listing the Catalog never starts one
10
+ * (ADR-0046).
11
+ *
12
+ * **Default behaviour does not change.** Without an `exportName` the describe
13
+ * surfaces still emit the Orchestration Program shape `{ name, description,
14
+ * args }`. The two shapes are separate documents, and nothing merges them.
15
+ *
16
+ * **A finding is not a failure.** The child exits `0` for each of the three
17
+ * finding codes. A non-zero exit stays reserved for a real CLI failure, such
18
+ * as bad argv, which exits 2.
19
+ *
20
+ * **`deviates` semantics.** The field is present only when the module's
21
+ * declared `name` differs from the Registry File entry's `name`. It is absent
22
+ * when the two names are equal, and absent when the caller supplied no
23
+ * `registeredName`. It carries both values and states no verdict. Every
24
+ * synonym on the *Divergence* avoid list of `CONTEXT.md` is banned here, so
25
+ * this contract says *deviates* and *name deviation*.
26
+ *
27
+ * **Metadata is `name`-only today**, because `AgentConfig` declares no
28
+ * `description` and no `tags`. Adding them is the follow-up ADR-0046 defers,
29
+ * and `AgentDeclaredMetadata` is where they land.
30
+ */
31
+
32
+ /** What a describe of a registered Agent Definition is asked for. */
33
+ export interface AgentDescribeRequest {
34
+ /** Module path, already resolved by the caller. */
35
+ readonly file: string;
36
+ /** The named export to inspect. */
37
+ readonly exportName: string;
38
+ /** The Registry File entry's name, when the caller has one. Absent = no name comparison. */
39
+ readonly registeredName?: string;
40
+ }
41
+
42
+ /** The Definition's real declared metadata. */
43
+ export interface AgentDeclaredMetadata {
44
+ readonly name: string;
45
+ }
46
+
47
+ /**
48
+ * A name deviation: the module's declared name differs from the Registry File
49
+ * entry's name. Both values ride along, and the reader decides which one is
50
+ * wrong.
51
+ */
52
+ export interface NameDeviation {
53
+ /** What the module's `defineAgent({ name })` says. */
54
+ readonly declared: string;
55
+ /** What the Registry File entry says. */
56
+ readonly registered: string;
57
+ }
58
+
59
+ /** Entry-level findings. A finding is never a tool failure and never a Run failure. */
60
+ export type AgentDescribeFindingCode =
61
+ | "EXPORT_NOT_FOUND"
62
+ | "MODULE_IMPORT_THREW"
63
+ | "NOT_AN_AGENT_DEFINITION";
64
+
65
+ export interface AgentDescribeFinding {
66
+ readonly code: AgentDescribeFindingCode;
67
+ /**
68
+ * One sanitized line. For `MODULE_IMPORT_THREW` it is the thrown message:
69
+ * the caller trims it to one line and drops the stack, because a raw
70
+ * `Error.stack` must not reach a model.
71
+ */
72
+ readonly detail: string;
73
+ }
74
+
75
+ /** The `described` branch: the Definition was imported and read. */
76
+ export interface DescribedAgent {
77
+ readonly outcome: "described";
78
+ readonly file: string;
79
+ readonly exportName: string;
80
+ readonly declared: AgentDeclaredMetadata;
81
+ readonly deviates?: NameDeviation;
82
+ }
83
+
84
+ /** The `finding` branch: the Definition could not be read, and why. */
85
+ export interface AgentDescribeFindingResult {
86
+ readonly outcome: "finding";
87
+ readonly file: string;
88
+ readonly exportName: string;
89
+ readonly finding: AgentDescribeFinding;
90
+ }
91
+
92
+ /** A described Definition, or one finding. Never both. */
93
+ export type AgentDescribeResult = DescribedAgent | AgentDescribeFindingResult;
94
+
95
+ /** The three finding codes, in declaration order. */
96
+ export const AGENT_DESCRIBE_FINDING_CODES: readonly AgentDescribeFindingCode[] = Object.freeze([
97
+ "EXPORT_NOT_FOUND",
98
+ "MODULE_IMPORT_THREW",
99
+ "NOT_AN_AGENT_DEFINITION",
100
+ ] as const);
101
+
102
+ /**
103
+ * The argv a caller gives the CLI child. The flag names are part of the frozen
104
+ * contract, so the argv builder and the argv parser cannot disagree.
105
+ */
106
+ export function agentDescribeArgv(request: AgentDescribeRequest): readonly string[] {
107
+ const argv = ["describe", request.file, "--export", request.exportName];
108
+ if (request.registeredName !== undefined) {
109
+ argv.push("--registered-name", request.registeredName);
110
+ }
111
+ return argv;
112
+ }
113
+
114
+ /**
115
+ * Builds a described result, and adds `deviates` only when the declared name
116
+ * and the registered name differ.
117
+ */
118
+ export function describedAgent(args: {
119
+ readonly file: string;
120
+ readonly exportName: string;
121
+ readonly declared: AgentDeclaredMetadata;
122
+ readonly registeredName?: string;
123
+ }): DescribedAgent {
124
+ const registered = args.registeredName;
125
+ const deviation =
126
+ registered !== undefined && registered !== args.declared.name
127
+ ? { deviates: { declared: args.declared.name, registered } }
128
+ : {};
129
+ return {
130
+ outcome: "described",
131
+ file: args.file,
132
+ exportName: args.exportName,
133
+ declared: args.declared,
134
+ ...deviation,
135
+ };
136
+ }
137
+
138
+ /** One JSON line plus `\n` — the exact bytes the child writes on stdout. */
139
+ export function encodeAgentDescribe(result: AgentDescribeResult): string {
140
+ return `${JSON.stringify(result)}\n`;
141
+ }
142
+
143
+ /**
144
+ * Narrows child stdout back to the contract.
145
+ *
146
+ * Throws `TypeError` when the text is not one JSON object of this shape.
147
+ */
148
+ export function parseAgentDescribe(stdout: string): AgentDescribeResult {
149
+ const value: unknown = parseJson(stdout);
150
+ if (isDescribedAgent(value) || isFindingResult(value)) return value;
151
+ throw new TypeError(`malformed agent describe: ${stdout.slice(0, 120)}`);
152
+ }
153
+
154
+ function parseJson(stdout: string): unknown {
155
+ try {
156
+ return JSON.parse(stdout) as unknown;
157
+ } catch {
158
+ throw new TypeError(`malformed agent describe: ${stdout.slice(0, 120)}`);
159
+ }
160
+ }
161
+
162
+ const FINDING_CODES: ReadonlySet<string> = new Set(AGENT_DESCRIBE_FINDING_CODES);
163
+
164
+ type DescribeEnvelope = { readonly file: string; readonly exportName: string };
165
+
166
+ function isEnvelope(value: unknown): value is DescribeEnvelope {
167
+ return (
168
+ typeof value === "object" &&
169
+ value !== null &&
170
+ !Array.isArray(value) &&
171
+ typeof Reflect.get(value, "file") === "string" &&
172
+ typeof Reflect.get(value, "exportName") === "string"
173
+ );
174
+ }
175
+
176
+ function isDescribedAgent(value: unknown): value is DescribedAgent {
177
+ if (!isEnvelope(value) || Reflect.get(value, "outcome") !== "described") return false;
178
+ return isDeclared(Reflect.get(value, "declared")) && isDeviation(Reflect.get(value, "deviates"));
179
+ }
180
+
181
+ function isFindingResult(value: unknown): value is AgentDescribeFindingResult {
182
+ if (!isEnvelope(value) || Reflect.get(value, "outcome") !== "finding") return false;
183
+ return isFinding(Reflect.get(value, "finding"));
184
+ }
185
+
186
+ function isDeclared(value: unknown): value is AgentDeclaredMetadata {
187
+ return (
188
+ typeof value === "object" && value !== null && typeof Reflect.get(value, "name") === "string"
189
+ );
190
+ }
191
+
192
+ function isDeviation(value: unknown): value is NameDeviation | undefined {
193
+ if (value === undefined) return true;
194
+ return (
195
+ typeof value === "object" &&
196
+ value !== null &&
197
+ typeof Reflect.get(value, "declared") === "string" &&
198
+ typeof Reflect.get(value, "registered") === "string"
199
+ );
200
+ }
201
+
202
+ function isFinding(value: unknown): value is AgentDescribeFinding {
203
+ if (typeof value !== "object" || value === null) return false;
204
+ const code: unknown = Reflect.get(value, "code");
205
+ return (
206
+ typeof code === "string" &&
207
+ FINDING_CODES.has(code) &&
208
+ typeof Reflect.get(value, "detail") === "string"
209
+ );
210
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The declared shape of a Catalog registry file. Types only: parsing lives in
3
+ * `registry-schema.ts` and reading files is not part of this module.
4
+ */
5
+
6
+ /**
7
+ * One registered Agent Definition — the only kind a registry file names
8
+ * (ADR-0046, the registration exception to ADR-0019).
9
+ *
10
+ * `file` resolves relative to the directory of the declaring registry file,
11
+ * never to the current working directory. Only `name` is verifiable against
12
+ * the module: `description` and `tags` are curated search metadata.
13
+ */
14
+ export interface AgentDefinitionEntry {
15
+ readonly file: string;
16
+ readonly exportName: string;
17
+ readonly name: string;
18
+ readonly description?: string;
19
+ readonly tags?: readonly string[];
20
+ }
21
+
22
+ /**
23
+ * The document one `registry.json` holds. The schema is lenient on purpose: an
24
+ * unknown key is preserved by the file and ignored by the parser, so an older
25
+ * yaag still reads a newer registry file.
26
+ */
27
+ export interface RegistryDocument {
28
+ readonly agents?: readonly AgentDefinitionEntry[];
29
+ }
30
+
31
+ /** Which layer a Catalog row came from. A `dir` query never matches `global`. */
32
+ export type CatalogLayer = "global" | "project";
33
+
34
+ /** Where a Catalog row came from, for disambiguating duplicate names. */
35
+ export interface CatalogSource {
36
+ readonly layer: CatalogLayer;
37
+ /** The declaring registry file (agents) or the Program Directory (programs). */
38
+ readonly origin: string;
39
+ }
@@ -0,0 +1,87 @@
1
+ import type { CatalogResult, CatalogRow } from "./catalog-result.ts";
2
+ import { parseRegistryFile } from "./registry-schema.ts";
3
+
4
+ /** The unreadable second registry file the fixture reports. */
5
+ const BROKEN_REGISTRY_FILE = "/repo/other/.yaag/registry.json";
6
+
7
+ /**
8
+ * The five contract cases. The order here is the order the cases were written,
9
+ * not the order a reader produces: `CatalogResult` states the global layer
10
+ * first, then the Program Directories in sorted order.
11
+ *
12
+ * A scanned program row carries no `description`: a program states its
13
+ * description inside `defineRun(...)`, and ADR-0046 forbids the import at list
14
+ * time. An agent row with a path states the stat the reader ran, so
15
+ * `fileMissing: false` means "checked and present", not "not checked".
16
+ */
17
+ const ROWS: readonly CatalogRow[] = [
18
+ {
19
+ kind: "program",
20
+ name: "review",
21
+ path: "/repo/programs/review.ts",
22
+ source: { layer: "project", origin: "/repo/programs" },
23
+ },
24
+ {
25
+ kind: "agent",
26
+ name: "reviewer",
27
+ description: "Reviews code quality",
28
+ tags: ["review", "quality"],
29
+ path: "/repo/programs/agents/reviewer.ts",
30
+ exportName: "reviewer",
31
+ source: { layer: "project", origin: "/repo/programs/.yaag/registry.json" },
32
+ fileMissing: false,
33
+ },
34
+ {
35
+ kind: "agent",
36
+ name: "archivist",
37
+ path: "/repo/programs/agents/archivist.ts",
38
+ exportName: "archivist",
39
+ source: { layer: "project", origin: "/repo/programs/.yaag/registry.json" },
40
+ fileMissing: true,
41
+ },
42
+ {
43
+ kind: "agent",
44
+ name: "reviewer",
45
+ description: "The global reviewer",
46
+ path: "/home/u/.config/yaag/agents/reviewer.ts",
47
+ exportName: "reviewer",
48
+ source: { layer: "global", origin: "/home/u/.config/yaag/registry.json" },
49
+ fileMissing: false,
50
+ },
51
+ {
52
+ kind: "agent",
53
+ name: "",
54
+ path: "",
55
+ exportName: "",
56
+ source: { layer: "project", origin: "/repo/programs/.yaag/registry.json" },
57
+ diagnostics: [
58
+ {
59
+ scope: "entry",
60
+ index: 2,
61
+ message: '$: must have required property "name"',
62
+ },
63
+ ],
64
+ },
65
+ ];
66
+
67
+ /**
68
+ * The in-memory Catalog every consumer test asserts against. Construction is
69
+ * pure and the result is deep-frozen, so a consumer cannot change the contract
70
+ * by accident. It holds five rows — a healthy program with no description, a
71
+ * healthy agent, an
72
+ * agent whose file is missing, a duplicate name across layers, and an entry
73
+ * that carries a diagnostic but is still listed — plus one file-scoped
74
+ * diagnostic whose message form is what `parseRegistryFile` emits.
75
+ */
76
+ export const CATALOG_FIXTURE: CatalogResult = deepFreeze({
77
+ rows: ROWS,
78
+ // Produced by the parser itself, so the fixture can never state a message
79
+ // form the real parser does not emit.
80
+ diagnostics: parseRegistryFile("{ not json", BROKEN_REGISTRY_FILE).diagnostics,
81
+ });
82
+
83
+ function deepFreeze<T>(value: T): T {
84
+ if (typeof value !== "object" || value === null) return value;
85
+ for (const item of Object.values(value)) deepFreeze(item);
86
+ return Object.freeze(value);
87
+ }
@@ -0,0 +1,77 @@
1
+ import { resolve } from "node:path";
2
+ import { PROJECT_CONFIG_DIR } from "../config/index.ts";
3
+ import type { CatalogQuery, CatalogRow } from "./catalog-result.ts";
4
+
5
+ /**
6
+ * Matches one row against a substring or glob pattern — never a regex. An
7
+ * absent, empty, or whitespace-only pattern matches everything. The haystack
8
+ * fields are tested independently: `name`, `description`, each tag, `path`,
9
+ * and `exportName`. Matching is case-insensitive.
10
+ *
11
+ * A pattern that contains `*` or `?` is a glob anchored per field (`*` is any
12
+ * run including empty, `?` is exactly one character). Every other character is
13
+ * escaped first, so a caller can never inject a regex.
14
+ */
15
+ export function matchesPattern(row: CatalogRow, pattern: string | undefined): boolean {
16
+ if (pattern === undefined || pattern.trim() === "") return true;
17
+ const needle = pattern.toLowerCase();
18
+ const fields = [row.name, row.description, row.path, row.exportName, ...(row.tags ?? [])];
19
+ const test = isGlob(needle) ? globTest(needle) : (field: string) => field.includes(needle);
20
+ return fields.some((field) => field !== undefined && test(field.toLowerCase()));
21
+ }
22
+
23
+ /**
24
+ * Applies `kind`, `dir`, and `pattern`. Preserves input order and duplicates,
25
+ * and never drops a row because it carries a diagnostic.
26
+ */
27
+ export function filterCatalog(
28
+ rows: readonly CatalogRow[],
29
+ query: CatalogQuery,
30
+ ): readonly CatalogRow[] {
31
+ return rows.filter(
32
+ (row) =>
33
+ (query.kind === undefined || row.kind === query.kind) &&
34
+ matchesDirectory(row, query.dir) &&
35
+ matchesPattern(row, query.pattern),
36
+ );
37
+ }
38
+
39
+ /**
40
+ * A `dir` query names one Program Directory. It matches a program by its
41
+ * origin and an agent by the Program Directory that owns the declaring
42
+ * registry file. It never matches a global row.
43
+ */
44
+ function matchesDirectory(row: CatalogRow, dir: string | undefined): boolean {
45
+ if (dir === undefined || dir === "") return true;
46
+ if (row.source.layer === "global") return false;
47
+ return programDirectoryOf(row.source.origin) === resolve(dir);
48
+ }
49
+
50
+ function programDirectoryOf(origin: string): string {
51
+ const absolute = resolve(origin);
52
+ const suffix = `/${PROJECT_CONFIG_DIR}/`;
53
+ const marker = absolute.lastIndexOf(suffix);
54
+ return marker === -1 ? absolute : absolute.slice(0, marker);
55
+ }
56
+
57
+ function isGlob(pattern: string): boolean {
58
+ return pattern.includes("*") || pattern.includes("?");
59
+ }
60
+
61
+ /**
62
+ * Builds the anchored expression of one glob in a single pass: a wildcard
63
+ * becomes its expression, and every other character is escaped. A second pass
64
+ * would turn an escaped literal, such as a backslash before a star, back into
65
+ * a wildcard.
66
+ */
67
+ function globTest(pattern: string): (field: string) => boolean {
68
+ const source = Array.from(pattern)
69
+ .map((character) => {
70
+ if (character === "*") return ".*";
71
+ if (character === "?") return ".";
72
+ return character.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
73
+ })
74
+ .join("");
75
+ const expression = new RegExp(`^${source}$`);
76
+ return (field) => expression.test(field);
77
+ }