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
package/AGENTS.md CHANGED
@@ -19,7 +19,7 @@ Five in-repo workspaces under `packages/` (monorepo migration):
19
19
  | `packages/contrib` | pi-braid-contrib | Community/experimental extensions (browser, codebase, diff, observatory, path-security, repl, …). Code-only; declares `pi.extensions`, no `pi.skills`. |
20
20
  | `packages/telegram` | @pi-braid/telegram | Bidirectional Telegram channel (outbound tool + inbound pull/poller). Declares `pi.extensions`. |
21
21
 
22
- `pi-braid-evaluation` (benchmarks and results) remains a separate project under `~/projects/agents/`.
22
+ `pi-braid-evaluation` (benchmarks and results) is a separate, non-public project: it is not part of this repository and nothing here should point at its location.
23
23
 
24
24
  **Install paths:**
25
25
 
@@ -169,23 +169,22 @@ ROADMAP.md. Key ongoing concerns:
169
169
 
170
170
  ## Child DOX Index
171
171
 
172
- | Path | Owns | AGENTS.md |
173
- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
174
- | `src/` | Top-level architecture: extensions/lib/loader/types split, delivery channel rules | [src/AGENTS.md](src/AGENTS.md) |
175
- | `src/extensions/` | All 25+ extensions grouped by agent-loop phase (core/cognitive/memory/scheduling/self/heartbeat/enforcement) | (per-extension AGENTS.md below) |
176
- | `src/extensions/core/` | Prompt-builder, agent-environment, skills-tool, polyfill | [src/extensions/core/AGENTS.md](src/extensions/core/AGENTS.md) |
177
- | `src/extensions/cognitive/` | Metacognition, reasoning, sycophancy/topic-drift/turn-outcome detectors | [src/extensions/cognitive/AGENTS.md](src/extensions/cognitive/AGENTS.md) |
178
- | `src/extensions/enforcement/` | Turn-pipeline infrastructure (handlers, detection, substate) | [src/extensions/enforcement/AGENTS.md](src/extensions/enforcement/AGENTS.md) |
179
- | `src/extensions/heartbeat/` | Background daemons (scheduler, analytics) | [src/extensions/heartbeat/AGENTS.md](src/extensions/heartbeat/AGENTS.md) |
180
- | `src/extensions/memory/` | All persistent state (context-lifecycle, three-stores, agent-bridge, etc.) | [src/extensions/memory/AGENTS.md](src/extensions/memory/AGENTS.md) |
181
- | `src/extensions/scheduling/` | Time triggers (timer) | [src/extensions/scheduling/AGENTS.md](src/extensions/scheduling/AGENTS.md) |
182
- | `src/extensions/self/` | Self-management (health, error-tracking, watchdog, etc.) | [src/extensions/self/AGENTS.md](src/extensions/self/AGENTS.md) |
183
- | `src/lib/` | Library subsystems - non-extension modules; a subdir carries an AGENTS.md where the module warrants one | [src/lib/AGENTS.md](src/lib/AGENTS.md) |
184
- | `src/loader/` | Extension loader + subagent API | [src/loader/AGENTS.md](src/loader/AGENTS.md) |
185
- | `docs/` | Reference docs: `ROADMAP.md` (open backlog and shipped milestones), `SETUP.md` (setup reference), `HISTORY.md` (narrative history and dated milestone summaries) | (no AGENTS.md - durable reference) |
186
- | `test/` | Test harness; no AGENTS.md needed (tests are leaf) | (no AGENTS.md) |
187
- | `scripts/` | Build/lint/test/check helpers; leaf | (no AGENTS.md) |
188
- | `~/projects/agents/pi-braid-evaluation/` | Benchmarks and results (separate project) | (no AGENTS.md) |
172
+ | Path | Owns | AGENTS.md |
173
+ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
174
+ | `src/` | Top-level architecture: extensions/lib/loader/types split, delivery channel rules | [src/AGENTS.md](src/AGENTS.md) |
175
+ | `src/extensions/` | All 25+ extensions grouped by agent-loop phase (core/cognitive/memory/scheduling/self/heartbeat/enforcement) | (per-extension AGENTS.md below) |
176
+ | `src/extensions/core/` | Prompt-builder, agent-environment, skills-tool, polyfill | [src/extensions/core/AGENTS.md](src/extensions/core/AGENTS.md) |
177
+ | `src/extensions/cognitive/` | Metacognition, reasoning, sycophancy/topic-drift/turn-outcome detectors | [src/extensions/cognitive/AGENTS.md](src/extensions/cognitive/AGENTS.md) |
178
+ | `src/extensions/enforcement/` | Turn-pipeline infrastructure (handlers, detection, substate) | [src/extensions/enforcement/AGENTS.md](src/extensions/enforcement/AGENTS.md) |
179
+ | `src/extensions/heartbeat/` | Background daemons (scheduler, analytics) | [src/extensions/heartbeat/AGENTS.md](src/extensions/heartbeat/AGENTS.md) |
180
+ | `src/extensions/memory/` | All persistent state (context-lifecycle, three-stores, agent-bridge, etc.) | [src/extensions/memory/AGENTS.md](src/extensions/memory/AGENTS.md) |
181
+ | `src/extensions/scheduling/` | Time triggers (timer) | [src/extensions/scheduling/AGENTS.md](src/extensions/scheduling/AGENTS.md) |
182
+ | `src/extensions/self/` | Self-management (health, error-tracking, watchdog, etc.) | [src/extensions/self/AGENTS.md](src/extensions/self/AGENTS.md) |
183
+ | `src/lib/` | Library subsystems - non-extension modules; a subdir carries an AGENTS.md where the module warrants one | [src/lib/AGENTS.md](src/lib/AGENTS.md) |
184
+ | `src/loader/` | Extension loader + subagent API | [src/loader/AGENTS.md](src/loader/AGENTS.md) |
185
+ | `docs/` | Reference docs: `ROADMAP.md` (open backlog and shipped milestones), `SETUP.md` (setup reference), `HISTORY.md` (narrative history and dated milestone summaries) | (no AGENTS.md - durable reference) |
186
+ | `test/` | Test harness; no AGENTS.md needed (tests are leaf) | (no AGENTS.md) |
187
+ | `scripts/` | Build/lint/test/check helpers; leaf | (no AGENTS.md) |
189
188
 
