wendkeep 0.76.8 → 0.77.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,36 @@ 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.77.0] — 2026-08-22
8
+
9
+ ### Added
10
+
11
+ - **Fechamento comprovado de worktrees.** `worktree finish <slug> --pr <ref>` valida no GitHub que o
12
+ PR foi merged, cruza branch e merge commit com a base local, executa preflight de checkout,
13
+ sessões, delivery, outbox e handoff, e fecha somente o active context da worktree alvo.
14
+ - **Cleanup auditável e retomável.** Reservas sob lock, remoção do ref local por CAS e receipts JSONL
15
+ append-only tornam o fechamento idempotente e retomável depois de crash; `doctor` diagnostica
16
+ estado interrompido, failed ou receipt inconsistente com recovery objetivo.
17
+ - **Comandos destrutivos explícitos.** `worktree cleanup --merged` e `worktree prune` são dry-run por
18
+ padrão e exigem `--apply`; `worktree remove --reason` preserva branch não merged. Exclusão remota
19
+ continua proibida sem `--delete-remote` e falha fechado quando a branch diverge.
20
+ - **Paridade operacional.** README e guia de worktrees PT-BR/EN documentam flags, blockers,
21
+ PowerShell/POSIX e recovery; a task local do VS Code oferece `WendKeep: Finish merged worktree`.
22
+
23
+ ## [0.76.9] — 2026-08-22
24
+
25
+ ### Fixed
26
+
27
+ - **Injeção de change causal.** `brain-inject` e `change-context` usam o active context da sessão
28
+ para marcar `ATUAL`, calcular o hash da sentinela e preservar o mesmo foco em todos os degraus do
29
+ budget; o backlog continua global sem promover a change irmã pelo pointer legado.
30
+ - **Store vazio fail-closed.** A presença de `active_contexts`, schema ou revision — inclusive
31
+ `active_contexts: {}` — impede fallback a `CURRENT_CHANGE.md` quando o contexto causal está ausente
32
+ ou ambíguo; compatibilidade legada permanece somente antes da inicialização contextual.
33
+ - **Criação contextual preservada.** Operações mutáveis como `delivery start` continuam recebendo a
34
+ identidade causal antes de existir um context record, enquanto hooks read-only exigem o registro
35
+ existente e nunca publicam foco de sibling.
36
+
7
37
  ## [0.76.8] — 2026-08-22
8
38
 
9
39
  ### Added
package/README.en.md CHANGED
@@ -116,6 +116,7 @@ npx wendkeep init
116
116
  1. Create the vault folder taxonomy and a templated `README.md` (default vault: `<project>/.<project-name>-vault`, e.g. `.MyApp-vault`; override with `--vault`).
117
117
  2. Write a provider-neutral **`.wendkeep.json`** binding at the project root and a matching `.brain/PROJECT.json` marker in the vault, then merge the session hooks into **`.claude/settings.json`**. The binding is provider-neutral by design: any agent resolves the same vault from its session `cwd`, with no machine-global environment variable. Older registrations already in `.claude/settings.json` are adopted automatically.
