pi-braid 0.40.3 → 0.40.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/AGENTS.md +17 -18
  2. package/README.md +116 -130
  3. package/TOOLS.md +35 -35
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/agent-environment/index.js +4 -3
  6. package/dist/extensions/core/prompt-builder/index.js +12 -7
  7. package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
  8. package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
  9. package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
  10. package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
  11. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  12. package/dist/extensions/core/skills-tool/auto-inject.d.ts +178 -17
  13. package/dist/extensions/core/skills-tool/auto-inject.js +264 -23
  14. package/dist/extensions/core/skills-tool/index.d.ts +70 -2
  15. package/dist/extensions/core/skills-tool/index.js +149 -15
  16. package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
  17. package/dist/extensions/core/skills-tool/reach.js +213 -0
  18. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +74 -13
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +105 -24
  20. package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
  21. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
  22. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
  23. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
  24. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
  25. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
  26. package/dist/extensions/enforcement/resume-state.d.ts +76 -0
  27. package/dist/extensions/enforcement/resume-state.js +90 -0
  28. package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
  29. package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
  30. package/dist/extensions/enforcement/whisper.d.ts +12 -0
  31. package/dist/extensions/enforcement/whisper.js +16 -1
  32. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
  33. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
  34. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
  35. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
  36. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
  37. package/dist/lib/config/braid-paths.d.ts +14 -0
  38. package/dist/lib/config/braid-paths.js +18 -0
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +16 -0
  41. package/dist/lib/detection/context-tiers.d.ts +47 -3
  42. package/dist/lib/detection/context-tiers.js +122 -13
  43. package/dist/lib/events/turn-boundary.d.ts +78 -0
  44. package/dist/lib/events/turn-boundary.js +91 -0
  45. package/dist/lib/orchestrator/workers.d.ts +3 -2
  46. package/dist/lib/orchestrator/workers.js +22 -4
  47. package/dist/lib/state/global-state.d.ts +1 -1
  48. package/docs/CONTEXT-POLICY.md +8 -0
  49. package/docs/LOCAL_DEV.md +0 -1
  50. package/docs/ROADMAP.md +5 -5
  51. package/docs/SETUP.md +19 -18
  52. package/package.json +2 -1
  53. package/skills/herdr-topology/SKILL.md +6 -1
  54. package/skills/research/SKILL.md +32 -0
  55. package/skills/subagent-orchestration/SKILL.md +2 -2
  56. package/src/extensions/core/agent-environment/index.ts +4 -3
  57. package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
  58. package/src/extensions/core/prompt-builder/index.ts +12 -7
  59. package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
  60. package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
  61. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  62. package/src/extensions/core/skills-tool/auto-inject.ts +350 -27
  63. package/src/extensions/core/skills-tool/index.ts +217 -15
  64. package/src/extensions/core/skills-tool/reach.ts +256 -0
  65. package/src/extensions/core/skills-tool/skill-triggers.ts +130 -23
  66. package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
  67. package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
  68. package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
  69. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
  70. package/src/extensions/enforcement/resume-state.ts +127 -0
  71. package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
  72. package/src/extensions/enforcement/whisper.ts +21 -1
  73. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
  74. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
  75. package/src/extensions/memory/AGENTS.md +25 -1
  76. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
  77. package/src/lib/config/braid-paths.ts +20 -0
  78. package/src/lib/config/braid-settings.ts +46 -0
  79. package/src/lib/detection/context-tiers.ts +186 -13
  80. package/src/lib/events/AGENTS.md +1 -0
  81. package/src/lib/events/turn-boundary.ts +115 -0
  82. package/src/lib/orchestrator/workers.ts +33 -12
  83. package/src/lib/state/global-state.ts +1 -0
  84. package/src/lib/utils/AGENTS.md +1 -1
  85. package/src/types/extension-context.d.ts +22 -79
