wendkeep 0.66.5 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,34 @@ All notable changes to **wendkeep** are documented here. Format based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project follows
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.67.0] — 2026-08-01
8
+
9
+ ### Added
10
+
11
+ - **O harness da LLM pode selecionar uma rota Wend temporária por solicitação.**
12
+ `profile route <FLOW|GUIDE|GOVERN|ASSURE> --session <id> --reason <texto>` grava uma lease
13
+ auditável ligada ao prompt atual, sem alterar o perfil persistente do projeto ou da sessão.
14
+ `OFF` permanece exclusivamente humano e é rejeitado na seleção adaptativa. Contexto sem prompt
15
+ causal completo e coincidente no registry falha antes de mutar, e `profile status --session`
16
+ mostra perfil-base e estado da lease também na saída humana.
17
+ - **A lease expira causalmente sem interromper implementações longas.** Um Stop aceito a consome
18
+ por CAS; bloqueio/retry a preserva, e o próximo prompt restaura o perfil-base mesmo depois de
19
+ crash ou hook ausente. Skills e AGENTS gerados ensinam a matriz FLOW/GUIDE/GOVERN/ASSURE.
20
+
21
+ ### Fixed
22
+
23
+ - **Sessões Obsidian não renderizam envelopes internos do assistente como HTML.** A captura remove
24
+ metadata completa ou truncada de citação somente das respostas do assistente e escapa tags
25
+ XML-like nas linhas geradas, preservando relatos do usuário e autolinks HTTP(S). Reimport e
26
+ `SessionStop` convergem no mesmo normalizador idempotente, e o encerramento migra somente campos
27
+ gerados reconhecíveis de notas antigas sem reescrever prosa autoral.
28
+ - **README e guias bilíngues explicam as letras `P/R/E/V/C` e a duração das escolhas.** A
29
+ documentação distingue `profile use` persistente de `profile route` por solicitação e deixa
30
+ explícito que a classificação semântica pertence ao harness, não a heurísticas do runtime.
31
+ - **Sensores vermelhos deixam diagnóstico acionável sem persistir logs verdes.** O runner captura
32
+ stdout/stderr com limite, redige segredos e grava no máximo 2.000 caracteres apenas na entrada
33
+ vermelha de `evidencia.json`, em vez de descartar a causa da falha.
34
+
7
35
  ## [0.66.5] — 2026-08-01
8
36
 
9
37
  ### Fixed
package/README.en.md CHANGED
@@ -15,6 +15,10 @@
15
15
 
16
16
  **Persistent memory for AI coding agents, built on your Obsidian vault.** Every Claude Code **and Codex** session is captured turn by turn into local Markdown — `init` wires both (Codex asks you to approve its hooks once; `import` backfills past sessions either way) — with token/cost tracking and automatically extracted decisions, bugs, and learnings. That always-on plane is **Keep Core**. On top of it, **Wend Runtime** provides a native, zero-dependency lifecycle (spec → change → TDD → sensor-gated archive), selected through the `OFF`, `FLOW`, `GUIDE`, `GOVERN`, and `ASSURE` Operating Profiles. 100% local, open-core.
17
17
 
18
+ When projecting sessions, trailing internal metadata is removed only from assistant responses;
19
+ user reports remain intact. XML-like tags are written as escaped text so Obsidian Reading view
20
+ does not interpret them as HTML.
21
+
18
22
  The runtime is being separated into six physical boundaries — `cli`, `harness`, `vault`, `mcp`,
19
23
  `integrations`, and `pi` — without fragmenting installation. The private `cli`, `harness`,
20
24
  `vault`, `mcp`, and `integrations` workspaces now canonically own the executable runtime,
@@ -235,13 +239,82 @@ deliberate opt-in and runs that command's own validations:
235
239
  | `GOVERN` | P → R → E → V | Current a2 loop and compatible fallback. |
236
240
  | `ASSURE` | P → R → E → V → C | Governance with confirmation and handoff. |
237
241
 
