wendkeep 0.62.0 → 0.64.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.
@@ -0,0 +1,349 @@
1
+ // wendkeep CLI — canonical private runtime.
2
+ // wendkeep init [--vault <path>] [--project <path>] [--no-mcp] [--yes] [--force]
3
+ // wendkeep hook <name> (invoked by the agent's settings.json; pipes stdin/stdout)
4
+ // wendkeep doctor [--vault <path>]
5
+ // wendkeep --version | --help
6
+ import { spawnSync } from 'node:child_process';
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { RUNNABLE_HOOKS } from '../../../src/taxonomy.mjs';
11
+
12
+ const here = dirname(fileURLToPath(import.meta.url));
13
+ const pkgRoot = join(here, '..', '..', '..');
14
+ const hooksDir = join(pkgRoot, 'hooks');
15
+
16
+ function version() {
17
+ try {
18
+ return JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')).version;
19
+ } catch {
20
+ return '0.0.0';
21
+ }
22
+ }
23
+
24
+ const HELP = `wendkeep ${version()} — keep durable AI sessions in an Obsidian vault, with optional governance.
25
+
26
+ Usage:
27
+ wendkeep init [options] Set up wendkeep in a project (cross-platform).
28
+ --vault <path> Obsidian vault folder (default: <project>/.<project-name>-vault).
29
+ --project <path> Project root to wire (default: current directory).
30
+ --profile <name> Operating profile: OFF, FLOW, GUIDE, GOVERN (default), or ASSURE.
31
+ --no-mcp Do not add the mcpvault MCP server to .mcp.json.
32
+ --companions <csv> Companion plugins/MCP to pin: context-mode,caveman,understand-anything
33
+ (default: none — opt in explicitly). dotcontext is legacy — the native a2 loop replaces it.
34
+ --no-companions Skip companion plugins/MCP entirely.
35
+ --no-colors Skip the Obsidian color system (.obsidian snippet + graph groups).
36
+ --dotcontext-mcp <v> dotcontext MCP placement: auto (default; skip project entry
37
+ if already global), project, or none.
38
+ --dotcontext-hooks <v> dotcontext hooks: full (default), light (no PostToolUse), none.
39
+ --yes, -y Non-interactive; accept defaults.
40
+ --force Overwrite existing wendkeep config blocks.
41
+
42
+ wendkeep hook <name> Run a session hook (used by settings.json). Reads the
43
+ agent's JSON on stdin. Names: ${RUNNABLE_HOOKS.join(', ')}.
44
+
45
+ wendkeep sync [--project P] Run init -> sync-defs -> doctor on the CURRENT project, in one
46
+ command — the three steps that repeat identically after every
47
+ package update. Stops at the first failing step. Install the
48
+ package first (npm i -D wendkeep@latest); a running process
49
+ cannot replace itself. · --vault P · --profile <name> · --yes.
50
+
51
+ wendkeep doctor [--vault P] Run a vault health check.
52
+ wendkeep change <sub> Change lifecycle: new [--simple] | use | bind <slug> --session <id> | continue | list | show |
53
+ status | done <id> | undone <id> | diff | archive [--force] | abandon | relink | backlink.
54
+ archive exige verdict (rode verify --deep); abandon descarta sem ADR.
55
+ backlink [--apply]: injeta o backlink pro proposta em design/tarefas/spec órfãos (open + _arquivo).
56
+ wendkeep theme sync Re-aplica o color system (snippet CSS + graph color groups) num vault
57
+ existente — recupera o grafo cinza sem re-init. --vault P.
58
+ wendkeep session <sub> Session registry: list | show <id> | use <id>.
59
+ wendkeep profile <sub> Operating profile: status | use <OFF|FLOW|GUIDE|GOVERN|ASSURE>.
60
+ --session <id> sets an audited session override; otherwise changes
61
+ the project default. The Vault/session/memory core is always active.
62
+ wendkeep flow <sub> Low-ceremony E -> V contract: start | status | show | finish | promote.
63
+ FLOW records scope, sensors and a receipt without creating a change.
64
+ wendkeep spec <sub> Specs: list | show | effective [--change] [--json] | migrate | rebase.
65
+ wendkeep sensors <sub> list | add <id> "<command>" [--severity --type --report].
66
+ wendkeep cost [opts] Aggregate AI-coding spend across the vault's sessions.
67
+ --since <date> · --top [N] (priciest) · --trend [day|week|month]
68
+ (+ run-rate projection) · --write (generate 00-Custo.md) · --json.
69
+ wendkeep cost rebuild Recalculate historical parent + subagent costs from SESSION_REGISTRY.
70
+ Dry-run by default · --apply writes notes + .brain/COST_REBUILD.json
71
+ · --session <id|file> · --limit N · --json.
72
+ wendkeep stats [--vault P] One shareable line: sessions · prompts · spend · span · models (--json).
73
+ wendkeep import [opts] Backfill: import this project's past Claude + Codex sessions into
74
+ the vault (deduped by session_id). --source all|claude|codex (default
75
+ all) · --stamp-ids (backfill session_id in existing notes) ·
76
+ --rescan-decisions (capture prose decisions from already-imported transcripts) ·
77
+ --from <dir> · --codex-from <dir> · --since <date> · --limit N ·
78
+ --dry-run · --json.
79
+ wendkeep verify [--deep] [--change s] Run a change's task sensors + record evidence (the gate);
80
+ --deep assembles the verification package for the wk-verify pass.
81
+ wendkeep dashboard [--force] (Re)generate the vault's folder-filtered Bases + 00-Dashboard MOC.
82
+ wendkeep renumber-decisions Renumber 04-Decisões to ADR-<NNNN>-<slug> in chronological order,
83
+ renaming files + rewriting every wikilink. Preview by default; --apply to
84
+ write. --vault P · --json.
85
+ wendkeep renumber-bugs Renumber 05-Bugs to BUG-<NNNN>-<slug> chronologically, moving notes
86
+ out of legacy "DIA N" subfolders into the month folder and rewriting
87
+ wikilinks. Preview by default; --apply · --vault P · --json.
88
+ wendkeep renumber-learnings Same for 06-Aprendizados/06-Learnings with APR-<NNNN>-<slug>.
89
+ wendkeep note new --type bug|learning "<título>" Create a numbered derived note (BUG-/APR-NNNN)
90
+ in the month folder and print its vault path. --date YYYY-MM-DD · --vault P.
91
+ wendkeep note relink [--apply] Backfill orphan derived notes (BUG/APR without a source session),
92
+ linking each to the modal source session of its type/month cohort. Dry-run
93
+ by default; --apply writes; skips notes with no sibling to infer from.
94
+ wendkeep note repair-frontmatter [--apply] Merge stacked frontmatter blocks in session notes
95
+ (damage from pre-lock concurrent writes) into a single block: base keys
96
+ from the original block, values from the newest. Dry-run by default;
97
+ --apply writes under the same lock as the hooks · --json.
98
+ wendkeep note repair-sections [--apply] Rebuild the derived sections (decisions/bugs/learnings)
99
+ in session notes from the linked derived notes — the body used to lag
100
+ behind the closing block. Dry-run by default · --apply · --json.
101
+ wendkeep lesson add "t" "l" Record a project-local lesson (injected at SessionStart).
102
+ wendkeep memory <sub> Shared memory v2: status | migrate [--apply] | repair |
103
+ reconcile <session> --by-session <session> --reason <text> [--apply] |
104
+ promote <candidate> | reject <candidate>. --vault P.
105
+ Reconcile is dry-run by default; the original attempt remains audited.
106
+ wendkeep validate-memory [path] Validate .brain/CORE.md against the compaction
107
+ protocol (cap 25, 3 sections, no secrets/PII).
108
+ --vault <path> validates the complete v2 bundle.
109
+ wendkeep sync-defs [opts] Copy versioned defs from the vault's .brain into the
110
+ project: .brain/agents/*.toml -> .codex/agents,
111
+ .brain/skills/<name> -> .claude/skills + .agents/skills. --vault P --project P.
112
+ --reseed re-semeia as skills wk-* com os seeds da versão instalada
113
+ (sobrescreve edições manuais nas wk-*) antes de copiar.
114
+ --check detecta drift sem modificar arquivos.
115
+ wendkeep --version Print version.
116
+ wendkeep --help Show this help.
117
+ `;
118
+
119
+ function runHook(name) {
120
+ if (!name) {
121
+ process.stderr.write('wendkeep hook: missing hook name\n');
122
+ process.exit(2);
123
+ }
124
+ if (!RUNNABLE_HOOKS.includes(name)) {
125
+ process.stderr.write(`wendkeep hook: unknown hook "${name}". Known: ${RUNNABLE_HOOKS.join(', ')}\n`);
126
+ process.exit(2);
127
+ }
128
+ const file = join(hooksDir, `${name}.mjs`);
129
+ if (!existsSync(file)) {
130
+ process.stderr.write(`wendkeep hook: hook file not found: ${file}\n`);
131
+ process.exit(2);
132
+ }
133
+ // Spawn exactly as the agent would run `node <hook>.mjs`: stdio inherited so the
134
+ // hook's stdin (agent JSON) and stdout (hookSpecificOutput) pass through untouched.
135
+ const r = spawnSync(process.execPath, [file], { stdio: 'inherit' });
136
+ process.exit(r.status ?? 0);
137
+ }
138
+
139
+ function optionValue(argv, name) {
140
+ const index = argv.indexOf(name);
141
+ if (index >= 0) return argv[index + 1] || '';
142
+ return argv.find((item) => item.startsWith(`${name}=`))?.slice(name.length + 1) || '';
143
+ }
144
+
145
+ async function preferProjectVault(argv) {
146
+ // Existing command modules still consume OBSIDIAN_VAULT_PATH internally. Populate it
147
+ // only inside this CLI process from the provider-neutral project binding, overriding
148
+ // any inherited machine-global value. An explicit --vault remains authoritative.
149
+ if (optionValue(argv, '--vault')) return;
150
+ try {
151
+ const { resolveProjectVault } = await import('../../../src/project-vault.mjs');
152
+ // A sensor may itself invoke WendKeep. `verify`/`flow finish` already selected the
153
+ // authoritative Vault explicitly, so preserve that choice across the child process
154
+ // instead of letting the sensor cwd's project binding redirect it.
155
+ const sensorVault = process.env.WENDKEEP_SENSOR_VAULT;
156
+ if (sensorVault) {
157
+ const selected = resolveProjectVault({
158
+ startDir: optionValue(argv, '--project') || process.cwd(),
159
+ explicitVault: sensorVault,
160
+ });
161
+ process.env.OBSIDIAN_VAULT_PATH = selected.base;
162
+ return;
163
+ }
164
+ const resolved = resolveProjectVault({ startDir: optionValue(argv, '--project') || process.cwd() });
165
+ process.env.OBSIDIAN_VAULT_PATH = resolved.base;
166
+ } catch (error) {
167
+ // Backward-compatible manual CLI behavior: individual commands still explain
168
+ // --vault / legacy env only when no project binding exists. A configured but
169
+ // corrupt/missing/mismatched binding must abort before dispatch to another Vault.
170
+ if (error?.code !== 'WENDKEEP_VAULT_UNCONFIGURED') throw error;
171
+ }
172
+ }
173
+
174
+ async function main(argv) {
175
+ const [cmd, ...rest] = argv;
176
+ // Universal --help: any subcommand with --help/-h prints usage and never executes.
177
+ // Intercepted BEFORE vault resolution so it works anywhere — help must never depend
178
+ // on project state, and no command may treat --help as a runnable default.
179
+ if (cmd && (rest.includes('--help') || rest.includes('-h'))) {
180
+ if (cmd === 'flow') {
181
+ const { FLOW_HELP } = await import('../../../src/flow.mjs');
182
+ process.stdout.write(FLOW_HELP);
183
+ } else if (cmd === 'profile') {
184
+ const { PROFILE_HELP } = await import('../../../src/profile.mjs');
185
+ process.stdout.write(PROFILE_HELP);
186
+ } else {
187
+ process.stdout.write(HELP);
188
+ }
189
+ process.exit(0);
190
+ }
191
+ const validatesStandaloneCore = cmd === 'validate-memory'
192
+ && !rest.includes('--vault')
193
+ && !rest.some((item) => item.startsWith('--vault='));
194
+ if (cmd
195
+ && !validatesStandaloneCore
196
+ // `sync` starts with `init` and resolves the freshly bound Vault itself. Pre-resolving
197
+ // here would prevent that repair step from reporting a corrupt binding as its own
198
+ // first-stage failure (and could never make it as far as the guarded init).
199
+ && !['init', 'sync', 'hook', '--version', '-v', '--help', '-h', 'help'].includes(cmd)) {
200
+ await preferProjectVault(rest);
201
+ }
202
+ switch (cmd) {
203
+ case 'init': {
204
+ const { runInit } = await import('../../../src/init.mjs');
205
+ await runInit(rest);
206
+ break;
207
+ }
208
+ case 'hook':
209
+ runHook(rest[0]);
210
+ break;
211
+ case 'doctor': {
212
+ const { runDoctor } = await import('../../../src/doctor.mjs');
213
+ process.exit(runDoctor(rest));
214
+ break;
215
+ }
216
+ case 'sync': {
217
+ const { runSync } = await import('../../../src/sync.mjs');
218
+ process.exit(await runSync(rest));
219
+ break;
220
+ }
221
+ case 'validate-memory': {
222
+ if (rest.includes('--vault') || rest.some((item) => item.startsWith('--vault='))) {
223
+ const { runValidateMemoryBundle } = await import('../../../src/memory.mjs');
224
+ runValidateMemoryBundle(rest);
225
+ } else {
226
+ const { runValidateMemory } = await import('../../../src/validate-core.mjs');
227
+ runValidateMemory(rest);
228
+ }
229
+ break;
230
+ }
231
+ case 'memory': {
232
+ const { runMemory } = await import('../../../src/memory.mjs');
233
+ runMemory(rest);
234
+ break;
235
+ }
236
+ case 'sync-defs': {
237
+ const { runSyncDefs } = await import('../../../src/sync-defs.mjs');
238
+ process.exit(runSyncDefs(rest));
239
+ break;
240
+ }
241
+ case 'change': {
242
+ const { runChange } = await import('../../../src/change.mjs');
243
+ runChange(rest);
244
+ break;
245
+ }
246
+ case 'session': {
247
+ const { runSession } = await import('../../../src/session.mjs');
248
+ runSession(rest);
249
+ break;
250
+ }
251
+ case 'profile': {
252
+ const { runProfile } = await import('../../../src/profile.mjs');
253
+ process.exit(runProfile(rest));
254
+ break;
255
+ }
256
+ case 'flow': {
257
+ const { runFlow } = await import('../../../src/flow.mjs');
258
+ process.exit(await runFlow(rest));
259
+ break;
260
+ }
261
+ case 'theme': {
262
+ const { runTheme } = await import('../../../src/theme.mjs');
263
+ runTheme(rest);
264
+ break;
265
+ }
266
+ case 'verify': {
267
+ const { runVerify } = await import('../../../src/verify.mjs');
268
+ runVerify(rest);
269
+ break;
270
+ }
271
+ case 'lesson': {
272
+ const { runLesson } = await import('../../../src/lessons.mjs');
273
+ runLesson(rest);
274
+ break;
275
+ }
276
+ case 'spec': {
277
+ const { runSpec } = await import('../../../src/spec.mjs');
278
+ runSpec(rest);
279
+ break;
280
+ }
281
+ case 'sensors': {
282
+ const { runSensors } = await import('../../../src/sensors.mjs');
283
+ runSensors(rest);
284
+ break;
285
+ }
286
+ case 'cost': {
287
+ const { runCost } = await import('../../../src/cost.mjs');
288
+ runCost(rest);
289
+ break;
290
+ }
291
+ case 'stats': {
292
+ const { runStats } = await import('../../../src/stats.mjs');
293
+ runStats(rest);
294
+ break;
295
+ }
296
+ case 'import': {
297
+ const { runImportCli } = await import('../../../src/import.mjs');
298
+ runImportCli(rest);
299
+ break;
300
+ }
301
+ case 'dashboard': {
302
+ const { runDashboard } = await import('../../../src/vault-views.mjs');
303
+ runDashboard(rest);
304
+ break;
305
+ }
306
+ case 'renumber-decisions': {
307
+ const { runRenumberDecisions } = await import('../../../src/renumber.mjs');
308
+ runRenumberDecisions(rest);
309
+ break;
310
+ }
311
+ case 'renumber-bugs': {
312
+ const { runRenumberBugs } = await import('../../../src/renumber.mjs');
313
+ runRenumberBugs(rest);
314
+ break;
315
+ }
316
+ case 'renumber-learnings': {
317
+ const { runRenumberLearnings } = await import('../../../src/renumber.mjs');
318
+ runRenumberLearnings(rest);
319
+ break;
320
+ }
321
+ case 'note': {
322
+ const { runNote } = await import('../../../src/note.mjs');
323
+ runNote(rest);
324
+ break;
325
+ }
326
+ case '--version':
327
+ case '-v':
328
+ process.stdout.write(`${version()}\n`);
329
+ break;
330
+ case undefined:
331
+ case '--help':
332
+ case '-h':
333
+ case 'help':
334
+ process.stdout.write(HELP);
335
+ break;
336
+ default:
337
+ process.stderr.write(`wendkeep: unknown command "${cmd}"\n\n${HELP}`);
338
+ process.exit(2);
339
+ }
340
+ }
341
+
342
+ export async function runCli(argv = process.argv.slice(2)) {
343
+ try {
344
+ await main(argv);
345
+ } catch (err) {
346
+ process.stderr.write(`wendkeep: ${err?.stack || err}\n`);
347
+ process.exit(1);
348
+ }
349
+ }