@@ -107,6 +107,38 @@ curl -sL --max-time 10 'https://<instance>/search?q=query&format=json'
107
107
 
108
108
  **Do not rely on this.** The JSON API is disabled on most public instances. Use Method A (DuckDuckGo HTML) instead.
109
109
 
110
+ ### Method E: Reading an X Post (oEmbed, No Auth)
111
+
112
+ A direct fetch of an X status URL is refused (403), and the page renders its
113
+ text with JavaScript. The embed endpoint serves the same post as JSON, with
114
+ no login and no key:
115
+
116
+ ```bash
117
+ curl -s "https://publish.x.com/oembed?url=https%3A%2F%2Fx.com%2F<account>%2Fstatus%2F<id>&omit_script=true"
118
+ ```
119
+
120
+ - `publish.x.com` is the live host. `publish.twitter.com` answers 301 to it,
121
+ so a client that does not follow redirects gets an empty body (`curl -L`
122
+ there).
123
+ - The `url` parameter is the status URL percent-encoded (`%3A` for `:`, `%2F`
124
+ for `/`). Unencoded, the link's own `?` and `&` read as oEmbed parameters
125
+ instead of as part of the link.
126
+ - The response is application/json: the author name and handle, and an HTML
127
+ blockquote holding the post text and its date. That text is HTML-escaped
128
+ (`&mdash;` before the author name), so decode entities before quoting.
129
+
130
+ **What it does not give.** Text only - no media, no reply thread, no quoted
131
+ post body. A post X will not render fails instead of degrading: deleted,
132
+ protected, and age-gated posts answer with an error page and a 4xx rather
133
+ than JSON (deleted verified at 404), so check the status and content type
134
+ before parsing. A bare account URL has no status id to embed - it returns a
135
+ timeline anchor link with no post text, so an account's page still needs
136
+ another route.
137
+
138
+ Verified against public posts of two different accounts. Public nitter
139
+ instances are not a fallback any more: X's cease-and-desist letters took them
140
+ down, and `nitter.net` now serves only an offline notice.
141
+
110
142
  ---
111
143
 
112
144
  ## Fact Verification
@@ -323,7 +323,7 @@ herdr action=send pane=<successor> text="[agent:orchestrator→successor] Read /
323
323
 
324
324
  Best for a successor that will orchestrate subagents. TUI pi persists, accepts signaling, can spawn its own workers.
325
325
 
326
- 3. Transfer mastership: the current session closes when the successor completes. The successor can close the predecessor's pane via `herdr action=stop pane=<predecessor-pane>`.
326
+ 3. Transfer mastership: the current session closes when the successor completes. The successor closes the predecessor's pane with `herdr_pane close <predecessor-pane>` - the predecessor cannot close the pane it runs in, so the incoming seat owns that one close and the transfer ends there.
327
327
  4. The successor starts clean (no bloat) and reads the handoff.
328
328
 
329
329
  This is a **pipeline, not a loop**: each session is a fresh stage. Never compact above 70% - cascade instead.
@@ -410,7 +410,7 @@ At regular intervals (every few turns, or when spawning new work), check for sta
410
410
  2. **Inspect each pane** - For each pane that looks complete (long idle, exited to shell prompt, error message), read its visible content:
411
411
  `herdr action=read pane=<id> source=visible`
412
412
  3. **Close completed panes** - If a worker signaled completion and was approved, or crashed and was not restarted:
413
- `herdr action=stop pane=<id>`
413
+ `herdr_pane close <pane>`
414
414
  4. **Close error-state panes** - If a pane shows a provider error or retry loop with no recovery path, close it rather than leaving it spinning.
415
415
 
416
416
  ### Lock cleanup
@@ -106,9 +106,10 @@ export function gatherL1Environment(_pi: ExtensionAPI, ctx: ExtensionContext): L
106
106
  };
107
107
  }
108
108
 