242
+ A route is a sequence of work stages, not a list of command names:
243
+
244
+ - `P` = **Plan/Propose** — understand the request, bound the scope, and record the approach when a change is needed.
245
+ - `R` = **Review** — inspect the proposal/design before execution; this is the formal a2-loop review.
246
+ - `E` = **Execute** — edit the permitted code or artifacts.
247
+ - `V` = **Validate** — run tests, sensors, and checks and record evidence.
248
+ - `C` = **Confirm/hand off** — obtain explicit confirmation and complete the handoff.
249
+
250
+ Thus, `P → R → E → V` means “plan/propose, review, execute, and validate”. `FLOW` starts at the
251
+ execution/validation microcontract; `OFF` applies no automatic Wend route and returns process
252
+ ownership to the native LLM harness.
253
+
254
+ ### Who selects the profile, and for how long?
255
+
256
+ The LLM harness (Codex, Claude, or another agent) **classifies the current implementation** and can
257
+ record a temporary choice with `wendkeep profile route`. Wend Runtime does not interpret prompt
258
+ text or use diff size, heuristics, or environment variables: it validates the choice, applies the
259
+ route in hooks, and expires the lease when the request ends. With no recorded route, the configured
260
+ base profile remains effective.
261
+
262
+ Resolution follows this order:
263
+
264
+ 1. a valid lease for the current request in `SESSION_REGISTRY.json`;
265
+ 2. a persistent session override in that registry;
266
+ 3. `harness.profile` in the project's `.wendkeep.json`;
267
+ 4. `GOVERN` when no valid setting exists.
268
+
269
+ Without `--session`, `profile use` changes the **project default** for conversations/hooks that do
270
+ not have a session override. With `--session <id>`, it changes only that session and leaves the
271
+ project default untouched. Therefore, `profile use OFF` without `--session` is not an isolated
272
+ test: it writes the project binding and can be shared if `.wendkeep.json` is committed.
273
+
274
+ `profile route` is different: it requires `--session` and `--reason`, accepts only `FLOW`, `GUIDE`,
275
+ `GOVERN`, or `ASSURE`, does not rewrite the project/persistent override, and applies only to the
276
+ current causal prompt. An accepted `Stop` consumes the lease; if the process dies first, the next
277
+ prompt advances the sequence and makes the old lease ineffective. `OFF` is never selected
278
+ automatically.
279
+
280
+ ```bash
281
+ npx wendkeep profile status
282
+ npx wendkeep profile use GUIDE # project default
283
+ npx wendkeep profile use FLOW --session <id> # one session only
284
+ npx wendkeep profile route FLOW --session <id> --reason "local fix" # current request
285
+ npx wendkeep profile status --session <id> # session-effective profile
286
+ ```
287
+
288
+ In human `status --session` output, `base=<profile>/<source>` and `lease=<state>` accompany the
289
+ effective profile; `--json` exposes the same data as `base_profile`, `base_source`, and
290
+ `task_lease`. `profile route` only accepts a session after `UserPromptSubmit` has recorded a
291
+ positive causal turn and sequence that agree in the registry.
292
+
293
+ ### Which profile fits a simple request?
294
+
295
+ “Small” describes size, not risk. The harness uses this matrix to choose and record a temporary
296
+ route; semantic inference remains in the agent, not Wend Runtime:
297
+
298
+ | Situation | Suggested profile |
299
+ |---|---|
300
+ | Question, inspection, or diagnosis with no mutation | No profile transition |
301
+ | Local, reversible fix with an allowlist and no contract/spec change | `FLOW` (`E → V`) |
302
+ | Small behavior change that needs a change but not formal Wend Runtime review | `GUIDE` (`P → E → V`) |
303
+ | Normal, ambiguous, public-contract, security, dependency, CI/release, or policy change | `GOVERN` (`P → R → E → V`) |
304
+ | Work requiring explicit confirmation and handoff | `ASSURE` (`P → R → E → V → C`) |
305
+
306
+ If the harness does not record a lease, a small fix remains under the configured profile —
307
+ `GOVERN` by default. `OFF` does not mean “simple task”: it is a persistent human choice that hands
308
+ governance to the native harness. The LLM may temporarily elevate an `OFF` base to a Wend route,
309
+ but it can never select `OFF` on its own.
310
+
238
311
  A corrupt binding never selects `OFF`: with one unambiguous explicit or legacy Vault, Keep Core
239
312
  remains active under `GOVERN`, the error stays visible, and mutation guards fail closed. Additional
240
313
  roots that FLOW must protect can be declared as project-relative paths under
241
314
  `harness.flow.protectedRoots` in `.wendkeep.json`; any change below them requires promotion.
242
315
  Invalid local config, marker, or identity never silently falls back to a parent/global Vault.
243
316
 
