brainclaw 1.8.0 → 1.9.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 (140) hide show
  1. package/README.md +12 -11
  2. package/dist/brainclaw-vscode.vsix +0 -0
  3. package/dist/cli.js +138 -13
  4. package/dist/commands/add-step.js +1 -1
  5. package/dist/commands/bootstrap.js +2 -26
  6. package/dist/commands/check-security-mcp.js +50 -33
  7. package/dist/commands/check-security.js +86 -43
  8. package/dist/commands/claim.js +22 -21
  9. package/dist/commands/confirm.js +26 -0
  10. package/dist/commands/context-diff.js +1 -1
  11. package/dist/commands/dispatch-watch.js +142 -0
  12. package/dist/commands/doctor.js +113 -2
  13. package/dist/commands/estimation-report.js +115 -16
  14. package/dist/commands/harvest.js +285 -22
  15. package/dist/commands/init.js +123 -21
  16. package/dist/commands/loops-handlers.js +4 -0
  17. package/dist/commands/mcp-read-handlers.js +198 -29
  18. package/dist/commands/mcp.js +588 -92
  19. package/dist/commands/memory.js +21 -17
  20. package/dist/commands/migrate.js +81 -17
  21. package/dist/commands/prune.js +78 -4
  22. package/dist/commands/reflect.js +26 -20
  23. package/dist/commands/register-agent.js +57 -1
  24. package/dist/commands/repair.js +20 -0
  25. package/dist/commands/session-end.js +15 -6
  26. package/dist/commands/session-start.js +18 -1
  27. package/dist/commands/setup-security.js +39 -18
  28. package/dist/commands/setup.js +26 -27
  29. package/dist/commands/stale.js +16 -2
  30. package/dist/commands/uninstall.js +126 -34
  31. package/dist/commands/update-step.js +6 -0
  32. package/dist/commands/worktree.js +60 -0
  33. package/dist/core/actions.js +12 -3
  34. package/dist/core/agent-capability.js +11 -13
  35. package/dist/core/agent-files.js +844 -547
  36. package/dist/core/agent-integrations.js +0 -3
  37. package/dist/core/agent-inventory.js +67 -0
  38. package/dist/core/agent-registry.js +163 -29
  39. package/dist/core/agentrun-reconciler.js +33 -2
  40. package/dist/core/agentruns.js +7 -1
  41. package/dist/core/ai-agent-detection.js +31 -44
  42. package/dist/core/archival.js +15 -9
  43. package/dist/core/assignment-reconciler.js +56 -0
  44. package/dist/core/assignment-sweeper.js +127 -4
  45. package/dist/core/assignments.js +69 -11
  46. package/dist/core/bootstrap.js +233 -67
  47. package/dist/core/brainclaw-version.js +22 -0
  48. package/dist/core/candidates.js +21 -1
  49. package/dist/core/claims.js +313 -150
  50. package/dist/core/config.js +6 -1
  51. package/dist/core/context-diff.js +148 -20
  52. package/dist/core/context.js +129 -8
  53. package/dist/core/coordination.js +22 -3
  54. package/dist/core/dispatch-status.js +79 -5
  55. package/dist/core/dispatcher.js +64 -11
  56. package/dist/core/entity-operations.js +45 -24
  57. package/dist/core/entity-registry.js +31 -5
  58. package/dist/core/event-log.js +138 -21
  59. package/dist/core/events/checkpoint.js +258 -0
  60. package/dist/core/events/genesis.js +220 -0
  61. package/dist/core/events/journal.js +507 -0
  62. package/dist/core/events/materialize.js +126 -0
  63. package/dist/core/events/registry-post-image.js +110 -0
  64. package/dist/core/events/verify.js +109 -0
  65. package/dist/core/execution-adapters.js +23 -0
  66. package/dist/core/facade-schema.js +38 -0
  67. package/dist/core/gc-semantic.js +130 -5
  68. package/dist/core/handoff-snapshot.js +68 -0
  69. package/dist/core/ids.js +19 -8
  70. package/dist/core/instruction-templates.js +34 -115
  71. package/dist/core/io.js +39 -3
  72. package/dist/core/json-store.js +10 -1
  73. package/dist/core/lock.js +153 -28
  74. package/dist/core/loops/bootstrap-acquire.js +25 -1
  75. package/dist/core/loops/facade-schema.js +2 -0
  76. package/dist/core/loops/hooks/survey-signals-baseline.js +36 -0
  77. package/dist/core/loops/index.js +1 -0
  78. package/dist/core/loops/presets/bootstrap.js +7 -0
  79. package/dist/core/loops/store.js +17 -0
  80. package/dist/core/loops/verbs.js +24 -1
  81. package/dist/core/markdown.js +8 -76
  82. package/dist/core/mcp-command-resolution.js +245 -0
  83. package/dist/core/memory-compactor.js +5 -3
  84. package/dist/core/memory-lifecycle.js +282 -0
  85. package/dist/core/merge-risk.js +150 -0
  86. package/dist/core/messaging.js +8 -1
  87. package/dist/core/migration.js +11 -1
  88. package/dist/core/observer-mode.js +26 -0
  89. package/dist/core/operations/memory-mutation.js +90 -65
  90. package/dist/core/operations/plan.js +27 -1
  91. package/dist/core/protocol-skills.js +210 -0
  92. package/dist/core/reflection-safety.js +6 -7
  93. package/dist/core/reputation.js +84 -2
  94. package/dist/core/runtime-signals.js +71 -9
  95. package/dist/core/runtime.js +84 -1
  96. package/dist/core/schema.js +114 -0
  97. package/dist/core/security-detectors.js +125 -0
  98. package/dist/core/security-extract.js +189 -0
  99. package/dist/core/security-guard.js +107 -29
  100. package/dist/core/security-packages.js +121 -0
  101. package/dist/core/security-scoring.js +76 -9
  102. package/dist/core/security.js +34 -2
  103. package/dist/core/sequence.js +11 -2
  104. package/dist/core/setup-flow.js +141 -13
  105. package/dist/core/staleness.js +72 -1
  106. package/dist/core/state.js +250 -54
  107. package/dist/core/store-resolution.js +19 -5
  108. package/dist/core/worktree.js +72 -8
  109. package/dist/facts.js +8 -8
  110. package/dist/facts.json +7 -7
  111. package/docs/PROTOCOL.md +223 -0
  112. package/docs/cli.md +11 -10
  113. package/docs/concepts/coordinator-runbook.md +129 -0
  114. package/docs/concepts/event-log-store-critique-A.md +333 -0
  115. package/docs/concepts/event-log-store-critique-B.md +353 -0
  116. package/docs/concepts/event-log-store-phase0-measurements.md +58 -0
  117. package/docs/concepts/event-log-store-proposal-A.md +365 -0
  118. package/docs/concepts/event-log-store-proposal-B.md +404 -0
  119. package/docs/concepts/event-log-store.md +928 -0
  120. package/docs/concepts/identity-model-proposal.md +371 -0
  121. package/docs/concepts/memory.md +5 -4
  122. package/docs/concepts/observer-protocol.md +361 -0
  123. package/docs/concepts/parallel-merge-protocol.md +71 -0
  124. package/docs/concepts/plans-and-claims.md +43 -0
  125. package/docs/concepts/skills.md +78 -0
  126. package/docs/concepts/workspace-bootstrapping.md +61 -0
  127. package/docs/integrations/agents.md +4 -4
  128. package/docs/integrations/cline.md +10 -11
  129. package/docs/integrations/codex.md +2 -2
  130. package/docs/integrations/continue.md +5 -5
  131. package/docs/integrations/copilot.md +14 -12
  132. package/docs/integrations/openclaw.md +7 -6
  133. package/docs/integrations/overview.md +7 -7
  134. package/docs/integrations/roo.md +3 -3
  135. package/docs/integrations/windsurf.md +6 -6
  136. package/docs/mcp-schema-changelog.md +29 -2
  137. package/docs/quickstart.md +48 -47
  138. package/docs/security.md +174 -15
  139. package/docs/storage.md +4 -2
  140. package/package.json +8 -6
