pi-advisor-flow 0.15.1-dev.2 → 0.15.2-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +16 -1
  3. package/dist/index.js +1157 -502
  4. package/docs/README.md +9 -0
  5. package/docs/benchmark.md +22 -0
  6. package/docs/configuration.md +194 -0
  7. package/docs/development.md +38 -0
  8. package/docs/herdr.md +169 -0
  9. package/docs/privacy.md +102 -0
  10. package/extensions/index.ts +23 -0
  11. package/locales/de.json +330 -0
  12. package/locales/en.json +331 -0
  13. package/locales/es.json +3 -0
  14. package/locales/fr.json +330 -0
  15. package/locales/pt-BR.json +3 -0
  16. package/locales/pt.json +3 -0
  17. package/locales/ru.json +3 -0
  18. package/locales/uk.json +3 -0
  19. package/locales/zh.json +3 -0
  20. package/package.json +15 -2
  21. package/skills/pi-advisor-flow/SKILL.md +62 -0
  22. package/src/commands/activation-preparation.ts +9 -2
  23. package/src/commands/activation.ts +28 -8
  24. package/src/commands/configuration-tool-models.ts +143 -0
  25. package/src/commands/configuration-tool-policy.ts +177 -0
  26. package/src/commands/configuration-tool-preview.ts +228 -0
  27. package/src/commands/configuration-tool-runtime.ts +40 -0
  28. package/src/commands/configuration-tool-transaction.ts +120 -0
  29. package/src/commands/configuration-tool-update.ts +230 -0
  30. package/src/commands/configuration-tool.ts +89 -0
  31. package/src/commands/lifecycle.ts +6 -1
  32. package/src/commands/manual-consultation.ts +6 -1
  33. package/src/commands/manual-progress.ts +4 -3
  34. package/src/commands/model-commands.ts +2 -1
  35. package/src/commands/model-options.ts +4 -6
  36. package/src/commands/model-picker.ts +16 -6
  37. package/src/commands/registration.ts +2 -0
  38. package/src/commands/runtime.ts +17 -4
  39. package/src/commands/settings-commands.ts +30 -7
  40. package/src/config/schema-validators.ts +104 -0
  41. package/src/config/schema.ts +35 -102
  42. package/src/config/storage.ts +160 -7
  43. package/src/i18n.ts +31 -0
  44. package/src/scout-group-serialization.ts +66 -0
  45. package/src/scout-groups.ts +3 -66
  46. package/src/scout-selection.ts +99 -0
  47. package/src/scout.ts +6 -93
  48. package/src/session-state.ts +27 -137
  49. package/src/tool-input-normalization.ts +119 -0
  50. package/src/tools/gate-policy.ts +13 -5
  51. package/src/tools/jev-filter.ts +2 -1
  52. package/src/tools/jev-turn-gate.ts +2 -1
  53. package/src/tools/register-lifecycle.ts +5 -1
  54. package/src/tools/register-outcome.ts +5 -1
  55. package/src/tools/register-renderers.ts +5 -2
  56. package/src/tools/render-advisor-result.ts +20 -8
  57. package/src/tools/render-common.ts +16 -4
  58. package/src/tools/scout-status.ts +10 -2
  59. package/src/ui/jev-classifier-submenu.ts +143 -38
  60. package/src/ui/jev-filter-submenu.ts +52 -14
  61. package/src/ui/jev-provider-submenu-view.ts +72 -20
  62. package/src/ui/jev-provider-submenu.ts +40 -12
  63. package/src/ui/jev-setup-support.ts +48 -19
  64. package/src/ui/manual-dialog-render.ts +71 -25
  65. package/src/ui/searchable-model-list.ts +18 -4
  66. package/src/ui/settings-formatting.ts +5 -2
  67. package/src/ui/settings-items-jev.ts +216 -0
  68. package/src/ui/settings-items.ts +216 -259
  69. package/src/ui/settings-selector.ts +9 -2
  70. package/src/ui/text-setting-submenu.ts +8 -1
  71. package/src/usage.ts +9 -3
