pi-lean-host 0.3.1 → 0.5.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.
@@ -4,13 +4,16 @@
4
4
  * Authoring entry points:
5
5
  * - `{domain, new: true}` → fresh template with `domains: [<domain>]`
6
6
  * pre-filled (regardless of existing guides).
7
- * - `{domain}` (no recipeFile) → fetch the current raw recipe of an existing
7
+ * - `{domain}` (no dir) → fetch the current raw recipe of an existing
8
8
  * guide (0 guides → template; 1 guide → raw recipe + dirName surfaced;
9
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
10
+ * `/tmp/pi-lean-host/<slug(shortName)>/` (guide.md + present siblings).
11
+ * - `{domain, dir}` → reads the staged directory (guide.md required,
12
+ * helper.ts / verify.json siblings mirrored), validates via
12
13
  * `parseApiGuide()`, writes to
13
- * `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`.
14
+ * `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/` —
15
+ * the write target is a function of the guide's own `shortName`, never
16
+ * the `domain` arg (the arg is cosmetic on the save branch).
14
17
  *
15
18
  * No half-write on validation error (validate first, write only on success).
16
19
  * Defaults are filled by the validator before writing.
@@ -25,16 +28,26 @@ import {
25
28
  import { Type } from "@earendil-works/pi-ai";
26
29
  import { Text } from "@earendil-works/pi-tui";
27
30
  import { appendFooter, contentText } from "./utils.js";
28
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
29
- import { tmpdir } from "node:os";
30
- import { join } from "node:path";
31
+ import {
32
+ existsSync,
33
+ mkdirSync,
34
+ readFileSync,
35
+ readdirSync,
36
+ renameSync,
37
+ rmSync,
38
+ writeFileSync,
39
+ } from "node:fs";
40
+ import { basename, join } from "node:path";
41
+ import { pathToFileURL } from "node:url";
31
42
  import {
32
43
  parseApiGuide,
33
44
  stampFrontmatterField,
45
+ } from "../core/parse-api-guide.js";
46
+ import {
34
47
  formatGuideListings,
35
48
  selectGuideByShortName,
36
49
  shortNameErrorText,
37
- } from "../core/parse-api-guide.js";
50
+ } from "../core/guide-catalog.js";
38
51
  import {
39
52
  GUIDE_SCHEMA_VERSION,
40
53
  type ApiGuide,
@@ -45,33 +58,31 @@ import {
45
58
  getUserGuidesDir,
46
59
  findGuidesByDomain,
47
60
  } from "../core/guide-store.js";
48
- import { assertSafeDomain } from "../core/path-template.js";
49
-
50
- // ═══════════════════════════════════════════════════════════════════
51
- // Staged working copy (/tmp) — the draft the agent edits between saves
52
- // ═══════════════════════════════════════════════════════════════════
53
-
54
- let _stagingRoot = join(tmpdir(), "pi-lean-host");
61
+ import { assertSafeDomain, slug } from "../core/path-template.js";
62
+ import { stagingDirFor, isUnderStagingRoot } from "../core/staging.js";
55
63
 
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
- }
64
+ // Staged working copy (/tmp) — the draft the agent edits between saves.
65
+ // Root + helpers live in core/staging.js (shared with api-scaffold).
61
66
 
62
- /** Deterministic draft path: `<root>/<domain>/guide.md`. */
63
- function stagingPathFor(domain: string): string {
64
- return join(_stagingRoot, domain, "guide.md");
67
+ /** Write the working copy (template or fetched raw recipe) to the staged
68
+ * dir. Returns the staged *dir* path (multi-file — siblings write to the
69
+ * same dir). */
70
+ function writeStagedDraft(key: string, raw: string): string {
71
+ const dir = stagingDirFor(key);
72
+ mkdirSync(dir, { recursive: true });
73
+ writeFileSync(join(dir, "guide.md"), raw, "utf-8");
74
+ return dir;
65
75
  }
66
76
 
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
- }
77
+ /** Sibling artifact names mirrored between the staged dir and the guides
78
+ * dir on save (guide.md is always written). The helper extension set mirrors
79
+ * core/local-helpers.ts's `findHelperFile` resolution (.ts → .mjs → .js). */
80
+ const SIBLING_NAMES = [
81
+ "helper.ts",
82
+ "helper.mjs",
83
+ "helper.js",
84
+ "verify.json",
85
+ ] as const;
75
86
 
76
87
  // ═══════════════════════════════════════════════════════════════════
77
88
  // Placeholder skeleton (retired worked example)
@@ -82,14 +93,25 @@ function writeStagedDraft(domain: string, raw: string): string {
82
93
  const DESCRIPTION_MAX = 200;
83
94
 
84
95
  /** Commented static-key auth block — the issue-#5 auth-wiring teaching,
85
- * API-agnostic, kept after the worked example retired. */
96
+ * API-agnostic, kept after the worked example retired. Nested SecretRef
97
+ * shape (v1): each ref is self-contained (secret + optional prefix/optional). */
86
98
  const STATIC_KEY_BLOCK = ` # Keyed API? Use kind: static-key — values live in the secrets store (/api secrets), never in the recipe:
87
99
  # kind: static-key
88
- # requires: [<secret-name>]
89
100
  # secretRefs:
90
- # Authorization: <secret-name> # header name → secret name (must match the name provisioned via /api secrets)
91
- # headerPrefixes:
92
- # Authorization: "Bearer "`;
101
+ # Authorization: # header name
102
+ # secret: <secret-name> # store name (must match /api secrets)
103
+ # prefix: "Bearer " # optional — prepended at fetch time
104
+ # optional: false # optional refs don't fail closed when absent`;
105
+
106
+ /** Commented oauth2 authorization_code block — mirrors the manual's worked
107
+ * example so the fresh template teaches the interactive-grant shape without
108
+ * the agent having to grep a sibling guide for the field names. */
109
+ const OAUTH2_AC_BLOCK = ` # OAuth2 API? Use kind: oauth2 — credentials are store names (/api secrets), minting via /api oauth <domain>:
110
+ # grant: authorization_code # or client_credentials (server-to-server: adds clientSecret, drops authorizeUrl)
111
+ # tokenUrl: https://…/oauth/token
112
+ # authorizeUrl: https://…/oauth/authorize # REQUIRED for authorization_code
113
+ # clientId: { secret: client_id }
114
+ # scopes: [read]`;
93
115
 
94
116
  /** Placeholder starter template — only `domains:` is real (the requested
95
117
  * domain). Every other field is a placeholder the agent fills (op blocks
@@ -100,6 +122,7 @@ function placeholderSkeleton(domain: string): string {
100
122
  return `---
101
123
  kind: api
102
124
  domains: [${domain}]
125
+ schemaVersion: ${GUIDE_SCHEMA_VERSION}
103
126
  organization: <org> # optional — org identity across guides (registrable domain)
104
127
  description: <one-line summary> # optional — one-line summary; aids disambiguation
105
128
  icon: <emoji>
@@ -112,6 +135,7 @@ gatherAllMax: 1000 # omitted → 1000
112
135
  auth:
113
136
  kind: none
114
137
  ${STATIC_KEY_BLOCK}
138
+ ${OAUTH2_AC_BLOCK}
115
139
 
116
140
  pagination:
117
141
  style: offset-limit
@@ -119,6 +143,14 @@ pagination:
119
143
  pageSizeParam: limit
120
144
  pageSize: 50
121
145
  itemsPath: results
146
+ # Path fields are dot-delimited. If the API's key itself contains a dot
147
+ # (OData's '@odata.nextLink' / '@iot.count' family), quote it as an atomic
148
+ # key or the dot splits the path and pagination silently misses:
149
+ # nextLinkPath: "['@odata.nextLink']" # single or double quotes
150
+ # For a cursor walk whose continuation value is an item field (derived-id
151
+ # cursor), declare the sort params on the op too — the executor serializes
152
+ # ONLY declared params, and an undeclared sort lets the API default apply,
153
+ # turning the walk into a moving feed that re-reads rows.
122
154
 
123
155
  responseShape:
124
156
  format: json
@@ -135,6 +167,8 @@ responseShape:
135
167
  # params:
136
168
  # id:
137
169
  # description: <what id selects>
170
+ # # listStyle: comma # array values serialize as comma | repeat | bracket — omit for single-valued
171
+ # # unknown params keys are a parse error (typo tripwire)
138
172
  ---
139
173
 
140
174
  # Optional agent-instruction prose goes AFTER the closing --- and is surfaced
@@ -145,17 +179,43 @@ responseShape:
145
179
 
146
180
  /** Save-summary auth line — names the header→secret mapping (names only,
147
181
  * never values: values live in the store). e.g.
148
- * `static-key · Authorization ← secret apiKey (Bearer )`. */
182
+ * `static-key · Authorization ← secret apiKey (Bearer )` or
183
+ * `oauth2 · grant client_credentials · clientId ← secret client_id`. */
149
184
  function authSummary(auth: AuthConfig): string {
150
185
  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}`);
186
+ switch (auth.kind) {
187
+ case "static-key":
188
+ for (const [header, ref] of Object.entries(auth.secretRefs ?? {})) {
189
+ parts.push(
190
+ `${header} ← secret ${ref.secret}${ref.prefix ? ` (${ref.prefix})` : ""}`,
191
+ );
192
+ }
193
+ for (const [param, ref] of Object.entries(auth.secretQueryRefs ?? {})) {
194
+ parts.push(`?${param} ← secret ${ref.secret}`);
195
+ }
196
+ for (const [token, ref] of Object.entries(auth.secretPathRefs ?? {})) {
197
+ parts.push(`{${token}} ← secret ${ref.secret}`);
198
+ }
199
+ break;
200
+ case "oauth2":
201
+ parts.push(
202
+ `grant ${auth.grant} · clientId ← secret ${auth.clientId.secret}` +
203
+ (auth.clientSecret
204
+ ? ` · clientSecret ← secret ${auth.clientSecret.secret}`
205
+ : ""),
206
+ );
207
+ for (const [header, ref] of Object.entries(auth.secretRefs ?? {})) {
208
+ parts.push(
209
+ `${header} ← secret ${ref.secret}${ref.prefix ? ` (${ref.prefix})` : ""}`,
210
+ );
211
+ }
212
+ break;
213
+ case "none":
214
+ break;
215
+ default: {
216
+ const _exhaustive: never = auth;
217
+ throw new Error(`Unhandled auth kind: ${_exhaustive}`);
218
+ }
159
219
  }
160
220
  return parts.length === 0
161
221
  ? `Auth: ${auth.kind}`
@@ -166,6 +226,31 @@ function authSummary(auth: AuthConfig): string {
166
226
  // Authoring manual + templates
167
227
  // ═══════════════════════════════════════════════════════════════════
168
228
 
229
+ /** Worked oauth2 examples shown in the authoring manual — exported so the
230
+ * parse test proves they parse as-is (the teaching can't rot silently).
231
+ * Field semantics mirror validateOAuth2Auth's grant invariants. */
232
+ export const OAUTH2_CC_EXAMPLE = ` # client_credentials — server-to-server, no browser:
233
+ auth:
234
+ kind: oauth2
235
+ grant: client_credentials
236
+ tokenUrl: https://api.example.com/oauth/token
237
+ clientId: { secret: client_id }
238
+ clientSecret: { secret: client_secret } # parser-required for this grant
239
+ # scopes: [read]
240
+ # secretRefs: # extra headers beside the Bearer token
241
+ # Client-Id:
242
+ # secret: client_id`;
243
+
244
+ export const OAUTH2_AC_EXAMPLE = ` # authorization_code — interactive; human consents in their browser and pastes the redirect (/api oauth):
245
+ auth:
246
+ kind: oauth2
247
+ grant: authorization_code
248
+ tokenUrl: https://api.example.com/oauth/token
249
+ authorizeUrl: https://example.com/oauth/authorize # REQUIRED for this grant; rejected for client_credentials
250
+ clientId: { secret: client_id }
251
+ # clientSecret: { secret: client_secret } # confidential clients only; PKCE public clients omit it
252
+ scopes: [read]`;
253
+
169
254
  /** The field reference + defaults + semantics manual. Travels with the
170
255
  * pull-to-/tmp action — prepended to every staged draft (template or
171
256
  * fetched recipe) so the author sees it at the moment of authoring. */
@@ -182,7 +267,7 @@ const AUTHORING_MANUAL = [
182
267
  ` \`apiHost\` — base URL. Version in apiHost XOR in each path — never both (see Key defaults)`,
183
268
  ` \`operations\` — a LIST of operation mappings — at least one entry`,
184
269
  ` \`operations[].name\` — unique operation name`,
185
- ` \`operations[].via\` — "restGet" or "paginate"`,
270
+ ` \`operations[].via\` — "restGet" or "paginate" — both issue GETs; the plugin is read-only by design (writes have no schema representation)`,
186
271
  ` \`operations[].path\` — path starting with /`,
187
272
  "",
188
273
  "## Key defaults",
@@ -202,65 +287,105 @@ const AUTHORING_MANUAL = [
202
287
  ` \`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
288
  ` \`helper\` — true → call this domain's local helper.ts for this op`,
204
289
  ` \`transform\` — true → run the helper.ts \`transform\` export on the parsed response`,
290
+ ` \`errorPath\` — JSON path to a present-only-on-error envelope element in a 200 body (e.g. \`OAI-PMH.error\`); anything other than \`undefined\` there (including null/""/0/false) fails the call as an error — declare a path that exists ONLY on error (Flickr \`message\`, World Bank \`0.message\`); root paths (\`$\`, \`.\`), malformed paths, and ops whose effective format is \`text\` are parse errors`,
205
291
  ` \`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
292
  ` \`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`,
293
+ ` \`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; an array default additionally requires \`listStyle\` and must be non-empty)`,
294
+ ` \`params.<name>.listStyle\` — comma | repeat | bracket — how an array value serializes on the query string (comma → id=a,b; repeat → id=a&id=b; bracket → id[]=a); scalars ignore the field`,
295
+ ` \`requiresAnyOf\` — [param, ...] — at least one of these params must be supplied (one group per op). Use it when the API identifies a resource by exactly one of several interchangeable params and rejects them together (id XOR symbol XOR slug — the "exclusive peers" 400). Members may not be \`required: true\` NOR carry a \`default\` (both parser-enforced) — a default would always fire alongside a caller-supplied sibling and cause the conflict. Use \`required: true\` for a single-param constraint; \`requiresAnyOf\` is for two or more interchangeable params`,
209
296
  ` \`passthrough\` — true → forward undeclared caller params onto the query string`,
210
297
  ` \`parse\` — op-level responseShape override (format/charset) for this operation`,
211
298
  "",
212
299
  "## Auth",
213
300
  ` \`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).`,
301
+ ` \`kind: oauth2\` — OAuth2 (client_credentials / authorization_code); token minting via /api oauth <domain>. ALL oauth2 credentials are store names, never literals — a shippable guide must not bake in one app's registration:`,
302
+ ` \`clientId\` — { secret: <store name> } — the client id's secrets-store name (e.g. clientId: { secret: client_id })`,
303
+ ` \`clientSecret\` — { secret: <store name> } — parser-required for client_credentials; absent for authorization_code (PKCE public clients)`,
304
+ ` \`secretRefs\` — { <request header>: { secret: <store name>, prefix?, optional? } } — headers merged alongside the Bearer token (e.g. Twitch's Client-Id)`,
305
+ ` \`scopes\` — optional static scope list (e.g. scopes: [read])`,
306
+ ` \`tokenEndpointAuthMethod\` — client_secret_post (default) | client_secret_basic | none — how the client authenticates at the token endpoint; none = PKCE public client (no clientSecret)`,
307
+ ` \`paramStyle\` — bearer-header (default) | query (sends ?access_token=…)`,
308
+ ` \`revokeUrl\` — optional revocation endpoint`,
309
+ "",
310
+ " Worked examples — copy one and edit; store names must match /api secrets <domain>:",
311
+ OAUTH2_CC_EXAMPLE,
312
+ "",
313
+ OAUTH2_AC_EXAMPLE,
314
+ "",
215
315
  " 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)`,
316
+ ` \`secretRefs\` — { <header name>: { secret: <store name>, prefix?, optional? } } ← self-contained ref`,
317
+ ` \`secretQueryRefs\` — { <query param>: { secret: <store name>, optional? } } ← query-param injection`,
318
+ ` \`secretPathRefs\` — { <path token>: { secret: <store name> } } ← path-token injection (/bot{token}/getMe); required-only: no prefix/optional`,
319
+ ` \`optional: true\` on a ref → proceeds unauthenticated if absent; default (required) → fail-closed. Values live in the secrets store; the store name must match /api secrets exactly.`,
219
320
  "",
220
321
  "## Executor semantics",
221
322
  " Pagination:",
222
323
  ` \`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`,
324
+ ` Page-size resolution (offset-limit/page): caller value → op param \`default\` → \`pagination.pageSize\` → 50. Cursor: caller value → op param \`default\` → \`pagination.pageSize\` → omit (server default applies)`,
224
325
  "",
225
326
  "## Guide prose (agent instructions)",
226
327
  " After the closing `---`, optional plaintext guidance for the reading agent —",
227
328
  " date formats, auth caveats, field semantics, endpoint quirks. Surfaced by",
228
329
  " api-guide as 'Guide notes'.",
229
330
  "",
230
- "Call api-learn({domain: '<domain>', recipeFile: '<staged file path>'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
331
+ "## Saving (mirror-save)",
332
+ " Save reads every staged file (guide.md + helper.ts + verify.json when present) and",
333
+ " mirrors it into the guides dir. A sibling present in the guides dir but absent from",
334
+ " the staged /tmp dir would be DELETED — save refuses and names it; re-call with",
335
+ " confirmDeletions: true to proceed (that flag is discovered only via the refusal message,",
336
+ " never the tool description). A guide declaring helper: true / transform: true must",
337
+ " have a loadable staged helper.ts.",
338
+ "",
339
+ "Call api-learn({domain: '<domain>', dir: '<staged dir>'}) to save the guide, then test each op via api-fetch({domain, operation, params: <your verify.json values>}) — pass the values yourself; verify.json feeds /api verify (the user's batch stamp), not api-fetch.",
231
340
  ].join("\n");
232
341
 
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).
342
+ /** Template path — write the placeholder skeleton to the staging dir and
343
+ * surface the guide.md path + staged dir (the agent edits the file, not an
344
+ * inline copy).
235
345
  * Fail-closed: the as-is template cannot save (placeholder `apiHost`
236
346
  * is rejected by requireHttpUrl). */
237
347
  function stageTemplate(domain: string): string {
238
- const path = writeStagedDraft(domain, placeholderSkeleton(domain));
348
+ const dir = writeStagedDraft(domain, placeholderSkeleton(domain));
239
349
  return (
240
350
  AUTHORING_MANUAL +
241
351
  "\n\n" +
242
- `📝 Template for '${domain}' written to ${path}\n` +
352
+ `📝 Template for '${domain}' written to ${join(dir, "guide.md")}\n` +
243
353
  ` Edit the file (or append ops via bash), then call ` +
244
- `api-learn({domain: "${domain}", recipeFile: "${path}"}) to validate and save.\n` +
354
+ `api-learn({domain: "${domain}", dir: "${dir}"}) to validate and save.\n` +
245
355
  ` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`
246
356
  );
247
357
  }
248
358
 
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. */
359
+ /** Fetch-recipe response — the saved guide's raw recipe (and present
360
+ * siblings) staged to the staging dir, with the dir path + resolved dirName
361
+ * surfaced. Staging keys on `slug(shortName)` (the on-disk dirName in steady
362
+ * state), and the re-save self-keys off the draft's own shortName — no
363
+ * "pass the directory name as domain" guidance (that arg is cosmetic on
364
+ * save). The inline YAML block is dropped: the staged files are the source
365
+ * of truth the agent edits. */
254
366
  function stageFetchedRecipe(
255
367
  domain: string,
256
368
  guide: ApiGuide,
257
369
  dirName: string,
258
370
  ): AgentToolResult<unknown> {
259
- const raw = readFileSync(
260
- join(getUserGuidesDir(), dirName, "guide.md"),
371
+ const sourceDir = join(getUserGuidesDir(), dirName);
372
+ const stagedKey = slug(guide.shortName);
373
+ const stagedDir = stagingDirFor(stagedKey);
374
+ mkdirSync(stagedDir, { recursive: true });
375
+ // guide.md always; helper.ts / verify.json when present.
376
+ writeFileSync(
377
+ join(stagedDir, "guide.md"),
378
+ readFileSync(join(sourceDir, "guide.md"), "utf-8"),
261
379
  "utf-8",
262
380
  );
263
- const path = writeStagedDraft(domain, raw);
381
+ const stagedSiblings: string[] = [];
382
+ for (const name of SIBLING_NAMES) {
383
+ const src = join(sourceDir, name);
384
+ if (existsSync(src)) {
385
+ writeFileSync(join(stagedDir, name), readFileSync(src, "utf-8"), "utf-8");
386
+ stagedSiblings.push(name);
387
+ }
388
+ }
264
389
  return {
265
390
  content: [
266
391
  {
@@ -270,14 +395,23 @@ function stageFetchedRecipe(
270
395
  "\n\n" +
271
396
  `📖 Current recipe for '${domain}' — guide '${guide.shortName}'\n` +
272
397
  ` 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` +
398
+ ` Staged dir: ${stagedDir}\n` +
399
+ (stagedSiblings.length > 0
400
+ ? ` Siblings staged: ${stagedSiblings.join(", ")}\n`
401
+ : "") +
402
+ ` To edit: edit the staged files with the edit tool or bash, then call ` +
403
+ `api-learn({domain: "${domain}", dir: "${stagedDir}"}) — the guide ` +
404
+ `saves to its own \`${stagedKey}\` folder (self-keyed by shortName).\n` +
277
405
  ` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`,
278
406
  },
279
407
  ],
280
- details: { mode: "fetch", domain, dirName, guide: guide.shortName },
408
+ details: {
409
+ mode: "fetch",
410
+ domain,
411
+ dirName,
412
+ guide: guide.shortName,
413
+ stagedDir,
414
+ },
281
415
  };
282
416
  }
283
417
 
@@ -310,27 +444,35 @@ export const apiLearnTool = defineTool({
310
444
  description:
311
445
  "Author an API guide for a domain. " +
312
446
  "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.",
447
+ "Call with {domain} and no dir to fetch an existing guide's current raw recipe (and its sibling files). " +
448
+ "Call with {domain, dir} to validate and save.\n\n" +
449
+ "Authoring order (follow this to avoid the common mis-ordering):\n" +
450
+ "1. (optional) api-probe({apiHost, path, params}) — discover a not-yet-guided endpoint's shape and draft an op block from the docs/example.\n" +
451
+ "2. api-learn({domain, new: true}) — get a fresh template, fill the recipe, then api-learn({domain, dir}) to save it.\n" +
452
+ "3. ONLY after the guide is saved: api-scaffold({domain, verify: true | helper: true}) — scaffold reads the SAVED guide, so scaffold-before-save fails. Fill the staged verify.json / helper.ts, then api-learn({domain, dir}) to save the siblings.\n" +
453
+ "4. Test each op: api-fetch({domain, operation, params: <your verify.json values>}) — verify.json feeds /api verify, not api-fetch, so pass the values yourself. Fix via api-learn({domain}) → edit staged → api-learn({domain, dir}). /api verify is the user's batch attestation stamp (runs every op + stamps verified:).\n" +
454
+ "Staged drafts live in /tmp/pi-lean-host/<slug(shortName)>/; the save target is self-keyed by the guide's shortName, never the domain arg.",
315
455
 
316
456
  parameters: Type.Object({
317
457
  domain: Type.String({
318
458
  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.",
459
+ "Domain (e.g. 'example.com'). With no dir it's the routing domain " +
460
+ "for fetch-recipe lookup; with `dir` it's display/error context only — " +
461
+ "the guide saves to its own slug(shortName) folder.",
321
462
  }),
322
- recipeFile: Type.Optional(
463
+ dir: Type.Optional(
323
464
  Type.String({
324
465
  description:
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).",
466
+ "Path to the staged directory (written by a prior api-learn fetch/template or api-scaffold call to /tmp/pi-lean-host/<slug(shortName)>/). " +
467
+ "guide.md is read, validated, and saved; present helper.ts / verify.json siblings are mirrored. " +
468
+ "Omit to fetch the current raw recipe of an existing guide (or get a template when none exists).",
327
469
  }),
328
470
  ),
329
471
  guide: Type.Optional(
330
472
  Type.String({
331
473
  description:
332
474
  "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).",
475
+ "Only used with the fetch-recipe path (no dir).",
334
476
  }),
335
477
  ),
336
478
  new: Type.Optional(
@@ -340,19 +482,24 @@ export const apiLearnTool = defineTool({
340
482
  "Does not touch any existing guide.",
341
483
  }),
342
484
  ),
485
+ // Undescribed by design — the only discovery path is the deletion-safety
486
+ // gate's refusal message.
487
+ confirmDeletions: Type.Optional(Type.Boolean()),
343
488
  }),
344
489
 
345
490
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
346
491
  const {
347
492
  domain,
348
- recipeFile,
493
+ dir,
349
494
  guide: guideSelector,
350
495
  new: isNew,
496
+ confirmDeletions,
351
497
  } = params as {
352
498
  domain: string;
353
- recipeFile?: string;
499
+ dir?: string;
354
500
  guide?: string;
355
501
  new?: boolean;
502
+ confirmDeletions?: boolean;
356
503
  };
357
504
 
358
505
  // ── Validate domain (path-traversal guard) ─────────────
@@ -378,10 +525,11 @@ export const apiLearnTool = defineTool({
378
525
  };
379
526
  }
380
527
 
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()) {
528
+ // ── No dir → fetch-recipe ──────────────────────────────
529
+ // 0 guides → template staged; 1 guide → raw recipe + siblings staged +
530
+ // dirName surfaced; N guides → disambiguation menu (guide selector
531
+ // resolves it).
532
+ if (!dir || !dir.trim()) {
385
533
  const matches = findGuidesByDomain(domain);
386
534
  if (matches.length === 0) {
387
535
  return {
@@ -425,28 +573,39 @@ export const apiLearnTool = defineTool({
425
573
  return stageFetchedRecipe(domain, sel.guide, sel.dirName);
426
574
  }
427
575
 
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.
576
+ // ── Save from a staged directory ────────────────────────
577
+ // Read guide.md (required) from the staged dir, then run the identical
578
+ // validate → stamp → write path. A missing/unreadable dir is a clear
579
+ // error; guides dir untouched.
431
580
  let recipe: string;
432
581
  try {
433
- recipe = readFileSync(recipeFile, "utf-8");
582
+ recipe = readFileSync(join(dir, "guide.md"), "utf-8");
434
583
  } catch {
435
584
  return {
436
585
  content: [
437
586
  {
438
587
  type: "text",
439
588
  text:
440
- `⚠ Could not read recipe file '${recipeFile}' — guide was NOT saved.\n` +
589
+ `⚠ Could not read staged guide from '${join(dir, "guide.md")}' — guide was NOT saved.\n` +
441
590
  ` 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.`,
591
+ `(or a template with {domain, new: true}), then edit the staged files and save with dir.`,
443
592
  },
444
593
  ],
445
- details: { error: "recipe_file_unreadable", domain, recipeFile },
594
+ details: { error: "staged_dir_unreadable", domain, dir },
446
595
  };
447
596
  }
448
597
 
449
- const parsed = parseApiGuide(recipe, { filename: domain });
598
+ // Stamp schemaVersion before validation: under the schemaVersion hard
599
+ // gate a recipe without a current stamp would fail validation before
600
+ // the stamp could land. Line-level frontmatter edit (comments + key
601
+ // order preserved); the write below persists the stamped text only on
602
+ // validation success.
603
+ const stamped = stampFrontmatterField(
604
+ recipe,
605
+ "schemaVersion",
606
+ String(GUIDE_SCHEMA_VERSION),
607
+ );
608
+ const parsed = parseApiGuide(stamped, { filename: domain });
450
609
  if (!parsed.ok) {
451
610
  const err = parsed.error;
452
611
  const lines: string[] = [
@@ -483,30 +642,97 @@ export const apiLearnTool = defineTool({
483
642
  };
484
643
  }
485
644
 
645
+ // Save target — a function of the guide's own `shortName`, never the
646
+ // `domain` arg. Two guides with different shortNames physically cannot
647
+ // share a directory. An empty/all-symbol shortName throws here (the
648
+ // slug flattens to empty) — refuse with a prescriptive error before
649
+ // any write.
650
+ let slugged: string;
651
+ try {
652
+ slugged = slug(parsed.guide.shortName);
653
+ } catch (err) {
654
+ return {
655
+ content: [
656
+ {
657
+ type: "text",
658
+ text:
659
+ `⚠ Invalid shortName — guide was NOT saved.\n` +
660
+ ` ${err instanceof Error ? err.message : `shortName '${parsed.guide.shortName}' does not slug to a directory name.`}\n` +
661
+ ` Set a valid shortName (lowercase letters, digits, and '-') in the recipe and save again.`,
662
+ },
663
+ ],
664
+ details: { error: "invalid_shortname", domain },
665
+ };
666
+ }
667
+
668
+ // ── Staged-dir collision guard (drift guard, part 1) ──
669
+ // The template stages by `domain` (shortName is still a placeholder at
670
+ // that point), but every later stage (fetch-recipe, scaffold) keys by
671
+ // `slug(shortName)`. When the draft's staged dir basename doesn't match
672
+ // its slug, the save re-stages it to the canonical slug dir (part 2).
673
+ // Before that, refuse if the canonical dir already holds a guide.md
674
+ // with a DIFFERENT shortName — a divergent save would clobber another
675
+ // guide's staged recipe (e.g. a shortName copied from another guide).
676
+ // Same shortName = legitimate update of this guide's own draft; no
677
+ // guide.md = only scaffold siblings, safe to re-stage beside them.
678
+ const canonicalStaged = stagingDirFor(slugged);
679
+ const divergent = basename(dir) !== slugged && isUnderStagingRoot(dir);
680
+ if (divergent && existsSync(join(canonicalStaged, "guide.md"))) {
681
+ const existing = parseApiGuide(
682
+ readFileSync(join(canonicalStaged, "guide.md"), "utf-8"),
683
+ { file: join(canonicalStaged, "guide.md"), filename: slugged },
684
+ );
685
+ const existingShort = existing.ok ? existing.guide.shortName : undefined;
686
+ if (existingShort !== parsed.guide.shortName) {
687
+ return {
688
+ content: [
689
+ {
690
+ type: "text",
691
+ text:
692
+ `⚠ Save refused — '${canonicalStaged}/guide.md' already holds ${existing.ok ? `a different guide ('${existing.guide.shortName}')` : "an unparseable guide"} — not the incoming '${parsed.guide.shortName}'.\n` +
693
+ ` Your draft is staged at '${dir}', but its shortName slugs to '${canonicalStaged}', which already holds staged files${existing.ok ? " for another guide" : ""}.\n` +
694
+ ` Resolve the collision, then save again:\n` +
695
+ ` - If this is a new guide, change \`shortName\` so it slugs to a distinct directory.\n` +
696
+ ` - If you're re-authoring this guide, delete the staged files in '${canonicalStaged}' (or move your draft there), then save.\n` +
697
+ ` Guides dir untouched.`,
698
+ },
699
+ ],
700
+ details: {
701
+ error: "staged_dir_collision",
702
+ domain,
703
+ dir,
704
+ canonicalStaged,
705
+ existing: existingShort ?? null,
706
+ incoming: parsed.guide.shortName,
707
+ },
708
+ };
709
+ }
710
+ }
711
+
486
712
  // Collision detection — another guide (different directory) already
487
713
  // claims one of this guide's `domains:` keys. Valid (that's the whole
488
714
  // point of multi-recipe), but warn so the author knows they're in
489
- // disambiguation territory. Updating the same directory is NOT a
490
- // collision. Names both the directory and the colliding `domains:` key
491
- // so the routing-vs-identity distinction is explicit.
715
+ // disambiguation territory. Updating the same directory (same slug) is
716
+ // NOT a collision. Names both the directory and the colliding `domains:`
717
+ // key so the routing-vs-identity distinction is explicit.
492
718
  const warnings: string[] = [];
493
719
  const collidingDomains: string[] = [];
494
720
  const collidingDirs: string[] = [];
495
721
  for (const d of parsed.guide.domains ?? []) {
496
722
  const existing = findGuidesByDomain(d);
497
723
  for (const m of existing) {
498
- if (m.dirName !== domain && !collidingDirs.includes(m.dirName)) {
724
+ if (m.dirName !== slugged && !collidingDirs.includes(m.dirName)) {
499
725
  collidingDirs.push(m.dirName);
500
726
  }
501
727
  }
502
- if (existing.some((m) => m.dirName !== domain)) {
728
+ if (existing.some((m) => m.dirName !== slugged)) {
503
729
  collidingDomains.push(d);
504
730
  }
505
731
  }
506
732
  if (collidingDomains.length > 0) {
507
733
  const keys = collidingDomains.join(", ");
508
734
  warnings.push(
509
- `⚠ Multi-recipe: writing to directory \`${domain}\`, but \`domains:\` declares [${keys}] which another guide already claims — disambiguation menu applies. Give each guide a distinct \`shortName\`.`,
735
+ `⚠ Multi-recipe: writing to directory \`${slugged}\`, but \`domains:\` declares [${keys}] which another guide already claims — disambiguation menu applies. Give each guide a distinct \`shortName\`.`,
510
736
  );
511
737
  if (desc === undefined) {
512
738
  warnings.push(
@@ -520,16 +746,17 @@ export const apiLearnTool = defineTool({
520
746
 
521
747
  // ── Fail-closed overwrite guard ─────────────────────────
522
748
  // 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.
749
+ // identity anchor. Since the write target is slug(shortName), a
750
+ // pre-existing guide.md there with a DIFFERENT shortName is reachable
751
+ // only via a slug collision — refuse and teach the rename-shortName
752
+ // convention. Same shortName = legitimate update, proceeds.
527
753
  const guidesDir = getUserGuidesDir();
528
- const domainDir = join(guidesDir, domain);
754
+ const domainDir = join(guidesDir, slugged);
529
755
  const filepath = join(domainDir, "guide.md");
530
756
  if (existsSync(filepath)) {
531
757
  const existing = parseApiGuide(readFileSync(filepath, "utf-8"), {
532
- filename: domain,
758
+ file: filepath,
759
+ filename: slugged,
533
760
  });
534
761
  const existingShort = existing.ok ? existing.guide.shortName : undefined;
535
762
  if (existingShort !== parsed.guide.shortName) {
@@ -539,13 +766,11 @@ export const apiLearnTool = defineTool({
539
766
  type: "text",
540
767
  text:
541
768
  `⚠ Refusing to overwrite — guide was NOT saved.\n` +
542
- ` Directory '${domain}' already holds guide '${existingShort ?? "?"}' (guide.md); ` +
769
+ ` Directory '${slugged}' already holds guide '${existingShort ?? "?"}' (guide.md); ` +
543
770
  `the incoming guide is '${parsed.guide.shortName}'.` +
544
771
  (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.`),
772
+ ? `\n Both shortNames slug to the same directory ('${slugged}') — a slug collision. Rename the incoming guide's \`shortName\` so it slugs to a distinct directory.`
773
+ : `\n The existing guide.md is malformed (won't parse). If you intend to replace it, ask the user to run /api delete ${slugged} first.`),
549
774
  },
550
775
  ],
551
776
  details: {
@@ -557,20 +782,174 @@ export const apiLearnTool = defineTool({
557
782
  };
558
783
  }
559
784
  }
785
+ // ── Deletion-safety gate ────────────────────────────────
786
+ // Mirror-save can wipe a sibling silently (accidental /tmp cleanup, or
787
+ // the same-shortName new:true case). Compute the deletion set — siblings
788
+ // in the guides dir absent from the staged dir — and refuse unless the
789
+ // agent confirms. `confirmDeletions` is undescribed by design; the
790
+ // refusal message is its only discovery path.
791
+ const stagedSiblingNames = SIBLING_NAMES.filter((n) =>
792
+ existsSync(join(dir, n)),
793
+ );
794
+ const doomed = SIBLING_NAMES.filter(
795
+ (n) => existsSync(join(domainDir, n)) && !stagedSiblingNames.includes(n),
796
+ );
797
+ if (doomed.length > 0 && !confirmDeletions) {
798
+ return {
799
+ content: [
800
+ {
801
+ type: "text",
802
+ text:
803
+ `⚠ Save refused — these sibling files exist in the guides dir but are absent from your staged /tmp dir and would be deleted: ${doomed.join(", ")}.\n` +
804
+ ` Re-call with confirmDeletions: true to delete them, or restore them in /tmp first.`,
805
+ },
806
+ ],
807
+ details: { error: "deletion_refused", domain, doomed },
808
+ };
809
+ }
810
+
811
+ // ── Guide↔helper validation at save time ───────────────
812
+ // A guide that declares helper/transform usage must have a loadable
813
+ // staged helper with the declared exports. Self-contained — does not
814
+ // touch core/local-helpers.ts (no loadHelper/loadTransform, no
815
+ // disabledHelpers side effects).
816
+ const ops = parsed.guide.operations;
817
+ const needsHelper = ops.some(
818
+ (o) => o.helper === true || o.transform === true,
819
+ );
820
+ if (needsHelper) {
821
+ const stagedHelper = SIBLING_NAMES.find(
822
+ (n) => n.startsWith("helper.") && existsSync(join(dir, n)),
823
+ );
824
+ if (!stagedHelper) {
825
+ return {
826
+ content: [
827
+ {
828
+ type: "text",
829
+ text:
830
+ `⚠ Save refused — the guide declares helper usage (helper: true / transform: true) but no helper.ts is in the staged dir.\n` +
831
+ ` Scaffold one via api-scaffold({domain: "${domain}", helper: true}), or remove the helper: true / transform: true declarations from the guide.`,
832
+ },
833
+ ],
834
+ details: { error: "helper_declared_missing_staged", domain },
835
+ };
836
+ }
837
+ try {
838
+ const mod = await import(pathToFileURL(join(dir, stagedHelper)).href);
839
+ if (
840
+ ops.some((o) => o.helper === true) &&
841
+ typeof mod.default !== "function"
842
+ ) {
843
+ return {
844
+ content: [
845
+ {
846
+ type: "text",
847
+ text:
848
+ `⚠ Save refused — staged ${stagedHelper} has no default export, but an op declares helper: true.\n` +
849
+ ` Uncomment the default export in the staged helper, or drop the helper: true declarations.`,
850
+ },
851
+ ],
852
+ details: { error: "helper_missing_default_export", domain },
853
+ };
854
+ }
855
+ if (
856
+ ops.some((o) => o.transform === true) &&
857
+ typeof mod.transform !== "function"
858
+ ) {
859
+ return {
860
+ content: [
861
+ {
862
+ type: "text",
863
+ text:
864
+ `⚠ Save refused — staged ${stagedHelper} has no transform export, but an op declares transform: true.\n` +
865
+ ` Uncomment the transform export in the staged helper, or drop the transform: true declarations.`,
866
+ },
867
+ ],
868
+ details: { error: "helper_missing_transform_export", domain },
869
+ };
870
+ }
871
+ } catch {
872
+ return {
873
+ content: [
874
+ {
875
+ type: "text",
876
+ text:
877
+ `⚠ Save refused — staged ${stagedHelper} failed to load (syntax error, broken import, or top-level throw).\n` +
878
+ ` Fix the staged helper, or remove the helper: true / transform: true declarations from the guide.`,
879
+ },
880
+ ],
881
+ details: { error: "helper_load_failed", domain },
882
+ };
883
+ }
884
+ }
885
+
886
+ // ── Self-correct the staged root (drift guard, part 2) ──
887
+ // Move the draft to the canonical slug dir and read from there for the
888
+ // rest of save. Runs after all gates pass, so a refused save never
889
+ // mutates /tmp. When the canonical dir already exists it holds the
890
+ // same guide's draft (or only scaffold siblings) — the collision guard
891
+ // above refused a different guide — so merge per-file; otherwise do an
892
+ // atomic whole-dir rename.
893
+ let reStagedNote: string | undefined;
894
+ // `writeDir` is the staged dir the write reads from — reassigned to the
895
+ // canonical slug dir when the passed dir diverges (see above). `dir`
896
+ // stays const so its earlier narrowing survives the closure captures.
897
+ let writeDir = dir;
898
+ if (divergent) {
899
+ const oldName = basename(writeDir);
900
+ try {
901
+ if (existsSync(canonicalStaged)) {
902
+ for (const name of readdirSync(writeDir)) {
903
+ renameSync(join(writeDir, name), join(canonicalStaged, name));
904
+ }
905
+ rmSync(writeDir, { recursive: true, force: true });
906
+ } else {
907
+ renameSync(writeDir, canonicalStaged);
908
+ }
909
+ } catch (err) {
910
+ return {
911
+ content: [
912
+ {
913
+ type: "text",
914
+ text:
915
+ `⚠ Could not re-stage the draft from '${writeDir}' to '${canonicalStaged}' — guide was NOT saved.\n` +
916
+ ` ${err instanceof Error ? err.message : String(err)}\n` +
917
+ ` Move the staged files manually (or re-fetch via api-learn({domain: "${domain}"})), then save again.`,
918
+ },
919
+ ],
920
+ details: { error: "restage_failed", domain, dir, canonicalStaged },
921
+ };
922
+ }
923
+ writeDir = canonicalStaged;
924
+ reStagedNote =
925
+ `Re-staged /${oldName} → ${writeDir} (slug of shortName) — ` +
926
+ `the staged draft moved here; edit these files from now on.`;
927
+ }
928
+
560
929
  mkdirSync(domainDir, { recursive: true });
561
930
 
562
- // ── Write guide ──────────────────────────────────────────
931
+ // ── Write guide + mirror siblings ───────────────────────
563
932
 
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
933
  writeFileSync(filepath, stamped, "utf-8");
934
+
935
+ // Mirror the staged dir: present siblings overwrite the guides-dir
936
+ // counterpart; confirmed-absent siblings are removed.
937
+ const writtenSiblings: string[] = [];
938
+ for (const name of stagedSiblingNames) {
939
+ writeFileSync(
940
+ join(domainDir, name),
941
+ readFileSync(join(writeDir, name), "utf-8"),
942
+ "utf-8",
943
+ );
944
+ writtenSiblings.push(name);
945
+ }
946
+ const deletedSiblings: string[] = [];
947
+ if (confirmDeletions) {
948
+ for (const name of doomed) {
949
+ rmSync(join(domainDir, name), { force: true });
950
+ deletedSiblings.push(name);
951
+ }
952
+ }
574
953
  invalidateCache(); // next api-fetch / api-guide read picks it up
575
954
 
576
955
  const opCount = parsed.guide.operations.length;
@@ -583,16 +962,23 @@ export const apiLearnTool = defineTool({
583
962
  {
584
963
  type: "text",
585
964
  text:
586
- `📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${domain}/guide.md\n` +
587
- ` Domain: ${domain}\n` +
965
+ `📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${slugged}/guide.md\n` +
966
+ ` Directory: ${slugged}\n` +
588
967
  ` Operations: ${opCount} — ${opNames}\n` +
589
968
  ` ${authSummary(parsed.guide.auth)}\n` +
590
969
  ` Verified: ${parsed.guide.verified}\n` +
591
970
  ` Schema version: ${GUIDE_SCHEMA_VERSION}\n` +
971
+ (writtenSiblings.length > 0
972
+ ? ` Written: ${writtenSiblings.join(", ")}\n`
973
+ : "") +
974
+ (deletedSiblings.length > 0
975
+ ? ` Deleted: ${deletedSiblings.join(", ")}\n`
976
+ : "") +
977
+ (reStagedNote ? ` ${reStagedNote}\n` : "") +
592
978
  `\n` +
593
979
  warningBlock +
594
- `Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify.` +
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.`,
980
+ `Test each op via api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}", params: <your verify.json values>}) — pass the values yourself (verify.json feeds /api verify, not api-fetch). /api verify is the user's batch stamp.` +
981
+ `\n⚠ Edit the staged /tmp files, not the saved guide.md — direct edits to guide.md are overwritten on save and invisible to api-fetch until then.`,
596
982
  },
597
983
  ],
598
984
  details: {
@@ -601,6 +987,9 @@ export const apiLearnTool = defineTool({
601
987
  domain,
602
988
  operations: opCount,
603
989
  verified: parsed.guide.verified,
990
+ ...(reStagedNote ? { reStaged: true } : {}),
991
+ ...(writtenSiblings.length > 0 ? { written: writtenSiblings } : {}),
992
+ ...(deletedSiblings.length > 0 ? { deleted: deletedSiblings } : {}),
604
993
  },
605
994
  };
606
995
  },
@@ -609,7 +998,7 @@ export const apiLearnTool = defineTool({
609
998
  const parts: string[] = [theme.fg("toolTitle", theme.bold("api-learn "))];
610
999
  parts.push(theme.fg("accent", `"${args.domain}"`));
611
1000
  if (args.new) parts.push(theme.fg("dim", "✨new"));
612
- else if (args.recipeFile) parts.push(theme.fg("dim", "📝"));
1001
+ else if (args.dir) parts.push(theme.fg("dim", "📝"));
613
1002
  else parts.push(theme.fg("dim", "📖"));
614
1003
  return new Text(parts.join(" "), 0, 0);
615
1004
  },