@@ -43,8 +43,8 @@ import { memoryDir } from './io.js';
43
43
  import { loadVersionedJsonFile } from './migration.js';
44
44
  import fs from 'node:fs';
45
45
  import path from 'node:path';
46
- import { buildInvokeCommand, resolveBriefMode, getCapabilityProfile, dispatchHasMcp, resolveConcurrencyLimit, resolveResourceKey, resolveModel, serializeConcurrencyLimit } from './agent-capability.js';
47
- import { getRuntimeSignalPath } from './runtime-signals.js';
46
+ import { buildInvokeCommand, resolveBriefMode, getCapabilityProfile, dispatchHasMcp, dispatchCanCommit, isSandboxedSpawn, resolveConcurrencyLimit, resolveResourceKey, resolveModel, serializeConcurrencyLimit } from './agent-capability.js';
47
+ import { getRuntimeSignalPath, getWorktreeHeartbeatPath } from './runtime-signals.js';
48
48
  import { attemptExecution } from './execution.js';
49
49
  import { createAssignment, transitionAssignment, generateAssignmentId, patchAssignmentMessageId } from './assignments.js';
50
50
  import { createAgentRun, transitionAgentRun } from './agentruns.js';
@@ -211,12 +211,28 @@ export function analyzeSequence(cwd) {
211
211
  * heartbeat. This is the worker-side half of the liveness contract whose
212
212
  * engine-side floor is the wrapper + reconciler (steps 4 + 1).
213
213
  */
214
- export function buildLivenessSection(cwd, assignmentId) {
215
- const hbPath = getRuntimeSignalPath(cwd, assignmentId, 'heartbeat');
214
+ export function buildLivenessSection(cwd, assignmentId, worktreePath, opts) {
215
+ // sprint 1.5 (dogfooding): the project-root signal path is NOT writable from
216
+ // inside worker sandboxes (Claude Code restricts writes to its working dirs;
217
+ // codex workspace-write roots exclude the project root) — the brief was
218
+ // demanding a heartbeat the worker could not write. When the worker has a
219
+ // worktree, point step 0 at a worktree-local heartbeat instead; every reader
220
+ // (reconciler, sweeper, dispatch_status fs-activity) checks both locations.
221
+ //
222
+ // pln#554 step 4 — sandbox-aware: codex workspace-write refuses even absolute
223
+ // paths in some configurations (cnd_asgn_7336aa79_heartbeat_sandbox /
224
+ // can_asgn_b0169fd8_heartbeat). When the execution adapter KNOWS the worker is
225
+ // sandboxed, point the write command at a worktree-RELATIVE path (the sandbox
226
+ // cwd is the worktree root) — same file, sandbox-proof spelling.
227
+ const sandboxRelative = opts?.sandboxed === true && !!worktreePath;
228
+ const hbPath = worktreePath
229
+ ? getWorktreeHeartbeatPath(worktreePath, assignmentId)
230
+ : getRuntimeSignalPath(cwd, assignmentId, 'heartbeat');
231
+ const targetPath = sandboxRelative ? `.brainclaw-heartbeat-${assignmentId}` : hbPath;
216
232
  const isWin = process.platform === 'win32';
217
233
  const writeCmd = isWin
218
- ? `echo work_loop_reached ${assignmentId} > "${hbPath}"`
219
- : `printf 'work_loop_reached ${assignmentId} %s' "$(date +%s)" > "${hbPath}"`;
234
+ ? `echo work_loop_reached ${assignmentId} > "${targetPath}"`
235
+ : `printf 'work_loop_reached ${assignmentId} %s' "$(date +%s)" > "${targetPath}"`;
220
236
  return [
221
237
  '## Liveness — DO THIS FIRST (step 0)',
222
238
  'Before ANY other action, prove you reached your work loop by writing a heartbeat,',
@@ -228,7 +244,28 @@ export function buildLivenessSection(cwd, assignmentId) {
228
244
  '```sh',
229
245
  writeCmd,
230
246
  '```',
231
- `Heartbeat file (absolute, writable): ${hbPath}`,
247
+ sandboxRelative
248
+ ? `Heartbeat file (worktree-RELATIVE — run it from the worktree root, your sandbox cwd; sandboxes refuse the absolute coordination path): ${targetPath}`
249
+ : `Heartbeat file (absolute, writable from your sandbox): ${hbPath}`,
250
+ ...(worktreePath ? ['If that write is denied, use any file edit in your worktree as your liveness signal and continue — do NOT stall on the heartbeat.'] : []),
251
+ '',
252
+ ].join('\n');
253
+ }
254
+ /**
255
+ * pln#554 step 4 — working defaults baked into every generated brief, distilled
256
+ * from the 2026-06-10 session: (a) incremental commits so a worker death costs
257
+ * one step max (the orphaned recoveries that night lost zero work ONLY because
258
+ * the diff was still on disk); (b) a split validation bar so parallel workers
259
+ * don't pile full test suites onto a memory-pressured machine.
260
+ */
261
+ export function buildWorkingDefaultsSection(opts) {
262
+ const commitRule = opts.canCommit
263
+ ? '- **Incremental commits**: commit after EACH completed step (conventional message). Never hold more than one step uncommitted — a worker death then costs at most one step, and the coordinator can harvest everything already on the branch.'
264
+ : '- **Incremental delivery**: your sandbox cannot `git commit` — finish steps in order and keep every file saved as you complete each step; the coordinator commits the worktree on your behalf at harvest. Never leave a step half-edited.';
265
+ return [
266
+ '## Working defaults',
267
+ commitRule,
268
+ '- **Validation bar**: run `tsc --noEmit` (or the project typecheck) + the targeted unit tests for the files you touched ONLY. Do NOT run the full default test suite — the coordinator runs the full gate after harvest (prevents test-suite pileups when several workers run in parallel).',
232
269
  '',
233
270
  ].join('\n');
234
271
  }
@@ -364,12 +401,18 @@ export function generateBrief(plan, item, cwd, briefMode, options) {
364
401
  if (plan.estimated_effort)
365
402
  parts.push(`Estimated effort: ${plan.estimated_effort} minutes`);
366
403
  parts.push('');
404
+ // Capability profile drives the sandbox-aware liveness path + the working
405
+ // defaults' commit rule (pln#554 step 4) and the transport addendum below.
406
+ const briefProfile = options?.agent ? getCapabilityProfile(options.agent) : undefined;
407
+ const briefSandboxed = briefProfile ? isSandboxedSpawn(briefProfile) : false;
367
408
  // pln#520 step 5 — liveness heartbeat instruction, first actionable block so
368
409
  // the worker writes work_loop_reached before anything else. Only when an
369
410
  // assignment id is known (the heartbeat is keyed by it).
370
411
  if (options?.assignmentId) {
371
- parts.push(buildLivenessSection(cwd, options.assignmentId));
412
+ parts.push(buildLivenessSection(cwd, options.assignmentId, options.worktreePath, { sandboxed: briefSandboxed }));
372
413
  }
414
+ // pln#554 step 4 — working defaults (incremental commits + validation bar).
415
+ parts.push(buildWorkingDefaultsSection({ canCommit: briefProfile ? dispatchCanCommit(briefProfile) : true }));
373
416
  // Steps if any
374
417
  if (plan.steps?.length) {
375
418
  parts.push('## Steps');
@@ -435,7 +478,6 @@ export function generateBrief(plan, item, cwd, briefMode, options) {
435
478
  // so the reconciler-independent path is preserved; this addendum disambiguates
436
479
  // the transport rather than stripping the section — the full compact reversal
437
480
  // is a separate human-owned call on the May-vs-June MCP-availability conflict.)
438
- const briefProfile = options?.agent ? getCapabilityProfile(options.agent) : undefined;
439
481
  if (briefProfile && !dispatchHasMcp(briefProfile)) {
440
482
  parts.push('## ⚠ Transport: sandboxed run (no MCP, no commit)');
441
483
  parts.push('Your runtime is sandboxed — the brainclaw MCP server is NOT reachable and `git commit` is unavailable (.git is outside the sandbox root). Any `bclaw_*` MCP instruction above does NOT apply to you. Report your outcome via the FILE protocol only — it is authoritative for this run:');
@@ -468,6 +510,15 @@ export function generateDispatchBrief(options) {
468
510
  if (options.worktreePath)
469
511
  parts.push(`Worktree: ${options.worktreePath}`);
470
512
  parts.push('');
513
+ const taskBriefProfile = options.agent ? getCapabilityProfile(options.agent) : undefined;
514
+ const taskSandboxed = taskBriefProfile ? isSandboxedSpawn(taskBriefProfile) : false;
515
+ // sprint 1.5 — task-based briefs get the same step-0 liveness contract as
516
+ // plan-based briefs (worktree-local heartbeat, writable from any sandbox).
517
+ if (options.assignmentId && options.worktreePath) {
518
+ parts.push(buildLivenessSection(options.worktreePath, options.assignmentId, options.worktreePath, { sandboxed: taskSandboxed }));
519
+ }
520
+ // pln#554 step 4 — working defaults (incremental commits + validation bar).
521
+ parts.push(buildWorkingDefaultsSection({ canCommit: taskBriefProfile ? dispatchCanCommit(taskBriefProfile) : true }));
471
522
  if (briefMode === 'full') {
472
523
  parts.push(buildProtocolSection({
473
524
  claimId: options.claimId,
@@ -476,7 +527,6 @@ export function generateDispatchBrief(options) {
476
527
  }));
477
528
  }
478
529
  // pln#528 — transport-aware addendum for sandboxed agents (see generateBrief).
479
- const taskBriefProfile = options.agent ? getCapabilityProfile(options.agent) : undefined;
480
530
  if (taskBriefProfile && !dispatchHasMcp(taskBriefProfile)) {
481
531
  parts.push('## ⚠ Transport: sandboxed run (no MCP, no commit)');
482
532
  parts.push('Your runtime is sandboxed — the brainclaw MCP server is NOT reachable and `git commit` is unavailable (.git is outside the sandbox root). Any `bclaw_*` MCP instruction above does NOT apply to you. Report your outcome via the FILE protocol only — it is authoritative for this run:');
@@ -679,7 +729,7 @@ export async function dispatch(options, cwd) {
679
729
  const invokeCmd = buildInvokeCommand(targetAgent, brief, { model: resolveModel(targetAgent, { override: options.model }) });
680
730
  if (invokeCmd) {
681
731
  const cmdPrefix = buildEnvPrefix(claimId);
682
- result.commands.push({ agent: targetAgent, lane: readyItem.lane, command: `${cmdPrefix}${invokeCmd.bashCommand}`, shell: process.platform === 'win32' ? 'cmd' : (invokeCmd.shell ? 'bash' : 'sh') });
732
+ result.commands.push({ agent: targetAgent, lane: readyItem.lane, plan_id: readyItem.plan.id, command: `${cmdPrefix}${invokeCmd.bashCommand}`, shell: process.platform === 'win32' ? 'cmd' : (invokeCmd.shell ? 'bash' : 'sh') });
683
733
  }
684
734
  const deliveryEntry = { agent: targetAgent, plan_id: readyItem.plan.id, message_id: '(dry-run)', lane: readyItem.lane, channel: 'inbox', claim_id: claimId };
685
735
  result.delivery_plan.push(deliveryEntry);
@@ -738,6 +788,7 @@ export async function dispatch(options, cwd) {
738
788
  result.commands.push({
739
789
  agent: targetAgent,
740
790
  lane: readyItem.lane,
791
+ plan_id: readyItem.plan.id,
741
792
  command: `${cmdPrefix}${invokeCmd.bashCommand}`,
742
793
  shell: process.platform === 'win32' ? 'cmd' : (invokeCmd.shell ? 'bash' : 'sh'),
743
794
  });
@@ -881,6 +932,7 @@ export async function dispatch(options, cwd) {
881
932
  status_reason: 'CLI spawn launched by dispatcher',
882
933
  tags: ['dispatch-run', ...(entry.lane ? [`lane:${entry.lane}`] : [])],
883
934
  }, cwd);
935
+ entry.run_id = run.id;
884
936
  transitionAgentRun(run.id, 'failed', {
885
937
  actor: options.dispatcherAgent,
886
938
  actor_id: options.dispatcherAgentId,
@@ -928,6 +980,7 @@ export async function dispatch(options, cwd) {
928
980
  status_reason: execResult.error,
929
981
  tags: ['dispatch-run', ...(entry.lane ? [`lane:${entry.lane}`] : [])],
930
982
  }, cwd);
983
+ entry.run_id = run.id;
931
984
  if (execResult.execution_status === 'delivered_and_started') {
932
985
  transitionAgentRun(run.id, 'launching', {
933
986
  actor: options.dispatcherAgent,
@@ -12,14 +12,15 @@
12
12
  * until later slices wire them in.
13
13
  */
14
14
  import path from 'node:path';
15
- import { loadState, persistState } from './state.js';
15
+ import { loadState, mutateState } from './state.js';
16
16
  import { archiveCandidate, listCandidates, loadCandidate, saveCandidate, } from './candidates.js';
17
17
  import { addCrossProjectLink, removeCrossProjectLink, resolveCrossProjectLinks, } from './cross-project.js';
18
- import { listClaims } from './claims.js';
18
+ import { listClaims, loadClaim, saveClaim } from './claims.js';
19
19
  import { listActionRequired } from './actions.js';
20
20
  import { deleteAssignment, listAssignments, loadAssignment, saveAssignment, transitionAssignment } from './assignments.js';
21
21
  import { listAgentRuns } from './agentruns.js';
22
22
  import { reconcileAgentRun, reconcileDeadPidRunningAgentRunAtRead, TERMINAL_STATUSES } from './agentrun-reconciler.js';
23
+ import { isObserverMode } from './observer-mode.js';
23
24
  import { deleteRuntimeNote, listRuntimeNotes, saveRuntimeNote, } from './runtime.js';
24
25
  import { createSequence, deleteSequence, listSequences, updateSequence, } from './sequence.js';
25
26
  import { createConstraint, createDecision, createTrap, } from './operations/memory-write.js';
@@ -102,6 +103,12 @@ export class InvalidTransitionError extends Error {
102
103
  */
103
104
  function loadAgentRunsWithReconciliation(cwd) {
104
105
  const runs = listAgentRuns(cwd);
106
+ // Observer mode (BRAINCLAW_OBSERVER=1) suppresses the lazy reconciliation
107
+ // pass. A dashboard reading agent_run records must never transition them —
108
+ // that loop drove the 2026-06-10 lock storm (every poll could mutate every
109
+ // non-terminal run, holding the mutation lock under each transition).
110
+ if (isObserverMode())
111
+ return runs;
105
112
  for (const run of runs) {
106
113
  if (run.status === 'running') {
107
114
  try {
@@ -441,6 +448,20 @@ export function updateEntity(name, id, patch, cwd) {
441
448
  saveAssignment(patched, cwd);
442
449
  return { entity: name, id };
443
450
  }
451
+ case 'claim': {
452
+ // sprint 1.5 — description + worktree_path (manual-worktree registration).
453
+ // Status changes still go through bclaw_transition / release flows.
454
+ let claim;
455
+ try {
456
+ claim = loadClaim(id, cwd);
457
+ }
458
+ catch {
459
+ throw new EntityNotFoundError(name, id);
460
+ }
461
+ const patched = { ...claim, ...patch };
462
+ saveClaim(patched, cwd);
463
+ return { entity: name, id };
464
+ }
444
465
  case 'candidate': {
445
466
  // Note: `candidate.type` is intentionally create-only (not in
446
467
  // candidate.updatable at entity-registry.ts) — no validation needed.
@@ -561,8 +582,9 @@ export function transitionEntity(name, id, to, cwd, _reason) {
561
582
  if (!spec.statusField) {
562
583
  throw new Error(`${name} has no lifecycle (statusField is undefined)`);
563
584
  }
585
+ const statusField = spec.statusField;
564
586
  const current = getEntity(name, id, cwd);
565
- const from = current[spec.statusField];
587
+ const from = current[statusField];
566
588
  if (!from) {
567
589
  throw new Error(`${name} '${id}' has no '${spec.statusField}' field set`);
568
590
  }
@@ -579,15 +601,15 @@ export function transitionEntity(name, id, to, cwd, _reason) {
579
601
  case 'decision':
580
602
  case 'constraint':
581
603
  case 'trap': {
582
- const state = loadState(cwd);
583
- const bucket = name === 'decision' ? state.recent_decisions
584
- : name === 'constraint' ? state.active_constraints
585
- : state.known_traps;
586
- const item = bucket.find((x) => x.id === id);
587
- if (!item)
588
- throw new EntityNotFoundError(name, id);
589
- item[spec.statusField] = to;
590
- persistState(state, cwd);
604
+ mutateState((state) => {
605
+ const bucket = name === 'decision' ? state.recent_decisions
606
+ : name === 'constraint' ? state.active_constraints
607
+ : state.known_traps;
608
+ const item = bucket.find((x) => x.id === id);
609
+ if (!item)
610
+ throw new EntityNotFoundError(name, id);
611
+ item[statusField] = to;
612
+ }, cwd);
591
613
  return { entity: name, id, from, to, side_effects: sideEffects };
592
614
  }
593
615
  case 'candidate': {
@@ -618,20 +640,19 @@ export function transitionEntity(name, id, to, cwd, _reason) {
618
640
  // ─── Helpers ──────────────────────────────────────────────────────────
619
641
  /**
620
642
  * Stamp provenance on a state-resident record (plan, decision, constraint, trap)
621
- * immediately after create. Writes one extra persistState call; acceptable for
622
- * v1 since create is infrequent compared to reads.
643
+ * immediately after create.
623
644
  */
624
645
  function stampProvenanceOnStateItem(name, id, provenance, cwd) {
625
- const state = loadState(cwd);
626
- const bucket = name === 'plan' ? state.plan_items
627
- : name === 'decision' ? state.recent_decisions
628
- : name === 'constraint' ? state.active_constraints
629
- : state.known_traps;
630
- const item = bucket.find((x) => x.id === id);
631
- if (!item)
632
- return;
633
- item.provenance = provenance;
634
- persistState(state, cwd);
646
+ mutateState((state) => {
647
+ const bucket = name === 'plan' ? state.plan_items
648
+ : name === 'decision' ? state.recent_decisions
649
+ : name === 'constraint' ? state.active_constraints
650
+ : state.known_traps;
651
+ const item = bucket.find((x) => x.id === id);
652
+ if (!item)
653
+ return;
654
+ item.provenance = provenance;
655
+ }, cwd);
635
656
  }
636
657
  function requireString(data, field) {
637
658
  const value = data[field];
@@ -44,7 +44,7 @@ const step = {
44
44
  name: 'step',
45
45
  shortLabelPrefix: 'stp',
46
46
  schema: PlanStepSchema,
47
- updatable: ['text', 'assignee'],
47
+ updatable: ['text', 'assignee', 'estimated_effort', 'actual_effort'],
48
48
  statusField: 'status',
49
49
  transitions: {
50
50
  todo: ['in_progress', 'blocked', 'done'],
@@ -63,7 +63,9 @@ const claim = {
63
63
  name: 'claim',
64
64
  shortLabelPrefix: 'clm',
65
65
  schema: ClaimSchema,
66
- updatable: ['description'],
66
+ // worktree_path: sprint 1.5 — coordinators register manual worktrees (or fix
67
+ // stale paths) so harvest/dispatch_status can resolve LANE-RESULT locations.
68
+ updatable: ['description', 'worktree_path'],
67
69
  statusField: 'status',
68
70
  transitions: {
69
71
  active: ['released', 'stale'],
@@ -107,7 +109,16 @@ const decision = {
107
109
  name: 'decision',
108
110
  shortLabelPrefix: 'dec',
109
111
  schema: DecisionSchema,
110
- updatable: ['text', 'tags', 'outcome', 'scope', 'related_paths', 'verified_at', 'verify_cmd'],
112
+ updatable: [
113
+ 'text', 'tags', 'outcome', 'scope', 'related_paths', 'verified_at', 'verify_cmd',
114
+ // pln#544 lifecycle (touched via memory-lifecycle.ts recordMemoryEvent;
115
+ // exposing them here keeps bclaw_update straight-through for tests and
116
+ // operator backfills).
117
+ 'last_confirmed_at', 'last_infirmed_at',
118
+ 'confirmation_count', 'infirmation_count',
119
+ 'saved_me_count', 'misled_me_count',
120
+ 'confirmations',
121
+ ],
111
122
  statusField: 'outcome',
112
123
  transitions: {
113
124
  pending: ['approved', 'rejected', 'deferred'],
@@ -121,7 +132,14 @@ const constraint = {
121
132
  name: 'constraint',
122
133
  shortLabelPrefix: 'cst',
123
134
  schema: ConstraintSchema,
124
- updatable: ['text', 'tags', 'category', 'scope', 'related_paths', 'expires_at'],
135
+ updatable: [
136
+ 'text', 'tags', 'category', 'scope', 'related_paths', 'expires_at',
137
+ // pln#544 lifecycle — see decision.updatable.
138
+ 'last_confirmed_at', 'last_infirmed_at',
139
+ 'confirmation_count', 'infirmation_count',
140
+ 'saved_me_count', 'misled_me_count',
141
+ 'confirmations',
142
+ ],
125
143
  statusField: 'status',
126
144
  transitions: {
127
145
  active: ['resolved', 'expired'],
@@ -137,7 +155,15 @@ const trap = {
137
155
  name: 'trap',
138
156
  shortLabelPrefix: 'trp',
139
157
  schema: TrapSchema,
140
- updatable: ['text', 'tags', 'severity', 'scope', 'related_paths', 'expires_at', 'platform_scope', 'verified_at', 'verify_cmd'],
158
+ updatable: [
159
+ 'text', 'tags', 'severity', 'scope', 'related_paths', 'expires_at', 'platform_scope',
160
+ 'verified_at', 'verify_cmd',
161
+ // pln#544 lifecycle — see decision.updatable.
162
+ 'last_confirmed_at', 'last_infirmed_at',
163
+ 'confirmation_count', 'infirmation_count',
164
+ 'saved_me_count', 'misled_me_count',
165
+ 'confirmations',
166
+ ],
141
167
  statusField: 'status',
142
168
  transitions: {
143
169
  active: ['resolved', 'expired'],
@@ -3,15 +3,18 @@ import path from 'node:path';
3
3
  import { memoryDir } from './io.js';
4
4
  import { nowISO } from './ids.js';
5
5
  import { logger } from './logger.js';
6
+ import { isObserverMode } from './observer-mode.js';
7
+ import { appendJournalRecords, resolveJournalMode } from './events/journal.js';
8
+ import { REGISTRY_POST_IMAGE_ITEM_TYPES } from './events/registry-post-image.js';
6
9
  const EVENT_LOG_FILE = 'events.jsonl';
7
10
  const CURSORS_DIR = '.cursors';
8
- // --- Writer ---
9
- export function appendEvent(event, cwd) {
11
+ export function appendEvent(event, cwd, options = {}) {
10
12
  try {
11
13
  const full = {
12
14
  ts: event.ts ?? nowISO(),
13
15
  agent: event.agent ?? 'unknown',
14
16
  agent_id: event.agent_id,
17
+ session_id: event.session_id ?? (process.env.BRAINCLAW_SESSION_ID?.trim() || undefined),
15
18
  user: event.user ?? process.env.USER ?? process.env.USERNAME,
16
19
  action: event.action,
17
20
  item_type: event.item_type,
@@ -25,6 +28,56 @@ export function appendEvent(event, cwd) {
25
28
  catch (err) {
26
29
  logger.debug('Failed to write event log entry:', err);
27
30
  }
31
+ if (options.journalDualWrite !== false) {
32
+ dualWriteToJournal(event, cwd);
33
+ }
34
+ }
35
+ /**
36
+ * v2 journal dual-write (pln#543 step 2). Mirrors every v1 emission into
37
+ * the segmented journal when BRAINCLAW_JOURNAL_MODE=dual; a no-op when off.
38
+ * Mapping per spec §2.1.1: the coarse `update/upgrade/rollback : state`
39
+ * store event becomes a `journal_note` kind `store_marker` (the per-entity
40
+ * events it stands for arrive with step 3 dirty-tracking).
41
+ */
42
+ function dualWriteToJournal(event, cwd) {
43
+ try {
44
+ if (resolveJournalMode(cwd) === 'off')
45
+ return;
46
+ const base = {
47
+ agent: event.agent,
48
+ agent_id: event.agent_id,
49
+ session_id: event.session_id,
50
+ user: event.user,
51
+ summary: event.summary,
52
+ ts: event.ts,
53
+ };
54
+ if (event.item_type === 'state') {
55
+ appendJournalRecords([{
56
+ ...base,
57
+ action: 'journal_note',
58
+ item_type: 'journal',
59
+ payload: { kind: 'store_marker', op: event.action, detail: event.summary },
60
+ }], cwd);
61
+ return;
62
+ }
63
+ // pln#568 — registry/coordination families now journal full entity-state
64
+ // post-images on their persist chokepoint (emitRegistryPostImage). Their
65
+ // legacy envelope-only dual-write here would be redundant noise (a
66
+ // registry-lifecycle record materialize ignores), so suppress it: in the v2
67
+ // journal these families appear ONLY as post-images. events.jsonl (above)
68
+ // still records the v1 lifecycle event for existing consumers.
69
+ if (REGISTRY_POST_IMAGE_ITEM_TYPES.has(event.item_type))
70
+ return;
71
+ appendJournalRecords([{
72
+ ...base,
73
+ action: event.action,
74
+ item_type: event.item_type,
75
+ item_id: event.item_id,
76
+ }], cwd);
77
+ }
78
+ catch (err) {
79
+ logger.debug('journal dual-write skipped:', err);
80
+ }
28
81
  }
29
82
  // --- Reader ---
30
83
  export function readAllEvents(cwd) {
@@ -43,39 +96,96 @@ export function readAllEvents(cwd) {
43
96
  }
44
97
  return events;
45
98
  }
99
+ function normalizeReader(reader) {
100
+ return typeof reader === 'string' ? { agent: reader } : reader;
101
+ }
46
102
  function cursorsDir(cwd) {
47
103
  return path.join(memoryDir(cwd), CURSORS_DIR);
48
104
  }
49
- function cursorPath(agent, cwd) {
50
- return path.join(cursorsDir(cwd), `${agent}.json`);
105
+ /** Cursor files are keyed by session_id when present, else by agent name. */
106
+ function cursorKey(reader) {
107
+ return reader.session_id?.trim() || reader.agent;
51
108
  }
52
- function loadCursor(agent, cwd) {
53
- const fp = cursorPath(agent, cwd);
54
- if (!fs.existsSync(fp))
55
- return { offset: 0, last_read: '' };
56
- try {
57
- return JSON.parse(fs.readFileSync(fp, 'utf-8'));
109
+ function cursorPath(key, cwd) {
110
+ return path.join(cursorsDir(cwd), `${key}.json`);
111
+ }
112
+ function loadCursor(reader, cwd) {
113
+ const fp = cursorPath(cursorKey(reader), cwd);
114
+ if (fs.existsSync(fp)) {
115
+ try {
116
+ return JSON.parse(fs.readFileSync(fp, 'utf-8'));
117
+ }
118
+ catch {
119
+ return { offset: 0, last_read: '' };
120
+ }
58
121
  }
59
- catch {
60
- return { offset: 0, last_read: '' };
122
+ // name→instance migration: a session-keyed cursor that does not exist yet
123
+ // seeds from the legacy name-keyed cursor, so an upgraded instance does not
124
+ // replay the whole log. Cursors are caches — worst case is a re-read.
125
+ if (reader.session_id?.trim()) {
126
+ const legacy = cursorPath(reader.agent, cwd);
127
+ if (fs.existsSync(legacy)) {
128
+ try {
129
+ return JSON.parse(fs.readFileSync(legacy, 'utf-8'));
130
+ }
131
+ catch { /* fall through to fresh cursor */ }
132
+ }
61
133
  }
134
+ return { offset: 0, last_read: '' };
62
135
  }
63
- function saveCursor(agent, cursor, cwd) {
136
+ function saveCursor(reader, cursor, cwd) {
64
137
  const dir = cursorsDir(cwd);
65
138
  if (!fs.existsSync(dir)) {
66
139
  fs.mkdirSync(dir, { recursive: true });
67
140
  }
68
- fs.writeFileSync(cursorPath(agent, cwd), JSON.stringify(cursor), 'utf-8');
141
+ fs.writeFileSync(cursorPath(cursorKey(reader), cwd), JSON.stringify(cursor), 'utf-8');
142
+ }
143
+ /**
144
+ * True when this reader already has a cursor — session-keyed, or the legacy
145
+ * name-keyed cursor a session reader would migrate from. Absence means first
146
+ * contact: the reader has never consumed this store's event log.
147
+ */
148
+ export function hasEventCursor(reader, cwd) {
149
+ const effectiveReader = normalizeReader(reader);
150
+ if (fs.existsSync(cursorPath(cursorKey(effectiveReader), cwd)))
151
+ return true;
152
+ if (effectiveReader.session_id?.trim()) {
153
+ return fs.existsSync(cursorPath(effectiveReader.agent, cwd));
154
+ }
155
+ return false;
156
+ }
157
+ /**
158
+ * Seed the reader's cursor at the current end of the event log WITHOUT
159
+ * reading it. First-contact path: a fresh agent on a mature store must not
160
+ * replay the whole history (its one chance to triage would be consumed by
161
+ * noise) — the arrival digest informs instead, and the diff becomes
162
+ * incremental from here. Returns the byte offset that was sealed.
163
+ */
164
+ export function seedCursorToEnd(reader, cwd) {
165
+ const effectiveReader = normalizeReader(reader);
166
+ const logPath = eventLogPath(cwd);
167
+ let size = 0;
168
+ try {
169
+ size = fs.statSync(logPath).size;
170
+ }
171
+ catch { /* missing log → offset 0 */ }
172
+ saveCursor(effectiveReader, { offset: size, last_read: nowISO() }, cwd);
173
+ return size;
69
174
  }
70
175
  /**
71
- * Read events unseen by this agent since their last read.
176
+ * Read events unseen by this reader since their last read.
72
177
  * Updates the cursor after reading.
178
+ *
179
+ * Self-exclusion is by SESSION when both sides carry one (pln#562 step 4):
180
+ * an instance skips only its own events, not those of a same-named sibling.
181
+ * Events or readers without session info fall back to name exclusion.
73
182
  */
74
- export function readUnseenEvents(agent, cwd) {
183
+ export function readUnseenEvents(reader, cwd) {
184
+ const effectiveReader = normalizeReader(reader);
75
185
  const logPath = eventLogPath(cwd);
76
186
  if (!fs.existsSync(logPath))
77
187
  return [];
78
- const cursor = loadCursor(agent, cwd);
188
+ const cursor = loadCursor(effectiveReader, cwd);
79
189
  const stat = fs.statSync(logPath);
80
190
  if (stat.size <= cursor.offset)
81
191
  return [];
@@ -90,8 +200,10 @@ export function readUnseenEvents(agent, cwd) {
90
200
  for (const line of lines) {
91
201
  try {
92
202
  const evt = JSON.parse(line);
93
- // Exclude events from self
94
- if (evt.agent !== agent) {
203
+ const isSelf = effectiveReader.session_id && evt.session_id
204
+ ? evt.session_id === effectiveReader.session_id
205
+ : evt.agent === effectiveReader.agent;
206
+ if (!isSelf) {
95
207
  events.push(evt);
96
208
  }
97
209
  }
@@ -99,8 +211,13 @@ export function readUnseenEvents(agent, cwd) {
99
211
  // skip
100
212
  }
101
213
  }
102
- // Update cursor
103
- saveCursor(agent, { offset: stat.size, last_read: nowISO() }, cwd);
214
+ // Update cursor. Observer mode (BRAINCLAW_OBSERVER=1) skips this — the
215
+ // dashboard impersonating an agent must not consume that agent's cursor
216
+ // (the 2026-06-10 leak where the extension drained Juan's claude-code
217
+ // unseen-events queue on every poll).
218
+ if (!isObserverMode()) {
219
+ saveCursor(effectiveReader, { offset: stat.size, last_read: nowISO() }, cwd);
220
+ }
104
221
  return events;
105
222
  }
106
223
  /**