wendkeep 0.80.1 → 0.85.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.en.md +31 -11
  3. package/README.md +31 -11
  4. package/docs/en/commands/capabilities.md +82 -0
  5. package/docs/en/commands/getting-started.md +3 -1
  6. package/docs/en/commands/mcp.md +99 -0
  7. package/docs/en/commands/operating-profiles.md +4 -0
  8. package/docs/en/commands/portable.md +88 -0
  9. package/docs/en/commands/sync-protocol.md +58 -0
  10. package/docs/en/commands/tdd.md +96 -0
  11. package/docs/en/commands/verify.md +5 -0
  12. package/docs/pt-BR/commands/capabilities.md +82 -0
  13. package/docs/pt-BR/commands/getting-started.md +3 -2
  14. package/docs/pt-BR/commands/mcp.md +99 -0
  15. package/docs/pt-BR/commands/operating-profiles.md +4 -0
  16. package/docs/pt-BR/commands/portable.md +87 -0
  17. package/docs/pt-BR/commands/sync-protocol.md +58 -0
  18. package/docs/pt-BR/commands/tdd.md +96 -0
  19. package/docs/pt-BR/commands/verify.md +5 -0
  20. package/hooks/active-context-store.mjs +2 -0
  21. package/hooks/change-core.mjs +5 -0
  22. package/hooks/project-scope.mjs +2 -1
  23. package/hooks/session-ensure.mjs +23 -7
  24. package/hooks/session-start.mjs +20 -5
  25. package/package.json +3 -3
  26. package/packages/cli/src/index.mjs +42 -2
  27. package/packages/harness/src/sensors-core.mjs +16 -3
  28. package/packages/integrations/src/capabilities.mjs +220 -0
  29. package/packages/integrations/src/index.mjs +1 -0
  30. package/packages/mcp/src/audit.mjs +49 -0
  31. package/packages/mcp/src/cli.mjs +78 -0
  32. package/packages/mcp/src/config.mjs +22 -1
  33. package/packages/mcp/src/effects.mjs +115 -0
  34. package/packages/mcp/src/executor.mjs +354 -0
  35. package/packages/mcp/src/index.mjs +7 -0
  36. package/packages/mcp/src/server.mjs +342 -0
  37. package/packages/mcp/src/stdio.mjs +38 -0
  38. package/packages/mcp/src/sync.mjs +56 -0
  39. package/packages/pi/package.json +2 -1
  40. package/packages/pi/src/index.mjs +29 -0
  41. package/schema/handoff-contract-v1.schema.json +4 -0
  42. package/schema/host-capability-manifest-v1.schema.json +46 -0
  43. package/schema/host-coverage-v1.schema.json +55 -0
  44. package/schema/mcp-effect-manifest-v1.schema.json +36 -0
  45. package/schema/mcp-tool-input-v1.schema.json +32 -0
  46. package/schema/mcp-tool-result-v1.schema.json +22 -0
  47. package/schema/portable-active-work-v1.schema.json +38 -0
  48. package/schema/portable-state-v1.schema.json +36 -0
  49. package/schema/sync-event-v1.schema.json +25 -0
  50. package/schema/sync-private-envelope-v1.schema.json +16 -0
  51. package/schema/sync-state-v1.schema.json +18 -0
  52. package/schema/task-contract-v1.schema.json +2 -0
  53. package/schema/tdd-attestation-v1.schema.json +39 -0
  54. package/schema/wendkeep.evidence-envelope-v2.schema.json +17 -0
  55. package/schema/wendkeep.sensors.schema.json +19 -0
  56. package/src/active-context-runtime.mjs +1 -0
  57. package/src/capabilities.mjs +50 -0
  58. package/src/doctor.mjs +28 -0
  59. package/src/evidence-envelope.mjs +12 -6
  60. package/src/host-capabilities.mjs +34 -0
  61. package/src/init.mjs +3 -3
  62. package/src/mcp.mjs +7 -0
  63. package/src/observer-snapshot.mjs +25 -0
  64. package/src/portable.mjs +558 -0
  65. package/src/profile.mjs +16 -3
  66. package/src/skills-seed.mjs +26 -0
  67. package/src/sync-adapters.mjs +188 -0
  68. package/src/sync-outbox.mjs +155 -0
  69. package/src/sync-protocol-cli.mjs +277 -0
  70. package/src/sync-protocol.mjs +368 -0
  71. package/src/sync.mjs +8 -0
  72. package/src/task-contracts.mjs +67 -2
  73. package/src/task.mjs +5 -1
  74. package/src/tdd-attestation-store.mjs +98 -0
  75. package/src/tdd-attestation.mjs +254 -0
  76. package/src/tdd.mjs +198 -0
  77. package/src/vault-readme.mjs +4 -4
  78. package/src/verify.mjs +24 -0