244
- `wendkeep profile status/use` makes the choice observable; `wendkeep flow
317
+ `wendkeep profile status/use/route` makes the choice observable; `wendkeep flow
245
318
  start/finish/promote` handles local adjustments without manufacturing an ADR and fails closed on
246
319
  physical escapes, Git metadata/hidden flags, mutating sensors, protected surfaces, or incomplete
247
320
  session projection. Bounded no-follow discovery sees empty/ignored protected aliases; Vault writes
@@ -379,7 +452,7 @@ explore → propose → apply (TDD) → verify → archive
379
452
 
380
453
  - **Propose** — `wendkeep change new <slug>` scaffolds `08-Mudanças/<slug>/` (`proposta.md`, `design.md`, `tarefas.md`; `--simple` skips the design). It becomes the global *current* change. When the change declares `spec_impact: required`, you author the delta yourself at `specs/<capability>/spec.md` — there is no placeholder to delete. Multiple changes may remain open: `change list`/`status` and the hooks show every pending one, while commands without `--change` act on the current one alone. `change use <slug>` changes focus and `change continue <archived> <new>` creates an auditable continuation.
381
454
  - **Apply** — implement each `tarefas.md` task. Mark machine proof with one or more `[sensor:<id>]` tags on the same task: every distinct ID enters the gate once, in declaration order. Also mark satisfied requirements with one or more `[req:<ID>]` tags.
382
- - **Verify** — `wendkeep verify` runs the sensors your tasks declared (from `wendkeep.sensors.json` at the project root) and writes `evidencia.json`. A red `critical` fails the gate; a red `warning` is advisory. `verify --deep` builds a self-contained package with complete effective requirements (living contract + this change's delta), so the independent verifier never needs to reconstruct unarchived requirements from `07-Specs`. Every change needs a `verdict.json` to archive; `verify --deep` writes a trivial one automatically when the change declares no `[req:]`.
455
+ - **Verify** — `wendkeep verify` runs the sensors your tasks declared (from `wendkeep.sensors.json` at the project root) and writes `evidencia.json`. A red `critical` fails the gate; a red `warning` is advisory. Failures retain only a bounded, sanitized diagnostic; green output is not persisted. `verify --deep` builds a self-contained package with complete effective requirements (living contract + this change's delta), so the independent verifier never needs to reconstruct unarchived requirements from `07-Specs`. Every change needs a `verdict.json` to archive; `verify --deep` writes a trivial one automatically when the change declares no `[req:]`.
383
456
  - **Archive** — `wendkeep change archive <slug>` **gates** on the evidence (blocks unless every declared critical sensor is green), promotes each capability's spec delta (`ADDED`/`MODIFIED`/`REMOVED`) into the living `07-Specs/<capability>.md`, moves the change to `_arquivo/`, and mints an ADR in `04-Decisões/`.
384
457
 
385
458
  > The gate blocks unless the scaffold is filled, no task is open, evidence is fresh, and every declared requirement is covered. **`--force` waives exactly one of those — the open-task check — and is the human's call, never the agent's.** An unfilled scaffold, a red critical sensor, stale evidence, an orphan requirement or a missing verdict block regardless.
package/README.md CHANGED
@@ -15,6 +15,10 @@
15
15
 
16
16
  **Persistent memory for AI coding agents, built on your Obsidian vault.** Every Claude Code **and Codex** session is captured turn by turn into local Markdown — `init` wires both (Codex asks you to approve its hooks once; `import` backfills past sessions either way) — with token/cost tracking and automatically extracted decisions, bugs, and learnings. That always-on plane is **Keep Core**. On top of it, **Wend Runtime** provides a native, zero-dependency lifecycle (spec → change → TDD → sensor-gated archive), selected through the `OFF`, `FLOW`, `GUIDE`, `GOVERN`, and `ASSURE` Operating Profiles. 100% local, open-core.
17
17
 
18
+ When projecting sessions, trailing internal metadata is removed only from assistant responses;
19
+ user reports remain intact. XML-like tags are written as escaped text so Obsidian Reading view
20
+ does not interpret them as HTML.
21
+
18
22
  The runtime is being separated into six physical boundaries — `cli`, `harness`, `vault`, `mcp`,
19
23
  `integrations`, and `pi` — without fragmenting installation. The private `cli`, `harness`,
20
24
  `vault`, `mcp`, and `integrations` workspaces now canonically own the executable runtime,
@@ -235,13 +239,82 @@ deliberate opt-in and runs that command's own validations:
235
239
  | `GOVERN` | P → R → E → V | Current a2 loop and compatible fallback. |
236
240
  | `ASSURE` | P → R → E → V → C | Governance with confirmation and handoff. |
237
241
 
242
+ A route is a sequence of work stages, not a list of command names:
243
+
244
+ - `P` = **Plan/Propose** — understand the request, bound the scope, and record the approach when a change is needed.
245
+ - `R` = **Review** — inspect the proposal/design before execution; this is the formal a2-loop review.
246
+ - `E` = **Execute** — edit the permitted code or artifacts.
247
+ - `V` = **Validate** — run tests, sensors, and checks and record evidence.
248
+ - `C` = **Confirm/hand off** — obtain explicit confirmation and complete the handoff.
249
+
250
+ Thus, `P → R → E → V` means “plan/propose, review, execute, and validate”. `FLOW` starts at the
251
+ execution/validation microcontract; `OFF` applies no automatic Wend route and returns process
252
+ ownership to the native LLM harness.
253
+
254
+ ### Who selects the profile, and for how long?
255
+
256
+ The LLM harness (Codex, Claude, or another agent) **classifies the current implementation** and can
257
+ record a temporary choice with `wendkeep profile route`. Wend Runtime does not interpret prompt
258
+ text or use diff size, heuristics, or environment variables: it validates the choice, applies the
259
+ route in hooks, and expires the lease when the request ends. With no recorded route, the configured
260
+ base profile remains effective.
261
+
262
+ Resolution follows this order:
263
+
264
+ 1. a valid lease for the current request in `SESSION_REGISTRY.json`;
265
+ 2. a persistent session override in that registry;
266
+ 3. `harness.profile` in the project's `.wendkeep.json`;
267
+ 4. `GOVERN` when no valid setting exists.
268
+
269
+ Without `--session`, `profile use` changes the **project default** for conversations/hooks that do
270
+ not have a session override. With `--session <id>`, it changes only that session and leaves the
271
+ project default untouched. Therefore, `profile use OFF` without `--session` is not an isolated
272
+ test: it writes the project binding and can be shared if `.wendkeep.json` is committed.
273
+
274
+ `profile route` is different: it requires `--session` and `--reason`, accepts only `FLOW`, `GUIDE`,
275
+ `GOVERN`, or `ASSURE`, does not rewrite the project/persistent override, and applies only to the
276
+ current causal prompt. An accepted `Stop` consumes the lease; if the process dies first, the next
277
+ prompt advances the sequence and makes the old lease ineffective. `OFF` is never selected
278
+ automatically.
279
+
280
+ ```bash
281
+ npx wendkeep profile status
282
+ npx wendkeep profile use GUIDE # project default
283
+ npx wendkeep profile use FLOW --session <id> # one session only
284
+ npx wendkeep profile route FLOW --session <id> --reason "local fix" # current request
285
+ npx wendkeep profile status --session <id> # session-effective profile
286
+ ```
287
+
288
+ In human `status --session` output, `base=<profile>/<source>` and `lease=<state>` accompany the
289
+ effective profile; `--json` exposes the same data as `base_profile`, `base_source`, and
290
+ `task_lease`. `profile route` only accepts a session after `UserPromptSubmit` has recorded a
291
+ positive causal turn and sequence that agree in the registry.
292
+
293
+ ### Which profile fits a simple request?
294
+
295
+ “Small” describes size, not risk. The harness uses this matrix to choose and record a temporary
296
+ route; semantic inference remains in the agent, not Wend Runtime:
297
+
298
+ | Situation | Suggested profile |
299
+ |---|---|
300
+ | Question, inspection, or diagnosis with no mutation | No profile transition |
301
+ | Local, reversible fix with an allowlist and no contract/spec change | `FLOW` (`E → V`) |
302
+ | Small behavior change that needs a change but not formal Wend Runtime review | `GUIDE` (`P → E → V`) |
303
+ | Normal, ambiguous, public-contract, security, dependency, CI/release, or policy change | `GOVERN` (`P → R → E → V`) |
304
+ | Work requiring explicit confirmation and handoff | `ASSURE` (`P → R → E → V → C`) |
305
+
306
+ If the harness does not record a lease, a small fix remains under the configured profile —
307
+ `GOVERN` by default. `OFF` does not mean “simple task”: it is a persistent human choice that hands
308
+ governance to the native harness. The LLM may temporarily elevate an `OFF` base to a Wend route,
309
+ but it can never select `OFF` on its own.
310
+
238
311
  A corrupt binding never selects `OFF`: with one unambiguous explicit or legacy Vault, Keep Core
239
312
  remains active under `GOVERN`, the error stays visible, and mutation guards fail closed. Additional
240
313
  roots that FLOW must protect can be declared as project-relative paths under
241
314
  `harness.flow.protectedRoots` in `.wendkeep.json`; any change below them requires promotion.
242
315
  Invalid local config, marker, or identity never silently falls back to a parent/global Vault.
243
316
 
244
- `wendkeep profile status/use` makes the choice observable; `wendkeep flow
317
+ `wendkeep profile status/use/route` makes the choice observable; `wendkeep flow
245
318
  start/finish/promote` handles local adjustments without manufacturing an ADR and fails closed on
