pi-lean-host 0.3.1 → 0.4.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,9 +28,18 @@ 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";
31
+ import {
32
+ existsSync,
33
+ mkdirSync,
34
+ readFileSync,
35
+ readdirSync,
36
+ renameSync,
37
+ rmSync,
38
+ writeFileSync,
39
+ } from "node:fs";
29
40
  import { tmpdir } from "node:os";
30
- import { join } from "node:path";
41
+ import { basename, join, sep } from "node:path";
42
+ import { pathToFileURL } from "node:url";
31
43
  import {
32
44
  parseApiGuide,
33
45
  stampFrontmatterField,
@@ -45,7 +57,7 @@ import {
45
57
  getUserGuidesDir,
46
58
  findGuidesByDomain,
47
59
  } from "../core/guide-store.js";
48
- import { assertSafeDomain } from "../core/path-template.js";
60
+ import { assertSafeDomain, slug } from "../core/path-template.js";
49
61
 
50
62
  // ═══════════════════════════════════════════════════════════════════
51
63
  // Staged working copy (/tmp) — the draft the agent edits between saves
@@ -59,20 +71,39 @@ export function setStagingRoot(dir: string): void {
59
71
  _stagingRoot = dir;
60
72
  }
61
73
 
62
- /** Deterministic draft path: `<root>/<domain>/guide.md`. */
63
- function stagingPathFor(domain: string): string {
64
- return join(_stagingRoot, domain, "guide.md");
74
+ /** Deterministic staged dir: `<root>/<key>/`. The key is the requested
75
+ * `domain` for templates (placeholder shortName) and `slug(shortName)` for
76
+ * fetched recipes (which is the on-disk dirName). */
77
+ function stagingDirFor(key: string): string {
78
+ return join(_stagingRoot, key);
79
+ }
80
+
81
+ /** True when `p` is a staged dir under the staging root (the root itself
82
+ * excluded — save must never try to rename the whole root). */
83
+ function isUnderStagingRoot(p: string): boolean {
84
+ return p !== _stagingRoot && p.startsWith(`${_stagingRoot}${sep}`);
65
85
  }
66
86
 
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;
87
+ /** Write the working copy (template or fetched raw recipe) to the staged
88
+ * dir. Returns the staged *dir* path (multi-file — siblings write to the
89
+ * same dir). */
90
+ function writeStagedDraft(key: string, raw: string): string {
91
+ const dir = stagingDirFor(key);
92
+ mkdirSync(dir, { recursive: true });
93
+ writeFileSync(join(dir, "guide.md"), raw, "utf-8");
94
+ return dir;
74
95
  }
75
96
 
97
+ /** Sibling artifact names mirrored between the staged dir and the guides
98
+ * dir on save (guide.md is always written). The helper extension set mirrors
99
+ * core/local-helpers.ts's `findHelperFile` resolution (.ts → .mjs → .js). */
100
+ const SIBLING_NAMES = [
101
+ "helper.ts",
102
+ "helper.mjs",
103
+ "helper.js",
104
+ "verify.json",
105
+ ] as const;
106
+
76
107
  // ═══════════════════════════════════════════════════════════════════
77
108
  // Placeholder skeleton (retired worked example)
78
109
  // ═══════════════════════════════════════════════════════════════════
@@ -150,9 +181,7 @@ function authSummary(auth: AuthConfig): string {
150
181
  const parts: string[] = [];
151
182
  for (const [header, secretName] of Object.entries(auth.secretRefs ?? {})) {
152
183
  const prefix = auth.headerPrefixes?.[header];
153
- parts.push(
154
- `${header} ← secret ${secretName}${prefix === undefined ? "" : ` (${prefix})`}`,
155
- );
184
+ parts.push(`${header} ← secret ${secretName}${prefix ? ` (${prefix})` : ""}`);
156
185
  }
157
186
  for (const [param, secretName] of Object.entries(auth.secretQueryRefs ?? {})) {
158
187
  parts.push(`?${param} ← secret ${secretName}`);
@@ -205,7 +234,7 @@ const AUTHORING_MANUAL = [
205
234
  ` \`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
235
  ` \`params.<name>.required\` — true → query param must be supplied (verify skips the op if missing; api-fetch errors before the request)`,
207
236
  ` \`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`,
237
+ ` \`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
238
  ` \`passthrough\` — true → forward undeclared caller params onto the query string`,
210
239
  ` \`parse\` — op-level responseShape override (format/charset) for this operation`,
211
240
  "",
@@ -227,40 +256,64 @@ const AUTHORING_MANUAL = [
227
256
  " date formats, auth caveats, field semantics, endpoint quirks. Surfaced by",
228
257
  " api-guide as 'Guide notes'.",
229
258
  "",
230
- "Call api-learn({domain: '<domain>', recipeFile: '<staged file path>'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
259
+ "## Saving (mirror-save)",
260
+ " Save reads every staged file (guide.md + helper.ts + verify.json when present) and",
261
+ " mirrors it into the guides dir. A sibling present in the guides dir but absent from",
262
+ " the staged /tmp dir would be DELETED — save refuses and names it; re-call with",
263
+ " confirmDeletions: true to proceed (that flag is discovered only via the refusal message,",
264
+ " never the tool description). A guide declaring helper: true / transform: true must",
265
+ " have a loadable staged helper.ts.",
266
+ "",
267
+ "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
268
  ].join("\n");
232
269
 
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).
270
+ /** Template path — write the placeholder skeleton to the staging dir and
271
+ * surface the guide.md path + staged dir (the agent edits the file, not an
272
+ * inline copy).
235
273
  * Fail-closed: the as-is template cannot save (placeholder `apiHost`
236
274
  * is rejected by requireHttpUrl). */
237
275
  function stageTemplate(domain: string): string {
238
- const path = writeStagedDraft(domain, placeholderSkeleton(domain));
276
+ const dir = writeStagedDraft(domain, placeholderSkeleton(domain));
239
277
  return (
240
278
  AUTHORING_MANUAL +
241
279
  "\n\n" +
242
- `📝 Template for '${domain}' written to ${path}\n` +
280
+ `📝 Template for '${domain}' written to ${join(dir, "guide.md")}\n` +
243
281
  ` Edit the file (or append ops via bash), then call ` +
244
- `api-learn({domain: "${domain}", recipeFile: "${path}"}) to validate and save.\n` +
282
+ `api-learn({domain: "${domain}", dir: "${dir}"}) to validate and save.\n` +
245
283
  ` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`
246
284
  );
247
285
  }
248
286
 
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. */
287
+ /** Fetch-recipe response — the saved guide's raw recipe (and present
288
+ * siblings) staged to the staging dir, with the dir path + resolved dirName
289
+ * surfaced. Staging keys on `slug(shortName)` (the on-disk dirName in steady
290
+ * state), and the re-save self-keys off the draft's own shortName — no
291
+ * "pass the directory name as domain" guidance (that arg is cosmetic on
292
+ * save). The inline YAML block is dropped: the staged files are the source
293
+ * of truth the agent edits. */
254
294
  function stageFetchedRecipe(
255
295
  domain: string,
256
296
  guide: ApiGuide,
257
297
  dirName: string,
258
298
  ): AgentToolResult<unknown> {
259
- const raw = readFileSync(
260
- join(getUserGuidesDir(), dirName, "guide.md"),
299
+ const sourceDir = join(getUserGuidesDir(), dirName);
300
+ const stagedKey = slug(guide.shortName);
301
+ const stagedDir = stagingDirFor(stagedKey);
302
+ mkdirSync(stagedDir, { recursive: true });
303
+ // guide.md always; helper.ts / verify.json when present.
304
+ writeFileSync(
305
+ join(stagedDir, "guide.md"),
306
+ readFileSync(join(sourceDir, "guide.md"), "utf-8"),
261
307
  "utf-8",
262
308
  );
263
- const path = writeStagedDraft(domain, raw);
309
+ const stagedSiblings: string[] = [];
310
+ for (const name of SIBLING_NAMES) {
311
+ const src = join(sourceDir, name);
312
+ if (existsSync(src)) {
313
+ writeFileSync(join(stagedDir, name), readFileSync(src, "utf-8"), "utf-8");
314
+ stagedSiblings.push(name);
315
+ }
316
+ }
264
317
  return {
265
318
  content: [
266
319
  {
@@ -270,14 +323,23 @@ function stageFetchedRecipe(
270
323
  "\n\n" +
271
324
  `📖 Current recipe for '${domain}' — guide '${guide.shortName}'\n` +
272
325
  ` 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` +
326
+ ` Staged dir: ${stagedDir}\n` +
327
+ (stagedSiblings.length > 0
328
+ ? ` Siblings staged: ${stagedSiblings.join(", ")}\n`
329
+ : "") +
330
+ ` To edit: edit the staged files with the edit tool or bash, then call ` +
331
+ `api-learn({domain: "${domain}", dir: "${stagedDir}"}) — the guide ` +
332
+ `saves to its own \`${stagedKey}\` folder (self-keyed by shortName).\n` +
277
333
  ` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`,
278
334
  },
279
335
  ],
280
- details: { mode: "fetch", domain, dirName, guide: guide.shortName },
336
+ details: {
337
+ mode: "fetch",
338
+ domain,
339
+ dirName,
340
+ guide: guide.shortName,
341
+ stagedDir,
342
+ },
281
343
  };
282
344
  }
283
345
 
@@ -310,27 +372,35 @@ export const apiLearnTool = defineTool({
310
372
  description:
311
373
  "Author an API guide for a domain. " +
312
374
  "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.",
375
+ "Call with {domain} and no dir to fetch an existing guide's current raw recipe (and its sibling files). " +
376
+ "Call with {domain, dir} to validate and save.\n\n" +
377
+ "Authoring order (follow this to avoid the common mis-ordering):\n" +
378
+ "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" +
379
+ "2. api-learn({domain, new: true}) — get a fresh template, fill the recipe, then api-learn({domain, dir}) to save it.\n" +
380
+ "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" +
381
+ "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" +
382
+ "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
383
 
316
384
  parameters: Type.Object({
317
385
  domain: Type.String({
318
386
  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.",
387
+ "Domain (e.g. 'example.com'). With no dir it's the routing domain " +
388
+ "for fetch-recipe lookup; with `dir` it's display/error context only — " +
389
+ "the guide saves to its own slug(shortName) folder.",
321
390
  }),
322
- recipeFile: Type.Optional(
391
+ dir: Type.Optional(
323
392
  Type.String({
324
393
  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).",
394
+ "Path to the staged directory (written by a prior api-learn fetch/template or api-scaffold call to /tmp/pi-lean-host/<slug(shortName)>/). " +
395
+ "guide.md is read, validated, and saved; present helper.ts / verify.json siblings are mirrored. " +
396
+ "Omit to fetch the current raw recipe of an existing guide (or get a template when none exists).",
327
397
  }),
328
398
  ),
329
399
  guide: Type.Optional(
330
400
  Type.String({
331
401
  description:
332
402
  "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).",
403
+ "Only used with the fetch-recipe path (no dir).",
334
404
  }),
335
405
  ),
336
406
  new: Type.Optional(
@@ -340,19 +410,24 @@ export const apiLearnTool = defineTool({
340
410
  "Does not touch any existing guide.",
341
411
  }),
342
412
  ),
413
+ // Undescribed by design — the only discovery path is the deletion-safety
414
+ // gate's refusal message.
415
+ confirmDeletions: Type.Optional(Type.Boolean()),
343
416
  }),
344
417
 
345
418
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
346
419
  const {
347
420
  domain,
348
- recipeFile,
421
+ dir,
349
422
  guide: guideSelector,
350
423
  new: isNew,
424
+ confirmDeletions,
351
425
  } = params as {
352
426
  domain: string;
353
- recipeFile?: string;
427
+ dir?: string;
354
428
  guide?: string;
355
429
  new?: boolean;
430
+ confirmDeletions?: boolean;
356
431
  };
357
432
 
358
433
  // ── Validate domain (path-traversal guard) ─────────────
@@ -378,10 +453,11 @@ export const apiLearnTool = defineTool({
378
453
  };
379
454
  }
380
455
 
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()) {
456
+ // ── No dir → fetch-recipe ──────────────────────────────
457
+ // 0 guides → template staged; 1 guide → raw recipe + siblings staged +
458
+ // dirName surfaced; N guides → disambiguation menu (guide selector
459
+ // resolves it).
460
+ if (!dir || !dir.trim()) {
385
461
  const matches = findGuidesByDomain(domain);
386
462
  if (matches.length === 0) {
387
463
  return {
@@ -425,24 +501,25 @@ export const apiLearnTool = defineTool({
425
501
  return stageFetchedRecipe(domain, sel.guide, sel.dirName);
426
502
  }
427
503
 
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.
504
+ // ── Save from a staged directory ────────────────────────
505
+ // Read guide.md (required) from the staged dir, then run the identical
506
+ // validate → stamp → write path. A missing/unreadable dir is a clear
507
+ // error; guides dir untouched.
431
508
  let recipe: string;
432
509
  try {
433
- recipe = readFileSync(recipeFile, "utf-8");
510
+ recipe = readFileSync(join(dir, "guide.md"), "utf-8");
434
511
  } catch {
435
512
  return {
436
513
  content: [
437
514
  {
438
515
  type: "text",
439
516
  text:
440
- `⚠ Could not read recipe file '${recipeFile}' — guide was NOT saved.\n` +
517
+ `⚠ Could not read staged guide from '${join(dir, "guide.md")}' — guide was NOT saved.\n` +
441
518
  ` 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.`,
519
+ `(or a template with {domain, new: true}), then edit the staged files and save with dir.`,
443
520
  },
444
521
  ],
445
- details: { error: "recipe_file_unreadable", domain, recipeFile },
522
+ details: { error: "staged_dir_unreadable", domain, dir },
446
523
  };
447
524
  }
448
525
 
@@ -483,30 +560,97 @@ export const apiLearnTool = defineTool({
483
560
  };
484
561
  }
485
562
 
563
+ // Save target — a function of the guide's own `shortName`, never the
564
+ // `domain` arg. Two guides with different shortNames physically cannot
565
+ // share a directory. An empty/all-symbol shortName throws here (the
566
+ // slug flattens to empty) — refuse with a prescriptive error before
567
+ // any write.
568
+ let slugged: string;
569
+ try {
570
+ slugged = slug(parsed.guide.shortName);
571
+ } catch (err) {
572
+ return {
573
+ content: [
574
+ {
575
+ type: "text",
576
+ text:
577
+ `⚠ Invalid shortName — guide was NOT saved.\n` +
578
+ ` ${err instanceof Error ? err.message : `shortName '${parsed.guide.shortName}' does not slug to a directory name.`}\n` +
579
+ ` Set a valid shortName (lowercase letters, digits, and '-') in the recipe and save again.`,
580
+ },
581
+ ],
582
+ details: { error: "invalid_shortname", domain },
583
+ };
584
+ }
585
+
586
+ // ── Staged-dir collision guard (drift guard, part 1) ──
587
+ // The template stages by `domain` (shortName is still a placeholder at
588
+ // that point), but every later stage (fetch-recipe, scaffold) keys by
589
+ // `slug(shortName)`. When the draft's staged dir basename doesn't match
590
+ // its slug, the save re-stages it to the canonical slug dir (part 2).
591
+ // Before that, refuse if the canonical dir already holds a guide.md
592
+ // with a DIFFERENT shortName — a divergent save would clobber another
593
+ // guide's staged recipe (e.g. a shortName copied from another guide).
594
+ // Same shortName = legitimate update of this guide's own draft; no
595
+ // guide.md = only scaffold siblings, safe to re-stage beside them.
596
+ const canonicalStaged = stagingDirFor(slugged);
597
+ const divergent = basename(dir) !== slugged && isUnderStagingRoot(dir);
598
+ if (divergent && existsSync(join(canonicalStaged, "guide.md"))) {
599
+ const existing = parseApiGuide(
600
+ readFileSync(join(canonicalStaged, "guide.md"), "utf-8"),
601
+ { filename: slugged },
602
+ );
603
+ const existingShort = existing.ok ? existing.guide.shortName : undefined;
604
+ if (existingShort !== parsed.guide.shortName) {
605
+ return {
606
+ content: [
607
+ {
608
+ type: "text",
609
+ text:
610
+ `⚠ 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` +
611
+ ` Your draft is staged at '${dir}', but its shortName slugs to '${canonicalStaged}', which already holds staged files${existing.ok ? " for another guide" : ""}.\n` +
612
+ ` Resolve the collision, then save again:\n` +
613
+ ` - If this is a new guide, change \`shortName\` so it slugs to a distinct directory.\n` +
614
+ ` - If you're re-authoring this guide, delete the staged files in '${canonicalStaged}' (or move your draft there), then save.\n` +
615
+ ` Guides dir untouched.`,
616
+ },
617
+ ],
618
+ details: {
619
+ error: "staged_dir_collision",
620
+ domain,
621
+ dir,
622
+ canonicalStaged,
623
+ existing: existingShort ?? null,
624
+ incoming: parsed.guide.shortName,
625
+ },
626
+ };
627
+ }
628
+ }
629
+
486
630
  // Collision detection — another guide (different directory) already
487
631
  // claims one of this guide's `domains:` keys. Valid (that's the whole
488
632
  // 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.
633
+ // disambiguation territory. Updating the same directory (same slug) is
634
+ // NOT a collision. Names both the directory and the colliding `domains:`
635
+ // key so the routing-vs-identity distinction is explicit.
492
636
  const warnings: string[] = [];
493
637
  const collidingDomains: string[] = [];
494
638
  const collidingDirs: string[] = [];
495
639
  for (const d of parsed.guide.domains ?? []) {
496
640
  const existing = findGuidesByDomain(d);
497
641
  for (const m of existing) {
498
- if (m.dirName !== domain && !collidingDirs.includes(m.dirName)) {
642
+ if (m.dirName !== slugged && !collidingDirs.includes(m.dirName)) {
499
643
  collidingDirs.push(m.dirName);
500
644
  }
501
645
  }
502
- if (existing.some((m) => m.dirName !== domain)) {
646
+ if (existing.some((m) => m.dirName !== slugged)) {
503
647
  collidingDomains.push(d);
504
648
  }
505
649
  }
506
650
  if (collidingDomains.length > 0) {
507
651
  const keys = collidingDomains.join(", ");
508
652
  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\`.`,
653
+ `⚠ 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
654
  );
511
655
  if (desc === undefined) {
512
656
  warnings.push(
@@ -520,16 +664,16 @@ export const apiLearnTool = defineTool({
520
664
 
521
665
  // ── Fail-closed overwrite guard ─────────────────────────
522
666
  // 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.
667
+ // identity anchor. Since the write target is slug(shortName), a
668
+ // pre-existing guide.md there with a DIFFERENT shortName is reachable
669
+ // only via a slug collision — refuse and teach the rename-shortName
670
+ // convention. Same shortName = legitimate update, proceeds.
527
671
  const guidesDir = getUserGuidesDir();
528
- const domainDir = join(guidesDir, domain);
672
+ const domainDir = join(guidesDir, slugged);
529
673
  const filepath = join(domainDir, "guide.md");
530
674
  if (existsSync(filepath)) {
531
675
  const existing = parseApiGuide(readFileSync(filepath, "utf-8"), {
532
- filename: domain,
676
+ filename: slugged,
533
677
  });
534
678
  const existingShort = existing.ok ? existing.guide.shortName : undefined;
535
679
  if (existingShort !== parsed.guide.shortName) {
@@ -539,13 +683,11 @@ export const apiLearnTool = defineTool({
539
683
  type: "text",
540
684
  text:
541
685
  `⚠ Refusing to overwrite — guide was NOT saved.\n` +
542
- ` Directory '${domain}' already holds guide '${existingShort ?? "?"}' (guide.md); ` +
686
+ ` Directory '${slugged}' already holds guide '${existingShort ?? "?"}' (guide.md); ` +
543
687
  `the incoming guide is '${parsed.guide.shortName}'.` +
544
688
  (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.`),
689
+ ? `\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.`
690
+ : `\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
691
  },
550
692
  ],
551
693
  details: {
@@ -557,9 +699,153 @@ export const apiLearnTool = defineTool({
557
699
  };
558
700
  }
559
701
  }
702
+ // ── Deletion-safety gate ────────────────────────────────
703
+ // Mirror-save can wipe a sibling silently (accidental /tmp cleanup, or
704
+ // the same-shortName new:true case). Compute the deletion set — siblings
705
+ // in the guides dir absent from the staged dir — and refuse unless the
706
+ // agent confirms. `confirmDeletions` is undescribed by design; the
707
+ // refusal message is its only discovery path.
708
+ const stagedSiblingNames = SIBLING_NAMES.filter((n) =>
709
+ existsSync(join(dir, n)),
710
+ );
711
+ const doomed = SIBLING_NAMES.filter(
712
+ (n) => existsSync(join(domainDir, n)) && !stagedSiblingNames.includes(n),
713
+ );
714
+ if (doomed.length > 0 && !confirmDeletions) {
715
+ return {
716
+ content: [
717
+ {
718
+ type: "text",
719
+ text:
720
+ `⚠ 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` +
721
+ ` Re-call with confirmDeletions: true to delete them, or restore them in /tmp first.`,
722
+ },
723
+ ],
724
+ details: { error: "deletion_refused", domain, doomed },
725
+ };
726
+ }
727
+
728
+ // ── Guide↔helper validation at save time ───────────────
729
+ // A guide that declares helper/transform usage must have a loadable
730
+ // staged helper with the declared exports. Self-contained — does not
731
+ // touch core/local-helpers.ts (no loadHelper/loadTransform, no
732
+ // disabledHelpers side effects).
733
+ const ops = parsed.guide.operations;
734
+ const needsHelper = ops.some(
735
+ (o) => o.helper === true || o.transform === true,
736
+ );
737
+ if (needsHelper) {
738
+ const stagedHelper = SIBLING_NAMES.find(
739
+ (n) => n.startsWith("helper.") && existsSync(join(dir, n)),
740
+ );
741
+ if (!stagedHelper) {
742
+ return {
743
+ content: [
744
+ {
745
+ type: "text",
746
+ text:
747
+ `⚠ Save refused — the guide declares helper usage (helper: true / transform: true) but no helper.ts is in the staged dir.\n` +
748
+ ` Scaffold one via api-scaffold({domain: "${domain}", helper: true}), or remove the helper: true / transform: true declarations from the guide.`,
749
+ },
750
+ ],
751
+ details: { error: "helper_declared_missing_staged", domain },
752
+ };
753
+ }
754
+ try {
755
+ const mod = await import(pathToFileURL(join(dir, stagedHelper)).href);
756
+ if (
757
+ ops.some((o) => o.helper === true) &&
758
+ typeof mod.default !== "function"
759
+ ) {
760
+ return {
761
+ content: [
762
+ {
763
+ type: "text",
764
+ text:
765
+ `⚠ Save refused — staged ${stagedHelper} has no default export, but an op declares helper: true.\n` +
766
+ ` Uncomment the default export in the staged helper, or drop the helper: true declarations.`,
767
+ },
768
+ ],
769
+ details: { error: "helper_missing_default_export", domain },
770
+ };
771
+ }
772
+ if (
773
+ ops.some((o) => o.transform === true) &&
774
+ typeof mod.transform !== "function"
775
+ ) {
776
+ return {
777
+ content: [
778
+ {
779
+ type: "text",
780
+ text:
781
+ `⚠ Save refused — staged ${stagedHelper} has no transform export, but an op declares transform: true.\n` +
782
+ ` Uncomment the transform export in the staged helper, or drop the transform: true declarations.`,
783
+ },
784
+ ],
785
+ details: { error: "helper_missing_transform_export", domain },
786
+ };
787
+ }
788
+ } catch {
789
+ return {
790
+ content: [
791
+ {
792
+ type: "text",
793
+ text:
794
+ `⚠ Save refused — staged ${stagedHelper} failed to load (syntax error, broken import, or top-level throw).\n` +
795
+ ` Fix the staged helper, or remove the helper: true / transform: true declarations from the guide.`,
796
+ },
797
+ ],
798
+ details: { error: "helper_load_failed", domain },
799
+ };
800
+ }
801
+ }
802
+
803
+ // ── Self-correct the staged root (drift guard, part 2) ──
804
+ // Move the draft to the canonical slug dir and read from there for the
805
+ // rest of save. Runs after all gates pass, so a refused save never
806
+ // mutates /tmp. When the canonical dir already exists it holds the
807
+ // same guide's draft (or only scaffold siblings) — the collision guard
808
+ // above refused a different guide — so merge per-file; otherwise do an
809
+ // atomic whole-dir rename.
810
+ let reStagedNote: string | undefined;
811
+ // `writeDir` is the staged dir the write reads from — reassigned to the
812
+ // canonical slug dir when the passed dir diverges (see above). `dir`
813
+ // stays const so its earlier narrowing survives the closure captures.
814
+ let writeDir = dir;
815
+ if (divergent) {
816
+ const oldName = basename(writeDir);
817
+ try {
818
+ if (existsSync(canonicalStaged)) {
819
+ for (const name of readdirSync(writeDir)) {
820
+ renameSync(join(writeDir, name), join(canonicalStaged, name));
821
+ }
822
+ rmSync(writeDir, { recursive: true, force: true });
823
+ } else {
824
+ renameSync(writeDir, canonicalStaged);
825
+ }
826
+ } catch (err) {
827
+ return {
828
+ content: [
829
+ {
830
+ type: "text",
831
+ text:
832
+ `⚠ Could not re-stage the draft from '${writeDir}' to '${canonicalStaged}' — guide was NOT saved.\n` +
833
+ ` ${err instanceof Error ? err.message : String(err)}\n` +
834
+ ` Move the staged files manually (or re-fetch via api-learn({domain: "${domain}"})), then save again.`,
835
+ },
836
+ ],
837
+ details: { error: "restage_failed", domain, dir, canonicalStaged },
838
+ };
839
+ }
840
+ writeDir = canonicalStaged;
841
+ reStagedNote =
842
+ `Re-staged /${oldName} → ${writeDir} (slug of shortName) — ` +
843
+ `the staged draft moved here; edit these files from now on.`;
844
+ }
845
+
560
846
  mkdirSync(domainDir, { recursive: true });
561
847
 
562
- // ── Write guide ──────────────────────────────────────────
848
+ // ── Write guide + mirror siblings ───────────────────────
563
849
 
564
850
  // Stamp schemaVersion on save — each guide records the schema vintage
565
851
  // it was authored against (the per-guide vintage that stale detection
@@ -571,6 +857,25 @@ export const apiLearnTool = defineTool({
571
857
  String(GUIDE_SCHEMA_VERSION),
572
858
  );
573
859
  writeFileSync(filepath, stamped, "utf-8");
860
+
861
+ // Mirror the staged dir: present siblings overwrite the guides-dir
862
+ // counterpart; confirmed-absent siblings are removed.
863
+ const writtenSiblings: string[] = [];
864
+ for (const name of stagedSiblingNames) {
865
+ writeFileSync(
866
+ join(domainDir, name),
867
+ readFileSync(join(writeDir, name), "utf-8"),
868
+ "utf-8",
869
+ );
870
+ writtenSiblings.push(name);
871
+ }
872
+ const deletedSiblings: string[] = [];
873
+ if (confirmDeletions) {
874
+ for (const name of doomed) {
875
+ rmSync(join(domainDir, name), { force: true });
876
+ deletedSiblings.push(name);
877
+ }
878
+ }
574
879
  invalidateCache(); // next api-fetch / api-guide read picks it up
575
880
 
576
881
  const opCount = parsed.guide.operations.length;
@@ -583,16 +888,23 @@ export const apiLearnTool = defineTool({
583
888
  {
584
889
  type: "text",
585
890
  text:
586
- `📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${domain}/guide.md\n` +
587
- ` Domain: ${domain}\n` +
891
+ `📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${slugged}/guide.md\n` +
892
+ ` Directory: ${slugged}\n` +
588
893
  ` Operations: ${opCount} — ${opNames}\n` +
589
894
  ` ${authSummary(parsed.guide.auth)}\n` +
590
895
  ` Verified: ${parsed.guide.verified}\n` +
591
896
  ` Schema version: ${GUIDE_SCHEMA_VERSION}\n` +
897
+ (writtenSiblings.length > 0
898
+ ? ` Written: ${writtenSiblings.join(", ")}\n`
899
+ : "") +
900
+ (deletedSiblings.length > 0
901
+ ? ` Deleted: ${deletedSiblings.join(", ")}\n`
902
+ : "") +
903
+ (reStagedNote ? ` ${reStagedNote}\n` : "") +
592
904
  `\n` +
593
905
  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.`,
906
+ `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.` +
907
+ `\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
908
  },
597
909
  ],
598
910
  details: {
@@ -601,6 +913,9 @@ export const apiLearnTool = defineTool({
601
913
  domain,
602
914
  operations: opCount,
603
915
  verified: parsed.guide.verified,
916
+ ...(reStagedNote ? { reStaged: true } : {}),
917
+ ...(writtenSiblings.length > 0 ? { written: writtenSiblings } : {}),
918
+ ...(deletedSiblings.length > 0 ? { deleted: deletedSiblings } : {}),
604
919
  },
605
920
  };
606
921
  },
@@ -609,7 +924,7 @@ export const apiLearnTool = defineTool({
609
924
  const parts: string[] = [theme.fg("toolTitle", theme.bold("api-learn "))];
610
925
  parts.push(theme.fg("accent", `"${args.domain}"`));
611
926
  if (args.new) parts.push(theme.fg("dim", "✨new"));
612
- else if (args.recipeFile) parts.push(theme.fg("dim", "📝"));
927
+ else if (args.dir) parts.push(theme.fg("dim", "📝"));
613
928
  else parts.push(theme.fg("dim", "📖"));
614
929
  return new Text(parts.join(" "), 0, 0);
615
930
  },