190
189
  ## User Preferences (durable)
191
190
 
package/README.md CHANGED
@@ -12,31 +12,26 @@ Honest self-aware agent with a metacognitive suite and extras on top of [pi-codi
12
12
 
13
13
  ---
14
14
 
15
- ## What it does
16
-
17
- pi-braid extends pi with a metacognitive layer:
18
-
19
- - **Enforcement** - belief-policy engine, structured signal delivery (L1–L3), sycophancy detection, verification nudges, behavioral pattern evolution
20
- - **Memory** - three-store recall (semantic + episodic + heuristic), cross-session context, scratchpad task tracking, workspace snapshots, conflict resolution
21
- - **Reasoning** - topic-drift detection, bidirectional verification, claim tracking, contradiction detection
22
- - **Self-improvement** - heuristic evolution, dreamer (offline consolidation), SOP extraction, degradation detection, reflection
23
- - **Utilities** - healthcheck, timers, system monitoring, web research, context lifecycle (S-MMU proposals, compaction, rotation)
24
-
25
- It runs as a pi _extension package_ - install once, use everywhere on your pi session.
26
-
27
15
  ## Install
28
16
 
29
17
  ```bash
30
18
  pi install npm:pi-braid
31
19
  ```
32
20
 
33
- One command, no clone, no build: `pi install` registers the package with pi and
34
- installs it under pi's npm directory. It carries the suite and the core skill
35
- set that ships with it. The on-demand skill pack and the other companions are
36
- add-ons, each its own install: `pi install npm:pi-braid-skills`,
21
+ One command, no clone, no build: `pi install` registers the package with pi,
22
+ writes the declaration to `~/.pi/agent/settings.json`, and installs it under
23
+ pi's npm directory. It carries the suite and the core skill set that ships with
24
+ it. The on-demand skill pack and the other companions are add-ons, each its own
25
+ install: `pi install npm:pi-braid-skills`,
37
26
  `pi install npm:pi-braid-contrib`, `pi install npm:pi-braid-providers`,
38
27
  `pi install npm:pi-braid-telegram`.
39
28
 
29
+ To enable braid for one project only, or to use all five workspaces, see
30
+ [docs/SETUP.md](docs/SETUP.md) § Install paths. For the full setup reference
31
+ (per-project installs, skills, module toggles, troubleshooting) see
32
+ **[`docs/SETUP.md`](docs/SETUP.md)**; new to pi and braid, start with
33
+ **[`docs/BEGINNERS.md`](docs/BEGINNERS.md)**.
34
+
40
35
  ### From a checkout (working on braid)
41
36
 
42
37
  Build the workspace and point pi at the local path:
@@ -46,19 +41,13 @@ git clone https://github.com/kifirkin/pi-braid.git ~/pi-braid
46
41
  cd ~/pi-braid && npm install && npm run build
47
42
  ```
48
43
 
49
- ```json
50
- {
51
- "packages": ["file:~/pi-braid/packages/core"]
52
- }
53
- ```
54
-
55
- pi loads each workspace through the `pi.extensions` / `pi.skills`
56
- fields in its `package.json` (no workspaces auto-discovery - register the paths
57
- you want).
58
- `packages/core` carries the suite and the core skill set that ships with it;
59
- `packages/skills` carries the on-demand skill pack, registered per project. Add
60
- `packages/providers`, `packages/contrib`, or `packages/telegram` as needed. The install-path
61
- reference is [`docs/SETUP.md`](docs/SETUP.md).
44
+ Register `packages/core` (plus `packages/skills` for the pack) under `packages`
45
+ in pi's settings; the root `package.json` has no `pi` field, so `file:~/pi-braid`
46
+ loads nothing. Each workspace is loaded through the `pi.extensions` /
47
+ `pi.skills` fields in its `package.json` (no workspaces auto-discovery). The
48
+ install-path reference is [`docs/SETUP.md`](docs/SETUP.md);
49
+ [`examples/`](https://github.com/kifirkin/pi-braid/tree/main/examples) carries
50
+ copy-ready settings.
62
51
 
63
52
  ## What this does not do
64
53
 
@@ -76,60 +65,9 @@ reference is [`docs/SETUP.md`](docs/SETUP.md).
76
65
 
77
66
  ---
78
67
 
79
- ## Fast start (TL;DR)
80
-
81
- ```bash
82
- # 1. Register braid with pi (one-time, user-global)
83
- pi install npm:pi-braid
84
-
85
- # 2. Use pi as normal — braid loads automatically
86
- pi
87
- ```
88
-
89
- That's it: `pi install` writes the declaration to `~/.pi/agent/settings.json`,
90
- so there is no clone, no build, and nothing to edit by hand. Working on braid
91
- itself? [§ Install](#install) carries the checkout path. To enable pi-braid only
92
- for one project, or to use all five workspaces, see
93
- [docs/SETUP.md](docs/SETUP.md) § Install paths. For the full setup
94
- reference (per-project installs, skills, module toggles, troubleshooting), see
95
- **[`docs/SETUP.md`](docs/SETUP.md)**. New to pi and braid? Start with
96
- **[`docs/BEGINNERS.md`](docs/BEGINNERS.md)**.
97
-
98
- ---
99
-
100
68
  ## How it fits pi
101
69
 
102
- pi loads extensions from a `packages` entry in `<cwd>/.pi/settings.json` (project) or `~/.pi/agent/settings.json` (user-global). braid is a regular extension package - point pi at it via `file:` or `git+https:` spec.
103
-
104
- ```
105
- ┌────────────────────────────────────────────┐
106
- │ pi-coding-agent │
107
- │ (base agent loop + tools) │
108
- ├────────────────────────────────────────────┤
109
- │ prompt-builder (system prompt) │
110
- ├──────────────┬─────────────────────────────┤
111
- │ enforcement │ metacognition │
112
- │ (signals, │ (think, verify, │
113
- │ drift, │ hypothesize, finalize) │
114
- │ reflection)│ │
115
- ├──────────────┴─────────────────────────────┤
116
- │ memory-agent-bridge │
117
- │ (memory_store, memory, conflict_qa, │
118
- │ explore_paths, session) │
119
- ├────────────────────────────────────────────┤
120
- │ three-memory-stores │ context-lifecycle │
121
- │ (episodes/heuristics)│ (S-MMU proposals) │
122
- ├──────────────┬─────────────────────────────┤
123
- │ heartbeat- │ scratchpad │
124
- │ scheduler │ workspace-snapshot │
125
- │ (budgets, │ timer │
126
- │ auto-finalize)│ │
127
- ├──────────────┴─────────────────────────────┤
128
- │ session-recall │ health-maintenance │
129
- │ error-tracking │ latent-activator │
130
- │ watchdog │ analytics │
131
- └────────────────────────────────────────────┘
132
- ```
70
+ pi loads extensions from a `packages` entry in `<cwd>/.pi/settings.json` (project) or `~/.pi/agent/settings.json` (user-global). braid is a regular extension package - point pi at it via a `file:` or `git+https:` spec.
133
71
 
134
72
  This package is the **core** workspace. The monorepo also contains four
135
73
  sibling packages (see the root [`README.md`](https://github.com/kifirkin/pi-braid/blob/main/README.md) for the full map):
@@ -144,26 +82,84 @@ sibling packages (see the root [`README.md`](https://github.com/kifirkin/pi-brai
144
82
 
145
83
  ---
146
84
 
147
- ## What you get
148
-
149
- 28 extensions ship; `health-maintenance` and `error-tracking` are off by default. See [`src/extensions/manifest.ts`](src/extensions/manifest.ts) for the flat list. Highlights:
150
-
151
- | Tool / Extension | What it adds |
152
- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
153
- | `think`, `verify`, `hypothesize`, `finalize` | Metacognitive tools (always-on). Use `think` for non-trivial reflection; `verify` to check work; `finalize` to close a task with evidence. |
154
- | `scratchpad` | Goal/plan/decision/learning tracker that survives context compaction |
155
- | `memory`, `memory_store`, `conflict_qa` | Three-store recall (episodes / semantic / heuristics) cross-searched; conflict resolution between sources |
156
- | `session` | Cross-session context recall (search / query past sessions) |
157
- | `context_compress`, `context_inspect`, `context_navigate` | S-MMU-style context management |
158
- | `topic_drift` | Anchor tracking + drift detection |
159
- | `behavior` | Activate / deactivate behavior patterns |
160
- | `timer` | Non-blocking session-scoped timers |
161
- | `workspace_snapshot` | Capture / diff / restore workspace state for time-travel debugging |
162
- | `system_monitor` | CPU / memory / disk metrics |
163
- | `healthcheck` | Diagnostic across all tools (recursive smoke tests) |
164
- | `fetch_content` | Web page fetching (pi-web-access): readable markdown, raw text, or a prompt-answered extraction; direct images, GitHub repos, PDFs, videos |
85
+ ## What it does
165
86
 
166
- Plus 9 pi-native tools ([`TOOLS.md`](TOOLS.md) is the canonical inventory), always available.
87
+ 28 extensions ship; `health-maintenance` and `error-tracking` are off by
88
+ default, and the flat list is
89
+ [`src/extensions/manifest.ts`](src/extensions/manifest.ts). They cover:
90
+
91
+ - **Enforcement** - the turn pipeline: turn validation, signal delivery, sycophancy and verification nudges, behavior patterns
92
+ - **Reasoning** - topic-drift detection, claim tracking, bidirectional verification, contradiction detection
93
+ - **Self-improvement** - heuristic evolution, reflection, offline consolidation
94
+ - **Utilities** - health, timers, workspace snapshots, context lifecycle
95
+
96
+ Five capabilities explain the rest of the file:
97
+
98
+ ### The prompt builder
99
+
100
+ The system prompt is assembled, not written once: named sections are composed
101
+ as `PromptSection` fragments
102
+ ([`section.ts`](src/extensions/core/prompt-builder/section.ts)) and published
103
+ through pi's section seam, so a section that changes re-sends alone instead of
104
+ the whole head prompt
105
+ ([`section-publish.ts`](src/extensions/core/prompt-builder/section-publish.ts)).
106
+ Sections a host or an earlier handler supplies on the prompt options are
107
+ rendered as their own blocks
108
+ ([`custom-sections.ts`](src/extensions/core/prompt-builder/custom-sections.ts)),
109
+ and because braid renders the whole prompt it suppresses pi's native preamble,
110
+ tool list, rules and docs. `prompt_inspect` prints the assembled result at any
111
+ point in a session, which is the point: most of braid's behavior is inspectable
112
+ prompt text rather than hardcoded replies.
113
+
114
+ ### Memory as a system
115
+
116
+ Three stores hold different kinds of memory: episodes (what happened, per
117
+ session, promoted to semantic when the agent keeps referencing them), semantic
118
+ entries (what it learned, written on shutdown and loaded next session), and the
119
+ heuristics (procedural rules) it applies while working. The scratchpad is working memory that
120
+ survives compaction, and a resume file hands the open plan to a fresh seat at
121
+ session start
122
+ ([`resume-state.ts`](src/extensions/enforcement/resume-state.ts)). `memory`
123
+ reads across the stores; `session` reads across past sessions. Deep source:
124
+ [`src/extensions/memory/AGENTS.md`](src/extensions/memory/AGENTS.md).
125
+
126
+ ### A worker fleet
127
+
128
+ `orchestrate` coordinates parallel agent workers: a per-project worker registry
129
+ with admission and lifecycle, one branch per worker, file locks, conflict
130
+ detection, close gates, and merge verification. Branch handling is git-optional:
131
+ with no repository it falls back to lock-only coordination. The working
132
+ procedure is the [`subagent-orchestration`](skills/subagent-orchestration/SKILL.md)
133
+ skill; the registry is
134
+ [`src/extensions/orchestrator/index.ts`](src/extensions/orchestrator/index.ts).
135
+
136
+ ### Context lifecycle
137
+
138
+ braid manages its own window: usage bands fire pruning, archiving and
139
+ compaction; a compaction reserve keeps headroom for the next turn;
140
+ auto-compaction arms on usage; oversized tool results are offloaded to disk and
141
+ stubbed. A failed compaction walks retries, then a bounded summarizer, then a
142
+ deterministic cut that needs no provider, so the session keeps compressing even
143
+ when the model stops answering. The
144
+ numbers are owned by [`docs/CONTEXT-POLICY.md`](docs/CONTEXT-POLICY.md); the
145
+ tools are `context_compress`, `context_inspect` and `context_navigate`.
146
+
147
+ ### Highlights
148
+
149
+ | Tool / Extension | What it adds |
150
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
151
+ | `think`, `verify`, `hypothesize`, `finalize` | Metacognitive tools (always-on). Use `think` for non-trivial reflection; `verify` to check work; `finalize` to close a task with evidence. |
152
+ | `scratchpad` | Goal/plan/decision/learning tracker that survives context compaction |
153
+ | `memory`, `memory_store`, `conflict_qa` | Three-store recall (episodes / semantic / heuristics) cross-searched; conflict resolution between sources |
154
+ | `session` | Cross-session context recall (search / query past sessions) |
155
+ | `topic_drift` | Anchor tracking + drift detection |
156
+ | `behavior` | Activate / deactivate behavior patterns |
157
+ | `timer` | Non-blocking session-scoped timers |
158
+ | `workspace_snapshot` | Capture / diff / restore workspace state for time-travel debugging |
159
+
160
+ [`TOOLS.md`](TOOLS.md) is the catalog: every tool this package registers, pi's
161
+ own builtins, and the cold tools that stay undeclared until `tool_search` loads
162
+ them. `set_tool_profile` switches the active set to a curated profile.
167
163
 
168
164
  ---
169
165
 
@@ -178,35 +174,19 @@ braid's loader follows a **four-tier precedence** (high → low):
178
174
  3. `BRAID_MODULES` env var
179
175
  4. Defaults - all non-opt-in extensions enabled
180
176
 
181
- #### `BRAID_MODULES` env var
177
+ A ref is either an **extension id** (`enforcement`, `error-tracking`) or a
178
+ **module group name** (`heartbeat`, `core`, `memory`), prefixed `+` to enable or
179
+ `-` to disable: `BRAID_MODULES="all,-error-tracking"`. Settings win over the env
180
+ var; the runtime API wins over both. Worked patterns are in
181
+ [`AGENTS.md`](AGENTS.md) § Common `BRAID_MODULES` patterns.
182
182
 
183
- ```bash
184
- unset BRAID_MODULES # default: all non-opt-in extensions
183
+ ### Settings
185
184
 
186
- export BRAID_MODULES="all,-error-tracking" # everything except one
187
- export BRAID_MODULES="-enforcement" # disable enforcement group
188
- export BRAID_MODULES="+heartbeat" # enable the heartbeat group
189
- ```
190
-
191
- A ref can be either an **extension id** (`enforcement`, `error-tracking`) or a **module group name** (`heartbeat`, `core`, `memory`). Prefixes: `+` to enable, `-` to disable.
192
-
193
- #### Persistent settings
194
-
195
- In `~/.pi/agent/settings.json`:
196
-
197
- ```json
198
- {
199
- "braid": {
200
- "modules": {
201
- "enforcement": true,
202
- "error-tracking": false,
203
- "heartbeat": true
204
- }
205
- }
206
- }
207
- ```
208
-
209
- Settings win over env var; runtime API wins over settings.
185
+ `braid.modules` is one leaf of the settings surface. The source is
186
+ `schema/braid.schema.json`, [`docs/SETUP.md`](docs/SETUP.md) § Configuration
187
+ reference lists every path with its default, and
188
+ [`examples/full-config.settings.json`](https://github.com/kifirkin/pi-braid/blob/main/examples/full-config.settings.json)
189
+ is copy-ready.
210
190
 
211
191
  ### Storage
212
192
 
@@ -219,9 +199,13 @@ All braid-specific data goes under `~/.pi/agent/braid/`. Use the constants in [`
219
199
  Skills come in two tiers: the core set ships inside this package (`skills/`,
220
200
  declared by `pi.skills` in `package.json`), and the on-demand pack is the
221
201
  content-only **`../skills`** workspace. Every skill is a `SKILL.md` with a
222
- `name` / `description` frontmatter header. Pi lists a registered package's
223
- skills in the system prompt's `<available_skills>` block; the agent opens a
224
- `SKILL.md` on demand.
202
+ `name` / `description` frontmatter header.
203
+
204
+ Discovery is on demand, not in the prompt: `list_skills` returns the catalog
205
+ ranked against the current task, each row priced by what the read will cost
206
+ (lines, bytes, token estimate, headings). When a skill's triggers match the
207
+ task, an excerpt is steered into the session, and `skill_stats` counts which
208
+ skills were suggested and which were actually read.
225
209
 
226
210
  The catalog table (one row per skill, with its verdict and one-line
227
211
  description, covering both tiers) lives in
@@ -237,6 +221,8 @@ time (`find packages/skills/skills -name SKILL.md | wc -l` counts the pack).
237
221
  | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
238
222
  | [`docs/BEGINNERS.md`](docs/BEGINNERS.md) | **First walkthrough**: install → how agents use braid → first extension |
239
223
  | [`docs/SETUP.md`](docs/SETUP.md) | **Full setup reference**, install paths, troubleshooting |
224
+ | [`TOOLS.md`](TOOLS.md) | Tool catalog: registered tools, pi builtins, cold tools |
225
+ | [`docs/CONTEXT-POLICY.md`](docs/CONTEXT-POLICY.md) | Window, usage bands, compaction reserve, caps, offload, archiving |
240
226
  | [`docs/ROADMAP.md`](docs/ROADMAP.md) | Active roadmap + shipped milestones + open themes |
241
227
  | [`README.md`](README.md) | This overview |
242
228
  | [`AGENTS.md`](AGENTS.md) | Repository structure, DOX contract, conventions |
package/TOOLS.md CHANGED
@@ -44,41 +44,41 @@ enablement (see appendix).
44
44
 
45
45
  <!-- TOOLS-CATALOG-BEGIN -->
46
46
 
47
- | Tool | Purpose | Enablement | Reflection |
48
- | -------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
49
- | `read` | Read file contents (text and images) | pi-core builtin; always on | when: ground truth for anything on disk, incl. images as attachments, instead of cat or sed; when-not: content search (grep/find); args: path, offset for long files; caveat: text truncated at 2000 lines / 50KB |
50
- | `bash` | Execute shell commands (ls, grep, find, tests, git) | pi-core builtin; always on | when: tests, builds, git, shell pipelines, or inspecting PI-prefixed env vars for model/session details — anything without a dedicated tool; when-not: file read/edit; args: command + timeout; caveat: output truncated to 2000 lines / 50KB |
51
- | `edit` | Make precise file edits with exact text replacement | pi-core builtin; always on | when: one precise change to a known file; when-not: new files (write) or whole-file overhauls; args: oldText must match a UNIQUE region exactly; caveat: multiple edits in one call must not overlap |
52
- | `write` | Create or overwrite files | pi-core builtin; always on | when: create or overwrite a whole file; when-not: small tweaks to an existing file (edit); args: path + full content; caveat: truncates in place; a failed write can leave a partial file |
53
- | `grep` | Search file contents for patterns (respects .gitignore) | pi-core builtin; always on | when: find where a symbol/string lives (file:line); when-not: full file contents (read); args: pattern + optional glob/path; caveat: respects .gitignore, 100-match / 50KB cap, long lines cut at 500 chars |
54
- | `find` | Find files by glob pattern (respects .gitignore) | pi-core builtin; always on | when: locate files by name or glob without shelling out; when-not: content search (grep); args: glob pattern + optional path; caveat: respects .gitignore |
55
- | `ls` | List directory contents | pi-core builtin; always on | when: see what is actually in a directory before reading or running; args: path + limit; caveat: includes dotfiles, '/' suffix marks directories |
56
- | `powershell` | Execute PowerShell commands | pi-core builtin; Windows shell | when: PowerShell-only commands, or inspecting PI-prefixed env vars for model/session details; when-not: POSIX shells (bash); args: command + timeout; caveat: same truncation rules as bash |
57
- | `tool_search` | Search deferred tools and load the matches into the next request | pi-core builtin (tool-search extension); activated by braid at session start | when: a tool you expected is missing from this list (braid defers its cold tools; this is how they come back); args: query + limit; caveat: matches are declared from your NEXT call, so load first, then call |
58
- | `think` | Deep structured reasoning before high-stakes decisions | metacognition - alwaysOn (manifest.ts:93) | when: high-stakes or hard-to-reverse decisions; args: decision + observation/reason/confidence |
59
- | `hypothesize` | Generate root-cause hypotheses when a first fix fails | metacognition - alwaysOn (manifest.ts:93) | when: a first fix attempt failed and the root cause is unclear; args: problem + evidence; caveat: name a specific, verifiable failure mode — never vague |
60
- | `finalize` | Mark a task complete and record it to session memory | metacognition - alwaysOn (manifest.ts:93) | when: task fully done and verified; when-not: unresolved verify() (it blocks); args: summary + completed (+ tasksRemaining); caveat: call once per task, then text only |
61
- | `verify` | Verify code, reasoning, or results after edits or when uncertain | metacognition - alwaysOn (manifest.ts:93) | when: after every edit, or any uncertain conclusion; when-not: finalizing before verification; args: target (code/reasoning/plan/result) + explicit criteria; caveat: name the failure mode each check guards |
62
- | `verify_claim` | Verify agent claims against retrieved context | metacognition/claim-verification - alwaysOn (manifest.ts:93) | when: a conclusion depends on retrieved evidence; when-not: local code checks (verify); args: claim + context strings; caveat: action=decomposition for task-coverage checks |
63
- | `scratchpad` | Structured session memory for goals, plans, decisions | scratchpad - alwaysOn (manifest.ts:99) | when: multi-step tasks — keep the resumable state here, it survives compaction; args: action (set_goal/add_plan/mark_done/…) + text |
64
- | `prompt_inspect` | Show the current system prompt from runtime | prompt-builder - alwaysOn (manifest.ts:111) | when: your own instructions feel ambiguous or prompt questions arise; args: match/truncate to filter long sections; caveat: shows the ASSEMBLED prompt |
65
- | `system_info` | Show the runtime environment (versions, paths, session, stats) | prompt-builder - alwaysOn (manifest.ts:111) | when: context or environment matters; args: detail=compact for essentials |
66
- | `workspace_snapshot` | Capture/list/diff/preview/restore workspace snapshots | workspace-snapshot - alwaysOn (manifest.ts:123) | when: before risky multi-file edits — capture, then restore on failure; args: action capture/restore; caveat: restore applies only changed files |
67
- | `set_tool_profile` | Switch curated tool profiles (lean/research/debugging/browser/deep) | context-management - alwaysOn (manifest.ts:268) | when: task scope is known — focused profiles cut prompt noise and token cost; args: lean/research/debugging/browser/deep |
68
- | `list_skills` | Discover skills on demand (paginated catalog) | skills-tool - default-enabled (manifest.ts:228) | 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 |
69
- | `skill_stats` | Per-skill usage counters (suggested vs loaded) | skills-tool - default-enabled (manifest.ts:228) | when: measure skill adoption — suggested vs loaded counters; args: none; caveat: session + all-time counters (durable, skills-usage.json) |
70
- | `topic_drift` | Check output for drift or reset topic anchors | topic-drift - default-enabled (manifest.ts:136, dep agent-environment) | when: multi-part requests — check output against the original ask before responding; args: action check + output; caveat: reset re-anchors the topic |
71
- | `timer` | Set/list/cancel non-blocking session-scoped timers | timer - default-enabled (manifest.ts:222) | when: non-blocking reminders between turns (babysit cadences, follow-ups); args: delay_seconds + reason; caveat: session-scoped; recurring via interval_seconds+count |
72
- | `orchestrate` | Coordinate parallel agent workers (spawn/check/merge, locks) | orchestrator - default-enabled (manifest.ts:233) | when: parallel workers share a tree — declare their files so edits don't collide; args: action register-worker/spawn-worker/check-worker/update-worker/list-workers/close-worker/verify-and-merge + files |
73
- | `behavior` | Manage behavior patterns (activate/deactivate/list/mix) | latent-activator - default-enabled (manifest.ts:243) | when: swap problem-solving modes to suit the task type (debugger/reviewer/explorer…); args: activate/deactivate/mix + behavior or scenario |
74
- | `memory_store` | Persist insights/patterns/errors to long-term memory | memory-agent-bridge - default-enabled (manifest.ts:197) | when: after fixes, conventions, root-cause findings — persist cross-session; when-not: session-local facts (scratchpad); args: content + memoryType; caveat: tags + importance shape recall |
75
- | `memory` | Unified memory: recall/episodes/heuristics | memory-agent-bridge - default-enabled (manifest.ts:197) | when: before non-trivial work — build on known context; args: action recall_search / episodes_search / heuristics_list + query |
76
- | `explore_paths` | Per-hypothesis file search with first-15-lines evidence | memory-agent-bridge - default-enabled (manifest.ts:197) | when: debugging with a named failure-mode hypothesis; args: hypothesis_1/2/3, each 'file because reason'; caveat: local search — no sub-agent |
77
- | `conflict_qa` | Resolve contradictions between sources via the evidence pool | memory-agent-bridge - default-enabled (manifest.ts:197) | when: sources or beliefs contradict; args: action resolve + verdict; caveat: evidence-pool based, reports classification |
78
- | `session` | Access past session history (search/query/analyze/stats/context) | session-recall - default-enabled (manifest.ts:176, dep three-memory-stores) | when: prior-work context needed across sessions (search/query/analyze/stats); args: action + query/sessionPath; caveat: project-scoped by default |
79
- | `error` | Inspect captured extension errors (list/get/clear/stats) | error-tracking - opt-in, disabledByDefault (manifest.ts:276) | when: a tool or extension failed and you need the captured error history; args: action list/get/clear/stats |
80
- | `session_health` | Read/reset session LLM-provider health state | health-maintenance - opt-in, disabledByDefault (manifest.ts:259) | when: provider errors / auth / balance events occurred; args: action get/diagnose/recover; caveat: recover only after the user acted |
81
- | `health_maintenance` | Health-based maintenance (check/commit/rollback/benchmark) | health-maintenance - opt-in, disabledByDefault (manifest.ts:259) | when: agent self-state hygiene (check/commit/rollback/benchmark); args: action; caveat: rollback needs a checkpoint hash |
47
+ | Tool | Purpose | Enablement | Reflection |
48
+ | -------------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
49
+ | `read` | Read file contents (text and images) | pi-core builtin; always on | when: ground truth for anything on disk, incl. images as attachments, instead of cat or sed; when-not: content search (grep/find); args: path, offset for long files; caveat: text truncated at 2000 lines / 50KB |
50
+ | `bash` | Execute shell commands (ls, grep, find, tests, git) | pi-core builtin; always on | when: tests, builds, git, shell pipelines, or inspecting PI-prefixed env vars for model/session details — anything without a dedicated tool; when-not: file read/edit; args: command + timeout; caveat: output truncated to 2000 lines / 50KB |
51
+ | `edit` | Make precise file edits with exact text replacement | pi-core builtin; always on | when: one precise change to a known file; when-not: new files (write) or whole-file overhauls; args: oldText must match a UNIQUE region exactly; caveat: multiple edits in one call must not overlap |
52
+ | `write` | Create or overwrite files | pi-core builtin; always on | when: create or overwrite a whole file; when-not: small tweaks to an existing file (edit); args: path + full content; caveat: truncates in place; a failed write can leave a partial file |
53
+ | `grep` | Search file contents for patterns (respects .gitignore) | pi-core builtin; always on | when: find where a symbol/string lives (file:line); when-not: full file contents (read); args: pattern + optional glob/path; caveat: respects .gitignore, 100-match / 50KB cap, long lines cut at 500 chars |
54
+ | `find` | Find files by glob pattern (respects .gitignore) | pi-core builtin; always on | when: locate files by name or glob without shelling out; when-not: content search (grep); args: glob pattern + optional path; caveat: respects .gitignore |
55
+ | `ls` | List directory contents | pi-core builtin; always on | when: see what is actually in a directory before reading or running; args: path + limit; caveat: includes dotfiles, '/' suffix marks directories |
56
+ | `powershell` | Execute PowerShell commands | pi-core builtin; Windows shell | when: PowerShell-only commands, or inspecting PI-prefixed env vars for model/session details; when-not: POSIX shells (bash); args: command + timeout; caveat: same truncation rules as bash |
57
+ | `tool_search` | Search deferred tools and load the matches into the next request | pi-core builtin (tool-search extension); activated by braid at session start | when: a tool you expected is missing from this list (braid defers its cold tools; this is how they come back); args: query + limit; caveat: matches are declared from your NEXT call, so load first, then call |
58
+ | `think` | Deep structured reasoning before high-stakes decisions | metacognition - alwaysOn (manifest.ts:93) | when: high-stakes or hard-to-reverse decisions; args: decision + observation/reason/confidence |
59
+ | `hypothesize` | Generate root-cause hypotheses when a first fix fails | metacognition - alwaysOn (manifest.ts:93) | when: a first fix attempt failed and the root cause is unclear; args: problem + evidence; caveat: name a specific, verifiable failure mode — never vague |
60
+ | `finalize` | Mark a task complete and record it to session memory | metacognition - alwaysOn (manifest.ts:93) | when: task fully done and verified; when-not: unresolved verify() (it blocks); args: summary + completed (+ tasksRemaining); caveat: call once per task, then text only |
61
+ | `verify` | Verify code, reasoning, or results after edits or when uncertain | metacognition - alwaysOn (manifest.ts:93) | when: after every edit, or any uncertain conclusion; when-not: finalizing before verification; args: target (code/reasoning/plan/result) + explicit criteria; caveat: name the failure mode each check guards |
62
+ | `verify_claim` | Verify agent claims against retrieved context | metacognition/claim-verification - alwaysOn (manifest.ts:93) | when: a conclusion depends on retrieved evidence; when-not: local code checks (verify); args: claim + context strings; caveat: action=decomposition for task-coverage checks |
63
+ | `scratchpad` | Structured session memory for goals, plans, decisions | scratchpad - alwaysOn (manifest.ts:99) | when: multi-step tasks — keep the resumable state here, it survives compaction; args: action (set_goal/add_plan/mark_done/…) + text |
64
+ | `prompt_inspect` | Show the current system prompt from runtime | prompt-builder - alwaysOn (manifest.ts:111) | when: your own instructions feel ambiguous or prompt questions arise; args: match/truncate to filter long sections; caveat: shows the ASSEMBLED prompt |
65
+ | `system_info` | Show the runtime environment (versions, paths, session, stats) | prompt-builder - alwaysOn (manifest.ts:111) | when: context or environment matters; args: detail=compact for essentials |
66
+ | `workspace_snapshot` | Capture/list/diff/preview/restore workspace snapshots | workspace-snapshot - alwaysOn (manifest.ts:123) | when: before risky multi-file edits — capture, then restore on failure; args: action capture/restore; caveat: restore applies only changed files |
67
+ | `set_tool_profile` | Switch curated tool profiles (lean/research/debugging/browser/deep) | context-management - alwaysOn (manifest.ts:268) | when: task scope is known — focused profiles cut prompt noise and token cost; args: lean/research/debugging/browser/deep |
68
+ | `list_skills` | Discover skills on demand (paginated catalog, ordered by relevance to the current task, + per-row reach) | skills-tool - default-enabled (manifest.ts:228) | 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 |
69
+ | `skill_stats` | Per-skill usage counters (suggested vs loaded) | skills-tool - default-enabled (manifest.ts:228) | when: measure skill adoption — suggested vs loaded counters; args: none; caveat: session + all-time counters (durable, skills-usage.json) |
70
+ | `topic_drift` | Check output for drift or reset topic anchors | topic-drift - default-enabled (manifest.ts:136, dep agent-environment) | when: multi-part requests — check output against the original ask before responding; args: action check + output; caveat: reset re-anchors the topic |
71
+ | `timer` | Set/list/cancel non-blocking session-scoped timers | timer - default-enabled (manifest.ts:222) | when: non-blocking reminders between turns (babysit cadences, follow-ups); args: delay_seconds + reason; caveat: session-scoped; recurring via interval_seconds+count |
72
+ | `orchestrate` | Coordinate parallel agent workers (spawn/check/merge, locks) | orchestrator - default-enabled (manifest.ts:233) | when: parallel workers share a tree — declare their files so edits don't collide; args: action register-worker/spawn-worker/check-worker/update-worker/list-workers/close-worker/verify-and-merge + files |
73
+ | `behavior` | Manage behavior patterns (activate/deactivate/list/mix) | latent-activator - default-enabled (manifest.ts:243) | when: swap problem-solving modes to suit the task type (debugger/reviewer/explorer…); args: activate/deactivate/mix + behavior or scenario |
74
+ | `memory_store` | Persist insights/patterns/errors to long-term memory | memory-agent-bridge - default-enabled (manifest.ts:197) | when: after fixes, conventions, root-cause findings — persist cross-session; when-not: session-local facts (scratchpad); args: content + memoryType; caveat: tags + importance shape recall |
75
+ | `memory` | Unified memory: recall/episodes/heuristics | memory-agent-bridge - default-enabled (manifest.ts:197) | when: before non-trivial work — build on known context; args: action recall_search / episodes_search / heuristics_list + query |
76
+ | `explore_paths` | Per-hypothesis file search with first-15-lines evidence | memory-agent-bridge - default-enabled (manifest.ts:197) | when: debugging with a named failure-mode hypothesis; args: hypothesis_1/2/3, each 'file because reason'; caveat: local search — no sub-agent |
77
+ | `conflict_qa` | Resolve contradictions between sources via the evidence pool | memory-agent-bridge - default-enabled (manifest.ts:197) | when: sources or beliefs contradict; args: action resolve + verdict; caveat: evidence-pool based, reports classification |
78
+ | `session` | Access past session history (search/query/analyze/stats/context) | session-recall - default-enabled (manifest.ts:176, dep three-memory-stores) | when: prior-work context needed across sessions (search/query/analyze/stats); args: action + query/sessionPath; caveat: project-scoped by default |
79
+ | `error` | Inspect captured extension errors (list/get/clear/stats) | error-tracking - opt-in, disabledByDefault (manifest.ts:276) | when: a tool or extension failed and you need the captured error history; args: action list/get/clear/stats |
80
+ | `session_health` | Read/reset session LLM-provider health state | health-maintenance - opt-in, disabledByDefault (manifest.ts:259) | when: provider errors / auth / balance events occurred; args: action get/diagnose/recover; caveat: recover only after the user acted |
81
+ | `health_maintenance` | Health-based maintenance (check/commit/rollback/benchmark) | health-maintenance - opt-in, disabledByDefault (manifest.ts:259) | when: agent self-state hygiene (check/commit/rollback/benchmark); args: action; caveat: rollback needs a checkpoint hash |
82
82
 
83
83
  <!-- TOOLS-CATALOG-END -->
84
84
 
package/build-info.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.40.3",
4
- "sha": "3f07ed16880eec5fea0c69493fff5cf59ac0cbf0",
5
- "shaShort": "3f07ed1",
3
+ "version": "0.40.6",
4
+ "sha": "61e31281b41bdf7326bfc45387ce3352e0c55a18",
5
+ "shaShort": "61e3128",
6
6
  "branch": "detached",
7
7
  "dirty": false,
8
- "packedAt": "2026-10-20T11:41:36.856Z"
8
+ "packedAt": "2026-10-23T20:45:10.724Z"
9
9
  }