118
118
  3. Wire the Codex hooks in **`.codex/hooks.json`** — twelve compatible entries: `brain-inject` + `session-start` + `observer-publish` on `SessionStart`, `session-ensure` + `evidence-context` + `change-context` on `UserPromptSubmit`, `session-stop` + `observer-publish` + `change-nag` on `Stop`, `subagent-stop` + `observer-publish` on `SubagentStop`, and `change-guard` on `PreToolUse` for `Bash`, `exec_command`, `apply_patch`, and mutable MCP tools, always in the `npx wendkeep hook <name>` form. For the Observer, `SessionStart` only drains the outbox, `Stop` enqueues the changed session, and `SubagentStop` enqueues only the affected transcript; full scanning is explicit through `observer reconcile`. The guard accepts object, raw-string, and argv Codex payloads; before a mutation it compares the session with the project, Git root, remote, branch, and worktree, denying missing or divergent targets. A raw `git checkout/switch` branch transition is denied before it can strand the session; use `wendkeep context switch <branch> [--create]`, which moves Git and the causal scope together in the same worktree with an audited revision and rollback. If a divergence is already quarantined, `context status --session <id>` inventories sanitized `reserved`/`observed` candidates; `context recover --session <id> --select <reserved|observed> --revision <n> --reason <text>` requires an explicit choice, CAS, and current-checkout proof, failing closed before clearing the conflict if revalidation changes. `doctor` diagnoses orphaned active contexts, removed worktrees, and expired `request-stop` leases without writing; `context repair --key <key> --revision <n> --reason <text> --session <id>` revalidates under lock, closes only the ownerless/removed context or expires only its lease, while preserving the record and all historical memory. The change lifecycle uses `active_contexts`, identified by `repository_id` + `worktree_id` + `work_session_id`; two matching sessions fail with ambiguity instead of selecting silently, `CURRENT_CHANGE.md` is only a derived projection for one unambiguous context, and migration never invents a worktree or session identity. The other four stay out because Codex offers no equivalent payload, tool, or event: `change-warn` (no reliable `tool_input.file_path`), `plan-capture` (no `ExitPlanMode`), `decision-capture` (`AskUserQuestion` is Claude-only), and `task-log` (`TaskCompleted` is not in Codex's event enum). Codex scope blocks use `permissionDecision: "deny"`; `ask` is never emitted in `PreToolUse`. The merge remains non-destructive, preserves third-party hooks, and migrates legacy `timeout` to `timeoutSec`. **Codex enumerates every hook as untrusted and runs none until you approve the “Hooks need review” prompt at startup — `init` cannot pre-approve them**.
119
+ Once `active_contexts` is initialized, `brain-inject` and `change-context` mark only the causal context's change as current; the backlog remains global, and an empty or ambiguous store never revives `CURRENT_CHANGE.md`.
119
120
  4. Add the **`wendkeep-vault`** MCP server to `.mcp.json` so the agent can read/write the vault. Skip with `--no-mcp` — e.g. when the agent already has a vault MCP. (`--no-mcp` skips *only wendkeep's own* MCP; companion MCPs still follow `--companions`.)
120
121
  5. Offer to pin **companion** plugins/MCP (multi-choice; **none** pre-checked — wendkeep is a neutral harness and presumes no third-party plugin). Each is wired the most agent-agnostic way it supports:
121
122
  - **`context-mode`** — context optimizer + FTS5 memory, wired as a Claude Code plugin. It ships its own MCP server, so wendkeep deliberately adds no `.mcp.json` entry (registering both cold-started two servers at once). On non-Claude agents, add the MCP by hand: `npx -y context-mode`.
@@ -146,7 +147,7 @@ npx wendkeep init --no-companions --no-mcp --yes # zero companions,
146
147
  | `--no-companions` | Pin no companions. |
147
148
  | `--no-mcp` | Skip **wendkeep's own** vault MCP (`wendkeep-vault`). Companion MCPs still follow `--companions`. |
148
149
  | `--no-colors` | Skip the Obsidian color system (`.obsidian` snippet + graph groups). |
149
- | `--vscode-worktree-tasks` | Create a local, Git-excluded `.vscode/tasks.json` for creating/listing/opening worktrees; never overwrites an existing file. Also accepted by `sync`. |
150
+ | `--vscode-worktree-tasks` | Create a local, Git-excluded `.vscode/tasks.json` for creating/listing/opening/finishing worktrees; never overwrites an existing file. Also accepted by `sync`. |
150
151
  | `--yes`, `-y` | Non-interactive; accept defaults (skips the language / vault / companion prompts). |
151
152
  | `--force` | Overwrite existing wendkeep config blocks. |
152
153
 
@@ -238,7 +239,7 @@ The README is the map; the guides provide syntax, options, exit codes, examples,
238
239
  | Group | Use it for | Detailed guide |
239
240
  |---|---|---|
240
241
  | **Installation and updates** | `init`, `sync`, companions, and the first project↔vault binding | [Installation and first use](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/getting-started.md) |
241
- | **Managed worktrees** | `worktree create/list/status/open`, Vault binding, and recovery | [Managed worktrees](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/worktrees.md) |
242
+ | **Managed worktrees** | `worktree create/list/status/open/finish/cleanup/remove/prune`, merge proof, preflight, and receipts | [Managed worktrees](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/worktrees.md) |
242
243
  | **Active context** | `active_contexts` by `repository_id`/`worktree_id`/`work_session_id`, causal transition, quarantine, and explicit recovery | [Active context](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/context.md) |
243
244
  | **Operating profiles** | `profile`, `flow`, always-on Keep Core, and Wend Runtime governance | [Operating profiles](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/operating-profiles.md) |
244
245
  | **Changes and verification** | `change`, specs, sensors, TDD, evidence, and archive | [Changes and verification](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/changes-and-verification.md) |
@@ -582,7 +583,7 @@ agent session ──hooks──▶ wendkeep ──▶ Markdown in vault ──
582
583
  (Claude/Codex) (Node) (02-Sessões/…) (CORE+SHARED, ledger, backlinks)
583
584
  ```
584
585
 
585
- The agent's settings.json points each hook at `npx wendkeep hook …`; **in Claude Code** the change-lifecycle hooks instead run the installed script directly (`node` on `${CLAUDE_PROJECT_DIR}/node_modules/wendkeep/hooks/<name>.mjs`) when the package is present locally, skipping an npx resolve on every event. `.codex/hooks.json` mirrors the same groups with PascalCase event keys, but always uses the `npx` form (`${CLAUDE_PROJECT_DIR}` does not exist in Codex) and spells its timeout `timeoutSec` — a plain `timeout` is neither a field nor an error there, it silently falls through to a 600s default, so `init` migrates that legacy key in place. On `Stop`, wendkeep parses the session transcript, appends the turn, updates token/cost data, emits derived notes, and publishes the sanitized handoff to the memory outbox. On `SessionStart` — startup, `/clear`, and `/compact` — `brain-inject` injects CORE + SHARED, every open change with its pending tasks, the global current-change marker, project lessons, and a `<wk_process>` router. Claude, Codex, or another agent can therefore resume work started elsewhere without hiding the rest of the backlog.
586
+ The agent's settings.json points each hook at `npx wendkeep hook …`; **in Claude Code** the change-lifecycle hooks instead run the installed script directly (`node` on `${CLAUDE_PROJECT_DIR}/node_modules/wendkeep/hooks/<name>.mjs`) when the package is present locally, skipping an npx resolve on every event. `.codex/hooks.json` mirrors the same groups with PascalCase event keys, but always uses the `npx` form (`${CLAUDE_PROJECT_DIR}` does not exist in Codex) and spells its timeout `timeoutSec` — a plain `timeout` is neither a field nor an error there, it silently falls through to a 600s default, so `init` migrates that legacy key in place. On `Stop`, wendkeep parses the session transcript, appends the turn, updates token/cost data, emits derived notes, and publishes the sanitized handoff to the memory outbox. On `SessionStart` — startup, `/clear`, and `/compact` — `brain-inject` injects CORE + SHARED, every open change with its pending tasks, the causal current-change marker, project lessons, and a `<wk_process>` router. The inventory remains global, but `CURRENT` and the sentinel hash come from the session's active context; `active_contexts: {}` fails closed instead of reviving `CURRENT_CHANGE.md`. Claude, Codex, or another agent can therefore resume work started elsewhere without hiding the rest of the backlog.
586
587
 
587
588
  The archive **gate** blocks unless: the change scaffold is filled (G0), no task is open (G1), every declared critical sensor is green (with fresh evidence), and a `verdict.json` is present and current. `--force` waives G1 only — G0 is inescapable by design (a placeholder change forced through once minted a fake ADR), and no flag turns a red sensor or a missing verdict green. The agent is instructed never to use it on its own.
588
589
 
package/README.md CHANGED
@@ -116,6 +116,7 @@ npx wendkeep init
116
116
  1. Create the vault folder taxonomy and a templated `README.md` (default vault: `<project>/.<project-name>-vault`, e.g. `.MyApp-vault`; override with `--vault`).
117
117
  2. Write a provider-neutral **`.wendkeep.json`** binding at the project root and a matching `.brain/PROJECT.json` marker in the vault, then merge the session hooks into **`.claude/settings.json`**. The binding is provider-neutral by design: any agent resolves the same vault from its session `cwd`, with no machine-global environment variable. Older registrations already in `.claude/settings.json` are adopted automatically.
118
118
  3. Wire the Codex hooks in **`.codex/hooks.json`** — twelve compatible entries: `brain-inject` + `session-start` + `observer-publish` on `SessionStart`, `session-ensure` + `evidence-context` + `change-context` on `UserPromptSubmit`, `session-stop` + `observer-publish` + `change-nag` on `Stop`, `subagent-stop` + `observer-publish` on `SubagentStop`, and `change-guard` on `PreToolUse` for `Bash`, `exec_command`, `apply_patch`, and mutable MCP tools, always in the `npx wendkeep hook <name>` form. For the Observer, `SessionStart` only drains the outbox, `Stop` enqueues the changed session, and `SubagentStop` enqueues only the affected transcript; full scanning is explicit through `observer reconcile`. The guard accepts object, raw-string, and argv Codex payloads; before a mutation it compares the session with the project, Git root, remote, branch, and worktree, denying missing or divergent targets. A raw `git checkout/switch` branch transition is denied before it can strand the session; use `wendkeep context switch <branch> [--create]`, which moves Git and the causal scope together in the same worktree with an audited revision and rollback. If a divergence is already quarantined, `context status --session <id>` inventories sanitized `reserved`/`observed` candidates; `context recover --session <id> --select <reserved|observed> --revision <n> --reason <text>` requires an explicit choice, CAS, and current-checkout proof, failing closed before clearing the conflict if revalidation changes. `doctor` diagnoses orphaned active contexts, removed worktrees, and expired `request-stop` leases without writing; `context repair --key <key> --revision <n> --reason <text> --session <id>` revalidates under lock, closes only the ownerless/removed context or expires only its lease, while preserving the record and all historical memory. The change lifecycle uses `active_contexts`, identified by `repository_id` + `worktree_id` + `work_session_id`; two matching sessions fail with ambiguity instead of selecting silently, `CURRENT_CHANGE.md` is only a derived projection for one unambiguous context, and migration never invents a worktree or session identity. The other four stay out because Codex offers no equivalent payload, tool, or event: `change-warn` (no reliable `tool_input.file_path`), `plan-capture` (no `ExitPlanMode`), `decision-capture` (`AskUserQuestion` is Claude-only), and `task-log` (`TaskCompleted` is not in Codex's event enum). Codex scope blocks use `permissionDecision: "deny"`; `ask` is never emitted in `PreToolUse`. The merge remains non-destructive, preserves third-party hooks, and migrates legacy `timeout` to `timeoutSec`. **Codex enumerates every hook as untrusted and runs none until you approve the “Hooks need review” prompt at startup — `init` cannot pre-approve them**.
119
+ Once `active_contexts` is initialized, `brain-inject` and `change-context` mark only the causal context's change as current; the backlog remains global, and an empty or ambiguous store never revives `CURRENT_CHANGE.md`.
119
120
  4. Add the **`wendkeep-vault`** MCP server to `.mcp.json` so the agent can read/write the vault. Skip with `--no-mcp` — e.g. when the agent already has a vault MCP. (`--no-mcp` skips *only wendkeep's own* MCP; companion MCPs still follow `--companions`.)
120
121
  5. Offer to pin **companion** plugins/MCP (multi-choice; **none** pre-checked — wendkeep is a neutral harness and presumes no third-party plugin). Each is wired the most agent-agnostic way it supports:
121
122
  - **`context-mode`** — context optimizer + FTS5 memory, wired as a Claude Code plugin. It ships its own MCP server, so wendkeep deliberately adds no `.mcp.json` entry (registering both cold-started two servers at once). On non-Claude agents, add the MCP by hand: `npx -y context-mode`.
@@ -146,7 +147,7 @@ npx wendkeep init --no-companions --no-mcp --yes # zero companions,
146
147
  | `--no-companions` | Pin no companions. |
147
148
  | `--no-mcp` | Skip **wendkeep's own** vault MCP (`wendkeep-vault`). Companion MCPs still follow `--companions`. |
148
149
  | `--no-colors` | Skip the Obsidian color system (`.obsidian` snippet + graph groups). |
149
- | `--vscode-worktree-tasks` | Create a local, Git-excluded `.vscode/tasks.json` for creating/listing/opening worktrees; never overwrites an existing file. Also accepted by `sync`. |
150
+ | `--vscode-worktree-tasks` | Create a local, Git-excluded `.vscode/tasks.json` for creating/listing/opening/finishing worktrees; never overwrites an existing file. Also accepted by `sync`. |
150
151
  | `--yes`, `-y` | Non-interactive; accept defaults (skips the language / vault / companion prompts). |
151
152
  | `--force` | Overwrite existing wendkeep config blocks. |
152
153
 
@@ -238,7 +239,7 @@ The README is the map; the guides provide syntax, options, exit codes, examples,
238
239
  | Group | Use it for | Detailed guide |
239
240
  |---|---|---|
240
241
  | **Installation and updates** | `init`, `sync`, companions, and the first project↔vault binding | [Installation and first use](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/getting-started.md) |
241
- | **Managed worktrees** | `worktree create/list/status/open`, Vault binding, and recovery | [Managed worktrees](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/worktrees.md) |
242
+ | **Managed worktrees** | `worktree create/list/status/open/finish/cleanup/remove/prune`, merge proof, preflight, and receipts | [Managed worktrees](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/worktrees.md) |
242
243
  | **Active context** | `active_contexts` by `repository_id`/`worktree_id`/`work_session_id`, causal transition, quarantine, and explicit recovery | [Active context](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/context.md) |
243
244
  | **Operating profiles** | `profile`, `flow`, always-on Keep Core, and Wend Runtime governance | [Operating profiles](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/operating-profiles.md) |
244
245
  | **Changes and verification** | `change`, specs, sensors, TDD, evidence, and archive | [Changes and verification](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/changes-and-verification.md) |
@@ -582,7 +583,7 @@ agent session ──hooks──▶ wendkeep ──▶ Markdown in vault ──
582
583
  (Claude/Codex) (Node) (02-Sessões/…) (CORE+SHARED, ledger, backlinks)
583
584
  ```
584
585
 
585
- The agent's settings.json points each hook at `npx wendkeep hook …`; **in Claude Code** the change-lifecycle hooks instead run the installed script directly (`node` on `${CLAUDE_PROJECT_DIR}/node_modules/wendkeep/hooks/<name>.mjs`) when the package is present locally, skipping an npx resolve on every event. `.codex/hooks.json` mirrors the same groups with PascalCase event keys, but always uses the `npx` form (`${CLAUDE_PROJECT_DIR}` does not exist in Codex) and spells its timeout `timeoutSec` — a plain `timeout` is neither a field nor an error there, it silently falls through to a 600s default, so `init` migrates that legacy key in place. On `Stop`, wendkeep parses the session transcript, appends the turn, updates token/cost data, emits derived notes, and publishes the sanitized handoff to the memory outbox. On `SessionStart` — startup, `/clear`, and `/compact` — `brain-inject` injects CORE + SHARED, every open change with its pending tasks, the global current-change marker, project lessons, and a `<wk_process>` router. Claude, Codex, or another agent can therefore resume work started elsewhere without hiding the rest of the backlog.
586
+ The agent's settings.json points each hook at `npx wendkeep hook …`; **in Claude Code** the change-lifecycle hooks instead run the installed script directly (`node` on `${CLAUDE_PROJECT_DIR}/node_modules/wendkeep/hooks/<name>.mjs`) when the package is present locally, skipping an npx resolve on every event. `.codex/hooks.json` mirrors the same groups with PascalCase event keys, but always uses the `npx` form (`${CLAUDE_PROJECT_DIR}` does not exist in Codex) and spells its timeout `timeoutSec` — a plain `timeout` is neither a field nor an error there, it silently falls through to a 600s default, so `init` migrates that legacy key in place. On `Stop`, wendkeep parses the session transcript, appends the turn, updates token/cost data, emits derived notes, and publishes the sanitized handoff to the memory outbox. On `SessionStart` — startup, `/clear`, and `/compact` — `brain-inject` injects CORE + SHARED, every open change with its pending tasks, the causal current-change marker, project lessons, and a `<wk_process>` router. The inventory remains global, but `CURRENT` and the sentinel hash come from the session's active context; `active_contexts: {}` fails closed instead of reviving `CURRENT_CHANGE.md`. Claude, Codex, or another agent can therefore resume work started elsewhere without hiding the rest of the backlog.
586
587
 
587
588
  The archive **gate** blocks unless: the change scaffold is filled (G0), no task is open (G1), every declared critical sensor is green (with fresh evidence), and a `verdict.json` is present and current. `--force` waives G1 only — G0 is inescapable by design (a placeholder change forced through once minted a fake ADR), and no flag turns a red sensor or a missing verdict green. The agent is instructed never to use it on its own.
588
589
 
@@ -117,6 +117,14 @@ unambiguous active context. With zero or multiple contexts it stays empty. Migra
117
117
  and never invents a worktree or session identity. The legacy pointer becomes a context only
118
118
  when one active session, a complete scope, and worktree metadata prove one identity.
119
119
 
120
+ The `brain-inject` (`SessionStart`) and `change-context` (`UserPromptSubmit`) hooks resolve the same
121
+ causal identity before marking a change as `CURRENT` or computing the sentinel hash. The backlog
122
+ remains global and lists every other change as `OPEN`, but a divergent `CURRENT_CHANGE.md` never
123
+ turns a sibling change into the session focus. The presence of `active_contexts`, its schema, or its
124
+ revision — including `active_contexts: {}` — disables legacy fallback: a missing or ambiguous
125
+ context fails closed without reviving the pointer. Fallback exists only before contextual-store
126
+ initialization.
127
+
120
128
  ## Common errors and diagnosis
121
129
 
122
130
  - `WENDKEEP_CONTEXT_AMBIGUOUS`: pass `--session <id>`; no candidate is selected silently.
@@ -4,23 +4,24 @@
4
4
 
5
5
  ## Purpose
6
6
 
7
- Create isolated linked worktrees that remain bound to the same project and canonical Vault,
8
- without copying private state into versioned files.
7
+ Create and finish isolated linked worktrees that remain bound to the same project and canonical
8
+ Vault, without copying private state into versioned files or discarding local work.
9
9
 
10
10
  ## When to use
11
11
 
12
- Use it to start isolated implementation work, list managed checkouts, diagnose a partial create,
13
- or open an already-ready worktree in VS Code.
12
+ Use it to start isolated implementation work, list managed checkouts, diagnose a partial operation,
13
+ open a worktree in VS Code, or clean it up after a provably merged PR.
14
14
 
15
15
  ## When not to use
16
16
 
17
- Do not use it to remove, merge, or self-merge worktrees. Those operations remain outside this
18
- capability.
17
+ Do not use it to merge the PR, discard a dirty/untracked checkout, or delete a remote branch without
18
+ explicit authorization. `finish` consumes an existing merge; it does not self-merge.
19
19
 
20
20
  ## Prerequisites
21
21
 
22
22
  - A Git repository whose project is already bound to its Vault through `.wendkeep.json`.
23
- - Git on `PATH`; opening also requires the VS Code `code` command.
23
+ - Git on `PATH`; `finish` also requires authenticated `gh` access to query GitHub.
24
+ - Opening also requires the VS Code `code` command.
24
25
 
25
26
  ## Syntax
26
27
 
@@ -29,48 +30,88 @@ npx --no-install wendkeep worktree create <slug> [--base <ref>] [--branch <name>
29
30
  npx --no-install wendkeep worktree list [--json]
30
31
  npx --no-install wendkeep worktree status [<slug>] [--json]
31
32
  npx --no-install wendkeep worktree open <slug> [--editor vscode] [--json]
33
+ npx --no-install wendkeep worktree finish <slug> [--pr <number|url>] [--delete-remote] [--open-main] [--json]
34
+ npx --no-install wendkeep worktree cleanup --merged [--dry-run|--apply] [--json]
35
+ npx --no-install wendkeep worktree remove <slug> --reason <text> [--json]
36
+ npx --no-install wendkeep worktree prune [--dry-run|--apply] [--json]
32
37
  ```
33
38
 
34
39
  All commands accept `--project <root>`. By default, create uses `.worktrees/<slug>`, the detected
35
- base, and branch `wk/<slug>`. When configured, `worktrees.root` must be a
36
- non-empty relative path. Git validates slugs and branches; paths escaping the root or crossing a
37
- symlink/junction are rejected before mutation.
40
+ base, and branch `wk/<slug>`. When configured, `worktrees.root` must be a non-empty relative path.
41
+ Git validates slugs and branches; paths escaping the root or crossing a symlink/junction are rejected
42
+ before mutation.
43
+
44
+ ## Safe finish
45
+
46
+ When `origin` exists, `finish` runs `git fetch --prune`, queries the PR through the GitHub adapter,
47
+ and requires `MERGED`, a matching branch, and a merge commit reachable from the local base. The
48
+ number/URL is associated with the registry. Before removal, preflight fails closed on dirty or
49
+ untracked files, an active session, active delivery, memory outbox, or pending handoff.
50
+
51
+ After reserving under lock, the command removes the linked worktree, closes only its active
52
+ contexts, prunes, deletes the local ref with CAS, and appends a JSONL receipt in the Git common-dir.
53
+ This accepts merge commits, squash, and rebase without `git branch -D`. Re-running the same proof is
54
+ idempotent; when the directory vanished between steps, the interrupted reservation resumes.
55
+ `doctor` reports interrupted/failed cleanup with an objective recovery command.
56
+
57
+ `--delete-remote` is the only authorization to delete the remote branch. The branch must remain at
58
+ the proven head; divergence or an unavailable network blocks the operation. An already-absent branch
59
+ is idempotent success. `--open-main` opens the main worktree only after completion.
60
+
61
+ ## Cleanup, remove, and prune
62
+
63
+ `cleanup --merged` and `prune` are dry-run by default. `--dry-run` makes that intent explicit; only
64
+ `--apply` permits mutation. Plans are slug-sorted and do not change Git, registry, contexts, or
65
+ receipts. `cleanup --merged` acts only on entries with an associated PR whose merge is revalidated.
66
+ `remove --reason` is the auditable escape hatch for explicit abandonment: it waives merge proof but
67
+ keeps every preflight and preserves both local and remote branches.
38
68
 
39
69
  ## Options and exit codes
40
70
 
41
71
  The registry lives in the Git common-dir at `wendkeep/worktrees-v1.json`, protected by a
42
- multi-process lock. It stores repository/worktree identity and the canonical binding;
43
- `.wendkeep.json` stays unchanged. `.worktrees/` is added to both the versioned ignore and the
44
- repository-private exclude. JSON `list`/`status` output exposes neither Vault paths nor contents.
45
- For each worktree, human output shows its slug, identity, checkout path, branch, HEAD, state, and
46
- binding health.
72
+ multi-process lock. It stores repository/worktree identity, canonical binding, PR, and transient
73
+ cleanup state; `.wendkeep.json` stays unchanged. Receipts live at
74
+ `wendkeep/worktree-cleanup-receipts-v1.jsonl`. `.worktrees/` is added to both the versioned ignore
75
+ and the repository-private exclude. JSON `list`/`status` output exposes neither Vault paths nor
76
+ contents.
47
77
 
48
78
  `create` is idempotent when slug, path, and branch already match. Collisions fail closed. Failures
49
- after reservation remain `failed`; run `worktree status <slug>` and follow the `recovery` field.
50
- `doctor` also reports this debt under `[worktrees]` without repairing it.
79
+ after reservation remain `failed`; run `worktree status <slug>` and follow `recovery`. `doctor`
80
+ also reports create or cleanup debt under `[worktrees]` without repairing it.
51
81
 
52
- ## VS Code and exit codes
82
+ ## VS Code
53
83
 
54
- `--open vscode` and `worktree open` validate `code --version`, then open a new window with
55
- `code -n`. Use `init --vscode-worktree-tasks` or `sync --vscode-worktree-tasks` to create local
56
- tasks; an existing or tracked `.vscode/tasks.json`, even when deleted in the checkout, is never
57
- overwritten.
84
+ `--open vscode` and `worktree open` validate `code --version`, then open a new window with `code -n`.
85
+ Use `init --vscode-worktree-tasks` or `sync --vscode-worktree-tasks` to create local tasks, including
86
+ **WendKeep: Finish merged worktree**; an existing or tracked `.vscode/tasks.json`, even when deleted
87
+ in the checkout, is never overwritten.
58
88
 
59
- Exit `0` means success. Usage, binding, safety, Git, or editor failures return `2` with a stable
60
- `WENDKEEP_WORKTREE_*` code. The command never removes or merges a worktree.
89
+ Exit `0` means success. Usage, binding, safety, proof, Git, or editor failures return `2` with a
90
+ stable `WENDKEEP_WORKTREE_*` code. No command merges or uses force to discard a checkout.
61
91
 
62
92
  ## Examples
63
93
 
64
- ```bash
94
+ PowerShell:
95
+
96
+ ```powershell
65
97
  npx --no-install wendkeep worktree create auth --open vscode
66
- npx --no-install wendkeep worktree status auth --json
67
- npx --no-install wendkeep worktree list
98
+ npx --no-install wendkeep worktree finish auth --pr 72 --open-main
99
+ npx --no-install wendkeep worktree cleanup --merged --dry-run --json
100
+ ```
101
+
102
+ POSIX:
103
+
104
+ ```bash
105
+ npx --no-install wendkeep worktree cleanup --merged --apply
106
+ npx --no-install wendkeep worktree remove spike --reason "PR cancelled"
107
+ npx --no-install wendkeep worktree prune --dry-run
68
108
  ```
69
109
 
70
110
  ## Expected result
71
111
 
72
- `create auth` produces `.worktrees/auth` on branch `wk/auth`; the main and linked worktrees resolve
73
- the same `projectId` and Vault, while the main checkout remains clean.
112
+ `create auth` produces `.worktrees/auth` on branch `wk/auth`. After a proven merge, `finish` removes
113
+ the checkout and local ref, closes only its active context, and preserves the Vault, sessions,
114
+ evidence, and receipt.
74
115
 
75
116
  ## Common errors and diagnosis
76
117
 
@@ -79,13 +120,20 @@ the same `projectId` and Vault, while the main checkout remains clean.
79
120
  - `WENDKEEP_WORKTREE_PATH_OUTSIDE_ROOT` or `WENDKEEP_WORKTREE_PATH_SYMLINK_ESCAPE`: use a relative
80
121
  root contained in the main worktree, without an intermediate symlink/junction.
81
122
  - `WENDKEEP_WORKTREE_COLLISION`: the slug, path, or branch represents different state; run `status`.
82
- - `WENDKEEP_WORKTREE_GIT_FAILED` or `WENDKEEP_WORKTREE_BASE_UNRESOLVED`: repair the Git state and
83
- retry the command shown in `recovery`.
123
+ - `WENDKEEP_WORKTREE_PR_INVALID`, `WENDKEEP_WORKTREE_PR_NOT_MERGED`,
124
+ `WENDKEEP_WORKTREE_PR_MISMATCH`, or `WENDKEEP_WORKTREE_PR_MERGE_UNREACHABLE`: correct/associate
125
+ the PR, update the local base, and retry without manually removing the worktree.
126
+ - `WENDKEEP_WORKTREE_DIRTY`, `WENDKEEP_WORKTREE_ACTIVE_SESSION`,
127
+ `WENDKEEP_WORKTREE_ACTIVE_DELIVERY`, `WENDKEEP_WORKTREE_OUTBOX_PENDING`, or
128
+ `WENDKEEP_WORKTREE_HANDOFF_PENDING`: complete the recovery named by the blocker.
129
+ - `WENDKEEP_WORKTREE_CLEANUP_BUSY`: another operation owns the reservation; if the directory is
130
+ already gone, retry the same command/proof to resume. Use `doctor` for failed/incomplete state.
131
+ - `WENDKEEP_WORKTREE_REMOTE_UNAVAILABLE` or `WENDKEEP_WORKTREE_REMOTE_DIVERGED`: the local branch is
132
+ preserved; recover the network or review the divergence before authorizing again.
84
133
  - `WENDKEEP_WORKTREE_REGISTRY_*`, `WENDKEEP_WORKTREE_*_MISMATCH`, or `WENDKEEP_VAULT_*` errors:
85
134
  preserve the artifacts and use `doctor` to diagnose the registry/binding.
86
135
  - `WENDKEEP_WORKTREE_EDITOR_NOT_FOUND` or `WENDKEEP_WORKTREE_EDITOR_OPEN_FAILED`: make `code`
87
136
  available on PATH or use `--open none`.
88
- - `failed`/`missing` state: read `recovery` from `status --json` and doctor's `[worktrees]` section.
89
137
 
90
138
  ## Next steps
91
139
 
@@ -114,6 +114,13 @@ contexto ativo inequívoco. Com zero ou múltiplos contextos, fica vazio. A migr
114
114
  não inventa uma identidade de worktree ou sessão. O ponteiro legado só vira contexto quando uma sessão
115
115
  ativa, scope completa e metadados da worktree provam uma única identidade.
116
116
 
117
+ Os hooks `brain-inject` (`SessionStart`) e `change-context` (`UserPromptSubmit`) resolvem a mesma
118
+ identidade causal antes de marcar uma change como `ATUAL` ou calcular o hash da sentinela. O backlog
119
+ continua global e lista as demais changes como `ABERTA`, mas um `CURRENT_CHANGE.md` divergente nunca
120
+ transforma a change irmã em foco da sessão. A presença de `active_contexts`, schema ou revision —
121
+ inclusive `active_contexts: {}` — desativa o fallback legado: contexto ausente ou ambíguo falha
122
+ fechado sem reativar o ponteiro. O fallback só existe antes da inicialização do store contextual.
123
+
117
124
  ## Erros comuns e diagnóstico
118
125
 
119
126
  - `WENDKEEP_CONTEXT_AMBIGUOUS`: informe `--session <id>`; nenhuma candidata é escolhida em silêncio.
@@ -4,23 +4,24 @@
4
4
 
5
5
  ## Objetivo
6
6
 
7
- Criar linked worktrees isoladas que continuam vinculadas ao mesmo projeto e Vault canônico,
8
- sem copiar estado privado para arquivos versionados.
7
+ Criar e encerrar linked worktrees isoladas que continuam vinculadas ao mesmo projeto e Vault
8
+ canônico, sem copiar estado privado para arquivos versionados nem descartar trabalho local.
9
9
 
10
10
  ## Quando usar
11
11
 
12
- Use ao iniciar uma implementação isolada, listar checkouts gerenciados, diagnosticar uma criação
13
- parcial ou abrir uma worktree já pronta no VS Code.
12
+ Use ao iniciar uma implementação isolada, listar checkouts gerenciados, diagnosticar uma operação
13
+ parcial, abrir uma worktree no VS Code ou limpá-la depois de um PR comprovadamente merged.
14
14
 
15
15
  ## Quando não usar
16
16
 
17
- Não use para remover, mesclar ou fazer self-merge de worktrees. Essas operações permanecem fora
18
- desta capability.
17
+ Não use para fazer merge do PR, descartar checkout dirty/untracked nem remover branch remota sem
18
+ autorização explícita. `finish` consome um merge já concluído; não faz self-merge.
19
19
 
20
20
  ## Pré-requisitos
21
21
 
22
22
  - Repositório Git com o projeto já vinculado ao Vault por `.wendkeep.json`.
23
- - Git disponível no `PATH`; para abertura, o comando `code` do VS Code também deve existir.
23
+ - Git disponível no `PATH`; `finish` também requer `gh` autenticado para consultar o GitHub.
24
+ - Para abertura, o comando `code` do VS Code deve existir.
24
25
 
25
26
  ## Sintaxe
26
27
 
@@ -29,46 +30,87 @@ npx --no-install wendkeep worktree create <slug> [--base <ref>] [--branch <nome>
29
30
  npx --no-install wendkeep worktree list [--json]
30
31
  npx --no-install wendkeep worktree status [<slug>] [--json]
31
32
  npx --no-install wendkeep worktree open <slug> [--editor vscode] [--json]
33
+ npx --no-install wendkeep worktree finish <slug> [--pr <número|url>] [--delete-remote] [--open-main] [--json]
34
+ npx --no-install wendkeep worktree cleanup --merged [--dry-run|--apply] [--json]
35
+ npx --no-install wendkeep worktree remove <slug> --reason <texto> [--json]
36
+ npx --no-install wendkeep worktree prune [--dry-run|--apply] [--json]
32
37
  ```
33
38
 
34
39
  Todas aceitam `--project <raiz>`. O padrão cria `.worktrees/<slug>` a partir da base detectada e
35
- usa a branch `wk/<slug>`. `worktrees.root`, quando configurado, deve ser um
36
- path relativo não vazio. Slug e branch são validados pelo Git; paths que escapam da raiz ou
37
- atravessam symlink/junction são rejeitados antes da mutação.
40
+ usa a branch `wk/<slug>`. `worktrees.root`, quando configurado, deve ser um path relativo não vazio.
41
+ Slug e branch são validados pelo Git; paths que escapam da raiz ou atravessam symlink/junction são
42
+ rejeitados antes da mutação.
43
+
44
+ ## Fechamento seguro
45
+
46
+ `finish` executa `git fetch --prune` quando existe `origin`, consulta o PR por adapter GitHub e
47
+ exige estado `MERGED`, branch coerente e merge commit alcançável pela base local. O número/URL fica
48
+ associado ao registry. Antes da remoção, o preflight falha fechado diante de checkout dirty ou
49
+ untracked, sessão ativa, delivery ativa, memory outbox ou handoff pendente.
50
+
51
+ Depois da reserva sob lock, o comando remove a linked worktree, fecha somente seus active contexts,
52
+ faz prune, apaga o ref local por CAS e grava receipt JSONL append-only no Git common-dir. Isso aceita
53
+ merge commit, squash e rebase sem usar `git branch -D`. Reexecução com a mesma prova é idempotente;
54
+ se a pasta sumiu entre etapas, a reserva interrompida é retomada. `doctor` mostra cleanup
55
+ interrompido/failed e uma recuperação objetiva.
56
+
57
+ `--delete-remote` é a única autorização para excluir a branch remota. A branch deve continuar no
58
+ head comprovado; divergência ou rede indisponível bloqueia. Branch já ausente é sucesso idempotente.
59
+ `--open-main` abre a worktree principal somente depois da conclusão.
60
+
61
+ ## Cleanup, remove e prune
62
+
63
+ `cleanup --merged` e `prune` são dry-run por padrão. `--dry-run` apenas torna essa intenção
64
+ explícita; somente `--apply` permite mutação. O plano é ordenado por slug e não altera Git,
65
+ registry, contexts ou receipts. `cleanup --merged` atua apenas em entries com PR associado e merge
66
+ revalidado. `remove --reason` é a saída auditável para abandono explícito: dispensa prova de merge,
67
+ mas mantém todo o preflight e preserva as branches local e remota.
38
68
 
39
69
  ## Opções e códigos de saída
40
70
 
41
71
  O registry fica no Git common-dir, em `wendkeep/worktrees-v1.json`, sob lock multiprocesso. Ele
42
- guarda identidade do repositório/worktree e o binding canônico; `.wendkeep.json` permanece
43
- inalterado. `.worktrees/` entra no ignore versionado e no exclude privado do repositório. A saída
44
- JSON de `list`/`status` não expõe path nem conteúdo do Vault. A saída humana apresenta, por
45
- worktree, slug, identidade, path do checkout, branch, HEAD, estado e saúde do binding.
72
+ guarda identidade do repositório/worktree, binding canônico, PR e estado transitório de cleanup;
73
+ `.wendkeep.json` permanece inalterado. Receipts ficam em
74
+ `wendkeep/worktree-cleanup-receipts-v1.jsonl`. `.worktrees/` entra no ignore versionado e no exclude
75
+ privado. A saída JSON de `list`/`status` não expõe path nem conteúdo do Vault.
46
76
 
47
77
  `create` é idempotente quando slug, path e branch já correspondem. Colisões falham fechadas.
48
- Falhas depois da reserva ficam como `failed`; rode `worktree status <slug>` e siga o campo
49
- `recovery`. `doctor` também lista dívida em `[worktrees]` sem repará-la.
78
+ Falhas depois da reserva ficam como `failed`; rode `worktree status <slug>` e siga `recovery`.
79
+ `doctor` também lista dívida de criação ou cleanup em `[worktrees]` sem repará-la.
50
80
 
51
- ## VS Code e códigos de saída
81
+ ## VS Code
52
82
 
53
83
  `--open vscode` e `worktree open` validam `code --version` e abrem uma janela nova com `code -n`.
54
- Use `init --vscode-worktree-tasks` ou `sync --vscode-worktree-tasks` para criar tarefas locais;
55
- um `.vscode/tasks.json` existente ou rastreado, mesmo removido no checkout, nunca é sobrescrito.
84
+ Use `init --vscode-worktree-tasks` ou `sync --vscode-worktree-tasks` para criar tarefas locais,
85
+ incluindo **WendKeep: Finish merged worktree**; um `.vscode/tasks.json` existente ou rastreado,
86
+ mesmo removido no checkout, nunca é sobrescrito.
56
87
 
57
- Exit `0` indica sucesso. Erro de uso, binding, segurança, Git ou editor retorna `2` com código
58
- estável `WENDKEEP_WORKTREE_*`. O comando nunca remove ou mescla uma worktree.
88
+ Exit `0` indica sucesso. Erro de uso, binding, segurança, prova, Git ou editor retorna `2` com código
89
+ estável `WENDKEEP_WORKTREE_*`. Nenhum comando faz merge ou usa force para descartar checkout.
59
90
 
60
91
  ## Exemplos
61
92
 
62
- ```bash
93
+ PowerShell:
94
+
95
+ ```powershell
63
96
  npx --no-install wendkeep worktree create auth --open vscode
64
- npx --no-install wendkeep worktree status auth --json
65
- npx --no-install wendkeep worktree list
97
+ npx --no-install wendkeep worktree finish auth --pr 72 --open-main
98
+ npx --no-install wendkeep worktree cleanup --merged --dry-run --json
99
+ ```
100
+
101
+ POSIX:
102
+
103
+ ```bash
104
+ npx --no-install wendkeep worktree cleanup --merged --apply
105
+ npx --no-install wendkeep worktree remove spike --reason "PR cancelado"
106
+ npx --no-install wendkeep worktree prune --dry-run
66
107
  ```
67
108
 
68
109
  ## Resultado esperado
69
110
 
70
- `create auth` produz `.worktrees/auth` na branch `wk/auth`; main e linked worktree resolvem o
71
- mesmo `projectId` e Vault, e o checkout principal permanece limpo.
111
+ `create auth` produz `.worktrees/auth` na branch `wk/auth`. Depois do merge comprovado, `finish`
112
+ remove o checkout e o ref local, fecha apenas seu active context e preserva Vault, sessões,
113
+ evidências e receipt.
72
114
 
73
115
  ## Erros comuns e diagnóstico
74
116
 
@@ -77,13 +119,20 @@ mesmo `projectId` e Vault, e o checkout principal permanece limpo.
77
119
  - `WENDKEEP_WORKTREE_PATH_OUTSIDE_ROOT` ou `WENDKEEP_WORKTREE_PATH_SYMLINK_ESCAPE`: use uma raiz
78
120
  relativa contida no main worktree, sem symlink/junction intermediário.
79
121
  - `WENDKEEP_WORKTREE_COLLISION`: slug, path ou branch já representa outro estado; rode `status`.
80
- - `WENDKEEP_WORKTREE_GIT_FAILED` ou `WENDKEEP_WORKTREE_BASE_UNRESOLVED`: corrija o estado Git e
81
- repita o comando indicado em `recovery`.
82
- - Erros `WENDKEEP_WORKTREE_REGISTRY_*`, `WENDKEEP_WORKTREE_*_MISMATCH` ou
83
- `WENDKEEP_VAULT_*`: preserve os artefatos e use `doctor` para diagnosticar registry/binding.
122
+ - `WENDKEEP_WORKTREE_PR_INVALID`, `WENDKEEP_WORKTREE_PR_NOT_MERGED`,
123
+ `WENDKEEP_WORKTREE_PR_MISMATCH` ou `WENDKEEP_WORKTREE_PR_MERGE_UNREACHABLE`: corrija/associe o PR,
124
+ atualize a base local e repita sem remover a worktree manualmente.
125
+ - `WENDKEEP_WORKTREE_DIRTY`, `WENDKEEP_WORKTREE_ACTIVE_SESSION`,
126
+ `WENDKEEP_WORKTREE_ACTIVE_DELIVERY`, `WENDKEEP_WORKTREE_OUTBOX_PENDING` ou
127
+ `WENDKEEP_WORKTREE_HANDOFF_PENDING`: conclua a recuperação indicada pelo blocker.
128
+ - `WENDKEEP_WORKTREE_CLEANUP_BUSY`: outra operação ainda possui a reserva; se a pasta já sumiu,
129
+ repita o mesmo comando/prova para retomar. Use `doctor` para reservations failed/incompletas.
130
+ - `WENDKEEP_WORKTREE_REMOTE_UNAVAILABLE` ou `WENDKEEP_WORKTREE_REMOTE_DIVERGED`: a branch local é
131
+ preservada; recupere rede ou revise a divergência antes de autorizar novamente.
132
+ - Erros `WENDKEEP_WORKTREE_REGISTRY_*`, `WENDKEEP_WORKTREE_*_MISMATCH` ou `WENDKEEP_VAULT_*`:
133
+ preserve os artefatos e use `doctor` para diagnosticar registry/binding.
84
134
  - `WENDKEEP_WORKTREE_EDITOR_NOT_FOUND` ou `WENDKEEP_WORKTREE_EDITOR_OPEN_FAILED`: disponibilize
85
135
  `code` no PATH ou use `--open none`.
86
- - Estado `failed`/`missing`: leia `recovery` em `status --json` e o bloco `[worktrees]` do `doctor`.
87
136
 
88
137
  ## Próximos passos
89
138
 
@@ -1,7 +1,12 @@
1
1
  import { readSessionRegistry } from './obsidian-common.mjs';
2
- import { resolveActiveContext } from './active-context-store.mjs';
2
+ import {
3
+ activeContextRegistryInitialized,
4
+ resolveActiveContext,
5
+ } from './active-context-store.mjs';
3
6
  import { resolveRuntimeActiveContext } from '../src/active-context-runtime.mjs';
4
7
 
8
+ export { activeContextRegistryInitialized } from './active-context-store.mjs';
9
+
5
10
  const IDENTITY_FIELDS = Object.freeze([
6
11
  ['work_session_id', 'workSessionId'],
7
12
  ['repository_id', 'repositoryId'],
@@ -26,12 +31,6 @@ function contextsOf(registry) {
26
31
  ? registry.active_contexts : {};
27
32
  }
28
33
 
29
- export function activeContextRegistryInitialized(registry = {}) {
30
- return Object.hasOwn(registry, 'active_contexts')
31
- || Object.hasOwn(registry, 'active_contexts_schema')
32
- || Object.hasOwn(registry, 'active_contexts_revision');
33
- }
34
-
35
34
  function assertAuthority(identity, context) {
36
35
  if (!identity || !context || context.state !== 'active') {
37
36
  throw contextError(
@@ -11,6 +11,12 @@ const ID_PATTERN = /^[A-Za-z0-9._-]{1,160}$/;
11
11
  const SLUG_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/;
12
12
  const DELIVERY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{1,100}$/;
13
13
 
14
+ export function activeContextRegistryInitialized(registry = {}) {
15
+ return Object.hasOwn(registry, 'active_contexts')
16
+ || Object.hasOwn(registry, 'active_contexts_schema')
17
+ || Object.hasOwn(registry, 'active_contexts_revision');
18
+ }
19
+
14
20
  function contextError(code, message) {
15
21
  const error = new Error(message);
16
22
  error.code = code;
@@ -254,7 +260,7 @@ export function migrateLegacyActiveContext(vaultBase, {
254
260
  const slug = legacyPointer(vaultBase);
255
261
  if (!slug) return { migrated: false, reason: 'no-pointer' };
256
262
  const registry = readSessionRegistry(vaultBase);
257
- if (Object.keys(contextsOf(registry)).length) return { migrated: false, reason: 'already-initialized' };
263
+ if (activeContextRegistryInitialized(registry)) return { migrated: false, reason: 'already-initialized' };
258
264
  if (typeof identityForSession !== 'function') return { migrated: false, reason: 'identity-unavailable' };
259
265
 
260
266
  const candidates = [];