pi-lean-host 0.2.1 → 0.3.1

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.
@@ -1,10 +1,16 @@
1
1
  /**
2
2
  * api-learn tool definition.
3
3
  *
4
- * Validates and writes an API guide recipe.
5
- * - `{domain, recipe}` → validates via `parseApiGuide()`, writes to
4
+ * Authoring entry points:
5
+ * - `{domain, new: true}` → fresh template with `domains: [<domain>]`
6
+ * pre-filled (regardless of existing guides).
7
+ * - `{domain}` (no recipeFile) → fetch the current raw recipe of an existing
8
+ * guide (0 guides → template; 1 guide → raw recipe + dirName surfaced;
9
+ * N guides → disambiguation menu by shortName), staged to
10
+ * `/tmp/pi-lean-host/<domain>/guide.md`.
11
+ * - `{domain, recipeFile}` → reads the staged draft, validates via
12
+ * `parseApiGuide()`, writes to
6
13
  * `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`.
7
- * - No `domain` → returns the worked-example recipe for authoring.
8
14
  *
9
15
  * No half-write on validation error (validate first, write only on success).
10
16
  * Defaults are filled by the validator before writing.
@@ -12,13 +18,28 @@
12
18
  * Mirrors portal's `web-learn`.
13
19
  */
14
20
 
15
- import { defineTool } from "@earendil-works/pi-coding-agent";
21
+ import {
22
+ defineTool,
23
+ type AgentToolResult,
24
+ } from "@earendil-works/pi-coding-agent";
16
25
  import { Type } from "@earendil-works/pi-ai";
17
26
  import { Text } from "@earendil-works/pi-tui";
18
27
  import { appendFooter, contentText } from "./utils.js";
19
- import { mkdirSync, writeFileSync } from "node:fs";
28
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
29
+ import { tmpdir } from "node:os";
20
30
  import { join } from "node:path";