package/docs/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # pi-advisor documentation
2
+
3
+ - [Configuration](configuration.md) — settings, defaults, Simple mode, persistent activation, context limits, and automatic loop gates.
4
+ - [Privacy and data handling](privacy.md) — conversation and repository context, redaction, tool policies, project preferences, outcome logging, session summaries, and Herdr.
5
+ - [Development](development.md) — local setup and required checks.
6
+ - [Benchmark](benchmark.md) — hermetic, decision-point, screening, and evaluation tiers.
7
+ - [Agent plans](https://github.com/philipbrembeck/pi-advisor/tree/main/docs/agents/plans) — implementation plans and internal design records.
8
+
9
+ For installation, core features, and the Executor/Advisor workflow, see the [project README](../README.md).
@@ -0,0 +1,22 @@
1
+ # Benchmarking pi-advisor
2
+
3
+ The repository-only benchmark lives in the [source repository](https://github.com/philipbrembeck/pi-advisor/tree/main/bench). It is not part of the npm package.
4
+
5
+ ## Tiers
6
+
7
+ - **Tier 1 replay:** `bun run bench:replay`. This is hermetic, deterministic, uses a local OpenAI-compatible mock, requires no API key or network, and runs in pull-request CI. A non-zero result is a regression in the shipped gate, disclosure, context, budget, or pin seams.
8
+ - **Tier 2 decisions:** `bun run bench:decisions`. Without `BENCH_LIVE=1` it validates the 24 decision fixtures and null/oracle controls. A live run needs `BENCH_BASE_URL`, `BENCH_API_KEY` (or `OPENAI_API_KEY`), non-zero pricing in a config file, and `BENCH_LIVE=1`; it is scheduled rather than run on PRs. `BENCH_SCOUT=1` enables the Scout on/off experiment. Live runs must name a registered pin set via `livePinSet` (default `openai-codex`; `zai-glm-5.3` is an exploratory Tier 2-only set). Reports across pin sets are not comparable. Empty Advisor responses are retried once, then excluded from quality denominators with per-arm coverage; a live arm under 80% usable is INVALID.
9
+ - **Tier 3 screening:** `BENCH_LIVE=1 bun run bench:screen`. It requires a successful Harbor/provider feasibility spike and the local Pi `openai-codex` OAuth session. If `BENCH_REACTBENCH_ROOT` and a runner are not supplied, the adapter fetches the pinned public ReactBench checkout and uses the checked-in Harbor command. It classifies tasks using the committed §1 preregistration and reports candidate-band prevalence as a proxy.
10
+ - **Tier 3 evaluation:** `BENCH_LIVE=1 bun run bench:evaluate`. It consumes a screening report and fresh, disjoint seeds, using the same host-side Pi/Codex OAuth broker. The committed §2 preregistration governs task-level majority aggregation, McNemar's exact test, and Q3's dominance threshold.
11
+
12
+ Live tiers are quality signals. They run only from `workflow_dispatch` or a schedule and do not block releases. Missing providers, budgets, or usage yield `UNAVAILABLE`, not a fabricated zero or a successful value claim. Tier 3's built-in Codex rates are normalized list-price equivalents for the subscription, not evidence of an API invoice.
13
+
14
+ ## Reading a report
15
+
16
+ Reports are versioned JSON plus a Markdown summary under `bench/reports/`. Always check the pins first: pi-advisor and Pi versions, model ids **and effort levels**, ReactBench SHA, React Doctor version, gate settings, and fixture hashes. `INVALID` means null/oracle controls failed and the quality number must be voided. `UNAVAILABLE` means the tier could not make its claim.
17
+
18
+ Tier 2 reports separate the positive mechanical location lower bound from the LLM judge, retain judge justifications, and report catch rate, false-alarm rate, `J`, cost per catch, and p50/p95 latency. With 24 items, differences within one item are ties; the tier does not support finer precision.
19
+
20
+ Tier 3 Q2 counts `E fails ∧ E+A passes` and `E passes ∧ E+A fails` after five seeds are reduced to one outcome per task. Per-seed counts are descriptive only. Q3's headline is the candidate-prevalence-reweighted USD/pass-rate point; the uplift-only plot is diagnostic. The report also gives the break-even number of Advisor consultations at the pinned settings.
21
+
22
+ The benchmark never reports an absolute ReactBench score. Its claims are paired comparisons between the fixed arms on the same tasks and seeds.
@@ -0,0 +1,194 @@
1
+ # Configuration
2
+
3
+ Use `/advisor-models` and `/advisor-settings` to configure pi-advisor. Both commands save to the global `advisor.json` in the Pi agent directory. `/advisor-settings` uses Pi's compact searchable settings list: type to fuzzy-search a control, press Enter or Space to change it, and every valid change is saved immediately.
4
+
5
+ Repository-controlled project `advisor.json` files are not applied. Models, prompts, gates, budgets, disclosure, redaction, integrations, and consent remain under the user's global configuration.
6
+
7
+ ## Configure from chat
8
+
9
+ When the user asks the Executor to configure pi-advisor, it can call `advisor_config` with `action: "read"` to inspect current effective settings and persisted global overrides, or `action: "update"` with a sparse `changes` object. Updates use the exact keys returned as `writableKeys`; `null` removes a saved override and restores the extension default. The tool validates the merged config, preserves unknown fields, displays the old-to-new changes, and requires interactive confirmation before writing. It remains available even when model-facing Advisor tools are disabled.
10
+
11
+ Model changes open the existing interactive picker rather than accepting a model-generated ref as approval. Saving an Executor model only pins it; run `/advisor` to activate that model in the current session. Jev classifier and credential provisioning stays in `/advisor-settings`. `advisorOutcomeLogging` is supported only as a separate update through its existing consent path. Always on changes apply to future sessions and do not start an Advisor call immediately.
12
+
13
+ `/advisor` also accepts `executor=`, `advisor=`, and `contextMaxChars=` overrides for the current activation. For example, `/advisor contextMaxChars=30000` sets the reconstructed-history limit; use `0` for no history. The `ALL` option in settings represents the complete current branch and remains subject to the Advisor model's context limit. When `executor` is unset, the Executor is the current Pi session model and thinking level (unless `executorEffort` is set); `/advisor` does not switch models. On first use, or when the saved Advisor ref is missing from the configuration or Pi's available model list, `/advisor` opens the available-model picker instead of silently choosing an unconfigured model. An explicit `executor` that is no longer available is picked again; choose **Current session model** to clear it. Selected refs are persisted only after the models pass activation checks.
14
+
15
+ All fields are optional. The model refs below are explicit examples of models available through your configured providers; omit them to choose models interactively with `/advisor`. Disclosure and redaction fields are explained in [Privacy and data handling](privacy.md).
16
+
17
+ ```json
18
+ {
19
+ "executor": "provider/executor-model",
20
+ "advisor": "provider/advisor-model",
21
+ "advisorFallbackModel": "provider/backup-advisor-model",
22
+ "executorEffort": "medium",
23
+ "advisorEffort": "xhigh",
24
+ "contextMaxChars": 25000,
25
+ "advisorModelWhitelist": [
26
+ "provider/fast-executor",
27
+ "provider/frontier-executor"
28
+ ],
29
+
30
+ "advisorPlanGate": true,
31
+ "advisorFailureGate": true,
32
+ "advisorCompletionGate": true,
33
+ "advisorCustomInvocation": "before changing a production deployment",
34
+ "advisorCollapseResponses": false,
35
+
36
+ "advisorAutoLoopGate": true,
37
+ "advisorLoopThreshold": 3,
38
+ "advisorMaxCallsPerSession": 5,
39
+ "advisorBlockOnBlocked": true,
40
+ "gateFailureMode": "block-session",
41
+
42
+ "advisorSessionSummary": false,
43
+ "advisorLogFeedback": false,
44
+ "advisorScoutEnabled": false,
45
+ "showUsageDetails": true,
46
+ "showUsageFooter": false,
47
+ "advisorGitContext": "summary",
48
+ "advisorGitContextMaxChars": 20000,
49
+ "simpleMode": false,
50
+ "advisorToolsEnabled": true,
51
+ "alwaysOn": false,
52
+ "advisorHerdrIntegration": true,
53
+ "advisorToolResultMaxLines": 2000,
54
+ "advisorToolResultMaxBytes": 51200,
55
+
56
+ "advisorRedactSecrets": false,
57
+ "advisorAgentsMdContext": true,
58
+ "advisorTrackedFileContent": false,
59
+ "advisorUntrackedContent": false,
60
+ "advisorDisableSameModel": true,
61
+ "advisorOutcomeLogging": false,
62
+ "advisorJevTransport": "typesafe-compatible",
63
+ "advisorJevBaseUrl": "https://api.codiv.ai",
64
+ "advisorJevKeyProvider": "openrouter",
65
+ "advisorToolPolicies": {
66
+ "bash": "summary",
67
+ "deploy": "exclude"
68
+ }
69
+ }
70
+ ```
71
+
72
+ ## Advisor fallback model
73
+
74
+ `advisorFallbackModel` is optional and empty by default. Select it from **Fallback Advisor model** in `/advisor-settings` or the optional slot in `/advisor-models`. When the primary Advisor cannot resolve credentials or the provider request fails, pi-advisor retries once with the fallback using the same privacy settings, model whitelist, budget reservation, and prepared request payload. A successful fallback counts as one consultation, not two, and the response is attributed to the model that answered. User cancellation, same-model suppression, and request-preparation failures do not silently bypass their existing controls. If both attempts fail, the combined primary and fallback error is surfaced. A fallback equal to the active Executor is skipped with a notice.
75
+
76
+ ## Same-model consultations
77
+
78
+ `advisorDisableSameModel` defaults to `true`. When the active Executor model is the same provider/model as the configured Advisor, `ask_advisor` returns a skipped result without calling the provider, screening with Jev, consuming a consultation, or using a tracked-file handoff. Manual calls and automatic gates are skipped too; they never create a tool or session block. The active model (including models selected by `/model`) is compared, not just the saved Executor setting. `/advisor`, `/advisor-models`, and model selection re-check the match and show a notice on transitions. Turn this setting off in `/advisor-settings` if you want a same-model consultation with a different reasoning level.
79
+
80
+ ## Follow-up consultations
81
+
82
+ Pass `followUpTo` with a new non-empty `question` to `ask_advisor` to continue an existing response. The tool reuses the exact post-redaction payload prefix captured for that `adviceId` and appends only the follow-up question, so Scout does not rebuild the conversation. Jev screening, same-model suppression, the whitelist, current privacy policy, and the shared call budget still apply. Follow-ups count once against `advisorMaxCallsPerSession` and render a distinct follow-up usage line.
83
+
84
+ Payloads are session-local and never persisted. They expire after five minutes, are cleared on a new user turn or after three subsequent non-Advisor tool results, and stop after three chained follow-ups. Reuse is bound to the original project directory, trust state, and disclosure settings. A successful follow-up advances the chain to a new `adviceId`; expired or unknown IDs return guidance to issue a fresh consultation. Follow-ups cannot add a draft, Git context override, or file attachments; use a fresh consultation for those.
85
+
86
+ ## Advisor model whitelist
87
+
88
+ `advisorModelWhitelist` is an optional global array of exact `provider/model` references. When it contains one or more entries, the Advisor tool and every automatic Advisor path are available only while the current Executor model matches one of those entries. A missing current model is denied when the list is non-empty. An empty list (the default) allows every model for backward compatibility. The same restriction applies even when `ask_advisor` is present in the active tool list.
89
+
90
+ The `/advisor-settings` row opens a searchable multi-select menu containing the models configured in Pi. Type to fuzzy-filter the list, use Space to toggle models, and press Enter to apply. The setting is checked before budgets, repeated-call tracking, Jev screening, or any Advisor provider request, so a denied model neither spends Advisor budget nor triggers a gate. Matching is exact and case-sensitive.
91
+
92
+ ## Simple mode and persistent activation
93
+
94
+ - `simpleMode` defaults to `false`. When enabled, `ask_advisor` remains available for voluntary second opinions when Advisor tools are enabled, and `/advisor-manual` remains available. Plan/failure/completion rules, loop gates, blocking, call budgets, and session summaries are disabled. Context limits, result caps, redaction, and tool disclosure policies still apply.
95
+ - `advisorToolsEnabled` defaults to `true` to preserve on-demand tool access. When `false`, Pi removes `ask_advisor` and `record_advisor_outcome` from the active tool set for new, resumed, forked, and reloaded sessions. This explicit opt-out takes precedence over `alwaysOn`. Re-enable tools in `/advisor-settings`, or run `/advisor`; the latter clears the opt-out only after successful activation.
96
+ - `alwaysOn` defaults to `false` and controls automatic flow activation separately from tool availability. When enabled and Advisor tools are enabled, Pi restores the configured Executor, if any, and activates the flow for new, resumed, forked, and reloaded sessions. If model refs are missing or unavailable, startup reports the problem without activating; run `/advisor` to choose available models interactively. A native subagent launcher that sets `PI_SUBAGENT_CHILD=1` keeps its host-selected model and thinking level; Advisor tools still activate, but the child is not switched to the parent Executor.
97
+ - With a pinned `executor`, an explicit `/model` selection made before `/advisor` is held for that session and adopted as the Executor on the next successful activation, and while the Advisor flow is active it is persisted as the Executor immediately. Without a pinned `executor`, `/model` only changes the session model, which the Executor follows. A model restored with a session or selected by cycling does not change the saved Executor.
98
+ - `/advisor-off` persists `advisorToolsEnabled: false` and turns `alwaysOn` off, keeping model-facing Advisor tools disabled in later sessions. `/advisor-manual` remains available.
99
+ - In Simple mode, settings keeps the Context window/history, Advisor tools, Simple mode, and Always on controls. Advanced values remain saved and take effect when Simple mode is disabled.
100
+ - Settings changes are applied and persisted as they happen; Escape closes the screen without a separate Save action.
101
+
102
+ ## Experimental Advisor Scout
103
+
104
+ `advisorScoutEnabled` defaults to `false` and can only be loaded from the global `advisor.json`. The `Experimental Advisor Scout` row appears in advanced `/advisor-settings`. Simple mode hides the row without changing its saved value.
105
+
106
+ When enabled, Scout runs before Executor-requested `ask_advisor` calls, `/advisor-manual`, and automatic gates. It resolves the Executor model (the session model unless `executor` is set) and `executorEffort`; it never substitutes the Advisor model or another model. The extra call adds latency and provider cost.
107
+
108
+ Scout receives at most 64 KiB of serialized manifest data in 64 protocol-safe groups, with a 24 KiB limit per group and bounded labels. It may select at most 32 groups and return up to 4 KiB of synthesis. The synthesis is labelled as untrusted inference and never replaces selected verbatim evidence. Required current-request context is always retained. The reconstructed Advisor conversation has a separate `contextMaxChars` budget, so manifest metadata does not consume that budget. If required context cannot fit either hard limit, Scout is skipped.
109
+
110
+ Scout has a 30-second total timeout. Missing model or authentication, provider errors, timeouts, invalid JSON, duplicate group IDs, and over-budget output produce a visible fallback. Unknown selected group IDs are ignored, required groups are retained automatically, and optional selections are trimmed to the selection limit. Fallback sends the exact original conversation to the Advisor and does not change the gate decision, blocking policy, Herdr state, or Advisor-call budget. Cancelling the parent operation stops Scout and prevents the Advisor call from starting.
111
+
112
+ Scout usage, latency, selection counts, pre-Scout omissions, and fallback reasons are displayed separately from Advisor usage. Usage and cost details are shown by default; set `showUsageDetails` to `false` to hide details from extension-rendered Advisor, Scout, and gate output without changing usage accounting or Pi's `/cost` totals. The cumulative Advisor footer is controlled independently by `showUsageFooter`, which defaults to `false`. Both settings apply immediately when saved and do not require a reload. These displays remain local and ephemeral and are not included in Session Advisor Summary or Herdr reports.
113
+
114
+ ## Advisor log feedback
115
+
116
+ `advisorLogFeedback` defaults to `false`. When enabled, pi-advisor adds remaining-call budget and Scout status messages to session logs. Turn on **Advisor log feedback** in `/advisor-settings` to include them. Actual Advisor call and result messages remain visible either way. This setting does not change call accounting, reservations, or enforcement.
117
+
118
+ ## Context and limits
119
+
120
+ - `contextMaxChars` defaults to `15000`. It preserves complete semantic entries and adds an omission marker rather than splitting a message.
121
+ - Set `contextMaxChars` to `0` to omit reconstructed history. `9007199254740991` is the persisted value for `ALL`.
122
+ - Tool results default to Pi's `2000` lines and `50 KiB` limits. Oversized results preserve their beginning and end with an omission marker.
123
+ - `advisorLoopThreshold` is an integer of at least `2`; its default is `3`.
124
+ - Omit `advisorMaxCallsPerSession` for an unlimited shared budget. Otherwise it must be a non-negative safe integer.
125
+
126
+ ## AGENTS.md and Advisor preferences
127
+
128
+ `advisorAgentsMdContext` defaults to `true`. In a trusted project, each Advisor call may include the project-root `AGENTS.md` and the global `~/.pi/agent/AGENTS.md` when present. Each source is origin-labelled, redacted when `advisorRedactSecrets` is enabled, capped at 8 KiB, and included in a combined 16 KiB rules budget. The Advisor receives them in a separate untrusted `<project_rules>` block as review guidance, never as executable instructions.
129
+
130
+ An untrusted project sends neither rules file; the Advisor is told that rules were withheld rather than being shown an apparently rule-free project. The global rules file is never sent for an untrusted project. Turn the setting off to restore the previous behavior.
131
+
132
+ `.pi/advisor-preferences.md` remains separate: it is an explicit, Advisor-specific project brief, while `AGENTS.md` supplies general project/global conventions. Both are untrusted context, and neither can override the Advisor system instructions; the explicit preferences brief is more specific when the two sources conflict.
133
+
134
+ ## Consultation responses
135
+
136
+ Normal consultations preserve the provider's final Markdown and never block execution. If the Advisor explicitly says it cannot review a specifically named file, the Executor may make a sequential follow-up call with `includeTrackedFiles` when global tracked-file consent is enabled; this is discretionary, not an automatic retry. When the Advisor has no material concern or recommendation, it may begin with the exact first line `Verdict: sound`. Pi renders that response with the static `◆ ADVISOR · SOUND` header for both `ask_advisor` results and `/advisor-manual`.
137
+
138
+ ## Jev/Decisions consultation filter
139
+
140
+ `advisorJevFilterEnabled` defaults to `false`. When enabled, one typed screening request checks each `ask_advisor` invocation. Only requests classified as both negligible-stakes and self-answerable are skipped; all others reach the Advisor unchanged.
141
+
142
+ The classifier selection and filter are separate settings rows. **Jev classifier** opens a searchable list of Pi classifier models whose providers have usable Pi authentication, plus the explicit **Jev API Key** option. Each selection is live-verified before it is saved. The **Jev/Decisions consultation filter** row only switches screening on and off; it stays off until an available classifier is selected. A classifier that later becomes unavailable fails open at runtime.
143
+
144
+ - **Classifier selection**: `/advisor-settings` → **Jev classifier** offers available Pi classifier models identified by concrete `provider/model` refs. Provider authentication remains Pi-managed. Prices shown in the picker are the live Pi catalog input/output rates per million tokens; pricing metadata is not copied into `advisor.json`.
145
+ - **Legacy settings**: existing `advisorJevTransport`, `advisorJevModel`, endpoint, provider, and `advisorJevPricePerMtok` fields are preserved for rollback compatibility but no longer route classifier calls or price native calls. Legacy settings/credentials are not automatically migrated into Pi authentication.
146
+ - **Custom classifier endpoints**: Pi's `models.json` chat-compatible endpoint configuration does not register a classifier implementation. Install/configure a Pi provider extension that registers a classifier model and implementation, then select it from the picker.
147
+ - **Jev API Key isolation**: selecting **Jev API Key** prompts for a masked TypeSafe key and sends it only as a request-scoped Pi classifier `apiKey`. It is stored in a separate `pi-advisor-jev-classifier` secure-store namespace (or a dedicated mode-0600 file fallback). No legacy Jev secret, environment variable, Pi provider login, or plaintext `advisor.json` key is read or migrated by this path.
148
+ - **API-key choice verification**: the explicit API-key flow locates Pi's built-in `typesafe/jev-latest` classifier even when Pi has no TypeSafe login. The submitted key is passed directly to that request and stored only after a successful live check. A missing stored key fails open; it never falls back to Pi authentication or legacy credentials.
149
+ - **Evidence and thresholds**: classifiers receive only the existing redacted and bounded Jev state, with no Git context, attachments, images, Scout output, or session summaries. Native bool probabilities and three-label stakes distributions feed the existing thresholds. Malformed results, missing models, provider errors, and timeouts fail open; caller cancellation propagates.
150
+ - **Pricing and totals**: Pi's model catalog input/cache rates price classifier input and cache tokens. JEV output tokens are always free and output cost is forced to zero even when catalog metadata contains an output rate. Missing usage is shown as unavailable; explicit zero input rates stay zero. Screening usage is combined once with Advisor usage in the `ask_advisor` tool result and Pi's generic tools cost bucket. Manual and turn-gate classifier usage remains local-only because Pi has no supported lifecycle cost aggregation API.
151
+
152
+ - **Fail-open and repeats**: a missing key, authentication failure, timeout, network error, or malformed response lets the consultation run; the outage is surfaced once per distinct failure. Exact repeats are still handled locally and free, even when filtering is off. `advisorJevFilterOverrideWindow` defaults to 10 turns; force-after-skip and automatic passthroughs are counted in the Session Advisor Summary. Skipped calls do not consume `advisorMaxCallsPerSession`.
153
+ - **Timeout**: `advisorJevTimeoutMs` (8000 ms by default) is a hard wall-clock deadline. Native classifier calls disable provider retries so cancellation and deadlines remain bounded. A skip consumes no Advisor-call budget.
154
+
155
+ ## Proactive Jev classifier turn gate
156
+
157
+ `advisorJevTurnGateEveryTurns` defaults to `0` (off). When set to N, every Nth completed turn **without a consultation** asks the selected Jev classifier whether a senior advisor should weigh in now. A confident yes (`advisorJevTurnGateNoulThreshold`, default `0.8`) runs a real Advisor consultation delivered as a steer message between turns; a no, uncertainty, or provider failure keeps the status quo. Turn-gate consultations consume the shared `advisorMaxCallsPerSession` budget, appear in the Session Advisor Summary under trigger `turn-gate`, and reset the without-consultation counter.
158
+
159
+ ## Automatic loop gate
160
+
161
+ The optional loop gate detects consecutive calls with the same normalized tool signature. By default, it consults the Advisor after three repeats.
162
+
163
+ Unlike ordinary consultations, a loop-gate reply must start with exactly one decision header:
164
+
165
+ ```text
166
+ Decision: proceed
167
+ Decision: revise
168
+ Decision: blocked
169
+ ```
170
+
171
+ | Decision | Effect |
172
+ | --------- | --------------------------------------------------- |
173
+ | `proceed` | Reset the repeat counter and allow the tool action. |
174
+ | `revise` | Block the repeated tool action. |
175
+ | `blocked` | Apply the configured gate-failure policy. |
176
+
177
+ Malformed, missing, duplicate, or contradictory decisions are gate failures. The same policy applies when the Advisor is unavailable or the shared call budget is exhausted.
178
+
179
+ | Failure mode | Effect |
180
+ | ------------------------- | ----------------------------------- |
181
+ | `block-session` (default) | Block the session. |
182
+ | `block-tool` | Block only the current tool action. |
183
+ | `warn-and-continue` | Show a warning and continue. |
184
+
185
+ | Condition | `block-session` | `block-tool` | `warn-and-continue` |
186
+ | -------------------------------------------------------- | --------------- | ----------------- | ------------------- |
187
+ | Advisor unavailable or timed out | Block session | Block tool action | Warn and continue |
188
+ | Missing, malformed, duplicate, or contradictory decision | Block session | Block tool action | Warn and continue |
189
+ | Shared budget exhausted | Block session | Block tool action | Warn and continue |
190
+ | `Decision: blocked` | Block session | Block tool action | Warn and continue |
191
+
192
+ `advisorBlockOnBlocked` controls whether a session block immediately aborts the active run. It never turns a session block into a tool-only block. A recorded session block remains fail-safe after `/advisor-off`; start a new session to resume tool execution.
193
+
194
+ See [Privacy and data handling](privacy.md) for repository context, disclosure, redaction, and integrations.
@@ -0,0 +1,38 @@
1
+ # Development
2
+
3
+ ## Local setup
4
+
5
+ ```bash
6
+ git clone git@github.com:philipbrembeck/pi-advisor.git
7
+ cd pi-advisor
8
+ bun install
9
+ bun run build
10
+ ```
11
+
12
+ Use Bun 1.4.4 or newer; the repository's `preinstall` check rejects older versions unless lifecycle scripts are disabled. The check skips packed installs, so package consumers don't need Bun. `bun run typecheck` uses the `bun check` command.
13
+
14
+ Pi loads `dist/index.js`, which bundles internal modules so settings controls and persistence share the same runtime state. Run `bun run build` once after checkout, then reload Pi. The pre-commit hook rebuilds and stages the bundle after linting source changes; `prepack` also rebuilds it for npm packaging.
15
+
16
+ A rebuilt bundle is not always picked up by `/reload` in a running process: the in-process module cache can keep serving the previous `dist/index.js`. After rebuilding, verify the change is live (for example, check new tool-result fields) or fully restart Pi and continue the session with `pi -c`.
17
+
18
+ ## Checks
19
+
20
+ Run the full project checks before opening a pull request:
21
+
22
+ ```bash
23
+ bun run test
24
+ bun run typecheck
25
+ bun run check:boundaries
26
+ bun run lint
27
+ bun run package:check
28
+ bun audit --audit-level=high
29
+ git -c diff.stat=false diff --no-ext-diff --check --no-stat
30
+ ```
31
+
32
+ `bun run format` formats the project with Bun's native formatter; `bun run format:check` verifies it. The pre-commit hook uses lint-staged to run Bun fmt and Oxlint on staged files while preserving partially staged changes.
33
+
34
+ `bun test` covers the normal suite. Run `bun run test:bench` for the repository-only benchmark tests.
35
+
36
+ `src/tools/register-ask-advisor.ts` exceeds the usual ~300-line target because registration and the sequential screening, budget, one-shot handoff, streaming, and error cleanup path share one ordered execution boundary; splitting that boundary risks changing when a call becomes chargeable or consumes consent.
37
+
38
+ GitHub Actions manages release tags and publishing from `package.json`. Do not create release tags manually.
package/docs/herdr.md ADDED
@@ -0,0 +1,169 @@
1
+ # Herdr integration
2
+
3
+ pi-advisor can report Advisor activity, blocked-state labels, and Advisor failures to [Herdr](https://herdr.dev/). The integration is optional and never controls whether Advisor work proceeds.
4
+
5
+ ## Compatibility baseline
6
+
7
+ This document was verified against:
8
+
9
+ - Herdr **0.9.3**, socket protocol **22**, schema version **1**, using the schema exported by the installed binary. Representative activity, block, clear, and notification requests produced by pi-advisor validate against that schema.
10
+ - Herdr **0.8.0**, socket protocol **19**, schema version **1**, and Herdr **0.7.5**, socket protocol **17**, schema version **1**, as older compatibility baselines.
11
+ - Herdr's stable [Socket API](https://herdr.dev/docs/socket-api/), [CLI reference](https://herdr.dev/docs/cli-reference/), and [Agent automation](https://herdr.dev/docs/agent-automation/) documentation.
12
+
13
+ The installed binary is the authority for a particular machine. Before changing request fields, inspect its schema:
14
+
15
+ ```bash
16
+ herdr --version
17
+ herdr api schema
18
+ herdr api schema --json
19
+ herdr api schema --output herdr-api.schema.json
20
+ ```
21
+
22
+ Herdr documents preview features separately under `/docs/preview/`. Do not implement against preview documentation unless the project deliberately raises its compatibility baseline.
23
+
24
+ ## Transport and discovery
25
+
26
+ Herdr's raw API uses newline-delimited JSON over a local Unix domain socket or a Windows named pipe. Each request has an `id`, `method`, and `params`; the response repeats the request `id` and contains either `result` or `error`.
27
+
28
+ Herdr injects these values into managed pane processes:
29
+
30
+ | Variable | pi-advisor use |
31
+ | ------------------- | ----------------------------------------- |
32
+ | `HERDR_ENV=1` | Confirms that Pi is running inside Herdr. |
33
+ | `HERDR_SOCKET_PATH` | Selects the local socket or pipe. |
34
+ | `HERDR_PANE_ID` | Identifies the pane receiving metadata. |
35
+
36
+ pi-advisor sends nothing unless all three values are available. On Windows, `src/herdr.ts` converts the injected socket value to a `\\.\pipe\...` endpoint.
37
+
38
+ Herdr's documented general socket-resolution order is an explicit CLI session, `HERDR_SOCKET_PATH`, `HERDR_SESSION`, then the default-session socket. pi-advisor does not perform that resolution itself; it uses only the injected `HERDR_SOCKET_PATH`.
39
+
40
+ ## Requests sent by pi-advisor
41
+
42
+ The exact TypeScript request types live in [`src/herdr-shared.ts`](../src/herdr-shared.ts); activity and notification behavior live in [`src/herdr.ts`](../src/herdr.ts).
43
+
44
+ ### Advisor activity
45
+
46
+ When the first overlapping consultation starts, pi-advisor sends a display label:
47
+
48
+ ```json
49
+ {
50
+ "id": "pi-advisor:advisor-activity:<sequence>",
51
+ "method": "pane.report_metadata",
52
+ "params": {
53
+ "pane_id": "<HERDR_PANE_ID>",
54
+ "source": "pi-advisor:advisor-activity",
55
+ "agent": "pi",
56
+ "applies_to_source": "herdr:pi",
57
+ "state_labels": { "working": "seeking advice" },
58
+ "seq": 123
59
+ }
60
+ }
61
+ ```
62
+
63
+ The label is cleared after the last overlapping consultation finishes, or when activity is explicitly reset:
64
+
65
+ ```json
66
+ {
67
+ "id": "pi-advisor:advisor-activity:<sequence>",
68
+ "method": "pane.report_metadata",
69
+ "params": {
70
+ "pane_id": "<HERDR_PANE_ID>",
71
+ "source": "pi-advisor:advisor-activity",
72
+ "agent": "pi",
73
+ "applies_to_source": "herdr:pi",
74
+ "clear_state_labels": true,
75
+ "seq": 124
76
+ }
77
+ }
78
+ ```
79
+
80
+ ### Blocked state
81
+
82
+ A gate block uses two separate paths:
83
+
84
+ 1. pi-advisor emits the in-process Pi event `herdr:blocked`. Herdr's Pi lifecycle integration owns the semantic blocked state.
85
+ 2. pi-advisor sends `pane.report_metadata` with a display-only `blocked` label and later clears that label.
86
+
87
+ This distinction matters. Herdr documents `pane.report_metadata` as presentation metadata: it can change visible labels, but it does **not** change semantic lifecycle state, waits, notifications, or rollups. Do not replace the in-process blocked event with a metadata-only report.
88
+
89
+ The blocked label is secret-redacted, stripped of control characters, whitespace-normalized, and capped at 200 characters by pi-advisor. Repeated calls update metadata but emit only the first false-to-true blocked edge. Clearing emits the true-to-false edge once. A previously reported block is still cleared if the setting was disabled after the block occurred.
90
+
91
+ ### Failure notification
92
+
93
+ Advisor failures can send:
94
+
95
+ ```json
96
+ {
97
+ "id": "pi-advisor:advisor-notification:<sequence>",
98
+ "method": "notification.show",
99
+ "params": {
100
+ "title": "<sanitized title>",
101
+ "body": "<sanitized body>",
102
+ "position": "top-left",
103
+ "sound": "request"
104
+ }
105
+ }
106
+ ```
107
+
108
+ Herdr 0.9.3 requires a visible title after normalization. It permits `sound` values `none`, `done`, or `request`; notification delivery may still report `disabled`, `rate_limited`, `no_foreground_client`, or `busy`. pi-advisor caps titles at 80 characters and bodies at 240 characters, matching Herdr's documented normalization limits. pi-advisor sends notifications best-effort and does not expose the delivery result to Advisor safety logic.
109
+
110
+ ## Metadata ownership and ordering
111
+
112
+ - `source` identifies pi-advisor's metadata owner. Herdr restricts source identifiers to 80 characters using ASCII letters, digits, colon, dot, underscore, and hyphen.
113
+ - `agent: "pi"` guards presentation fields so they apply only to a Pi agent.
114
+ - `applies_to_source: "herdr:pi"` guards presentation fields so they apply only while Herdr's Pi lifecycle integration is authoritative.
115
+ - `seq` prevents stale updates from winning. For the same pane and source, Herdr accepts but ignores sequence numbers less than or equal to the last accepted value.
116
+ - Each new sequence uses the greater of the current clock baseline and the previous sequence plus one. A numeric watermark on `globalThis` survives module reloads in the same JavaScript realm; retries keep their original request ID and sequence.
117
+ - `clear_state_labels: true` clears labels owned by that metadata source; it does not clear semantic agent state.
118
+
119
+ Keep activity and block reports on their existing distinct sources. Combining them would let one cleanup operation erase the other's label.
120
+
121
+ The clock baseline helps a long-running Pi overtake earlier reports from a later-started process as time advances. It is not a shared counter or ownership lock between processes or JavaScript realms; same-millisecond reports, clock rollback, or a historical sequence above the current clock can still prevent a later report from winning. Recovery requires an actual clear request to be created and delivered with a higher sequence. Startup and ordinary turns do not automatically reconcile a stored label when there is no local activity to clear.
122
+
123
+ ## Available Herdr features not used here
124
+
125
+ Herdr 0.9.3 also supports pane titles, displayed agent names, state-label keys for `idle`, `working`, `blocked`, `done`, and `unknown`, named sidebar tokens, token TTLs, and explicit title/display-name clearing. pi-advisor intentionally uses only the display-only `working: "seeking advice"` label and bounded `blocked` label. Titles and tokens add no needed signal today and could expose more consultation context than the privacy boundary allows.
126
+
127
+ Herdr also supports semantic lifecycle and session reports through `pane.report_agent`, `pane.report_agent_session`, `resume_argv`, and `pane.release_agent`. Those remain owned by Herdr's `herdr:pi` integration; pi-advisor must not become a competing lifecycle authority.
128
+
129
+ ## Failure behavior and privacy
130
+
131
+ Herdr is best-effort in pi-advisor:
132
+
133
+ - requests use a 500 ms first attempt and a 1500 ms retry window;
134
+ - metadata reports are serialized per source and pending replacements are coalesced;
135
+ - notifications are not retried after any payload write, avoiding duplicate toasts;
136
+ - pending notifications are capped at 16 while Herdr is unavailable;
137
+ - socket, emitter, and reporting errors are swallowed; and
138
+ - Herdr transport failures never weaken or strengthen Advisor safety policy.
139
+
140
+ Ordinary Bun, benchmark, and Node loader tests initialize with `HERDR_ENV=0` and remove inherited pane/socket variables. Transport fixtures explicitly enable their own temporary sockets.
141
+
142
+ Activity reports contain fixed labels only. Block labels and notification text pass through pi-advisor's local secret redaction before they leave the process. Session summaries and Advisor conversation context are never sent to Herdr.
143
+
144
+ The local socket has no pi-advisor-specific authentication handshake or encryption. Access control comes from the local socket or named-pipe environment managed by Herdr.
145
+
146
+ ## Configuration
147
+
148
+ `advisorHerdrIntegration` is a boolean setting and defaults to `true`. Change it through `/advisor-settings` or in the global `~/.pi/agent/advisor.json` configuration. See [Configuration](configuration.md) and [Privacy and data handling](privacy.md).
149
+
150
+ Disabling the setting suppresses new activity, block-label, and failure-notification reports. Cleanup for an already reported blocked state remains enabled so Herdr is not left showing stale state.
151
+
152
+ ## Change checklist
153
+
154
+ Before changing the integration:
155
+
156
+ 1. Run `herdr --version` and export the installed schema.
157
+ 2. Validate every changed request against that schema and the stable online Socket API.
158
+ 3. Preserve the semantic-state versus display-metadata boundary.
159
+ 4. Test overlapping activity, block edges, clearing after disablement, sanitization, socket errors, and timeouts.
160
+ 5. Run the repository checks in [Development](development.md), then verify the state and notification behavior in a reloaded Herdr-hosted Pi TUI.
161
+
162
+ ## Sources
163
+
164
+ - [Herdr stable Socket API](https://herdr.dev/docs/socket-api/)
165
+ - [Herdr stable CLI reference](https://herdr.dev/docs/cli-reference/)
166
+ - [Herdr stable Agent automation guide](https://herdr.dev/docs/agent-automation/)
167
+ - [Herdr repository](https://github.com/herdrdev/herdr)
168
+ - [`src/herdr-shared.ts`](../src/herdr-shared.ts) — pi-advisor's request types, ordering, and transport implementation
169
+ - [`src/herdr.ts`](../src/herdr.ts) — pi-advisor's activity and notification behavior
@@ -0,0 +1,102 @@
1
+ # Privacy and data handling
2
+
3
+ Advisor context can contain user messages, tool calls, tool results, and repository information. Configure disclosure deliberately.
4
+
5
+ Redaction and output limits reduce accidental disclosure; they are not a data-classification system and cannot guarantee every secret is found. Use tool policies for content that must not be sent to the Advisor.
6
+
7
+ ## Chat-based configuration
8
+
9
+ The `advisor_config` tool reads recognized effective settings and persisted global overrides, while omitting Jev endpoint and credential-provisioning fields. Updates are global, validated, and shown in an interactive confirmation before saving. Enabling full Git context, tracked/untracked file handoff, automatic gates, or Always on shows the relevant disclosure, blocking, or cost warning. Classifier credentials remain in the masked `/advisor-settings` flow; unknown `advisor.json` fields are preserved but never returned to the model.
10
+
11
+ ## Repository context
12
+
13
+ - `advisorGitContext` defaults to `summary` and controls how much of the working tree reaches the Advisor:
14
+ - `off` sends no repository information.
15
+ - `summary` sends changed file names, change status, and line counts. It never sends file contents.
16
+ - `full` additionally sends the patch.
17
+ - Changes are measured against the last commit and cover staged and unstaged work. Untracked files are always listed by name only; `gitContext: full` never sends their contents.
18
+ - `advisorTrackedFileContent` defaults to `false`. When enabled, `includeTrackedFiles` can attach only exact named, repository-relative, tracked regular files from the current working tree. This is intended for a discretionary sequential follow-up when the Advisor explicitly names a missing file; sibling files remain withheld.
19
+ - `advisorUntrackedContent` defaults to `false`. When enabled, `includeUntracked` can attach only exact named, repository-relative, untracked regular files. Files are redacted and capped before egress; sibling files remain withheld.
20
+ - Tracked and untracked text attachments share the 8 KiB per-file and 24 KiB aggregate limits. Binary non-image files, symlinks, directories, submodules, traversal paths, and files outside the repository are refused. Current tracked bodies may include unstaged edits.
21
+ - For an image-capable Advisor, selected user messages and full-policy tool results may forward PNG, JPEG, GIF, or WebP pixels (not just their descriptions). Tool `summary` and `exclude` policies withhold result images; conversation and Scout selection limits also apply. Scout sees bounded image markers, never the pixels. Text-only models receive an explicit no-pixels notice.
22
+ - Explicit `includeTrackedFiles` and `includeUntracked` paths with supported image extensions can forward image files under the same tracked one-shot handoff and global file-content consent rules. Images have a separate cap of 4 MiB each, four images and 8 MiB total across history and files. Mismatched MIME/format, unsupported formats (including SVG), invalid data and oversized images are withheld. When pixels are unavailable, the Advisor is told not to claim visual review.
23
+ - Credential redaction cannot inspect or scrub pixels. Do not attach screenshots containing sensitive data unless you intend the Advisor provider to receive it.
24
+ - `advisorGitContextMaxChars` defaults to `20000`. Repository context may claim its own cap or half of `contextMaxChars`, whichever is smaller, so it cannot crowd out the conversation.
25
+ - The Executor may pass `gitContext` to `ask_advisor` as `none`, `summary`, or `full`. `advisorGitContext` is the ceiling. A larger request is narrowed to the configured level, and the Advisor is told that a fuller view was withheld.
26
+ - `summary` deliberately excludes diff hunk headers. Git derives those from surrounding file content, so a hunk header can reproduce a line the change never touched, including a credential.
27
+ - Redaction runs before the region is capped. Repository content is labelled as untrusted data, and paths and patch text are escaped so a crafted path cannot close the region early and have the remainder read as instructions.
28
+ - File names can be sensitive. `summary` withholds file contents, not file names; use `off` when names must not leave the machine.
29
+ - Collection shares a single overall time budget across its Git commands and degrades to a stated failure rather than implying a clean tree.
30
+
31
+ ## Secret redaction and tool policies
32
+
33
+ - `advisorRedactSecrets` defaults to `false`. When enabled, pi-advisor locally redacts common credential patterns before including context or targeted questions in an Advisor request. The raw targeted question remains available to local UI displays but is not sent to the provider.
34
+ - `advisorToolPolicies` matches an **exact tool name**. Each tool may use `full`, `summary`, or `exclude`:
35
+ - `full` includes call arguments and capped result output.
36
+ - `summary` omits call arguments and result output but includes result status and size metadata.
37
+ - `exclude` omits both call details and output.
38
+ - Tools not listed in `advisorToolPolicies`, including custom and newly added tools, use `full` for backward compatibility.
39
+
40
+ ## Codemode disclosure
41
+
42
+ Pi Codemode calls the same registered `ask_advisor` tool, with the same screening, context reconstruction, redaction, repository ceilings, and attachment consent. Nested tool results are not stored as transcript entries; pi-advisor does not retrieve them from Codemode's local variables or nested-call metadata.
43
+
44
+ The existing `draft` can carry a concise, permitted summary of collected results. It is optionally redacted, capped at 8 KiB, and labelled as an unverified Executor claim, not independent evidence. It also reaches Jev when screening is enabled. Draft and question text are explicit disclosure and are not filtered by the source tools' `advisorToolPolicies`. Do not use them to copy excluded output, secrets, or file bodies withheld by repository or attachment settings. Prefer `gitContext` for patches so the configured ceiling remains effective.
45
+
46
+ Historical Codemode calls and their emitted results are governed by the exact `codemode` tool policy, not by policies for tools called inside the script. Set `advisorToolPolicies.codemode` to `summary` or `exclude` when scripts or their output must be withheld from reconstructed history.
47
+
48
+ ## Fallback and follow-up egress
49
+
50
+ `advisorFallbackModel` receives the same prepared, redacted request as the primary model after a retryable primary resolution or provider failure. No fallback request is sent when the operation is cancelled, the fallback matches the active Executor, or request preparation fails. If both models fail, the local error includes both attempts without persisting either payload.
51
+
52
+ `followUpTo` reuses the exact post-redaction message payload held in memory for the prior `adviceId` and appends the new question after applying the current-or-stricter redaction policy. The cache is never written to the session or filesystem. It expires after five minutes, is cleared by a new user input or three later non-Advisor tool results, and is capped at three follow-up levels. Reuse is bound to the original project directory and trust state. Changing any tracked disclosure, tool-policy, context-cap, or redaction setting invalidates that cache instead of sending the old prefix under different privacy rules. Use a fresh consultation when new files, Git context, or other context must be disclosed.
53
+
54
+ ## Project rules and preferences
55
+
56
+ `advisorAgentsMdContext` defaults to `true`. In a trusted project, the project-root `AGENTS.md` and global `~/.pi/agent/AGENTS.md` may be sent with each Advisor call. The files are read through the same trusted-reader protections as project preferences: no symlinks, realpath containment, redaction, an 8 KiB per-source cap, and a combined 16 KiB rules cap. They are origin-labelled inside a separate `<project_rules>` block and framed as untrusted review guidance, not executable instructions.
57
+
58
+ An untrusted project withholds both files and tells the Advisor that rules were withheld. The global file is never sent for an untrusted project. Disable `advisorAgentsMdContext` to prevent either file from being read or sent.
59
+
60
+ In a trusted project, `.pi/advisor-preferences.md` may provide a short local brief. It is never written by pi-advisor, remains separate from `AGENTS.md`, is treated as lower-priority untrusted text, and is redacted and capped before egress. Symlinks, unreadable files, and paths outside the project are ignored. The explicit preferences brief is more specific than general `AGENTS.md` conventions, but neither source overrides the Advisor system instructions.
61
+
62
+ ## Experimental Advisor Scout
63
+
64
+ `advisorScoutEnabled` defaults to `false`. When enabled, Scout sends a bounded manifest of Advisor-eligible conversation and tool history to the configured Executor model and provider before every Advisor invocation.
65
+
66
+ The same tool disclosure policies, tool-result limits, and optional secret redaction run before Scout sees historical content. Image content is represented by non-pixel markers for selection; image bytes never reach Scout. Advisor image pixels are bound to selected evidence groups, not to markers repeated in Scout's synthesis. Tool-call and result messages are grouped atomically. Incomplete historical fragments are omitted rather than sent as orphan evidence. Required current-request context cannot be partially truncated to force a Scout call.
67
+
68
+ Scout does not receive the deterministic Git context, Executor draft, project preferences, or explicitly attached tracked and untracked files. These regions bypass Scout and retain their existing disclosure, redaction, escaping, and cap rules when the final Advisor request is assembled.
69
+
70
+ Scout returns selected opaque group IDs and a bounded synthesis. The Advisor receives the selected verbatim groups plus a label that identifies the synthesis as untrusted, non-authoritative inference. Scout free-form text never replaces the evidence.
71
+
72
+ The Scout call creates separate provider usage and cost. Its metrics are local and ephemeral. pi-advisor does not persist a Scout trajectory, add Scout data to Session Advisor Summary, send it to Herdr, or charge it against the Advisor-call budget. An ordinary Scout failure uses the original conversation; parent cancellation stops the complete operation.
73
+
74
+ ## Outcome logging
75
+
76
+ `advisorOutcomeLogging` defaults to `false` and is global-only: a project config cannot enable it.
77
+
78
+ `/advisor-stats` reads the local ledger only. It reports counts and rates from retained records, including the first and last timestamps and distinct pseudonymous advice hashes; it does not reconstruct advice or fabricate historical usage/cost. The ledger is capped at 1 MiB and rewritten on overflow, so the report covers only the retained window. Truncated or malformed lines are ignored.
79
+
80
+ When enabled, `~/.pi/agent/advisor-outcomes.jsonl` stores bounded, rotating JSONL records containing only a version, timestamp, salted truncated advice digest, trigger, adoption, and validation status. It stores no prompt, advice, paths, tool output, repository data, session ID, or advice ID.
81
+
82
+ ## Jev classifier screening and the turn gate
83
+
84
+ The optional consultation filter (`advisorJevFilterEnabled`) and proactive turn gate (`advisorJevTurnGateEveryTurns`) are off by default. `/advisor-settings` → **Jev classifier** offers classifier models registered with Pi whose providers have usable Pi-managed authentication, plus the explicit **Jev API Key** path. Custom classifiers require a Pi provider extension; `models.json` alone does not register classifier implementations. `advisorJevClassifier` stores only a concrete `provider/model` ref or `jev-api-key`.
85
+
86
+ The selected classifier receives the existing bounded Jev evidence: a `role` marker, the Executor's question and draft (each redacted and capped at 8 KiB when present), and a recent-conversation digest capped by `advisorJevDigestMaxChars` (default 4,000 characters). The digest uses the Advisor context pipeline, so tool disclosure policies, tool-result caps, and optional secret redaction apply, and older entries are dropped first. The proactive turn gate sends the digest alone. No Git context, file attachments, images, Scout output, session summary, or project preferences are sent to classifiers.
87
+
88
+ Classifier questions use typed bool and three-choice stakes outputs. The skip decision remains local: both negligible-stakes probability and self-answerability must pass the existing thresholds (`advisorJevFilterSkipConfidence` 0.85 and `advisorJevFilterNoulMargin` 0.35 by default). Probabilities outside `[0,1]`, incomplete distributions, invalid labels, unavailable models, classifier errors, and timeouts fail open. Caller cancellation propagates instead of triggering an Advisor retry. Nothing about screening activity is sent to Herdr; turn-gate consultations remain ordinary Advisor egress.
89
+
90
+ The explicit Jev API Key is entered through a masked UI prompt and sent only as a request-scoped TypeSafe classifier API key. It is stored in the separate `pi-advisor-jev-classifier` secret namespace or a dedicated mode-0600 file fallback. The new-key path never reads legacy TypeSafe/OpenAI/custom-endpoint secret stores, legacy environment variables, Pi TypeSafe credentials, or plaintext keys in `advisor.json`. No key is copied into Pi provider auth, logged, placed in classifier state, sent to Herdr, or written to configuration. Missing isolated-key data fails open and never falls back to other credential sources.
91
+
92
+ Pi catalog input/cache rates are used for classifier input/cache cost; JEV output tokens are always free and normalized to zero output cost. Missing usage remains unavailable rather than fabricated as zero. Screening usage is carried in the `ask_advisor` tool result and included in Pi's generic tools cost bucket exactly once. Manual consultation and turn-gate classifier calls are accounted only in the local Jev ledger because Pi exposes no supported lifecycle usage-attribution API. Legacy provider selections, endpoints, and credentials remain untouched during compatibility; they are not used by the new classifier path. The Advisor request/response rendering and blocking behavior are unchanged.
93
+
94
+ ## Session summary and Herdr
95
+
96
+ The optional Session Advisor Summary defaults to off. When enabled, it is local and in-memory only, appears after a non-blocked settled run, and is never persisted.
97
+
98
+ It distinguishes regular Markdown advice from gate decisions and records the trigger, model, usage and cost when available, failures, budget, and execution effect.
99
+
100
+ [Herdr](https://github.com/herdrdev/herdr) integration is enabled by default. It reports Advisor activity and a bounded, redacted blocked-state summary through Herdr's metadata paths. Disable it with `advisorHerdrIntegration`. Previously reported state is still cleared when integration is disabled.
101
+
102
+ See [Configuration](configuration.md) for all settings and defaults.
@@ -3,6 +3,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import { registerCommands } from "../src/commands/registration.ts";
4
4
  import { getAdvisorSettings } from "../src/config/state.ts";
5
5
  import { herdrAdvisorActivity, HerdrAdvisorBlock } from "../src/herdr.ts";
6
+ import { I18N_NAMESPACE } from "../src/i18n.ts";
6
7
  import { AdvisorSessionState } from "../src/session-state.ts";
7
8
  import {
8
9
  consultAdvisor as consultAdvisorImplementation,
@@ -36,6 +37,28 @@ export const runAdvisorGate = (
36
37
  ...args: Parameters<typeof runAdvisorGateImplementation>
37
38
  ) => runAdvisorGateImplementation(...args);
38
39
 
40
+ interface I18nLoader {
41
+ registerLocalesFromDir: (
42
+ namespace: string,
43
+ packageUrl: string,
44
+ options?: { label?: string }
45
+ ) => void;
46
+ }
47
+
48
+ try {
49
+ // SAFETY: the loader subpath exports registerLocalesFromDir per the soft-peer contract; older versions resolve undefined and throw into this catch.
50
+ const loader = (await import("@juicesharp/rpiv-i18n/loader")) as I18nLoader;
51
+ // Both entry files (dist/index.js, extensions/index.ts) sit one level below
52
+ // the package root, so ../ anchors locale lookup at <root>/locales/.
53
+ loader.registerLocalesFromDir(
54
+ I18N_NAMESPACE,
55
+ new URL("../", import.meta.url).href,
56
+ { label: "pi-advisor" }
57
+ );
58
+ } catch {
59
+ // SDK absent — extension still loads with English-only UI.
60
+ }
61
+
39
62
  export default function registerPiAdvisor(pi: ExtensionAPI) {
40
63
  const sessionState = new AdvisorSessionState();
41
64
  const scoutStatus = new ScoutStatusManager();