109
- // The L1 environment section renders in the prompt-builder's instanceSection
110
- // (instance-composition.ts), which carries the volatile data in the Instance
111
- // block instead of a separate section.
109
+ // The L1 environment data is consumed by instance-composition.ts: the
110
+ // volatile stats (elapsed, last event, turns, tool average) render only in
111
+ // the system_info tool, while the compact prompt line takes just the PID,
112
+ // which is process-stable.
112
113
 
113
114
  export default function agentEnvironmentExtension(pi: ExtensionAPI) {
114
115
  registerSessionStartHandler(pi, SessionPhase.Background, async (_event, ctx) => {
@@ -19,28 +19,32 @@ Every file in this folder either:
19
19
  ## Ownership
20
20
 
21
21
  | File | Purpose |
22
- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- |
22
+ | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
23
23
  | `index.ts` | Main handler. Wires `before_agent_start`, calls the 4 `deliver*` functions, composes the final prompt. |
24
24
  | `section.ts` | The `PromptSection` primitive + `composeSections` joiner + `simpleSection`, `linesSection`, `headingSection` builders. |
25
25
  | `identity.ts` | Framing constants: `IDENTITY_INTRO` (generalist identity), `DISCOVERY` (D1 guarded exploration stance), `WORK_ETHIC` (methodical precision, signal-not-noise), `REPAIR_DISCIPLINE` (root cause named falsifiably before repair; re-derivation of claims that are not yours; weighted repair decisions), `SELF_MANAGEMENT` (memory workspace, evidence-carrying done items, known-open-check done gate), `COMMUNICATION` (conclusion-first, output style), `EPISTEMIC_STANCE` (identity-core: claim gate, self-state gate, retrieved-context preference), `SELF_AUDIT` (symmetric doubt; handoff ends with the unverified), `PHILOSOPHY` (character-level stance - silence, calm strategist, precise self-irony). |
26
26
  | `surface-discipline-section.ts` | `SURFACE_DISCIPLINE` (signal discipline across code, commits, tests, docs, reports, logs) + `surfaceDisciplineSection()` - its own section, rendered between the identity and identity-core blocks. Text pinned verbatim by test-prompt-budget.mjs. |
27
- | `instance-composition.ts` | **v3.8** Instance (consolidated): agent identity + pi-core version + root (pi-core npm package folder) + cwd + userland settings dir + os/pid + session (id + elapsed/last-event/turns/tool-avg) + top-level pi extension packages (settings-driven, scope-tagged `project` or `user-global`). Full block rendered on demand via the `system_info` tool; the prompt carries only the compact orientation line. |
27
+ | `instance-composition.ts` | **v3.8** Full Instance block: agent identity + pi-core version + core root + cwd + settings dir + os/pid + session (id + elapsed/last-event/turns/tool-avg) + top-level extension packages. Served on demand by the `system_info` tool. The prompt carries `renderCompactInstance`: braid build + install root, model, PID, session id, and skill/memory counts (process-stable facts only; see Local Contracts). |
28
28
  | `top-level-extensions.ts` | **v3.8** Discovery logic for top-level pi extension PACKAGES. Reads pi-core's `packages` field from `<cwd>/.pi/settings.json` (project) and `~/.pi/agent/settings.json` (user-global); project wins on collision. Resolves `npm:` specs in pi's managed install tree (`<agentDir>/npm/node_modules`) first, falling back to the global npm root (`npm root -g`); resolves local paths in place. Source tags: `project` / `user-global`. |
29
29
  | `project-docs-section.ts` | Project docs (AGENTS.md / CLAUDE.md) pointer-only rendering as plain-text bullets (`- <basename> at <path>`). Mirrors the skills discoverability model but uses plain text (no XML tags) so the system prompt stays prose. Includes fingerprint cache and `RESOURCES_DISCOVER` invalidation. |
30
30
  | `memory-section.ts` | Memory store pointer block (episodes + semantic + heuristics) as plain-text bullets (`- episodes at PATH`; count-free - per-store counts go stale at print time and are not rendered). Mirrors project-docs. Cached per session (static content, no fingerprint needed); invalidated on `RESOURCES_DISCOVER`. |
31
31
  | `context-section.ts` | **v3.6** body fragment for the unified context block: context %, session health, steps-since-checkpoint. Returns `""` when nothing to surface. Composer (`index.ts`) joins this with project-docs and memory bodies. No heading. (Memory stores render pointer-only: per-store entry counts are not rendered; the whisper carries token counts, not memory counts.) |
32
32
  | `awareness-whisper.ts` | Once-per-session context-hygiene steer whisper (customType `hygiene`): tokens in context + delta since the previous emission's baseline, the inspector pointer, and the injection-channel catalog; `formatAwarenessText` is tool-availability-aware; the TG inbound row is state-aware: it asserts reachability only when the poller liveness registry (`lib/state/telegram-poller-liveness.ts`) says the poller is running, else it hedges and names `telegram_poller status`. The catalog describes subsystem whispers by their stable envelope (produced by `lib/utils/whisper-format.ts`) instead of enumerating subsystems. |
33
33
  | ~~`contrast-phrases.ts`~~ | **DELETED 2026-08-12 (keep+cut)** - legacy RepE-style phrase library (TRUTH_FIRST, ANTI_SYCOPHANCY, EPISTEMIC_STABILITY, KNOWLEDGE_BOUNDARY). Consolidated into `EPISTEMIC_STANCE` (identity.ts) on 2026-07-16; zero importers; provenance in the deleted file's git history. |
34
- | ~~`resources-section.ts`~~ | **DELETED** - the `Resources: N skills` pointer line was dead: duplicated by the skills-loading contract and the list_skills tool description. Discovery is served by `list_skills` at runtime; skill counts are not rendered in the prompt (the once-per-session awareness whisper carries context token counts, not skill counts). `excludeSkillsBlock` in `inspect.ts` keeps its Resources parser (absent-degrades-to-0) for non-braid prompt shapes. |
34
+ | ~~`resources-section.ts`~~ | **DELETED** - the standalone `Resources: N skills` pointer line was dead: duplicated by the skills-loading contract and the list_skills tool description. The counts return only on the compact instance line (`Resources: N skills, M memories`) as a load signal. `excludeSkillsBlock` in `inspect.ts` keeps its Resources parser (absent-degrades-to-0) for non-braid prompt shapes. |
35
35
  | `tool-pipelines.ts` | Guarded multi-tool usage pipelines (research/debugging - the implementation pipeline was dropped, merged into COMMUNICATION's understand-before-act; the verification pipeline was dropped as a restatement of the verify/verify_claim/finalize rows); pinned by test-tool-pipelines.mjs. |
36
36
  | `tool-guidelines.ts` | Per-tool guideline sync: `TOOL_GUIDELINES` (tool → one-line reflection, synced 1:1 with `packages/core/TOOLS.md`; mirror when-nots were trimmed and description restatements) + `perToolGuidelines()` `if has <tool>`-gated renderer + `resolveOwnedToolLine()` (tools-section resolver: owned lines only, the description fallback renders no row); pinned by the `tool-guidelines` describe block in test-tool-pipelines.mjs. |
37
37
  | `pi-reference-section.ts` | Pi docs seat: `PI_REFERENCE_POINTER` + `piReferenceSection()` - a static pointer to the `pi-reference` skill (docs index + install paths), rendered after the tools section. Replaced the native `<docs>` re-emission; the parity registry marks the native `docs` key dropped. |
38
- | `system-info-tool.ts` | `system_info` tool: full Instance data on demand (detail=full | compact). |
38
+ | `system-info-tool.ts` | `system_info` tool: full Instance data on demand (detail full or compact). The seat for volatile facts (elapsed, last event, turns, tool average) and the core/cwd/settings path triple; a tool result is not a cached prefix. |
39
39
  | `inspect.ts` | `prompt_inspect` tool: reads the actual system prompt from runtime. |
40
40
  | `tool-description-trim.ts` | Third-party tool-description trim: `before_provider_request` handler that shortens registered descriptions of `herdr_*` tools to 1-2 lines in the API tools channel (curated map + prefix fallback); the deep form moved to the `herdr-topology` skill (progressive disclosure). When-gate preserved in every rewrite. |
41
41
 
42
42
  ## Local Contracts
43
43
 
44
+ ### Compact instance line (volatility rule)
45
+
46
+ `renderCompactInstance` renders the one-line `instance` section in the system prompt. The system prompt is a cached prefix, so the line carries process-stable facts only: braid build + install root, model (provider/id), PID, session id, and skill/memory counts. A timestamp, elapsed time, turn count, tool average, or context size would rewrite that prefix on every request and cost more than the field is worth; those facts stay in the `system_info` tool, which is a fresh turn by construction. The counts answer "did the skill pack and memory stores load", not "how many exactly". `test-instance-block.mjs` pins the line: no cwd field, no timestamp or duration token, and a 320-byte cap.
47
+
44
48
  ### Identity vs behaviors (architectural split)
45
49
 
46
50
  This folder holds the **shared identity layer** -- IDENTITY framings, not project-specific behaviors. The split:
@@ -40,7 +40,7 @@ import {
40
40
  } from "./project-docs-section.js";
41
41
  import { setCachedSkills, getCachedVisibleSkillNames } from "../skills-tool/index.js";
42
42
  import { reconstructMemorySection, resetMemorySectionCache } from "./memory-section.js";
43
- import { gatherInstanceData } from "./instance-composition.js";
43
+ import { gatherInstanceData, renderCompactInstance } from "./instance-composition.js";
44
44
  import { sendTrackedMessage } from "../../../lib/utils/injection-tracker.js";
45
45
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
46
46
  import { flushRecoveredFires } from "../../../extensions/scheduling/timer/wake-retry.js";
@@ -434,7 +434,10 @@ export default function promptBuilderExtension(pi: ExtensionAPI) {
434
434
  } catch {
435
435
  /* already init'd or non-fatal */
436
436
  }
437
- memoryCount = memory.getAll(3).length;
437
+ // getAll(limit) slices the in-memory store, so a small limit turned the
438
+ // rendered memory count into a floor of 3. The instance line reports a
439
+ // true count: ask for the whole store.
440
+ memoryCount = memory.getAll(Number.MAX_SAFE_INTEGER).length;
438
441
  } catch {
439
442
  /* memory unavailable - non-fatal */
440
443
  }
@@ -480,9 +483,12 @@ export default function promptBuilderExtension(pi: ExtensionAPI) {
480
483
  // Build the prompt as a flat list of sections. Every section is a
481
484
  // `PromptSection`; the top-level handler never touches raw strings
482
485
  // or arrays of strings.
483
- // Instance: compact 1-line orientation (version/cwd/session at a
484
- // glance); full data via the system_info tool. The agent should not
485
- // need a tool call to discover its own version/cwd/session.
486
+ // Instance: compact one-line orientation (build + install root, model,
487
+ // PID, session, resource counts); full data stays in the system_info
488
+ // tool. The block carries process-stable facts only: the system prompt
489
+ // is a cached prefix, so a field that changes between turns (a clock,
490
+ // elapsed time, turn or tool counters, context size) would invalidate
491
+ // that prefix on every request and cost more than the field is worth.
486
492
  const instanceData = await gatherInstanceData(pi, ctx, {
487
493
  skillCount: skills.length,
488
494
  skillDirs,
@@ -493,8 +499,7 @@ export default function promptBuilderExtension(pi: ExtensionAPI) {
493
499
  })),
494
500
  memoryCount,
495
501
  });
496
- const sessionId = ctx.sessionManager?.getSessionId() ?? "";
497
- const compactInstanceLine = `Agent: Braid v${instanceData.braidVersion} (over pi-core v${instanceData.pi.version}) | Cwd: ${instanceData.cwd} | Session: ${sessionId}`;
502
+ const compactInstanceLine = renderCompactInstance(instanceData);
498
503
  // Discovery & exploration stance. Guarded by tool availability: each
499
504
  // line only appears when its tools exist; the stance paragraph is
500
505
  // unconditional. Placed after guidelines, before tools — a stance, not
@@ -1,14 +1,26 @@
1
1
  /**
2
- * Instance Composition: renders the full Instance block (Agent + pi-core
3
- * version, runtime paths, OS/PID, session, extension packages, other pi
4
- * instances) on demand via renderInstance (system_info tool); the prompt
5
- * carries only a compact one-line orientation (version | cwd | session).
6
- * Invariants: "Root" = pi-core's npm package folder; packages come from
7
- * the settings `packages` field (project / user-global, pi-core
8
- * precedence), never a sibling walk; pi-core version resolves from the
9
- * running pi binary; skills+memory live in memory-section.ts / the list_skills
10
- * tool; output
11
- * never contains internal module paths or "->".
2
+ * Instance Composition: two renders over the same gathered data.
3
+ *
4
+ * renderInstance is the full block (versions, runtime paths, OS/PID,
5
+ * session stats, extension packages, other pi instances) served on demand by
6
+ * the system_info tool. renderCompactInstance is the one-line orientation in
7
+ * the system prompt (braid version + install root, model, PID, session id,
8
+ * resource counts).
9
+ *
10
+ * Volatility rule: the system prompt is a cached prefix, so the compact line
11
+ * may carry only process-stable facts. A timestamp, elapsed time, turn count,
12
+ * tool average or context size would rewrite the prefix on every request and
13
+ * cost more than the field is worth; those facts stay in the system_info
14
+ * tool, which is a fresh turn by construction.
15
+ *
16
+ * Invariants: "Core" = pi-core's npm package folder, "braid root" = the
17
+ * loaded pi-braid package folder; packages come from the settings `packages`
18
+ * field (project / user-global, pi-core precedence), never a sibling walk;
19
+ * the pi-core version is pi-core's own `VERSION` export (the library braid is
20
+ * loaded into names the core that is running), with a filesystem walk as the
21
+ * fallback and as the source of the binary/package-folder fields; skills+memory
22
+ * live in memory-section.ts / the list_skills tool; output never contains
23
+ * internal module paths or "->".
12
24
  */
13
25
 
14
26
  import { execSync, spawnSync } from "node:child_process";
@@ -16,7 +28,7 @@ import { readFileSync, existsSync, realpathSync } from "node:fs";
16
28
  import { dirname, join } from "node:path";
17
29
  import { fileURLToPath } from "node:url";
18
30
  import * as os from "node:os";
19
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
31
+ import { getAgentDir, VERSION as PI_CORE_VERSION } from "@earendil-works/pi-coding-agent";
20
32
  import type { PromptSection } from "./section.js";
21
33
  import { discoverTopLevelExtensions, type TopLevelExtension } from "./top-level-extensions.js";
22
34
  import { gatherL1Environment, type L1EnvironmentData } from "../agent-environment/index.js";
@@ -33,13 +45,43 @@ export interface SkillEntry {
33
45
  }
34
46
 
35
47
  interface PiVersionInfo {
48
+ /** The running library's own `VERSION`; the package.json version found by
49
+ * the walk only when that export is unavailable. */
36
50
  version: string;
37
51
  root: string;
38
52
  /** Path to the resolved `pi` binary. */
39
53
  binary: string;
40
54
  }
41
55
 
56
+ /**
57
+ * The pi-core version of the library braid is loaded into, read from pi-core's
58
+ * own `VERSION` export.
59
+ *
60
+ * Braid is loaded by the harness, so that constant names the core actually
61
+ * running. A filesystem walk cannot answer the same question: the managed
62
+ * install keeps the entrypoint as a regular shell shim at `bin/pi` (so
63
+ * `realpathSync` changes nothing) and the package in a sibling
64
+ * `install/releases/<version>/node_modules` subtree, which no ancestor of
65
+ * `bin/` contains. Null when the export is absent or is not a version, so the
66
+ * caller falls back to the walk.
67
+ */
68
+ function piCoreVersionFromLibrary(): string | null {
69
+ const value = typeof PI_CORE_VERSION === "string" ? PI_CORE_VERSION.trim() : "";
70
+ return /^\d+\.\d+\.\d+/.test(value) ? value : null;
71
+ }
72
+
73
+ /** The pi-core the current process is running over: the library's `VERSION`
74
+ * for the version, the filesystem walk for the binary and package folder. */
42
75
  function discoverRunningPi(): PiVersionInfo {
76
+ const located = locateRunningPi();
77
+ const libraryVersion = piCoreVersionFromLibrary();
78
+ return libraryVersion ? { ...located, version: libraryVersion } : located;
79
+ }
80
+
81
+ /** Walk PATH and the filesystem for the running pi binary and its package
82
+ * folder. Supplies `root` and `binary`, and a version only as the fallback
83
+ * for a runtime where pi-core's `VERSION` export is missing. */
84
+ function locateRunningPi(): PiVersionInfo {
43
85
  // 1. Find the actually-running `pi` binary. We DON'T just call
44
86
  // `which pi` because that follows PATH order and can return a
45
87
  // stale binary from a sibling repo's `node_modules/.bin` (e.g.
@@ -175,7 +217,10 @@ function readBraidVersion(): { version: string; root: string } {
175
217
  } catch {
176
218
  // fall through
177
219
  }
178
- return { version: "unknown", root: process.cwd() };
220
+ // No cwd fallback: the compact line renders this path as the braid root,
221
+ // and a cwd there would read as a real install while duplicating the
222
+ // pi-injected <cwd>. An unresolved root is the honest value.
223
+ return { version: "unknown", root: "" };
179
224
  }
180
225
 
181
226
  // Discovers all `pi` processes running on the system (including the current
@@ -328,8 +373,14 @@ export interface InstanceContext {
328
373
  /** Exported for system-info-tool — the full Instance data shape. */
329
374
  export interface InstanceData {
330
375
  braidVersion: string;
376
+ /** Folder of the running pi-braid package (where the loaded build lives).
377
+ * Empty when resolution failed. */
378
+ braidRoot: string;
331
379
  /** Resolved pi-core info (version + npm package folder). */
332
380
  pi: PiVersionInfo;
381
+ /** Session model as pi sees it (provider + model id); null when the
382
+ * runtime has no model selected. */
383
+ model: { provider: string; id: string } | null;
333
384
  /** Userland pi settings directory (~/.pi/agent or
334
385
  * PI_CODING_AGENT_DIR override). The agent uses this to find
335
386
  * its own settings, skills, memory, and session files. */
@@ -371,7 +422,7 @@ export async function gatherInstanceData(
371
422
  instanceCtx: InstanceContext,
372
423
  ): Promise<InstanceData> {
373
424
  const pi = discoverRunningPi();
374
- const braid = readBraidVersion();
425
+ const { version: braidVersion, root: braidRoot } = readBraidVersion();
375
426
  const session = gatherL1Environment(_pi, ctx);
376
427
  const topLevelExtensions = discoverTopLevelExtensions();
377
428
  const osInfo = {
@@ -388,8 +439,10 @@ export async function gatherInstanceData(
388
439
  };
389
440
  const otherPiInstances = discoverOtherPiInstances();
390
441
  return {
391
- braidVersion: braid.version,
442
+ braidVersion,
443
+ braidRoot,
392
444
  pi,
445
+ model: ctx.model ? { provider: String(ctx.model.provider), id: ctx.model.id } : null,
393
446
  settingsDir: getAgentDir(),
394
447
  os: osInfo,
395
448
  cwd: process.cwd(),
@@ -418,6 +471,37 @@ export async function instanceSection(
418
471
  };
419
472
  }
420
473
 
474
+ /**
475
+ * The compact Instance line for the system prompt.
476
+ *
477
+ * One field per question the agent would otherwise spend a tool call on:
478
+ *
479
+ * Agent which braid and pi-core build is answering?
480
+ * Root which pi-braid folder is loaded (stale local install vs global)?
481
+ * Model which provider/model will the next request go to?
482
+ * PID which OS process is this session, for ps/lock checks?
483
+ * Session which session file holds this transcript?
484
+ * Resources did the skill pack and memory stores load at all?
485
+ *
486
+ * A field answering only "nice to know" does not belong here, and neither
487
+ * does anything volatile: see the volatility rule in the module docstring.
488
+ * The block is process-stable by construction, so it renders byte-identical
489
+ * on every turn and the provider prefix cache holds across the session.
490
+ */
491
+ export function renderCompactInstance(d: InstanceData): string {
492
+ const model = d.model ? `${d.model.provider}/${d.model.id}` : "(unset)";
493
+ const skills = `${d.skillCount} skill${d.skillCount === 1 ? "" : "s"}`;
494
+ const memories = `${d.memoryCount} memor${d.memoryCount === 1 ? "y" : "ies"}`;
495
+ return [
496
+ `Agent: Braid v${d.braidVersion} (over pi-core v${d.pi.version})`,
497
+ `Root: ${d.braidRoot || "(unknown)"}`,
498
+ `Model: ${model}`,
499
+ `PID: ${d.session.pid}`,
500
+ `Session: ${d.sessionId || "(unknown)"}`,
501
+ `Resources: ${skills}, ${memories}`,
502
+ ].join(" | ");
503
+ }
504
+
421
505
  /** Exported for system-info-tool — renders InstanceData to plain text. */
422
506
  export async function renderInstance(d: InstanceData): Promise<string> {
423
507
  const lines: string[] = [];
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Extracts the Instance section (Agent version, pi-core version, paths,
5
5
  * OS, session stats, extensions, other instances) from the system prompt
6
- * into a read-on-demand tool. The prompt keeps only a compact one-line
7
- * orientation (version | cwd | session) at the bottom; the full Instance
8
- * block lives here.
6
+ * into a read-on-demand tool. The prompt keeps only the compact one-line
7
+ * orientation (build + install root, model, PID, session, resource counts)
8
+ * at the bottom; the full Instance block lives here.
9
9
  *
10
10
  * This saves ~60-100+ tokens per prompt turn while keeping the data
11
11
  * available when the agent actually needs it.
@@ -96,7 +96,7 @@ export const TOOL_GUIDELINES: Record<string, string> = {
96
96
 
97
97
  // ── skills-tool (default-enabled) ──
98
98
  list_skills:
99
- "when: entering a domain that may have a skill; when-not: after the skill is loaded; args: page/pageSize; caveat: read the WHOLE SKILL.md before acting in the domain",
99
+ "when: entering a domain that may have a skill; when-not: after the skill is loaded; args: page/pageSize/sectionsMax/rank; caveat: rows arrive ordered by relevance to the current task (rows with evidence carry relevance {score, reason}; the response carries ranking {tier, basis, policy}; rank: catalog for the plain order) and reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections) prices the read — read the WHOLE SKILL.md before acting in the domain",
100
100
  skill_stats:
101
101
  "when: measure skill adoption — suggested vs loaded counters; args: none; caveat: session + all-time counters (durable, skills-usage.json)",
102
102