@@ -0,0 +1,88 @@
1
+ # Portable state
2
+
3
+ **English** · [Português](../../pt-BR/commands/portable.md)
4
+
5
+ ## Purpose
6
+
7
+ Publish the reviewable Vault subset and a compact `active-work` snapshot to
8
+ `.wendkeep/portable/state.json` without turning private runtime into Git data. The command never
9
+ runs `git add`, commit, or push.
10
+
11
+ ## When to use
12
+
13
+ Use `portable export` before a PR that shares specs/decisions or before moving machines;
14
+ `portable status`/`diff` to review drift; and `portable import` after creating and binding the Vault
15
+ of a clean clone.
16
+
17
+ ## When not to use
18
+
19
+ Do not use it as real-time remote sync, transcript backup, secret transport, or a replacement for
20
+ `context switch`. Import restores a resume hint but never invents a session ID, active context, or
21
+ lease.
22
+
23
+ ## Prerequisites
24
+
25
+ - A Git project bound to its Vault through `.wendkeep.json`.
26
+ - Valid `PROJECT.json`; a worktree registry when generating new identity.
27
+ - Human review of the JSON before adding it to Git.
28
+
29
+ ## Syntax
30
+
31
+ ```bash
32
+ npx --no-install wendkeep portable status [--project <root>] [--vault <vault>] [--input <file>] [--json]
33
+ npx --no-install wendkeep portable export [--project <root>] [--vault <vault>] [--output <file>] [--json]
34
+ npx --no-install wendkeep portable import [--project <root>] [--vault <vault>] [--input <file>] [--json]
35
+ npx --no-install wendkeep portable diff [--project <root>] [--vault <vault>] [--input <file>] [--json]
36
+ ```
37
+
38
+ ## Options and exit codes
39
+
40
+ - `--input`/`--output`: override the default `.wendkeep/portable/state.json` path.
41
+ - `--project`/`--vault`: select the binding; `--json` emits structured results.
42
+ - Exit `0`: valid status/export/import or equal diff. Exit `1`: different diff. Exit `2`: invalid
43
+ schema, project, integrity, path, or argument.
44
+ - `status` returns `not_configured`, `current`, `diverged`, or `invalid`.
45
+
46
+ ## Examples
47
+
48
+ ```bash
49
+ npx --no-install wendkeep portable export
50
+ npx --no-install wendkeep portable diff
51
+ git diff -- .wendkeep/portable/state.json
52
+ git add -- .wendkeep/portable/state.json
53
+ ```
54
+
55
+ `.gitattributes` fixes LF for `/.wendkeep/portable/*.json`. Projects may ignore this directory and
56
+ retain the complete local Keep Core.
57
+
58
+ ## Expected result
59
+
60
+ The inventory classifies `.brain/CORE.md`, ADRs, proposal/design/tasks, and `specs/` deltas as
61
+ `authored`; `07-Specs`, evidence/verification/verdict, and archives as `derived`; registries, leases,
62
+ locks, outboxes, and full receipts as `runtime`; transcripts, prompts/responses, tokens/costs,
63
+ secrets, and environment as `secret`. Only authored data and `07-Specs` enter the bundle. Export
64
+ normalizes LF, excludes symlinks/hardlinks, and removes Windows/POSIX absolute paths, known token
65
+ shapes, and values of `Authorization`, `token`, `password`, `secret`, and `api_key`.
66
+
67
+ Each `active-work` contains `project_id`, `repository_id`, `change_slug`, `task_id`, branch/SHAs,
68
+ hashes, completed/next work, blockers, references, timestamp, and revision. It never contains
69
+ `work_session_id`, `worktree_id`, local paths, or tokens. Import stores the private hint in
70
+ `.brain/runtime/PORTABLE_ACTIVE_WORK.json`; export/import append metadata and hashes only to
71
+ `.brain/runtime/PORTABLE_PROVENANCE.jsonl`.
72
+
73
+ ## Common errors and diagnosis
74
+
75
+ - `WENDKEEP_PORTABLE_STALE`: incoming revision is older than local state.
76
+ - `WENDKEEP_PORTABLE_CONFLICT`: the same revision carries a different hash.
77
+ - `WENDKEEP_PORTABLE_PATH_UNSAFE`: traversal, non-allowlisted path, or symlink.
78
+ - `WENDKEEP_PORTABLE_INTEGRITY`: content/hash was tampered with.
79
+
80
+ All fail before the first write. `doctor` reports `[portable] diverged` and recommends diff/export;
81
+ `not_configured` is a valid opt-out. Schemas: `schema/portable-state-v1.schema.json` and
82
+ `schema/portable-active-work-v1.schema.json`.
83
+
84
+ ## Next steps
85
+
86
+ Review the small human-readable diff, add only the confirmed snapshot, and open the PR. In the
87
+ destination clone, run `init`, `portable import`, inspect `portable status`, and start a new causal
88
+ session.
@@ -0,0 +1,58 @@
1
+ # Local-first sync protocol
2
+
3
+ **English** · [Português](../../pt-BR/commands/sync-protocol.md)
4
+
5
+ ## Purpose
6
+
7
+ Synchronize authored state and active work across machines without making the backend authoritative. The protocol uses revisions, compare-and-swap (CAS), causality, a durable outbox, expiring leases, and explicit conflicts; it never silently applies last-write-wins.
8
+
9
+ ## When to use
10
+
11
+ Use `wendkeep sync push` and `pull` when one project must share its portable state across devices, branches, or worktrees. Sync is optional and creates runtime only after a write operation.
12
+
13
+ ## When not to use
14
+
15
+ Do not use it as a private-data backup, transcript transport, or Git replacement. CORE, credentials, and local runtime are excluded. Private content may travel only inside an authenticated E2E envelope.
16
+
17
+ ## Prerequisites
18
+
19
+ The project must be bound to a Vault and have `.wendkeep/portable/state.json`, generated by `wendkeep portable export`. Choose stable actor and device identities. Select a backend with `--remote` or `--url`; tokens are read only from the environment variable named by `--token-env`.
20
+
21
+ ## Syntax
22
+
23
+ ```text
24
+ wendkeep sync status [--project <dir>] [--json]
25
+ wendkeep sync push --actor <id> --device <id> (--remote <dir> | --url <url>)
26
+ wendkeep sync pull (--remote <dir> | --url <url>) [--no-import]
27
+ wendkeep sync conflicts [--json]
28
+ wendkeep sync resolve --record <key> --select <event> --reason <text> --actor <id> --device <id> (--remote <dir> | --url <url>)
29
+ ```
30
+
31
+ ## Options and exit codes
32
+
33
+ `--remote` uses the reference filesystem adapter; `--url` uses the replaceable HTTP adapter. `--token-env NAME` reads a secret without persisting it. `--no-import` downloads and validates without applying portable state. Exit `0` means converged, `1` an operational failure, and `2` invalid usage or a conflict requiring a human decision.
34
+
35
+ ## Examples
36
+
37
+ ```powershell
38
+ wendkeep portable export --project .
39
+ wendkeep sync push --project . --actor roger --device desktop --remote D:\wk-sync
40
+ wendkeep sync pull --project . --remote D:\wk-sync
41
+ wendkeep sync conflicts --project . --json
42
+ ```
43
+
44
+ ## Expected result
45
+
46
+ Retries are idempotent. Out-of-order events wait for causal parents. Concurrent writes from one revision form an order-independent stable conflict set. Resolution creates a new event and an auditable decision; tombstones and lease history remain intact.
47
+
48
+ `doctor`, the sanitized Observer snapshot, and the semantic MCP surface expose only health, counts, and candidate metadata; those queries never return authored payloads or local paths.
49
+
50
+ ## Common errors and diagnosis
51
+
52
+ Use `wendkeep doctor` and `wendkeep sync status`. `WENDKEEP_SYNC_BACKEND_UNAVAILABLE` retains events in the outbox for retry. `WENDKEEP_SYNC_OUTBOX_CORRUPT` blocks sending until local review. Conflicts appear in `sync conflicts` and are never resolved automatically.
53
+
54
+ Threat model: duplicate delivery, replay, and reordering are contained by hashes, idempotent IDs, revisions, and causal parents. Partitions retain the outbox. Client clocks do not choose a lease winner. A malicious backend can omit or retain events, but cannot forge content without breaking hashes or read private AES-256-GCM envelopes. Key and timestamp metadata may still leak; losing a private key is unrecoverable. Backend rollback is detectable through cursors and revisions, while availability remains the operator's responsibility.
55
+
56
+ ## Next steps
57
+
58
+ Review conflicts with `wendkeep sync conflicts`, resolve them explicitly, and confirm state with `wendkeep portable diff`. See [Portable state](portable.md) and [Local Observer](observer.md).
@@ -0,0 +1,96 @@
1
+ # Causal TDD attestation
2
+
3
+ **English** · [Português](../../pt-BR/commands/tdd.md)
4
+
5
+ ## Purpose
6
+
7
+ `wendkeep tdd` records auditable proof that a test bound to a task and requirement was observed
8
+ RED and then GREEN in the same project, repository, worktree, work session, and change. It
9
+ complements coverage, mutation, sensors, and review; it replaces none of them.
10
+
11
+ ## When to use
12
+
13
+ Use before and after implementing testable behavior bound to a `[tdd]` task.
14
+
15
+ ## When not to use
16
+
17
+ Do not use it for health checks, already-green tests, or environment failures. Use sensors/doctor
18
+ for infrastructure and a human waiver only when the behavior is genuinely not testable.
19
+
20
+ ## Prerequisites
21
+
22
+ An active change, causal active context, task with `[req:ID]`, project-relative test, and a
23
+ deterministic command that can be repeated in RED and GREEN.
24
+
25
+ ## Syntax
26
+
27
+ ```bash
28
+ wendkeep tdd red <task-id> --requirement <ID> --test <path> --command "<command>" --session <id>
29
+ wendkeep tdd green <task-id> --command "<command>" --session <id>
30
+ wendkeep tdd status <task-id> --session <id> [--json]
31
+ wendkeep tdd waive <task-id> --requirement <ID> --reason "<reason>" --authority "<human>" --session <id>
32
+ ```
33
+
34
+ `--test` is repeatable. Every path is project-relative. `--change <slug>`, `--project <root>`,
35
+ `--vault <vault>`, and `--json` follow the other commands' conventions.
36
+
37
+ ## RED → GREEN contract
38
+
39
+ - Valid RED is a behavioral failure. An already-green test, syntax/import error, missing module,
40
+ invalid configuration, or unknown command yields `invalid`.
41
+ - GREEN must preserve the RED causal identity and branch, pass, and observe a production change
42
+ after RED. GREEN from another worktree, task, or requirement cannot close the cycle.
43
+ - A changed test path is recorded in `review_flags`. A refactor or commit after GREEN makes proof
44
+ stale until `tdd green` runs again; the previous GREEN remains in `green_history`.
45
+ - A waiver requires both a reason and explicit human authority. Silent waivers do not exist.
46
+
47
+ The `08-Mudanças/<slug>/tdd-attestations.json` store retains SHA-256 digests, a sanitized tail
48
+ bounded to 2,000 characters, and relative paths — never full output. The Evidence Envelope,
49
+ `verificacao.json`, handoff, and Observer expose the attestation and its ID to reviewers.
50
+
51
+ ## Profile gate
52
+
53
+ - `OFF` and `FLOW`: optional.
54
+ - `GUIDE`: recommended for testable behavior.
55
+ - `GOVERN`: required when a task carries `[tdd]`.
56
+ - `ASSURE`: required for an executable task with a requirement or sensor, unless explicitly waived.
57
+
58
+ Mark a task as follows:
59
+
60
+ ```markdown
61
+ - [ ] 1.1 persists the preference [req:UI-1] [sensor:tests] [tdd]
62
+ ```
63
+
64
+ Stale/invalid proof, a surviving mutant, or a missing GREEN/waiver produces
65
+ `TASK_TDD_ATTESTATION_MISSING_OR_INVALID` in the Task Contract and blocks Execute → Verify.
66
+
67
+ ## Examples
68
+
69
+ ```bash
70
+ wendkeep tdd red 1.1 --requirement UI-1 --test tests/ui.test.mjs --command "npm test" --session abc
71
+ wendkeep tdd green 1.1 --command "npm test" --session abc
72
+ wendkeep tdd status 1.1 --session abc --json
73
+ ```
74
+
75
+ ## Expected result
76
+
77
+ A causal entry in `tdd-attestations.json`, referenced by the Task Contract and evidence surfaces,
78
+ with an auditable current state and revalidation history.
79
+
80
+ ## Options and exit codes
81
+
82
+ - `0`: the observed state is valid (`red-observed`, `green-observed`, or `waived`; green/waived status).
83
+ - `1`: observation ran but is `invalid`, RED has not reached GREEN, or status is stale.
84
+ - `2`: invalid usage, context, identity, store, or waiver authority.
85
+
86
+ ## Common errors and diagnosis
87
+
88
+ - `TDD_RED_ALREADY_GREEN`: first write a discriminating test that fails.
89
+ - `TDD_RED_INFRASTRUCTURE_FAILURE`: fix import, syntax, configuration, or command and repeat RED.
90
+ - `TDD_GREEN_STALE_AFTER_REFACTOR`: repeat GREEN in the current checkout.
91
+ - `TDD_IMPLEMENTATION_NOT_AFTER_RED`: proof observed no production diff after RED.
92
+
93
+ ## Next steps
94
+
95
+ Run [verify](verify.md), request the independent pass, and continue the
96
+ [change lifecycle](changes-and-verification.md).
@@ -87,6 +87,11 @@ temporary in the same directory and an atomic rename. In deep mode, `verificacao
87
87
  `verdict.json` carry the same `evidenceEnvelopeId` and complete `evidenceBinding`; the independent
88
88
  reviewer must preserve both.
89
89
 
90
+ The envelope carries `tdd_attestations`, and `verificacao.json` carries `tddAttestations`. Under GOVERN, a task marked
91
+ `[tdd]` requires a current GREEN or explicit waiver; under ASSURE this applies to testable
92
+ behavior. A later refactor/commit or a surviving mutant invalidates GREEN in the Task Contract.
93
+ See [Causal TDD attestation](tdd.md).
94
+
90
95
  V1 evidence remains readable as `legacy-unbound`, never as equivalent authority. Run
91
96
  `wendkeep change status <slug>` to inspect `bound`, `stale`, or `context-mismatch`.
92
97
 
@@ -0,0 +1,82 @@
1
+ # Capacidades dos hosts
2
+
3
+ [English](../../en/commands/capabilities.md)
4
+
5
+ ## Objetivo
6
+
7
+ Mostrar a matriz versionada das 17 capacidades de lifecycle e efeitos que cada host realmente
8
+ oferece como `native`, `adapted`, `polled`, `manual` ou `unavailable`.
9
+
10
+ ## Quando usar
11
+
12
+ Use antes de depender de hooks de sessão, tool use, conclusão de tarefa, subagentes, transcript ou
13
+ usage; e ao diagnosticar diferenças entre Claude Code, Codex, Pi e clientes MCP/CLI genéricos.
14
+
15
+ ## Quando não usar
16
+
17
+ Não use a matriz como prova de que um evento manual ocorreu. Estado `manual` tem autoridade apenas
18
+ `reported`; somente eventos native/adapted/polled podem ser `verified`.
19
+
20
+ ## Pré-requisitos
21
+
22
+ Node.js 18+ e o pacote WendKeep instalado. O comando é puro e não requer Vault. A cobertura gravada
23
+ na sessão usa o host detectado e pode receber a versão por `WENDKEEP_HOST_VERSION`.
24
+
25
+ ## Sintaxe
26
+
27
+ ```text
28
+ wendkeep capabilities [--host <claude|codex|pi|generic-mcp>] [--host-version <v>] [--json]
29
+ ```
30
+
31
+ Sem `--host`, o comando lista todos os manifests. Host desconhecido degrada explicitamente para
32
+ `generic-mcp`; versão fora da faixa fica `HOST_VERSION_UNPROVEN`.
33
+
34
+ ## Opções e códigos de saída
35
+
36
+ - `--host <id>` seleciona um host; ids desconhecidos não são promovidos silenciosamente.
37
+ - `--host-version <v>` compara o major observado com o manifest.
38
+ - `--json` emite o contrato `host-coverage-v1`.
39
+ - exit `0`: matriz emitida; exit `2`: argumento inválido.
40
+
41
+ `wendkeep.sensors.json` pode declarar `requires_host_capabilities` e waivers humanos explícitos em
42
+ `host_capability_waivers`. `verify` sai `1` se uma capacidade requerida estiver manual/unavailable
43
+ sem waiver com `authority: human`, `approved_by` e `reason`. ASSURE aplica a mesma regra ao handoff.
44
+
45
+ ## Exemplos
46
+
47
+ ```powershell
48
+ wendkeep capabilities --host codex --host-version 1.2.0
49
+ wendkeep capabilities --host generic-mcp --json
50
+ ```
51
+
52
+ ```json
53
+ {
54
+ "requires_host_capabilities": ["task.completed"],
55
+ "host_capability_waivers": [{
56
+ "capability": "task.completed",
57
+ "authority": "human",
58
+ "approved_by": "maintainer",
59
+ "reason": "confirmação manual"
60
+ }]
61
+ }
62
+ ```
63
+
64
+ ## Resultado esperado
65
+
66
+ A cobertura entra no registro da sessão, active context, handoff, envelope de evidência e resumo do
67
+ Observer. Lacunas são injetadas no contexto no início, antes que o agente assuma paridade inexistente.
68
+ Efeitos MCP vêm do manifest assinado: reads conhecidos pulam o mutation gate; writes/destructive
69
+ continuam sujeitos aos gates; efeito desconhecido falha fechado.
70
+
71
+ ## Erros comuns e diagnóstico
72
+
73
+ - `HOST_UNKNOWN`: use o fallback MCP/CLI ou publique um adapter isolado.
74
+ - `HOST_VERSION_UNPROVEN`: atualize o manifest ou opere em modo degradado.
75
+ - `HOST_CAPABILITY_UNAVAILABLE`: remova a dependência ou obtenha waiver humano explícito.
76
+ - `HOST_ENVELOPE_UNKNOWN`: versão/evento não reconhecido nunca vira evidência verificada.
77
+ - Tool com nome parecido não define efeito; confira o catálogo assinado com `wendkeep mcp inspect`.
78
+
79
+ ## Próximos passos
80
+
81
+ Veja [MCP nativo](mcp.md), [sessões e importação](sessions-and-import.md),
82
+ [changes e verificação](changes-and-verification.md) e [Observer](observer.md).
@@ -86,8 +86,9 @@ cofre efetivamente selecionado.
86
86
 
87
87
  Quando MCP está habilitado, o `init` preserva propriedades e servidores existentes em `.mcp.json`
88
88
  e adiciona `wendkeep-vault`. Se o JSON existente for inválido, o arquivo original permanece byte
89
- a byte intacto e a proposta reconciliada é gravada em `.mcp.json.new`. Desde a versão 0.65, essa
90
- composição pertence ao kernel MCP privado, sem alterar comandos, flags ou a superfície npm pública.
89
+ a byte intacto e a proposta reconciliada é gravada em `.mcp.json.new`. A entrada executa o servidor
90
+ semântico instalado com `npx --no-install wendkeep mcp serve --vault <vault>`, sem download
91
+ dinâmico `@latest`. Veja [MCP nativo](mcp.md) para tools, gates, limites e snippets de clientes.
91
92
 
92
93
  As regras puras que projetam os hooks de Claude/Codex e interpretam envelopes, transcripts, uso e
93
94
  identidade pertencem ao workspace privado `@wendkeep/integrations`. As fachadas históricas mantêm
@@ -0,0 +1,99 @@
1
+ # MCP nativo
2
+
3
+ [English](../../en/commands/mcp.md)
4
+
5
+ ## Objetivo
6
+
7
+ Expor estado semântico local de projeto, contexto, memória, changes, tarefas, evidência e Observer
8
+ sem leitura arbitrária do filesystem ou dependência dinâmica `@latest`.
9
+
10
+ ## Quando usar
11
+
12
+ Use quando um cliente MCP precisar descobrir e consultar o WendKeep ou executar um write causal
13
+ explicitamente autorizado por capability, active context e lease.
14
+
15
+ ## Quando não usar
16
+
17
+ Não use para delivery, merge, push, tag, publicação, exclusão ou acesso genérico a arquivos. Essas
18
+ operações ficam fora da superfície padrão e continuam nos fluxos CLI/ASSURE apropriados.
19
+
20
+ ## Pré-requisitos
21
+
22
+ - pacote `wendkeep` instalado no projeto ou acessível pelo binário;
23
+ - binding válido de projeto↔Vault;
24
+ - Node.js 18+ para Core; Node.js 22.13+ somente para Observer SQL;
25
+ - para writes: sessão causal, active context e autorização vigentes.
26
+
27
+ ## Sintaxe
28
+
29
+ ```powershell
30
+ wendkeep mcp serve --vault <vault>
31
+ wendkeep mcp serve --vault <vault> --timeout-ms <n>
32
+ wendkeep mcp config --client generic --vault <vault>
33
+ wendkeep mcp config --client claude --vault <vault>
34
+ wendkeep mcp config --client codex --vault <vault>
35
+ wendkeep mcp config --client cursor --vault <vault>
36
+ ```
37
+
38
+ ## Opções e códigos de saída
39
+
40
+ - `--vault <path>` seleciona o Vault; é obrigatório em `config` e opcional em `serve`. Sem a
41
+ flag, o stdio inicia sem depender do checkout do processo e resolve o binding/auditoria de cada
42
+ chamada somente pelo `project_root` declarado; um projeto nunca reutiliza o auditor de outro.
43
+ - `--timeout-ms <n>` aceita 1 a 120000; padrão 10000 por chamada.
44
+ - `--client` aceita `generic`, `claude`, `codex` ou `cursor`.
45
+ - Exit 0: transporte/configuração concluído; Exit 2: subcomando, cliente ou opção inválida.
46
+ - Tool errors usam resultado MCP `isError` com `schema_version: 1`, código `MCP_*`, mensagem
47
+ sanitizada e `retryable`; não encerram o servidor.
48
+
49
+ ## Exemplos
50
+
51
+ O `init` gera a entrada genérica reproduzível:
52
+
53
+ ```json
54
+ {
55
+ "mcpServers": {
56
+ "wendkeep-vault": {
57
+ "type": "stdio",
58
+ "command": "npx",
59
+ "args": ["--no-install", "wendkeep", "mcp", "serve", "--vault", "<vault>"]
60
+ }
61
+ }
62
+ }
63
+ ```
64
+
65
+ Reads: `wendkeep_project_status`, `wendkeep_context_status`, `wendkeep_memory_recall`,
66
+ `wendkeep_memory_conflicts`, `wendkeep_change_list`, `wendkeep_change_show`,
67
+ `wendkeep_change_status`, `wendkeep_spec_effective`, `wendkeep_task_show`,
68
+ `wendkeep_task_evaluate`, `wendkeep_handoff_current`, `wendkeep_evidence_latest` e
69
+ `wendkeep_observer_query`.
70
+
71
+ Writes: `wendkeep_memory_assert`, `wendkeep_checkpoint_create`, `wendkeep_context_select`,
72
+ `wendkeep_task_claim`, `wendkeep_task_complete` e `wendkeep_handoff_publish`.
73
+
74
+ ## Resultado esperado
75
+
76
+ O handshake e `tools/list` retornam JSON-RPC válido. Cada tool declara effect/capability e schemas
77
+ versionados. Reads conhecidas não entram no mutation gate, mas mantêm binding explícito de
78
+ projeto/worktree, paginação por cursor, budget padrão de 1 MiB, redaction, timeout e cancelamento.
79
+ Observer aparece indisponível abaixo de Node 22.13 sem impedir Core no Node 18.
80
+
81
+ Writes exigem `project_root`, `session_id`, `active_context_id`, `actor`, `reason`, capability exata
82
+ e `lease.id`/`lease.expires_at`; o executor revalida a autorização causal e os gates da CLI. A
83
+ auditoria local `.brain/runtime/MCP_AUDIT.jsonl` guarda somente tool, effect, capability, resultado,
84
+ código e duração — nunca argumentos ou payload.
85
+
86
+ ## Erros comuns e diagnóstico
87
+
88
+ - `MCP_TOOL_UNKNOWN`: tool/alias não consta no catálogo verificado; atualize o cliente ou pacote.
89
+ - `MCP_CAPABILITY_REQUIRED` / `MCP_SCOPE_AUTH_REQUIRED`: capability ausente ou não autorizada.
90
+ - `MCP_LEASE_EXPIRED`: obtenha autorização/lease nova; não altere timestamp manualmente.
91
+ - `MCP_PROJECT_SCOPE_MISMATCH`: `project_root` e `worktree_root` pertencem a bindings diferentes.
92
+ - `MCP_REQUEST_TOO_LARGE` / `MCP_RESPONSE_TOO_LARGE`: use `limit` e o cursor retornado.
93
+ - `MCP_RUNTIME_UNSUPPORTED`: use Node 22.13+ para Observer; Core permanece disponível.
94
+
95
+ ## Próximos passos
96
+
97
+ Rode `wendkeep mcp config --client <client> --vault <vault>`, instale o snippet no cliente e faça
98
+ `initialize` → `tools/list` → uma read conhecida. Para identidade causal, veja [Contexto](context.md);
99
+ para o backend SQL opcional, veja [Observer](observer.md).
@@ -139,6 +139,10 @@ harness nativo da LLM.
139
139
  ausente, ambíguo ou stale falha fechado sem mutação parcial.
140
140
  - `.wendkeep.json` continua em `schemaVersion: 1`; o campo aditivo usa, por exemplo,
141
141
  `"harness": { "profile": "GOVERN" }`. Binding legado sem o campo também resolve `GOVERN`.
142
+ - Em worktree vinculada, `profile use` e `profile status` usam o binding canônico da worktree
143
+ principal descoberto pelo registry Git compartilhado. A seleção é persistida uma vez para o
144
+ projeto e o `.wendkeep.json` versionado da worktree vinculada permanece intacto, inclusive no
145
+ Windows quando caminhos longos e aliases 8.3 identificam o mesmo Vault.
142
146
  - Binding corrompido nunca equivale a `OFF`. Quando o payload ou a integração legada identifica
143
147
  um Vault inequívoco, o Keep Core continua ativo sob `GOVERN` e o hook expõe um diagnóstico;
144
148
  guards de mutação falham fechados até o binding ser reparado. Configuração local inválida,
@@ -0,0 +1,87 @@
1
+ # Estado portátil
2
+
3
+ **PT-BR** · [English](../../en/commands/portable.md)
4
+
5
+ ## Objetivo
6
+
7
+ Publicar em `.wendkeep/portable/state.json` a parte revisável do Vault e um snapshot compacto
8
+ `active-work`, sem transformar runtime privado em dados de Git. O comando nunca executa `git add`,
9
+ commit ou push.
10
+
11
+ ## Quando usar
12
+
13
+ Use `portable export` antes de um PR que compartilhe specs/decisões ou antes de trocar de máquina;
14
+ `portable status`/`diff` para revisar drift; e `portable import` depois de criar e vincular o Vault
15
+ de um clone limpo.
16
+
17
+ ## Quando não usar
18
+
19
+ Não use como sync remoto em tempo real, backup de transcritos, transporte de secrets ou substituto
20
+ de `context switch`. O import restaura uma indicação de retomada, mas não inventa session ID, active
21
+ context ou lease.
22
+
23
+ ## Pré-requisitos
24
+
25
+ - Projeto Git vinculado ao Vault por `.wendkeep.json`.
26
+ - `PROJECT.json` válido; worktree registry para gerar identidade nova.
27
+ - Revisão humana do JSON antes de adicioná-lo ao Git.
28
+
29
+ ## Sintaxe
30
+
31
+ ```powershell
32
+ npx --no-install wendkeep portable status [--project <raiz>] [--vault <cofre>] [--input <arquivo>] [--json]
33
+ npx --no-install wendkeep portable export [--project <raiz>] [--vault <cofre>] [--output <arquivo>] [--json]
34
+ npx --no-install wendkeep portable import [--project <raiz>] [--vault <cofre>] [--input <arquivo>] [--json]
35
+ npx --no-install wendkeep portable diff [--project <raiz>] [--vault <cofre>] [--input <arquivo>] [--json]
36
+ ```
37
+
38
+ ## Opções e códigos de saída
39
+
40
+ - `--input`/`--output`: substituem o path padrão `.wendkeep/portable/state.json`.
41
+ - `--project`/`--vault`: selecionam o binding; `--json` emite resultado estruturado.
42
+ - Exit `0`: status/export/import válido ou diff igual. Exit `1`: diff diferente. Exit `2`: schema,
43
+ project, integridade, path ou argumento inválido.
44
+ - `status` retorna `not_configured`, `current`, `diverged` ou `invalid`.
45
+
46
+ ## Exemplos
47
+
48
+ ```powershell
49
+ npx --no-install wendkeep portable export
50
+ npx --no-install wendkeep portable diff
51
+ git diff -- .wendkeep/portable/state.json
52
+ git add -- .wendkeep/portable/state.json
53
+ ```
54
+
55
+ O `.gitattributes` fixa LF para `/.wendkeep/portable/*.json`. Projetos podem ignorar essa pasta e
56
+ continuar usando todo o Keep Core local.
57
+
58
+ ## Resultado esperado
59
+
60
+ O inventário classifica `.brain/CORE.md`, ADRs, proposta/design/tarefas e deltas de `specs/` como
61
+ `authored`; `07-Specs`, evidência/verificação/verdict e arquivo como `derived`; registries, leases,
62
+ locks, outboxes e receipts completos como `runtime`; transcritos, prompts/respostas, tokens/custos,
63
+ secrets e environment como `secret`. Só authored e `07-Specs` entram. O export normaliza LF,
64
+ exclui symlink/hardlink e remove caminhos absolutos Windows/POSIX, tokens conhecidos e valores de
65
+ `Authorization`, `token`, `password`, `secret` e `api_key`.
66
+
67
+ Cada `active-work` contém `project_id`, `repository_id`, `change_slug`, `task_id`, branch/SHAs,
68
+ hashes, tarefas concluídas/próximas, blockers, references, timestamp e revision. Nunca contém
69
+ `work_session_id`, `worktree_id`, path local ou token. O import grava a dica privada em
70
+ `.brain/runtime/PORTABLE_ACTIVE_WORK.json`; export/import registram somente metadados e hashes em
71
+ `.brain/runtime/PORTABLE_PROVENANCE.jsonl`.
72
+
73
+ ## Erros comuns e diagnóstico
74
+
75
+ - `WENDKEEP_PORTABLE_STALE`: revision recebida é inferior à local.
76
+ - `WENDKEEP_PORTABLE_CONFLICT`: mesma revision tem hash diferente.
77
+ - `WENDKEEP_PORTABLE_PATH_UNSAFE`: traversal, path fora da allowlist ou symlink.
78
+ - `WENDKEEP_PORTABLE_INTEGRITY`: conteúdo/hash foi adulterado.
79
+
80
+ Todos falham antes da primeira escrita. O `doctor` mostra `[portable] diverged` e recomenda diff/export;
81
+ `not_configured` é opt-out válido. Schemas: `schema/portable-state-v1.schema.json` e
82
+ `schema/portable-active-work-v1.schema.json`.
83
+
84
+ ## Próximos passos
85
+
86
+ Revise o diff humano pequeno, adicione somente o snapshot confirmado e abra o PR. No clone destino,
87
+ execute `init`, `portable import`, consulte `portable status` e inicie uma nova sessão causal.
@@ -0,0 +1,58 @@
1
+ # Protocolo local-first de sync
2
+
3
+ **PT-BR** · [English](../../en/commands/sync-protocol.md)
4
+
5
+ ## Objetivo
6
+
7
+ Sincronizar estado autorado e trabalho ativo entre máquinas sem transformar o backend em autoridade. O protocolo usa revisões, compare-and-swap (CAS), causalidade, outbox durável, leases expirantes e conflitos explícitos; não usa last-write-wins silencioso.
8
+
9
+ ## Quando usar
10
+
11
+ Use `wendkeep sync push` e `pull` quando o mesmo projeto precisa compartilhar seu estado portátil entre dispositivos, branches ou worktrees. O sync é opcional e só cria runtime depois de uma operação de escrita.
12
+
13
+ ## Quando não usar
14
+
15
+ Não use como backup de dados privados, transporte de transcripts ou substituto de Git. CORE, credenciais e runtime local não entram no protocolo. Conteúdo privado só pode ser enviado como envelope E2E autenticado.
16
+
17
+ ## Pré-requisitos
18
+
19
+ O projeto deve estar vinculado a um Vault e possuir `.wendkeep/portable/state.json`, gerado por `wendkeep portable export`. Defina identidades estáveis de ator e dispositivo. Escolha um backend por `--remote` ou `--url`; tokens são lidos apenas da variável indicada por `--token-env`.
20
+
21
+ ## Sintaxe
22
+
23
+ ```text
24
+ wendkeep sync status [--project <dir>] [--json]
25
+ wendkeep sync push --actor <id> --device <id> (--remote <dir> | --url <url>)
26
+ wendkeep sync pull (--remote <dir> | --url <url>) [--no-import]
27
+ wendkeep sync conflicts [--json]
28
+ wendkeep sync resolve --record <chave> --select <evento> --reason <texto> --actor <id> --device <id> (--remote <dir> | --url <url>)
29
+ ```
30
+
31
+ ## Opções e códigos de saída
32
+
33
+ `--remote` usa o adaptador de referência em filesystem; `--url` usa HTTP substituível. `--token-env NOME` lê o segredo sem gravá-lo. `--no-import` baixa e valida sem aplicar ao estado portátil. O código `0` indica convergência, `1` falha operacional, `2` uso inválido ou conflito que exige decisão humana.
34
+
35
+ ## Exemplos
36
+
37
+ ```powershell
38
+ wendkeep portable export --project .
39
+ wendkeep sync push --project . --actor roger --device desktop --remote D:\wk-sync
40
+ wendkeep sync pull --project . --remote D:\wk-sync
41
+ wendkeep sync conflicts --project . --json
42
+ ```
43
+
44
+ ## Resultado esperado
45
+
46
+ Reenvios são idempotentes. Eventos fora de ordem aguardam seus pais causais. Escritas concorrentes da mesma revisão formam um conjunto de conflito estável, independente da ordem de chegada. Uma resolução gera novo evento e decisão auditável; tombstones e histórico de lease são preservados.
47
+
48
+ O `doctor`, o snapshot sanitizado do Observer e a superfície semântica MCP expõem apenas saúde, contagens e metadados de candidatos; payload autoral e caminhos locais não são retornados por essas consultas.
49
+
50
+ ## Erros comuns e diagnóstico
51
+
52
+ Use `wendkeep doctor` e `wendkeep sync status`. `WENDKEEP_SYNC_BACKEND_UNAVAILABLE` mantém eventos no outbox para retry. `WENDKEEP_SYNC_OUTBOX_CORRUPT` bloqueia envio até revisão local. Conflitos aparecem em `sync conflicts` e nunca são resolvidos automaticamente.
53
+
54
+ Modelo de ameaças: entrega duplicada, replay e reordenação são neutralizados por hashes, IDs idempotentes, revisões e pais causais. Partições mantêm o outbox. Relógios de clientes não decidem o vencedor de lease. Backend malicioso pode omitir ou reter eventos, mas não pode forjar conteúdo sem quebrar hashes nem ler envelopes privados AES-256-GCM. Metadados de chaves e horários ainda podem vazar; perda de chave privada é irrecuperável. Rollback do backend é detectável por cursor/revisão, mas disponibilidade continua sendo responsabilidade do operador.
55
+
56
+ ## Próximos passos
57
+
58
+ Revise conflitos com `wendkeep sync conflicts`, resolva-os explicitamente e confirme o estado com `wendkeep portable diff`. Veja também [Estado portátil](portable.md) e [Observer local](observer.md).