@@ -61,9 +61,10 @@ export function gatherL1Environment(_pi, ctx) {
61
61
  },
62
62
  };
63
63
  }
64
- // The L1 environment section renders in the prompt-builder's instanceSection
65
- // (instance-composition.ts), which carries the volatile data in the Instance
66
- // block instead of a separate section.
64
+ // The L1 environment data is consumed by instance-composition.ts: the
65
+ // volatile stats (elapsed, last event, turns, tool average) render only in
66
+ // the system_info tool, while the compact prompt line takes just the PID,
67
+ // which is process-stable.
67
68
  export default function agentEnvironmentExtension(pi) {
68
69
  registerSessionStartHandler(pi, SessionPhase.Background, async (_event, ctx) => {
69
70
  const state = getExtensionState(ctx, "agent-environment", createEnvState);
@@ -21,7 +21,7 @@ import { skillsLoadingText } from "../skills-tool/loading-guidance.js";
21
21
  import { reconstructProjectDocsSection, resetProjectDocsSectionCache, } from "./project-docs-section.js";
22
22
  import { setCachedSkills, getCachedVisibleSkillNames } from "../skills-tool/index.js";
23
23
  import { reconstructMemorySection, resetMemorySectionCache } from "./memory-section.js";
24
- import { gatherInstanceData } from "./instance-composition.js";
24
+ import { gatherInstanceData, renderCompactInstance } from "./instance-composition.js";
25
25
  import { sendTrackedMessage } from "../../../lib/utils/injection-tracker.js";
26
26
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
27
27
  import { flushRecoveredFires } from "../../../extensions/scheduling/timer/wake-retry.js";
@@ -349,7 +349,10 @@ export default function promptBuilderExtension(pi) {
349
349
  catch {
350
350
  /* already init'd or non-fatal */
351
351
  }
352
- memoryCount = memory.getAll(3).length;
352
+ // getAll(limit) slices the in-memory store, so a small limit turned the
353
+ // rendered memory count into a floor of 3. The instance line reports a
354
+ // true count: ask for the whole store.
355
+ memoryCount = memory.getAll(Number.MAX_SAFE_INTEGER).length;
353
356
  }
354
357
  catch {
355
358
  /* memory unavailable - non-fatal */
@@ -393,9 +396,12 @@ export default function promptBuilderExtension(pi) {
393
396
  // Build the prompt as a flat list of sections. Every section is a
394
397
  // `PromptSection`; the top-level handler never touches raw strings
395
398
  // or arrays of strings.
396
- // Instance: compact 1-line orientation (version/cwd/session at a
397
- // glance); full data via the system_info tool. The agent should not
398
- // need a tool call to discover its own version/cwd/session.
399
+ // Instance: compact one-line orientation (build + install root, model,
400
+ // PID, session, resource counts); full data stays in the system_info
401
+ // tool. The block carries process-stable facts only: the system prompt
402
+ // is a cached prefix, so a field that changes between turns (a clock,
403
+ // elapsed time, turn or tool counters, context size) would invalidate
404
+ // that prefix on every request and cost more than the field is worth.
399
405
  const instanceData = await gatherInstanceData(pi, ctx, {
400
406
  skillCount: skills.length,
401
407
  skillDirs,
@@ -406,8 +412,7 @@ export default function promptBuilderExtension(pi) {
406
412
  })),
407
413
  memoryCount,
408
414
  });
409
- const sessionId = ctx.sessionManager?.getSessionId() ?? "";
410
- const compactInstanceLine = `Agent: Braid v${instanceData.braidVersion} (over pi-core v${instanceData.pi.version}) | Cwd: ${instanceData.cwd} | Session: ${sessionId}`;
415
+ const compactInstanceLine = renderCompactInstance(instanceData);
411
416
  // Discovery & exploration stance. Guarded by tool availability: each
412
417
  // line only appears when its tools exist; the stance paragraph is
413
418
  // unconditional. Placed after guidelines, before tools — a stance, not