246
319
  physical escapes, Git metadata/hidden flags, mutating sensors, protected surfaces, or incomplete
247
320
  session projection. Bounded no-follow discovery sees empty/ignored protected aliases; Vault writes
@@ -379,7 +452,7 @@ explore → propose → apply (TDD) → verify → archive
379
452
 
380
453
  - **Propose** — `wendkeep change new <slug>` scaffolds `08-Mudanças/<slug>/` (`proposta.md`, `design.md`, `tarefas.md`; `--simple` skips the design). It becomes the global *current* change. When the change declares `spec_impact: required`, you author the delta yourself at `specs/<capability>/spec.md` — there is no placeholder to delete. Multiple changes may remain open: `change list`/`status` and the hooks show every pending one, while commands without `--change` act on the current one alone. `change use <slug>` changes focus and `change continue <archived> <new>` creates an auditable continuation.
381
454
  - **Apply** — implement each `tarefas.md` task. Mark machine proof with one or more `[sensor:<id>]` tags on the same task: every distinct ID enters the gate once, in declaration order. Also mark satisfied requirements with one or more `[req:<ID>]` tags.
382
- - **Verify** — `wendkeep verify` runs the sensors your tasks declared (from `wendkeep.sensors.json` at the project root) and writes `evidencia.json`. A red `critical` fails the gate; a red `warning` is advisory. `verify --deep` builds a self-contained package with complete effective requirements (living contract + this change's delta), so the independent verifier never needs to reconstruct unarchived requirements from `07-Specs`. Every change needs a `verdict.json` to archive; `verify --deep` writes a trivial one automatically when the change declares no `[req:]`.
455
+ - **Verify** — `wendkeep verify` runs the sensors your tasks declared (from `wendkeep.sensors.json` at the project root) and writes `evidencia.json`. A red `critical` fails the gate; a red `warning` is advisory. Failures retain only a bounded, sanitized diagnostic; green output is not persisted. `verify --deep` builds a self-contained package with complete effective requirements (living contract + this change's delta), so the independent verifier never needs to reconstruct unarchived requirements from `07-Specs`. Every change needs a `verdict.json` to archive; `verify --deep` writes a trivial one automatically when the change declares no `[req:]`.
383
456
  - **Archive** — `wendkeep change archive <slug>` **gates** on the evidence (blocks unless every declared critical sensor is green), promotes each capability's spec delta (`ADDED`/`MODIFIED`/`REMOVED`) into the living `07-Specs/<capability>.md`, moves the change to `_arquivo/`, and mints an ADR in `04-Decisões/`.
384
457
 
385
458
  > The gate blocks unless the scaffold is filled, no task is open, evidence is fresh, and every declared requirement is covered. **`--force` waives exactly one of those — the open-task check — and is the human's call, never the agent's.** An unfilled scaffold, a red critical sensor, stale evidence, an orphan requirement or a missing verdict block regardless.
@@ -14,9 +14,9 @@ opt-in and runs that command's own validations and gates.
14
14
 
15
15
  ## When to use
16
16
 
17
- Use `profile` to inspect or explicitly select an Operating Profile. Use `FLOW` for local,
18
- reversible `spec_impact:none` maintenance that fits an Execute Validate microcontract without a
19
- change.
17
+ Use `profile use` for a persistent human selection and `profile route` for the harness to record
18
+ the temporary route for the current implementation. Use `FLOW` for local, reversible
19
+ `spec_impact:none` maintenance that fits an Execute → Validate microcontract without a change.
20
20
 
21
21
  ## When not to use
22
22
 
@@ -28,7 +28,8 @@ change.
28
28
  ## Prerequisites
29
29
 
30
30
  - An initialized project whose `.wendkeep.json` is bound to the correct Vault.
31
- - For a session override, one unambiguous session in `SESSION_REGISTRY.json`.
31
+ - For an override or temporary route, one unambiguous session in `SESSION_REGISTRY.json`; `route`
32
+ also requires the current prompt to have a recorded causal frontier.
32
33
  - For FLOW, a Git repository, a path allowlist, a reason, and at least one existing sensor in
33
34
  `wendkeep.sensors.json`.
34
35
 
@@ -37,6 +38,7 @@ change.
37
38
  ```bash
38
39
  npx wendkeep profile status [--project <path>] [--vault <path>] [--session <id>] [--json]
39
40
  npx wendkeep profile use <profile> [--project <path>] [--vault <path>] [--session <id>] [--json]
41
+ npx wendkeep profile route <FLOW|GUIDE|GOVERN|ASSURE> --session <id> --reason <text> [--project <path>] [--vault <path>] [--json]
40
42
  npx wendkeep flow start <slug> --allow <path> [--allow <path>...] --sensor <id> [--sensor <id>...] --reason <text> [--session <id>]
41
43
  npx wendkeep flow status [<id>]
42
44
  npx wendkeep flow show <id> [--session <id>]
@@ -75,15 +77,42 @@ Harness. The workspaces remain private and are not published as independent npm
75
77
  | `GOVERN` | P → R → E → V | Current a2 loop and conservative fallback. |
76
78
  | `ASSURE` | P → R → E → V → C | Governance plus confirmation and handoff. |
77
79
 
78
- - Resolution is explicit session override → project `harness.profile` → `GOVERN`. Heuristics,
79
- diff size, prompt text, environment variables, or read failures never select `OFF`.
80
- - `profile status` prints the effective profile and source; `--json` emits structured output. When
81
- an explicit Vault preserves the selection despite a corrupt binding, output includes
80
+ ### Route legend
81
+
82
+ The letters are work stages, not individual commands:
83
+
84
+ - `P` = **Plan/Propose** — understand the request, bound the scope, and record the approach.
85
+ - `R` = **Review** — inspect the proposal/design before execution; this is the formal a2-loop review.
86
+ - `E` = **Execute** — edit the permitted paths and artifacts.
87
+ - `V` = **Validate** — run tests, sensors, and checks and record evidence.
88
+ - `C` = **Confirm/hand off** — obtain explicit confirmation and complete the handoff.
89
+
90
+ So, `P → R → E → V` means “plan/propose, review, execute, and validate”. `FLOW` starts at the
91
+ execution/validation microcontract; `OFF` imposes no automatic Wend route and returns process
92
+ ownership to the native LLM harness.
93
+
94
+ - The LLM harness semantically classifies the request and records `profile route`; Wend Runtime
95
+ does not classify text, diff size, heuristics, or environment variables. It validates and applies
96
+ the deterministic lease.
97
+ - For a local, reversible fix with no contract/spec change, choose `FLOW`. For a compact behavior
98
+ change that needs a change but no formal review, choose `GUIDE`. For uncertainty, risk, security,
99
+ public contracts, dependencies, CI/release, or policy, choose `GOVERN`. Use `ASSURE` when
100
+ confirmation and handoff are part of the contract.
101
+ - `OFF` can never be an adaptive route; only a human persists it explicitly through
102
+ `profile use OFF`. An `OFF` base may still receive a temporary elevation to a Wend route.
103
+
104
+ - Resolution is active prompt lease → persistent session override → project
105
+ `harness.profile` → `GOVERN`. Invalid/expired leases and read failures never select `OFF`.
106
+ - `profile status` prints the effective profile and source. With `--session`, human output adds
107
+ `base=<profile>/<source>` and `lease=<state>`; `--json` emits the same data structurally. When an
108
+ explicit Vault preserves the selection despite a corrupt binding, output includes
82
109
  `binding_error` and the diagnostic is also written to stderr.
83
110
  - `profile use` validates names and flags strictly; a duplicate/incomplete singleton option or a
84
111
  value beginning with `--` fails before I/O. Without `--session`, it atomically changes the
85
112
  project binding; with `--session`, it records override, source, and timestamp without changing
86
113
  session identity.
114
+ - `profile route` requires `--session` and `--reason`, accepts only the four adaptive profiles,
115
+ and records lease id, reason, turn/sequence, and timestamp without touching persistent profiles.
87
116
  - `.wendkeep.json` stays on `schemaVersion: 1`; the additive field is, for example,
88
117
  `"harness": { "profile": "GOVERN" }`. A legacy binding without it also resolves to `GOVERN`.
89
118
  - A corrupt binding never means `OFF`. When the payload or legacy integration identifies one
@@ -127,13 +156,39 @@ Harness. The workspaces remain private and are not published as independent npm
127
156
  - Exit `0` means a successful query or transition; exit `1` means a policy/red-sensor block; exit
128
157
  `2` means invalid profile, session, flow, or arguments, with no partial mutation.
129
158
 
159
+ ### Selection scope
160
+
161
+ Without `--session`, `profile use` writes `harness.profile` to `.wendkeep.json` and changes the
162
+ project default for conversations/hooks that have no session override. With `--session <id>`, it
163
+ writes an override only to that session's `SESSION_REGISTRY.json` and leaves the project default
164
+ unchanged. Therefore, `profile use OFF` without `--session` is not an isolated test; if
165
+ `.wendkeep.json` is committed, that choice is shared with other checkouts as well.
166
+
167
+ `profile route` creates a lease only for the current request. An accepted `Stop` consumes it by
168
+ CAS; if cleanup does not run, the next `UserPromptSubmit` advances the sequence and the lease is no
169
+ longer effective. A blocked Stop preserves it for a retry of the same request. There is no
170
+ wall-clock TTL that can interrupt long work. A session with no causal prompt recorded yet (missing
171
+ turn, zero sequence, or missing/mismatched causal map entry) is rejected before any mutation.
172
+ `status --session` includes the base profile and lease state in both human and `--json` output; in
173
+ JSON the fields are `base_profile`, `base_source`, and `task_lease.state` (`active`, `consumed`,
174
+ `expired`, `invalid`, or `absent`).
175
+
176
+ ```bash
177
+ npx wendkeep profile status # project default
178
+ npx wendkeep profile use GUIDE # change the project default
179
+ npx wendkeep profile use FLOW --session <id> # one session only
180
+ npx wendkeep profile route FLOW --session <id> --reason "local adjustment" # current request
181
+ npx wendkeep profile status --session <id> # session-effective profile
182
+ ```
183
+
130
184
  ## Examples
131
185
 
132
- Inspect the effective default and apply an override only to the current session:
186
+ Inspect the effective default and route only the current implementation:
133
187
 
134
188
  ```bash
135
189
  npx wendkeep profile status
136
- npx wendkeep profile use OFF --session 019abc-session-id --json
190
+ npx wendkeep profile route FLOW --session 019abc-session-id --reason "fix local typo" --json
191
+ npx wendkeep profile status --session 019abc-session-id --json
137
192
  ```
138
193
 
139
194
  Run FLOW maintenance while capturing the `flow_id` returned by `start`:
@@ -81,7 +81,13 @@ Each canonical session points to the matching provider, transcript, note file, a
81
81
  registry keeps one `SessionStart` epoch per activation plus the latest native turn; multiple
82
82
  `Stop` events may acknowledge turns in that epoch without closing it. Repeated imports of the
83
83
  same `session_id` deduplicate; human focus does not close or re-identify live hooks. Every
84
- automatic iteration remains valid Markdown even when a message must be truncated.
84
+ automatic iteration remains valid Markdown even when a message must be truncated. Complete or
85
+ truncated trailing internal metadata is removed only from assistant messages; a reproduction
86
+ written by the user remains in the transcript. In the note, XML-like tags are encoded as visible
87
+ text — including placeholders such as `<session>` — without changing `<https://...>` autolinks.
88
+ Reimport and `SessionStop` share the same idempotent normalizer; when an older note is finalized,
89
+ only recognized generated fields under `Iterações` and `Encerramento` are migrated, without rewriting
90
+ authored prose.
85
91
  Duplicate/stale hooks converge on the same frontier, and imports may refresh only observability
86
92
  without creating a new turn block.
87
93
 
@@ -73,15 +73,17 @@ npx wendkeep memory status --gate --vault .MyApp-vault
73
73
  ## Expected result
74
74
 
75
75
  `evidencia.json` contains sensor results and a seal binds proof to the current `tarefas.md` hash.
76
- Deep mode packages requirements, tasks, and evidence for read-only review; the verdict covers every
77
- `[req:]` before archive.
76
+ When a sensor is red, its entry receives only a local, sanitized diagnostic bounded to 2,000
77
+ characters; stdout/stderr from green sensors is not persisted. Deep mode packages requirements,
78
+ tasks, and evidence for read-only review; the verdict covers every `[req:]` before archive.
78
79
 
79
80
  ## Common errors and diagnosis
80
81
 
81
82
  - `no change`: this is exit 2 and a valid idle state; create/use a change or skip verify.
82
83
  - Zero/missing sensors: inspect every same-line tag and `sensors list`; multiple tags on one task
83
84
  are valid and all of them enter the gate.
84
- - Red gate: fix the cause and rerun; never choose `archive --force` on your own.
85
+ - Red gate: inspect the bounded `note` field on the `evidencia.json` entry, fix the cause, and
86
+ rerun; never choose `archive --force` on your own.
85
87
  - Missing/stale verdict: regenerate `--deep` and request a fresh independent pass.
86
88
  - Surviving mutants: strengthen the discriminating test; after three rounds, review manually.
87
89
 
@@ -14,9 +14,9 @@ deliberado e executa as validações e gates próprios daquele comando.
14
14
 
15
15
  ## Quando usar
16
16
 
17
- Use `profile` para consultar ou selecionar explicitamente um Perfil de Operação. Use `FLOW` para
18
- manutenção local, reversível e com `spec_impact:none` que caiba num microcontrato Executar
19
- Validar, sem change.
17
+ Use `profile use` para uma seleção humana persistente e `profile route` para o harness registrar a
18
+ rota temporária da implementação atual. Use `FLOW` para manutenção local, reversível e com
19
+ `spec_impact:none` que caiba num microcontrato Executar → Validar, sem change.
20
20
 
21
21
  ## Quando não usar
22
22
 
@@ -28,7 +28,8 @@ gates/policies do WendKeep; promova o trabalho para uma change.
28
28
  ## Pré-requisitos
29
29
 
30
30
  - Projeto inicializado, com `.wendkeep.json` vinculado ao Vault correto.
31
- - Para override de sessão, uma sessão inequívoca no `SESSION_REGISTRY.json`.
31
+ - Para override ou rota temporária, uma sessão inequívoca no `SESSION_REGISTRY.json`; `route`
32
+ também exige que o prompt atual já tenha fronteira causal registrada.
32
33
  - Para FLOW, repositório Git, allowlist de paths, motivo e ao menos um sensor existente em
33
34
  `wendkeep.sensors.json`.
34
35
 
@@ -37,6 +38,7 @@ gates/policies do WendKeep; promova o trabalho para uma change.
37
38
  ```bash
38
39
  npx wendkeep profile status [--project <path>] [--vault <path>] [--session <id>] [--json]
39
40
  npx wendkeep profile use <perfil> [--project <path>] [--vault <path>] [--session <id>] [--json]
41
+ npx wendkeep profile route <FLOW|GUIDE|GOVERN|ASSURE> --session <id> --reason <texto> [--project <path>] [--vault <path>] [--json]
40
42
  npx wendkeep flow start <slug> --allow <path> [--allow <path>...] --sensor <id> [--sensor <id>...] --reason <texto> [--session <id>]
41
43
  npx wendkeep flow status [<id>]
42
44
  npx wendkeep flow show <id> [--session <id>]
@@ -76,15 +78,42 @@ independentes.
76
78
  | `GOVERN` | P → R → E → V | Loop a2 atual e fallback conservador. |
77
79
  | `ASSURE` | P → R → E → V → C | Governança acrescida de confirmação e handoff. |
78
80
 
79
- - A resolução segue override explícito da sessão → `harness.profile` do projeto → `GOVERN`.
80
- Heurística, tamanho do diff, texto do prompt, variável de ambiente ou erro de leitura nunca
81
+ ### Legenda da rota
82
+
83
+ As letras são etapas do trabalho, não comandos individuais:
84
+
85
+ - `P` = **Planejar/Propor** — entender o pedido, delimitar o escopo e registrar a abordagem.
86
+ - `R` = **Revisar** — revisar proposta/design antes da execução; é a revisão formal do loop a2.
87
+ - `E` = **Executar** — editar os paths e artefatos permitidos.
88
+ - `V` = **Validar** — rodar testes, sensores e verificações e registrar evidência.
89
+ - `C` = **Confirmar/entregar** — obter confirmação explícita e fazer handoff.
90
+
91
+ Logo, `P → R → E → V` é “planejar/propor, revisar, executar e validar”. `FLOW` começa no
92
+ microcontrato de execução/validação; `OFF` não impõe rota Wend automática e entrega o processo ao
93
+ harness nativo da LLM.
94
+
95
+ - O harness da LLM classifica semanticamente o pedido e registra `profile route`; o Wend Runtime
96
+ não classifica texto, tamanho do diff, heurística ou variável de ambiente. Ele valida e aplica a
97
+ lease determinística.
98
+ - Para correção local, reversível e sem contrato/spec, escolha `FLOW`. Para mudança compacta de
99
+ comportamento que precisa de change sem revisão formal, escolha `GUIDE`. Em dúvida, risco,
100
+ segurança, contrato público, dependências, CI/release ou policy, escolha `GOVERN`. Use `ASSURE`
101
+ quando confirmação e handoff forem parte do contrato.
102
+ - `OFF` nunca pode ser uma rota adaptativa; somente uma pessoa o persiste explicitamente por
103
+ `profile use OFF`. Uma base `OFF` ainda pode receber uma elevação temporária para rota Wend.
104
+
105
+ - A resolução segue lease ativa do prompt → override persistente da sessão →
106
+ `harness.profile` do projeto → `GOVERN`. Lease inválida/expirada e erro de leitura nunca
81
107
  selecionam `OFF`.
82
- - `profile status` mostra perfil efetivo e origem; `--json` produz saída estruturada. Quando um
83
- Vault explícito preserva a escolha apesar de binding corrompido, a saída inclui `binding_error`
84
- e o diagnóstico também vai para stderr.
108
+ - `profile status` mostra perfil efetivo e origem. Com `--session`, a saída humana acrescenta
109
+ `base=<perfil>/<origem>` e `lease=<estado>`; `--json` produz os mesmos dados estruturados. Quando
110
+ um Vault explícito preserva a escolha apesar de binding corrompido, a saída inclui
111
+ `binding_error` e o diagnóstico também vai para stderr.
85
112
  - `profile use` valida nome e flags estritamente; opção singleton duplicada, incompleta ou com
86
113
  valor iniciado por `--` falha antes de I/O. Sem `--session`, altera atomicamente o binding do
87
114
  projeto; com `--session`, grava override, origem e timestamp sem trocar a identidade da sessão.
115
+ - `profile route` exige `--session` e `--reason`, aceita somente os quatro perfis adaptativos e
116
+ grava `lease_id`, motivo, turno/sequência e timestamp sem tocar no perfil persistente.
88
117
  - `.wendkeep.json` continua em `schemaVersion: 1`; o campo aditivo usa, por exemplo,
89
118
  `"harness": { "profile": "GOVERN" }`. Binding legado sem o campo também resolve `GOVERN`.
90
119
  - Binding corrompido nunca equivale a `OFF`. Quando o payload ou a integração legada identifica
@@ -126,13 +155,39 @@ independentes.
126
155
  - Exit `0` indica consulta ou transição concluída; exit `1` indica política/sensor vermelho; exit
127
156
  `2` indica perfil, sessão, flow ou argumentos inválidos, sem mutação parcial.
128
157
 
158
+ ### Escopo da escolha
159
+
160
+ Sem `--session`, `profile use` grava `harness.profile` no `.wendkeep.json` e muda o padrão do
161
+ projeto para as conversas/hooks que não tenham override de sessão. Com `--session <id>`, grava o
162
+ override somente no `SESSION_REGISTRY.json` daquela sessão e preserva o padrão do projeto. Por
163
+ isso, `profile use OFF` sem `--session` não é um teste isolado; se o `.wendkeep.json` for commitado,
164
+ essa escolha também será compartilhada com outros checkouts.
165
+
166
+ `profile route` cria uma lease apenas para a solicitação atual. Um `Stop` aceito a consome por
167
+ CAS; se o cleanup não rodar, o próximo `UserPromptSubmit` avança a sequência e a lease deixa de ser
168
+ efetiva. Stop bloqueado preserva a lease para o retry do mesmo pedido. Não há TTL de relógio que
169
+ interrompa trabalho longo. Sessão ainda sem prompt causal registrado (turno ausente, sequência
170
+ zero, mapa causal ausente ou divergente) é rejeitada antes de qualquer mutação. `status --session`
171
+ inclui o perfil-base e o estado da lease tanto na saída humana quanto em `--json`; neste, os campos
172
+ são `base_profile`, `base_source` e `task_lease.state` (`active`, `consumed`, `expired`, `invalid` ou
173
+ `absent`).
174
+
175
+ ```bash
176
+ npx wendkeep profile status # padrão do projeto
177
+ npx wendkeep profile use GUIDE # altera o padrão do projeto
178
+ npx wendkeep profile use FLOW --session <id> # altera somente uma sessão
179
+ npx wendkeep profile route FLOW --session <id> --reason "ajuste local" # pedido atual
180
+ npx wendkeep profile status --session <id> # consulta a sessão efetiva
181
+ ```
182
+
129
183
  ## Exemplos
130
184
 
131
- Consultar o padrão efetivo e aplicar override somente à sessão atual:
185
+ Consultar o padrão efetivo e rotear somente a implementação atual:
132
186
 
133
187
  ```bash
134
188
  npx wendkeep profile status
135
- npx wendkeep profile use OFF --session 019abc-session-id --json
189
+ npx wendkeep profile route FLOW --session 019abc-session-id --reason "corrige typo local" --json
190
+ npx wendkeep profile status --session 019abc-session-id --json
136
191
  ```
137
192
 
138
193
  Executar uma manutenção FLOW capturando o `flow_id` retornado por `start`:
@@ -80,7 +80,13 @@ Cada sessão canônica aponta para provider, transcript, arquivo de nota e custo
80
80
  O registry mantém um epoch de `SessionStart` por activation e o turno nativo mais recente; vários
81
81
  `Stop` podem confirmar turnos do mesmo epoch sem fechá-lo. Importações repetidas do mesmo
82
82
  `session_id` são deduplicadas; o foco humano não encerra nem altera a identidade dos hooks. Cada
83
- iteração automática permanece Markdown válido mesmo quando uma fala precisa ser truncada. Hooks
83
+ iteração automática permanece Markdown válido mesmo quando uma fala precisa ser truncada.
84
+ Metadados internos terminais completos ou truncados são removidos somente das mensagens do
85
+ assistente; uma reprodução escrita pelo usuário permanece no transcript. Na nota, tags XML-like
86
+ são codificadas como texto visível — inclusive placeholders como `<session>` — sem alterar
87
+ autolinks `<https://...>`. Reimport e `SessionStop` compartilham o mesmo normalizador idempotente;
88
+ ao finalizar uma nota antiga, somente campos gerados reconhecíveis em `Iterações` e
89
+ `Encerramento` são migrados, sem reescrever a prosa autoral. Hooks
84
90
  duplicados/stale convergem no mesmo frontier, e importações podem atualizar só a observabilidade
85
91
  sem criar um novo bloco de turno.
86
92
 
@@ -74,15 +74,18 @@ npx wendkeep memory status --gate --vault .MeuApp-vault
74
74
  ## Resultado esperado
75
75
 
76
76
  `evidencia.json` contém resultados dos sensores e um selo liga a prova ao hash atual de
77
- `tarefas.md`. No deep, o pacote contém requisitos, tarefas e evidência suficientes para revisão
78
- read-only; o verdict cobre cada `[req:]` antes do archive.
77
+ `tarefas.md`. Quando um sensor fica vermelho, sua entrada recebe somente um diagnóstico local
78
+ sanitizado e limitado a 2.000 caracteres; stdout/stderr de sensores verdes não é persistido. No
79
+ deep, o pacote contém requisitos, tarefas e evidência suficientes para revisão read-only; o
80
+ verdict cobre cada `[req:]` antes do archive.
79
81
 
80
82
  ## Erros comuns e diagnóstico
81
83
 
82
84
  - `no change`: isso é exit 2 e estado ocioso válido; crie/use uma change ou não rode verify.
83
85
  - Zero/sensores ausentes: confira todas as tags na mesma linha e `sensors list`; várias tags na
84
86
  mesma tarefa são válidas e todas entram no gate.
85
- - Gate vermelho: corrija a causa e repita; não use `archive --force` por conta própria.
87
+ - Gate vermelho: consulte o campo `note` limitado da entrada em `evidencia.json`, corrija a causa
88
+ e repita; não use `archive --force` por conta própria.
86
89
  - Verdict stale/ausente: regenere `--deep` e peça novo passe independente.
87
90
  - Mutantes sobreviventes: fortaleça o teste discriminante; após três rodadas, revise manualmente.
88
91
 
@@ -13,6 +13,7 @@ import {
13
13
  profileSentinelId,
14
14
  resolveHookOperatingProfile,
15
15
  } from './operating-profile-runtime.mjs';
16
+ import { consumeSessionTaskOperatingProfile } from './operating-profile-task-store.mjs';
16
17
 
17
18
  export function nagDecision(input, vaultBase, { profile = 'GOVERN' } = {}) {
18
19
  if (input && input.stop_hook_active) return null; // anti-loop: sempre primeiro
@@ -39,6 +40,13 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
39
40
  : runtime.bindingError
40
41
  ? { decision: 'block', reason: profileRuntimeError(runtime.bindingError) }
41
42
  : nagDecision(input, runtime.vaultBase, { profile: runtime.profile });
43
+ if (!decision && runtime.taskLease?.state === 'active') {
44
+ consumeSessionTaskOperatingProfile(
45
+ runtime.vaultBase,
46
+ runtime.identity?.canonicalConversationId || input?.session_id || input?.sessionId || '',
47
+ runtime.taskLease.lease_id,
48
+ );
49
+ }
42
50
  writeHookOutput(decision || {});
43
51
  } catch {
44
52
  writeHookOutput({});