21
- import { parseApiGuide } from "../core/parse-api-guide.js";
31
+ import {
32
+ parseApiGuide,
33
+ stampFrontmatterField,
34
+ formatGuideListings,
35
+ selectGuideByShortName,
36
+ shortNameErrorText,
37
+ } from "../core/parse-api-guide.js";
38
+ import {
39
+ GUIDE_SCHEMA_VERSION,
40
+ type ApiGuide,
41
+ type AuthConfig,
42
+ } from "../core/api-guide-types.js";
22
43
  import {
23
44
  invalidateCache,
24
45
  getUserGuidesDir,
@@ -27,69 +48,257 @@ import {
27
48
  import { assertSafeDomain } from "../core/path-template.js";
28
49
 
29
50
  // ═══════════════════════════════════════════════════════════════════
30
- // Worked example
51
+ // Staged working copy (/tmp) — the draft the agent edits between saves
52
+ // ═══════════════════════════════════════════════════════════════════
53
+
54
+ let _stagingRoot = join(tmpdir(), "pi-lean-host");
55
+
56
+ /** Test override — mirrors `setUserGuidesDir` so tests keep drafts out of
57
+ * the real /tmp root. */
58
+ export function setStagingRoot(dir: string): void {
59
+ _stagingRoot = dir;
60
+ }
61
+
62
+ /** Deterministic draft path: `<root>/<domain>/guide.md`. */
63
+ function stagingPathFor(domain: string): string {
64
+ return join(_stagingRoot, domain, "guide.md");
65
+ }
66
+
67
+ /** Write the working copy (template or fetched raw recipe) to the staging
68
+ * path. Returns the path. */
69
+ function writeStagedDraft(domain: string, raw: string): string {
70
+ const path = stagingPathFor(domain);
71
+ mkdirSync(join(_stagingRoot, domain), { recursive: true });
72
+ writeFileSync(path, raw, "utf-8");
73
+ return path;
74
+ }
75
+
76
+ // ═══════════════════════════════════════════════════════════════════
77
+ // Placeholder skeleton (retired worked example)
31
78
  // ═══════════════════════════════════════════════════════════════════
32
79
 
33
80
  /** Max length for `description:` enforced on the write path (strict-on-write,
34
81
  * lenient-on-read — the loader accepts any length). One-liner, not prose. */
35
82
  const DESCRIPTION_MAX = 200;
36
83
 
37
- const WORKED_EXAMPLE = `---
84
+ /** Commented static-key auth block — the issue-#5 auth-wiring teaching,
85
+ * API-agnostic, kept after the worked example retired. */
86
+ const STATIC_KEY_BLOCK = ` # Keyed API? Use kind: static-key — values live in the secrets store (/api secrets), never in the recipe:
87
+ # kind: static-key
88
+ # requires: [<secret-name>]
89
+ # secretRefs:
90
+ # Authorization: <secret-name> # header name → secret name (must match the name provisioned via /api secrets)
91
+ # headerPrefixes:
92
+ # Authorization: "Bearer "`;
93
+
94
+ /** Placeholder starter template — only `domains:` is real (the requested
95
+ * domain). Every other field is a placeholder the agent fills (op blocks
96
+ * sourced from api-probe({apiHost, path})). Fails closed: an unsaved,
97
+ * as-is template is rejected by the parser because `apiHost: <base url>`
98
+ * is not a valid URL — no wrong-API guide can be saved silently. */
99
+ function placeholderSkeleton(domain: string): string {
100
+ return `---
38
101
  kind: api
39
- domains: [boe.es, www.boe.es]
40
- organization: boe.es # optional — org identity across guides (registrable domain)
41
- description: Spanish official gazette legislation API. # optional — one-line summary; aids disambiguation
42
- icon: ⚖️
43
- shortName: BOE
44
- updated: 2026-07-15
45
- apiHost: https://apidatos.boe.es/v1
46
- verified: 2026-07-15
47
- docs: https://www.boe.es/datosabiertos/api/api.php
48
- gatherAllMax: 500
102
+ domains: [${domain}]
103
+ organization: <org> # optional — org identity across guides (registrable domain)
104
+ description: <one-line summary> # optional — one-line summary; aids disambiguation
105
+ icon: <emoji>
106
+ shortName: <short>
107
+ # updated / verified are stamped by the tool when omitted (defaults to today)
108
+ apiHost: <base url> # REQUIRED — base URL. Version in apiHost XOR in each path — never both (/v3/v3/items → 404)
109
+ # docs: <api docs url> # optional — API documentation URL
110
+ gatherAllMax: 1000 # omitted → 1000
49
111
 
50
112
  auth:
51
113
  kind: none
114
+ ${STATIC_KEY_BLOCK}
52
115
 
53
116
  pagination:
54
117
  style: offset-limit
55
118
  pageParam: page
56
119
  pageSizeParam: limit
57
120
  pageSize: 50
58
- itemsPath: data
121
+ itemsPath: results
59
122
 
60
123
  responseShape:
61
124
  format: json
62
125
  charset: utf-8
63
126
 
64
- operations:
65
- - name: searchDiary
66
- via: restGet
67
- path: /diario/{date}
68
- accept: json
69
- dateParams: # normalize a date QUERY param before sending (path tokens aren't reached by dateParams)
70
- since: yyyy-mm-dd
71
- params:
72
- date: # docs-only — describes the {date} path token; never a query param
73
- description: Diary date in yyyy-mm-dd form (e.g. 2026-07-15).
74
- since:
75
- description: Lower-bound publication date; ISO YYYY-MM-DD auto-converted to yyyy-mm-dd.
76
- limit:
77
- default: 50
78
- parse:
79
- format: xml
80
- charset: iso-8859-1
81
-
82
- - name: listConsolidada
83
- via: paginate
84
- path: /legislacion-consolidada
85
- accept: json
86
- pagination:
87
- style: cursor
88
- cursorParam: cursor
89
- cursorPath: pagination.nextCursor
90
- itemsPath: results
127
+ # Add one operation per endpoint here — source the block from
128
+ # api-probe({apiHost, path}) (it drafts real ops with real values):
129
+ # operations:
130
+ # - name: <op>
131
+ # via: restGet
132
+ # path: /<path>
133
+ # accept: json
134
+ # # requiresAnyOf: [id, slug, code] # at least one of these params must be supplied
135
+ # params:
136
+ # id:
137
+ # description: <what id selects>
91
138
  ---
139
+
140
+ # Optional agent-instruction prose goes AFTER the closing --- and is surfaced
141
+ # to the reading agent (as "Guide notes" via api-guide): date formats, auth
142
+ # caveats, field semantics, endpoint quirks. Delete this note before saving.
92
143
  `;
144
+ }
145
+
146
+ /** Save-summary auth line — names the header→secret mapping (names only,
147
+ * never values: values live in the store). e.g.
148
+ * `static-key · Authorization ← secret apiKey (Bearer )`. */
149
+ function authSummary(auth: AuthConfig): string {
150
+ const parts: string[] = [];
151
+ for (const [header, secretName] of Object.entries(auth.secretRefs ?? {})) {
152
+ const prefix = auth.headerPrefixes?.[header];
153
+ parts.push(
154
+ `${header} ← secret ${secretName}${prefix === undefined ? "" : ` (${prefix})`}`,
155
+ );
156
+ }
157
+ for (const [param, secretName] of Object.entries(auth.secretQueryRefs ?? {})) {
158
+ parts.push(`?${param} ← secret ${secretName}`);
159
+ }
160
+ return parts.length === 0
161
+ ? `Auth: ${auth.kind}`
162
+ : `Auth: ${auth.kind} · ${parts.join(", ")}`;
163
+ }
164
+
165
+ // ═══════════════════════════════════════════════════════════════════
166
+ // Authoring manual + templates
167
+ // ═══════════════════════════════════════════════════════════════════
168
+
169
+ /** The field reference + defaults + semantics manual. Travels with the
170
+ * pull-to-/tmp action — prepended to every staged draft (template or
171
+ * fetched recipe) so the author sees it at the moment of authoring. */
172
+ const AUTHORING_MANUAL = [
173
+ "# API guide authoring manual",
174
+ "",
175
+ "💡 Start a new guide: call api-learn({domain: '<domain>', new: true}) — it returns a ",
176
+ " template with `domains` pre-filled. Discover the API's shape first with ",
177
+ " api-probe({apiHost, path}) — it drafts a YAML operation block ",
178
+ " to paste into the template.",
179
+ "",
180
+ "## Required fields",
181
+ ` \`domains\` — list of domain names this guide applies to`,
182
+ ` \`apiHost\` — base URL. Version in apiHost XOR in each path — never both (see Key defaults)`,
183
+ ` \`operations\` — a LIST of operation mappings — at least one entry`,
184
+ ` \`operations[].name\` — unique operation name`,
185
+ ` \`operations[].via\` — "restGet" or "paginate"`,
186
+ ` \`operations[].path\` — path starting with /`,
187
+ "",
188
+ "## Key defaults",
189
+ ` \`apiHost\` — base URL. \`path\` is always resolved relative to it — \`joinUrl\` strips a leading \`/\`, so \`/items\` + \`apiHost: https://host/v3\` → \`https://host/v3/items\`. Keep the version in \`apiHost\` (e.g. \`https://api.example.com/v3\`) or leave it bare with the version in each \`path\` — pick one per guide; both at once doubles the segment (\`/v3/v3/items\` → 404)`,
190
+ ` \`auth\` — omitted → kind: none`,
191
+ ` \`verified\` — omitted → today's date`,
192
+ ` \`docs\` — optional API documentation URL (http/https); omitted → no docs line`,
193
+ ` \`gatherAllMax\` — omitted → 1000`,
194
+ ` \`responseShape\` — omitted → json/utf-8`,
195
+ ` \`operation.accept\` — omitted → json`,
196
+ "",
197
+ "## Optional fields (multi-recipe disambiguation)",
198
+ ` \`organization\` — org identity across guides (use the org's registrable domain, e.g. archive.org)`,
199
+ ` \`description\` — one-line API summary (≤${DESCRIPTION_MAX} chars); the primary signal when several guides share a domain`,
200
+ "",
201
+ "## Optional fields (operation-level)",
202
+ ` \`dateParams\` — normalize date QUERY params before sending: map name → iso8601 | yyyymmdd | yyyy-mm-dd (path tokens are documented via params.<token>.description; core dateParams does not reach path tokens)`,
203
+ ` \`helper\` — true → call this domain's local helper.ts for this op`,
204
+ ` \`transform\` — true → run the helper.ts \`transform\` export on the parsed response`,
205
+ ` \`params.<token>.description\` — docs-only description for a {token} path param (format, e.g. 'yyyy-mm-dd'); never sent as a query param, shown in api-guide`,
206
+ ` \`params.<name>.required\` — true → query param must be supplied (verify skips the op if missing; api-fetch errors before the request)`,
207
+ ` \`params.<name>.default\` — value (any YAML scalar: string, number, boolean) used when the caller omits the param (verify runs the op with it; a \`required\`+\`default\` op is always verifiable without a verify.json sidecar)`,
208
+ ` \`requiresAnyOf\` — [param, ...] — at least one of these params must be supplied (one group per op). Members may not be \`required: true\` — a group member is a plain optional param (verify it via a verify.json sidecar value). Use \`required: true\` for a single-param constraint; \`requiresAnyOf\` is for two or more interchangeable params`,
209
+ ` \`passthrough\` — true → forward undeclared caller params onto the query string`,
210
+ ` \`parse\` — op-level responseShape override (format/charset) for this operation`,
211
+ "",
212
+ "## Auth",
213
+ ` \`kind: static-key\` — keyed-header auth mode (values live in the secrets store, never in the recipe):`,
214
+ ` \`requires\` = fail-closed if unprovisioned; \`optional\` = proceeds unauthenticated if absent. Both are names only — values live in the secrets store, and each name must match exactly the one passed to /api secrets. Each \`requires\` / \`optional\` name must also appear as a secretRefs/secretQueryRefs value (parser-enforced).`,
215
+ " static-key (keyed APIs):",
216
+ ` \`secretRefs\` — { <header name>: <secret name> } ← header → secret direction`,
217
+ ` \`headerPrefixes\` — { <header>: "Bearer " } ← scheme prefix; store holds the raw token`,
218
+ ` \`requires\` — [<secret-name>] ← fail-closed if unprovisioned (literal name, must match the store)`,
219
+ "",
220
+ "## Executor semantics",
221
+ " Pagination:",
222
+ ` \`pagination.base\` seeds the page param for offset-limit/page styles (caller value wins, then \`base\`, then the param \`default\`); use \`base: 1\` for 1-based offset APIs`,
223
+ ` The page-size param is a real knob: caller value → op param \`default\` → \`pagination.pageSize\` → 50`,
224
+ "",
225
+ "## Guide prose (agent instructions)",
226
+ " After the closing `---`, optional plaintext guidance for the reading agent —",
227
+ " date formats, auth caveats, field semantics, endpoint quirks. Surfaced by",
228
+ " api-guide as 'Guide notes'.",
229
+ "",
230
+ "Call api-learn({domain: '<domain>', recipeFile: '<staged file path>'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
231
+ ].join("\n");
232
+
233
+ /** Template path — write the placeholder skeleton to the staging path and
234
+ * surface the file path (the agent edits the file, not an inline copy).
235
+ * Fail-closed: the as-is template cannot save (placeholder `apiHost`
236
+ * is rejected by requireHttpUrl). */
237
+ function stageTemplate(domain: string): string {
238
+ const path = writeStagedDraft(domain, placeholderSkeleton(domain));
239
+ return (
240
+ AUTHORING_MANUAL +
241
+ "\n\n" +
242
+ `📝 Template for '${domain}' written to ${path}\n` +
243
+ ` Edit the file (or append ops via bash), then call ` +
244
+ `api-learn({domain: "${domain}", recipeFile: "${path}"}) to validate and save.\n` +
245
+ ` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`
246
+ );
247
+ }
248
+
249
+ /** Fetch-recipe response — the saved guide's raw recipe staged to the
250
+ * staging path, with the file path + resolved dirName surfaced so re-save
251
+ * keys on the directory, not the routing domain (sibling-clobber
252
+ * mitigation). The inline YAML block is dropped: the staged file is the
253
+ * source of truth the agent edits. */
254
+ function stageFetchedRecipe(
255
+ domain: string,
256
+ guide: ApiGuide,
257
+ dirName: string,
258
+ ): AgentToolResult<unknown> {
259
+ const raw = readFileSync(
260
+ join(getUserGuidesDir(), dirName, "guide.md"),
261
+ "utf-8",
262
+ );
263
+ const path = writeStagedDraft(domain, raw);
264
+ return {
265
+ content: [
266
+ {
267
+ type: "text",
268
+ text:
269
+ AUTHORING_MANUAL +
270
+ "\n\n" +
271
+ `📖 Current recipe for '${domain}' — guide '${guide.shortName}'\n` +
272
+ ` Directory: ${dirName}\n` +
273
+ ` Staged draft: ${path}\n` +
274
+ ` To edit: edit the staged file with the edit tool or bash, then call ` +
275
+ `api-learn({domain: "${dirName}", recipeFile: "${path}"}) — pass the ` +
276
+ `directory name as \`domain\` on re-save so a sibling guide is not clobbered.\n` +
277
+ ` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`,
278
+ },
279
+ ],
280
+ details: { mode: "fetch", domain, dirName, guide: guide.shortName },
281
+ };
282
+ }
283
+
284
+ /** Disambiguation menu for the N-guide fetch-recipe case (mirrors
285
+ * api-guide's menu). */
286
+ function renderFetchMenu(
287
+ domain: string,
288
+ matches: { guide: ApiGuide; dirName: string }[],
289
+ ): AgentToolResult<unknown> {
290
+ const lines: string[] = [];
291
+ lines.push(`${matches.length} API guides for '${domain}':`);
292
+ lines.push(formatGuideListings(matches));
293
+ const example = matches[0]!.guide.shortName;
294
+ lines.push(
295
+ `Call api-learn({domain: "${domain}", guide: "${example}"}) to fetch one guide's recipe.`,
296
+ );
297
+ return {
298
+ content: [{ type: "text", text: lines.join("\n") }],
299
+ details: { mode: "menu", domain, disambiguation: matches.length },
300
+ };
301
+ }
93
302
 
94
303
  // ═══════════════════════════════════════════════════════════════════
95
304
  // Tool definition
@@ -99,87 +308,53 @@ export const apiLearnTool = defineTool({
99
308
  name: "api-learn",
100
309
  label: "API Learn",
101
310
  description:
102
- "Save or update an API guide for a domain. " +
103
- "The recipe is written in YAML frontmatter format. " +
104
- "Call with no params to see the worked example recipe and field reference.",
311
+ "Author an API guide for a domain. " +
312
+ "Call with {domain, new: true} for a fresh domain-specific template. " +
313
+ "Call with {domain} and no recipeFile to fetch an existing guide's current raw recipe. " +
314
+ "Call with {domain, recipeFile} to validate and save.",
105
315
 
106
316
  parameters: Type.Object({
107
- domain: Type.Optional(
317
+ domain: Type.String({
318
+ description:
319
+ "Domain (e.g. 'example.com'). With `recipeFile` it's the save directory; " +
320
+ "with no recipeFile it's the routing domain for fetch-recipe lookup.",
321
+ }),
322
+ recipeFile: Type.Optional(
108
323
  Type.String({
109
324
  description:
110
- "Primary domain (e.g. 'boe.es'). Used as the filename. Omit to see the worked example.",
325
+ "Path to the staged draft guide file (written by a prior api-learn fetch/template call to /tmp/pi-lean-host/<domain>/guide.md). " +
326
+ "Read, validated, and saved. Omit to fetch the current raw recipe of an existing guide (or get a template when none exists).",
111
327
  }),
112
328
  ),
113
- recipe: Type.Optional(
329
+ guide: Type.Optional(
114
330
  Type.String({
115
331
  description:
116
- "Full recipe string including YAML frontmatter (---\\n...\\n---) and optional prose body. Required when domain is provided.",
332
+ "When a domain claims multiple guides, select one by shortName (shown in the disambiguation menu). " +
333
+ "Only used with the fetch-recipe path (no recipeFile).",
334
+ }),
335
+ ),
336
+ new: Type.Optional(
337
+ Type.Boolean({
338
+ description:
339
+ "true → return a fresh domain-specific template (domains pre-filled) regardless of existing guides. " +
340
+ "Does not touch any existing guide.",
117
341
  }),
118
342
  ),
119
343
  }),
120
344
 
121
345
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
122
- const { domain, recipe } = params as {
123
- domain?: string;
124
- recipe?: string;
346
+ const {
347
+ domain,
348
+ recipeFile,
349
+ guide: guideSelector,
350
+ new: isNew,
351
+ } = params as {
352
+ domain: string;
353
+ recipeFile?: string;
354
+ guide?: string;
355
+ new?: boolean;
125
356
  };
126
357
 
127
- // ── No domain → return worked example ────────────────────
128
- if (!domain) {
129
- const text = [
130
- "# Example recipe — copy, edit, and call api-learn({domain: '...', recipe: '...'})",
131
- "",
132
- "💡 For a not-yet-guided API, discover its shape first with api-probe({apiHost, path, params}) ",
133
- " — it drafts a YAML operation block to paste straight into the recipe below.",
134
- "",
135
- "```yaml",
136
- WORKED_EXAMPLE,
137
- "```",
138
- "",
139
- "## Required fields",
140
- ` \`domains\` — list of domain names this guide applies to`,
141
- ` \`apiHost\` — base URL including version prefix`,
142
- ` \`operations\` — at least one operation mapping`,
143
- ` \`operations[].name\` — unique operation name`,
144
- ` \`operations[].via\` — "restGet" or "paginate"`,
145
- ` \`operations[].path\` — path starting with /`,
146
- "",
147
- "## Key defaults",
148
- ` \`apiHost\` — base URL. \`path\` is always resolved relative to it — \`joinUrl\` strips a leading \`/\`, so \`/items\` + \`apiHost: https://host/v3\` → \`https://host/v3/items\`. Keep the version in \`apiHost\` (worked-example style) or leave it bare with the version in each \`path\` — pick one per guide; both at once doubles the segment (\`/v3/v3/items\` → 404)`,
149
- ` \`auth\` — omitted → kind: none`,
150
- ` \`verified\` — omitted → today's date`,
151
- ` \`docs\` — optional API documentation URL (http/https); omitted → no docs line`,
152
- ` \`gatherAllMax\` — omitted → 1000`,
153
- ` \`responseShape\` — omitted → json/utf-8`,
154
- ` \`operation.accept\` — omitted → json`,
155
- "",
156
- "## Optional fields (multi-recipe disambiguation)",
157
- ` \`organization\` — org identity across guides (use the org's registrable domain, e.g. archive.org)`,
158
- ` \`description\` — one-line API summary (≤${DESCRIPTION_MAX} chars); the primary signal when several guides share a domain`,
159
- "",
160
- "## Optional fields (operation-level)",
161
- ` \`dateParams\` — normalize date QUERY params before sending: map name → iso8601 | yyyymmdd | yyyy-mm-dd (path tokens are documented via params.<token>.description; core dateParams does not reach path tokens)`,
162
- ` \`helper\` — true → call this domain's local helper.ts for this op`,
163
- ` \`transform\` — true → run the helper.ts \`transform\` export on the parsed response`,
164
- ` \`params.<token>.description\` — docs-only description for a {token} path param (format, e.g. 'yyyy-mm-dd'); never sent as a query param, shown in api-guide`,
165
- ` \`passthrough\` — true → forward undeclared caller params onto the query string`,
166
- ` \`parse\` — op-level responseShape override (format/charset) for this operation`,
167
- "",
168
- "## Executor semantics",
169
- " Pagination:",
170
- ` \`pagination.base\` seeds the page param for offset-limit/page styles (caller value wins, then \`base\`, then the param \`default\`); use \`base: 1\` for 1-based offset APIs`,
171
- ` The page-size param is a real knob: caller value → op param \`default\` → \`pagination.pageSize\` → 50`,
172
- " Auth:",
173
- ` \`requires\` = fail-closed if unprovisioned; \`optional\` = proceeds unauthenticated if absent. Both are names only — values live in the secrets store.`,
174
- "",
175
- "Call api-learn({domain: '...', recipe: '...'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
176
- ].join("\n");
177
- return {
178
- content: [{ type: "text", text }],
179
- details: {},
180
- };
181
- }
182
-
183
358
  // ── Validate domain (path-traversal guard) ─────────────
184
359
  try {
185
360
  assertSafeDomain(domain);
@@ -195,16 +370,79 @@ export const apiLearnTool = defineTool({
195
370
  };
196
371
  }
197
372
 
198
- // ── Validate recipe ──────────────────────────────────────
199
- if (!recipe || !recipe.trim()) {
373
+ // ── new: true → fresh template regardless of existing guides ──
374
+ if (isNew) {
375
+ return {
376
+ content: [{ type: "text", text: stageTemplate(domain) }],
377
+ details: { mode: "template", domain },
378
+ };
379
+ }
380
+
381
+ // ── No recipeFile → fetch-recipe ─────────────────────────
382
+ // 0 guides → template staged; 1 guide → raw recipe staged + dirName
383
+ // surfaced; N guides → disambiguation menu (guide selector resolves it).
384
+ if (!recipeFile || !recipeFile.trim()) {
385
+ const matches = findGuidesByDomain(domain);
386
+ if (matches.length === 0) {
387
+ return {
388
+ content: [{ type: "text", text: stageTemplate(domain) }],
389
+ details: { mode: "template", domain },
390
+ };
391
+ }
392
+ if (matches.length === 1) {
393
+ const { guide, dirName } = matches[0]!;
394
+ return stageFetchedRecipe(domain, guide, dirName);
395
+ }
396
+ // N guides → disambiguation by shortName (mirrors api-guide).
397
+ if (!guideSelector) {
398
+ return renderFetchMenu(domain, matches);
399
+ }
400
+ const sel = selectGuideByShortName(matches, guideSelector);
401
+ if (!sel.ok) {
402
+ return {
403
+ content: [
404
+ {
405
+ type: "text",
406
+ text: shortNameErrorText(
407
+ sel,
408
+ domain,
409
+ guideSelector,
410
+ `Call api-learn({domain: "${domain}"}) to see the menu.`,
411
+ ),
412
+ },
413
+ ],
414
+ details:
415
+ sel.reason === "no_match"
416
+ ? { error: "no_guide_by_shortname", domain, guide: guideSelector }
417
+ : {
418
+ error: "ambiguous_shortname",
419
+ domain,
420
+ guide: guideSelector,
421
+ directories: sel.directories,
422
+ },
423
+ };
424
+ }
425
+ return stageFetchedRecipe(domain, sel.guide, sel.dirName);
426
+ }
427
+
428
+ // ── Save from a staged file ─────────────────────────────
429
+ // Read the draft, then run the identical validate → stamp → write
430
+ // path. A missing/unreadable file is a clear error; guide.md untouched.
431
+ let recipe: string;
432
+ try {
433
+ recipe = readFileSync(recipeFile, "utf-8");
434
+ } catch {
200
435
  return {
201
436
  content: [
202
437
  {
203
438
  type: "text",
204
- text: `Recipe is required when domain is provided. Call api-learn() with no params to see the worked example.`,
439
+ text:
440
+ `⚠ Could not read recipe file '${recipeFile}' — guide was NOT saved.\n` +
441
+ ` Fetch the current recipe first via api-learn({domain: "${domain}"}) ` +
442
+ `(or a template with {domain, new: true}), then edit the staged file and save with recipeFile.`,
205
443
  },
206
444
  ],
207
- details: { error: "missing_recipe" },
445
+ details: { error: "recipe_file_unreadable", domain, recipeFile },
208
446
  };
209
447
  }
210
448
 
@@ -218,7 +456,6 @@ export const apiLearnTool = defineTool({
218
456
  ` Found: ${err.found}`,
219
457
  ];
220
458
  if (err.fix) lines.push(` Fix: ${err.fix}`);
221
- lines.push("");
222
459
  lines.push("Fix the recipe and call api-learn again.");
223
460
  return {
224
461
  content: [{ type: "text", text: lines.join("\n") }],
@@ -254,8 +491,14 @@ export const apiLearnTool = defineTool({
254
491
  // so the routing-vs-identity distinction is explicit.
255
492
  const warnings: string[] = [];
256
493
  const collidingDomains: string[] = [];
494
+ const collidingDirs: string[] = [];
257
495
  for (const d of parsed.guide.domains ?? []) {
258
496
  const existing = findGuidesByDomain(d);
497
+ for (const m of existing) {
498
+ if (m.dirName !== domain && !collidingDirs.includes(m.dirName)) {
499
+ collidingDirs.push(m.dirName);
500
+ }
501
+ }
259
502
  if (existing.some((m) => m.dirName !== domain)) {
260
503
  collidingDomains.push(d);
261
504
  }
@@ -270,15 +513,64 @@ export const apiLearnTool = defineTool({
270
513
  ` \`description:\` is absent — adding one is recommended when several guides share a domain (it's the primary disambiguation signal).`,
271
514
  );
272
515
  }
516
+ warnings.push(
517
+ ` If an existing guide is wrong, ask the user to run /api delete ${collidingDirs.join(" ")} to remove it (the agent has no delete tool).`,
518
+ );
273
519
  }
274
520
 
275
- // ── Write guide ──────────────────────────────────────────
521
+ // ── Fail-closed overwrite guard ─────────────────────────
522
+ // A guide.md already in the target directory is that directory's
523
+ // identity anchor. If its shortName differs from the incoming
524
+ // guide's, this save would silently replace a sibling guide (the
525
+ // multi-recipe clobber bug). Refuse and teach the directory
526
+ // convention instead. Same shortName = legitimate update, proceeds.
276
527
  const guidesDir = getUserGuidesDir();
277
528
  const domainDir = join(guidesDir, domain);
278
- mkdirSync(domainDir, { recursive: true });
279
529
  const filepath = join(domainDir, "guide.md");
530
+ if (existsSync(filepath)) {
531
+ const existing = parseApiGuide(readFileSync(filepath, "utf-8"), {
532
+ filename: domain,
533
+ });
534
+ const existingShort = existing.ok ? existing.guide.shortName : undefined;
535
+ if (existingShort !== parsed.guide.shortName) {
536
+ return {
537
+ content: [
538
+ {
539
+ type: "text",
540
+ text:
541
+ `⚠ Refusing to overwrite — guide was NOT saved.\n` +
542
+ ` Directory '${domain}' already holds guide '${existingShort ?? "?"}' (guide.md); ` +
543
+ `the incoming guide is '${parsed.guide.shortName}'.` +
544
+ (existing.ok
545
+ ? `\n To save a SECOND guide for the same routing domain, use a distinct directory:\n` +
546
+ ` api-learn({domain: "${domain}-${parsed.guide.shortName}", recipeFile: "${recipeFile}"})\n` +
547
+ ` Keep \`domains: [${parsed.guide.domains?.join(", ")}]\` in the recipe for routing.`
548
+ : `\n The existing guide.md is malformed (won't parse). If you intend to replace it, ask the user to run /api delete ${domain} first.`),
549
+ },
550
+ ],
551
+ details: {
552
+ error: "overwrite_refused",
553
+ domain,
554
+ existing: existingShort ?? null,
555
+ incoming: parsed.guide.shortName,
556
+ },
557
+ };
558
+ }
559
+ }
560
+ mkdirSync(domainDir, { recursive: true });
280
561
 
281
- writeFileSync(filepath, recipe, "utf-8");
562
+ // ── Write guide ──────────────────────────────────────────
563
+
564
+ // Stamp schemaVersion on save — each guide records the schema vintage
565
+ // it was authored against (the per-guide vintage that stale detection
566
+ // compares against). Line-level frontmatter edit; comments + key order
567
+ // preserved (no YAML round-trip).
568
+ const stamped = stampFrontmatterField(
569
+ recipe,
570
+ "schemaVersion",
571
+ String(GUIDE_SCHEMA_VERSION),
572
+ );
573
+ writeFileSync(filepath, stamped, "utf-8");
282
574
  invalidateCache(); // next api-fetch / api-guide read picks it up
283
575
 
284
576
  const opCount = parsed.guide.operations.length;
@@ -294,15 +586,17 @@ export const apiLearnTool = defineTool({
294
586
  `📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${domain}/guide.md\n` +
295
587
  ` Domain: ${domain}\n` +
296
588
  ` Operations: ${opCount} — ${opNames}\n` +
297
- ` Auth: ${parsed.guide.auth.kind}\n` +
589
+ ` ${authSummary(parsed.guide.auth)}\n` +
298
590
  ` Verified: ${parsed.guide.verified}\n` +
591
+ ` Schema version: ${GUIDE_SCHEMA_VERSION}\n` +
299
592
  `\n` +
300
593
  warningBlock +
301
594
  `Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify.` +
302
- `\n⚠ Direct edits to guide.md are ignored until the next api-learn save (per-session cache). Re-run api-learn to apply changes.`,
595
+ `\n⚠ Edit the staged /tmp file, not the saved guide.md — direct edits to guide.md are overwritten on save and invisible to api-fetch until then.`,
303
596
  },
304
597
  ],
305
598
  details: {
599
+ mode: "saved",
306
600
  filePath: filepath,
307
601
  domain,
308
602
  operations: opCount,
@@ -313,12 +607,10 @@ export const apiLearnTool = defineTool({
313
607
 
314
608
  renderCall(args, theme, _context) {
315
609
  const parts: string[] = [theme.fg("toolTitle", theme.bold("api-learn "))];
316
- if (args.domain) {
317
- parts.push(theme.fg("accent", `"${args.domain}"`));
318
- parts.push(theme.fg("dim", "📝"));
319
- } else {
320
- parts.push(theme.fg("dim", "(example)"));
321
- }
610
+ parts.push(theme.fg("accent", `"${args.domain}"`));
611
+ if (args.new) parts.push(theme.fg("dim", "✨new"));
612
+ else if (args.recipeFile) parts.push(theme.fg("dim", "📝"));
613
+ else parts.push(theme.fg("dim", "📖"));
322
614
  return new Text(parts.join(" "), 0, 0);
323
615
  },
324
616
 
@@ -329,15 +621,24 @@ export const apiLearnTool = defineTool({
329
621
  return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
330
622
  }
331
623
 
624
+ const mode = d?.mode as string | undefined;
332
625
  const domain = d?.domain as string | undefined;
333
626
  const opCount = d?.operations as number | undefined;
627
+ const dirName = d?.dirName as string | undefined;
628
+ const disambig = d?.disambiguation as number | undefined;
334
629
 
335
630
  let text: string;
336
- if (domain && opCount !== undefined) {
631
+ if (mode === "fetch" && dirName) {
632
+ text = theme.fg("accent", theme.bold(`📖 ${dirName}`));
633
+ text += " — fetched recipe";
634
+ } else if (mode === "template" && domain) {
635
+ text = theme.fg("accent", theme.bold(`📝 Template for ${domain}`));
636
+ } else if (mode === "menu" && domain) {
637
+ text = theme.fg("dim", theme.bold("📖 menu"));
638
+ text += ` — ${disambig ?? "?"} guides for ${domain}`;
639
+ } else {
337
640
  text = theme.fg("accent", theme.bold(`📝 Saved guide for ${domain}`));
338
641
  text += ` — ${opCount} ops`;
339
- } else {
340
- text = theme.fg("dim", "📝 Worked example");
341
642
  }
342
643
 
343
644
  return new Text(appendFooter(text, expanded, result, theme, 600), 0, 0);