osborn 0.9.278 → 0.9.280

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/dist/index.js CHANGED
@@ -34,16 +34,15 @@ import { createGunzip } from 'node:zlib';
34
34
  const __filename = fileURLToPath(import.meta.url);
35
35
  const __dirname = dirname(__filename);
36
36
  import { createPatch } from 'diff';
37
- import { loadConfig, getMcpServers, getEnabledMcpServerNames, getVoiceMode, getDirectConfig, listSessions, listAllClaudeSessions, invalidateSessionListCache, getMostRecentSessionId, sessionExists, getSessionSummary, getConversationHistory, ensureSessionWorkspace, getMcpServerStatusList, buildMcpServersForKeys, listWorkspaceArtifacts } from './config.js';
37
+ import { loadConfig, getMcpServers, getEnabledMcpServerNames, getVoiceMode, getDirectConfig, listSessions, listAllClaudeSessions, extractCwd, slugToPath, getClaudeProjectsDir, invalidateSessionListCache, getMostRecentSessionId, sessionExists, getSessionSummary, getConversationHistory, ensureSessionWorkspace, getMcpServerStatusList, buildMcpServersForKeys, listWorkspaceArtifacts } from './config.js';
38
38
  import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
39
39
  import { cleanupHousekeeping } from './housekeeping.js';
40
40
  import { createSTT, createTTS } from './voice-io.js';
41
41
  import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from './claude-llm.js';
42
42
  import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
43
- import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight } from './claude-auth.js';
44
- import { probeActiveProviderKey } from './key-health.js';
43
+ import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight, probeActiveProviderKey } from './claude-auth.js';
45
44
  import { statusManager } from './status-manager.js';
46
- import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd, pickConnectWorkingDir } from './session-switch.js';
45
+ import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd } from './session-switch.js';
47
46
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
48
47
  import { DIRECT_MODE_PROMPT } from './prompts.js';
49
48
  import { MCP_CATALOG } from './config.js';
@@ -283,12 +282,34 @@ let bugReportHook = null;
283
282
  // in the background without depending on main()'s closure directly.
284
283
  let codeServerStartHook = null;
285
284
  // ── Model-provider health (module scope — shared between startApiServer + main) ──
286
- // #87: the per-key self-test result for the ACTIVE fallback provider, written by
287
- // main()'s connect path (probeActiveProviderKey) and read by startApiServer's
288
- // GET /health so a dead/expired key surfaces as "No working model" instead of a
289
- // silent non-reply. Null until the async probe lands (or never, on the Claude
290
- // path / an ambiguous result) — never a fabricated verdict.
285
+ // #87: the tier the agent is really answering on + that tier's key self-test. Both
286
+ // ride GET /health, so the badge names the real model and a dead key surfaces as
287
+ // "No working model" instead of a silent non-reply. Null = not known yet (or an
288
+ // ambiguous probe) — never a fabricated verdict.
289
+ let agentActiveProvider = null;
291
290
  let agentKeyHealth = null;
291
+ /**
292
+ * House-tier key self-test (#87) for whichever tier is active, fire-and-forget so
293
+ * it costs the connect path nothing. A user's OWN Anthropic key is skipped — the
294
+ * SDK surfaces its failures directly. Always clears the previous tier's verdict
295
+ * first, so a tier swap cannot leave a stale "No working model" on screen.
296
+ */
297
+ function startKeyHealthProbe() {
298
+ const provider = agentActiveProvider;
299
+ agentKeyHealth = null;
300
+ if (provider !== 'zai' && provider !== 'openrouter')
301
+ return;
302
+ void probeActiveProviderKey(provider)
303
+ .then((entry) => {
304
+ // The tier may have changed while this 8s probe was in flight (a sign-in
305
+ // mid-session) — a late verdict for the tier we left is not news.
306
+ if (!entry || agentActiveProvider !== provider)
307
+ return;
308
+ agentKeyHealth = [entry];
309
+ console.log(`${entry.status === 'ok' ? '✅' : '⚠️'} [key-health] ${entry.provider} self-test: ${entry.status}`);
310
+ })
311
+ .catch(() => { });
312
+ }
292
313
  // ── IDE reverse-proxy (module scope — shared between startApiServer + main) ──
293
314
  // code-server runs on 127.0.0.1:8300; the agent proxies it through its own
294
315
  // public HTTP server so no Cloudflare tunnel is needed.
@@ -763,9 +784,10 @@ function startApiServer(workingDir, port) {
763
784
  },
764
785
  // Whole-machine memory — what the OOM killer watches. All values in MB.
765
786
  memory: { totalMb, usedMb, availableMb, usedPct, processRssMb },
766
- // #87: per-key self-test for the active fallback provider. Absent until
767
- // the async probe lands (and omitted entirely on the Claude path); the
768
- // frontend surfaces "No working model" when every entry failed/expired.
787
+ // #87: the tier actually answering + its key self-test. `provider` is the
788
+ // LIVE reading — agent_ready fires once, so it goes stale the moment a
789
+ // mid-session sign-in swaps the tier.
790
+ ...(agentActiveProvider ? { provider: agentActiveProvider } : {}),
769
791
  ...(agentKeyHealth ? { keyHealth: agentKeyHealth } : {}),
770
792
  }));
771
793
  return;
@@ -3713,11 +3735,14 @@ async function main() {
3713
3735
  // Set by the agent_ready retry loop; a switch must stop it so a late
3714
3736
  // agent_ready (preSelectedSessionId = A) doesn't reset the UI back to A.
3715
3737
  let stopReadyRetries = null;
3738
+ // Connect AWAITS this, so keep every lookup cheap: no listAllClaudeSessions().
3716
3739
  function resolveCwdForSession(sessionId, hint) {
3717
3740
  return resolveSessionCwd(sessionId, hint, workingDir, {
3718
3741
  exists: (id, wd) => sessionExists(id, wd),
3719
- listCwd: async (id) => (await listAllClaudeSessions()).find(s => s.sessionId === id)?.cwd ?? null,
3720
- scanCwd: (id) => scanSlugCwd(id, join(homedir(), '.claude', 'projects'), { readdir: (d) => readdirSync(d), exists: (p) => existsSync(p) }),
3742
+ lookupCwd: (id) => scanSlugCwd(id, getClaudeProjectsDir(), {
3743
+ readdir: (d) => readdirSync(d), exists: (p) => existsSync(p),
3744
+ decodeSlug: (s) => slugToPath(s), readCwd: (p) => extractCwd(p),
3745
+ }),
3721
3746
  });
3722
3747
  }
3723
3748
  function findSlotKey(sessionId) {
@@ -5107,18 +5132,13 @@ async function main() {
5107
5132
  if (Number.isFinite(c) && c > 0)
5108
5133
  connectTiming.clickTs = c;
5109
5134
  }
5110
- // Working directory for this connection (resume-mismatch fix, #112).
5111
- //
5112
- // The client's workingDirectory is only a HINT. When a session is pre-
5113
- // selected, the agent is AUTHORITATIVE about where that session lives:
5114
- // resolve its real project dir (the only dir whose slug holds the
5115
- // session's JSONL) and boot there, so `--resume <id>` finds it instead of
5116
- // coming up in /workspace root — or silently as a different session —
5117
- // when the hint is stale or empty (e.g. a switch rewrote the URL without
5118
- // a cwd). resolveCwdForSession returns null only when the JSONL exists
5119
- // nowhere yet (fresh sprite / brand-new project), in which case the hint
5120
- // is honoured and created so the SDK spawn still has a valid cwd.
5121
- const wdHint = (metadata.workingDirectory && typeof metadata.workingDirectory === 'string' && metadata.workingDirectory.length > 0)
5135
+ // Working directory for this connection (resume-mismatch fix, #112). The
5136
+ // client's workingDirectory is only a HINT; for a pre-selected session the
5137
+ // agent is AUTHORITATIVE about where that session lives, so `--resume`
5138
+ // finds its JSONL instead of coming up in the workspace root — or as a
5139
+ // different session — on a stale or empty hint. null = the JSONL is
5140
+ // nowhere yet (fresh sprite / new project), so the hint stands.
5141
+ const wdHint = (typeof metadata.workingDirectory === 'string' && metadata.workingDirectory.length > 0)
5122
5142
  ? metadata.workingDirectory
5123
5143
  : null;
5124
5144
  let resolvedConnectCwd = null;
@@ -5128,19 +5148,17 @@ async function main() {
5128
5148
  }
5129
5149
  catch (e) {
5130
5150
  console.warn('⚠️ connect cwd resolve failed:', e instanceof Error ? e.message : e);
5131
- resolvedConnectCwd = null;
5132
5151
  }
5133
5152
  }
5134
- const connectWd = pickConnectWorkingDir({ preSelectedSessionId, resolved: resolvedConnectCwd, hint: wdHint, defaultDir: defaultWorkingDir });
5135
- // Recursive mkdirSync is a no-op when the dir already exists; only the
5136
- // hint path (new project / fresh sprite) needs creating — the resolved
5137
- // dir exists by construction, the default is the agent's own boot dir.
5138
- if (connectWd.createIfMissing && !existsSync(connectWd.dir)) {
5139
- mkdirSync(connectWd.dir, { recursive: true });
5140
- console.log(`📁 Created project directory: ${connectWd.dir}`);
5153
+ workingDir = resolvedConnectCwd || wdHint || defaultWorkingDir;
5154
+ // Only the HINT is ever created: a resolved cwd can come from an imported
5155
+ // session's JSONL and name another machine's path, and creating that tree
5156
+ // would boot the agent in an empty dir (scanSlugCwd won't either).
5157
+ if (workingDir === wdHint && !existsSync(workingDir)) {
5158
+ mkdirSync(workingDir, { recursive: true });
5159
+ console.log(`📁 Created project directory: ${workingDir}`);
5141
5160
  }
5142
- workingDir = connectWd.dir;
5143
- console.log(`📂 Working directory (${connectWd.source}): ${workingDir}`);
5161
+ console.log(`📂 Working directory: ${workingDir}`);
5144
5162
  }
5145
5163
  catch (err) {
5146
5164
  console.log('⚠️ Could not parse participant metadata, using config voiceMode:', voiceMode);
@@ -5181,35 +5199,11 @@ async function main() {
5181
5199
  // BEFORE session creation so the OpenRouter redirect env vars (tier 3) are
5182
5200
  // set before the first query() spawn inherits process.env. No-op for
5183
5201
  // tier-1 (real Claude login) and tier-2 (user's own ANTHROPIC_API_KEY).
5184
- // #87: it also RETURNS the provider it selected (claude / zai / openrouter /
5185
- // anthropic / none) — the single source of truth, since the tier is known at
5186
- // decision time. Drives agent_ready.provider so the model badge names the
5187
- // real model instead of the old hardcoded 'claude'.
5202
+ // #87: record WHICH tier it selected — that drives agent_ready.provider and
5203
+ // /health. The key self-test for it fires after session start.
5188
5204
  const activeProvider = applyAuthFallback();
5205
+ agentActiveProvider = activeProvider === 'none' ? null : activeProvider;
5189
5206
  console.log(`🧭 Active model provider: ${activeProvider}`);
5190
- // #87: HOUSE-tier key self-test. Presence of a key ≠ validity (the test
5191
- // account's z.ai key failed and its OpenRouter key had expired, yet the
5192
- // session showed "Listening" and never replied — the #70 symptom). Fire ONE
5193
- // tiny real request, fire-and-forget, AFTER the session starts below, so it
5194
- // adds ZERO latency to the connect path. Scoped to the house fallback tiers
5195
- // (zai / openrouter) — a user's OWN Anthropic key is their concern and the
5196
- // SDK surfaces its failures directly; we never ping it per connect. The
5197
- // result rides GET /health; a definitive failure surfaces "No working model"
5198
- // instead of a silent non-reply.
5199
- agentKeyHealth = null;
5200
- if (activeProvider === 'zai' || activeProvider === 'openrouter') {
5201
- void probeActiveProviderKey(activeProvider)
5202
- .then((entry) => {
5203
- if (!entry)
5204
- return;
5205
- agentKeyHealth = [entry];
5206
- if (entry.status === 'ok')
5207
- console.log(`✅ [key-health] ${entry.provider} self-test: ok`);
5208
- else
5209
- console.warn(`⚠️ [key-health] ${entry.provider} self-test: ${entry.status}`);
5210
- })
5211
- .catch(() => { });
5212
- }
5213
5207
  // Create session based on voice mode (from frontend or config)
5214
5208
  let session;
5215
5209
  let agent;
@@ -5286,6 +5280,8 @@ async function main() {
5286
5280
  }
5287
5281
  currentSession = session;
5288
5282
  currentAgent = agent; // Store for updateChatCtx() context injection
5283
+ // #87: the session is live — NOW run the house-tier key self-test.
5284
+ startKeyHealthProbe();
5289
5285
  // CLICK-TIME OVERLAP (default-ON; OSBORN_CONNECT_OVERLAP=off): for a resumed
5290
5286
  // session, kick the JSONL replay NOW (fire-and-forget) so it overlaps the
5291
5287
  // user getting situated + speaking — instead of paying it serially on the
@@ -5865,10 +5861,11 @@ async function main() {
5865
5861
  type: 'agent_ready',
5866
5862
  // #87: the REAL active provider (claude / zai / openrouter / anthropic),
5867
5863
  // not a hardcoded 'claude' — so the model badge is honest on a fallback
5868
- // session. 'none' (no model configured at all) is emitted as null so the
5869
- // badge stays neutral instead of rendering a literal "none" pill; that
5870
- // dead-end is surfaced by the Claude sign-in flow, not the badge.
5871
- provider: activeProvider === 'none' ? null : activeProvider,
5864
+ // session. Null when no model is configured at all, so the badge stays
5865
+ // neutral instead of rendering a literal "none" pill; that dead-end is
5866
+ // surfaced by the Claude sign-in flow. /health re-serves this live, which
5867
+ // is what keeps it true after a sign-in (agent_ready fires only once).
5868
+ provider: agentActiveProvider,
5872
5869
  voiceMode: sessionVoiceMode,
5873
5870
  hasRecentSession,
5874
5871
  recentSessionId,
@@ -6183,8 +6180,17 @@ async function main() {
6183
6180
  // Only when a fallback redirect was actually active: live persistent
6184
6181
  // sessions restart BEFORE their next turn (deferred — a streaming
6185
6182
  // turn finishes normally), resuming the same sessionId on Claude.
6186
- if (fallbackCleared)
6187
- requestAuthRestart();
6183
+ if (!fallbackCleared)
6184
+ return;
6185
+ // Publish the new tier and drop the dead one's verdict BEFORE the
6186
+ // respawn, or /health keeps serving {provider:'zai', status:'expired'}
6187
+ // and the UI claims "The session can't answer" while Claude answers
6188
+ // fine. fallbackCleared is only reachable once Claude auth really
6189
+ // exists (every other outcome of the flow rejects), including the
6190
+ // CLI/Keychain case that isClaudeAuthenticated() cannot see.
6191
+ agentActiveProvider = 'claude';
6192
+ startKeyHealthProbe();
6193
+ requestAuthRestart();
6188
6194
  });
6189
6195
  }
6190
6196
  }
@@ -47,7 +47,7 @@ export type MeetingRoster = MeetingAgentDef[];
47
47
  * coupling this leaf module to the LLM module — the runtime can override at
48
48
  * startup via setRoster(Object.keys(NAMED_AGENTS)).
49
49
  */
50
- export declare const DEFAULT_AGENT_NAMES: readonly ["osborn", "researcher", "reasoner", "writer", "planner", "reviewer", "tester"];
50
+ export declare const DEFAULT_AGENT_NAMES: readonly ["osborn", "researcher", "reasoner", "writer", "planner", "reviewer", "tester", "steward"];
51
51
  /** The orchestrator's canonical id — the main agent / "the bot" itself. An
52
52
  * utterance addressed to it is NOT routed to a Tier-2 worker (the orchestrator
53
53
  * already IS the turn's handler); only a NON-orchestrator target is routable. */
@@ -45,6 +45,7 @@ export const DEFAULT_AGENT_NAMES = [
45
45
  'planner',
46
46
  'reviewer',
47
47
  'tester',
48
+ 'steward',
48
49
  ];
49
50
  /** The orchestrator's canonical id — the main agent / "the bot" itself. An
50
51
  * utterance addressed to it is NOT routed to a Tier-2 worker (the orchestrator
@@ -111,13 +111,14 @@ THE SUB-AGENTS:
111
111
  · reasoner (Opus) — architecture decisions, complex tradeoffs, implementation planning. Read-only.
112
112
  · writer (Sonnet) — ALL file changes outside the workspace. The ONLY agent with write access outside the workspace.
113
113
  · tester (Sonnet) — TDD verifier. Dispatched IN PARALLEL with the writer: writes tests from the SPEC, blind to the writer's implementation. After the writer finishes, its tests are RUN against the new code (PASS/FAIL).
114
- · reviewer (Sonnet) — dispatched AFTER the writer completes: reads the diff and returns VERDICT: ACCEPT/REJECT.
115
- · NEVER use the SDK's built-in 'general-purpose' agent — it is not configured for this project and will hit write blocks. Always pick researcher, reasoner, writer, tester, or reviewer explicitly.
114
+ · steward (Sonnet) — owns duplication and regressions. On a plan: "does this already exist?" for each new thing. On the writer's diff (after the tests): refactors to reuse existing code, cuts what is not needed, checks callers; returns CLEAN / REFACTORED / BLOCK. It never reviews its own refactor.
115
+ · reviewer (Sonnet) — dispatched AFTER the writer (and the steward): reads the diff and returns VERDICT: ACCEPT/REJECT.
116
+ · NEVER use the SDK's built-in 'general-purpose' agent — it is not configured for this project and will hit write blocks. Always pick researcher, reasoner, planner, writer, tester, steward, or reviewer explicitly.
116
117
 
117
118
  DIVISION OF LABOR — follow this chain by default for any substantive or code task:
118
- researcher (gather facts) → after the researcher returns on a substantive question, dispatch the `reasoner` GATE to judge whether the research is complete and well-sourced (GATE: PASS / NEEDS-MORE); on NEEDS-MORE send the researcher back with the named gaps and re-gate (at most 2 rounds) → planner (step plan for multi-step work) → THEN dispatch writer AND tester IN THE SAME STEP, in parallel: the writer executes the plan while the tester writes tests from the spec, blind to the implementation (TDD) → after the writer returns, RUN the tester's tests against the new code AND dispatch the reviewer on the diff → on test-FAIL or REJECT, send the writer back to fix and re-verify (at most 2 rounds) → you synthesize and speak.
119
+ researcher (gather facts) → after the researcher returns on a substantive question, dispatch the `reasoner` GATE to judge whether the research is complete and well-sourced (GATE: PASS / NEEDS-MORE); on NEEDS-MORE send the researcher back with the named gaps and re-gate (at most 2 rounds) → planner (step plan for multi-step work) → steward on the plan (reuse map) → THEN dispatch writer AND tester IN THE SAME STEP, in parallel: the writer executes the plan while the tester writes tests from the spec, blind to the implementation (TDD) → after the writer returns, RUN the tester's tests against the new code → dispatch the steward on the diff (if it REFACTORED, run the tests again; on BLOCK, ask the user) → dispatch the reviewer on the final diff → on test-FAIL or REJECT, send the writer back to fix and re-verify (at most 2 rounds) → you synthesize and speak.
119
120
  For a quick factual lookup: researcher only → you speak (a trivial lookup needs no gate).
120
- NEVER skip verification — it is symmetric across both flows: the reasoner GATE after substantive research, and the tester+reviewer after a code change. Both are the same pattern (generate → an INDEPENDENT agent verifies before you rely on it). Dispatch the tester IN PARALLEL with the writer (not after) so tests are written independently of the code.
121
+ NEVER skip verification — it is symmetric across both flows: the reasoner GATE after substantive research, and the tester + steward + reviewer after a code change. Both are the same pattern (generate → an INDEPENDENT agent verifies before you rely on it). Dispatch the tester IN PARALLEL with the writer (not after) so tests are written independently of the code.
121
122
  You may OVERRIDE this chain at any time — stop a running agent, inject, or reorder — because you can see each task's live state. The chain is the default, not a cage.
122
123
  Surfacing findings and communicating to the user is YOUR job, not a sub-agent's.
123
124
  </turn-shape>
package/dist/prompts.js CHANGED
@@ -553,15 +553,15 @@ RECOMMENDATION (if applicable):
553
553
  <role>
554
554
  You are an orchestrator with specialist sub-agents. You verify everything via tools before stating it. You are thorough, parallel-capable, and source-disciplined.
555
555
 
556
- You have three named agents available via the Task tool:
556
+ Your named agents, via the Task tool (planner, tester, steward and reviewer appear in the chain below):
557
557
  · researcher — Sonnet, fast information gathering. Use for: reading multiple files, web research, finding patterns.
558
558
  · reasoner — Opus, deep analysis. Use for: architecture decisions, complex tradeoffs, implementation planning.
559
559
  · writer — Sonnet, file changes. Use for: ALL file creation, editing, modification. Verifies before and after changes.
560
560
 
561
561
  DIVISION OF LABOR — follow this chain by default for any substantive or code task:
562
- researcher (gather facts) → planner (write a step plan for multi-step work) → writer (execute the plan) → tester AND reviewer in parallel (verify the change) → you synthesize and speak.
562
+ researcher (gather facts) → planner (write a step plan for multi-step work) → steward on the plan ("does this already exist?") → writer (execute the plan) + tester → steward on the diff (reuse existing code, cut what is not needed, check callers) → re-run tests if the steward refactored → reviewer → you synthesize and speak.
563
563
  For a quick factual query: researcher only → you speak.
564
- NEVER skip tester and reviewer after a code change.
564
+ NEVER skip tester, steward and reviewer after a code change. The steward never reviews its own refactor: the reviewer always runs after it.
565
565
  You may OVERRIDE this chain at any time — stop a running agent, inject a step, or reorder — because you can see each task's live state. The chain is the default, not a cage.
566
566
  Surfacing findings and communicating to the user is YOUR job, not a sub-agent's.
567
567
 
@@ -78,15 +78,13 @@ export declare function planSwitch(decision: SessionSwitchDecision, ctx: SwitchP
78
78
  export interface SessionCwdDeps {
79
79
  /** sessionExists(id, projectPath) from config.ts. */
80
80
  exists: (sessionId: string, cwd: string) => boolean;
81
- /** Routing cwd from listAllClaudeSessions() (slug-derived), or null. */
82
- listCwd: (sessionId: string) => Promise<string | null | undefined>;
83
- /** Last resort: find <id>.jsonl in any project slug and decode its cwd. */
84
- scanCwd: (sessionId: string) => Promise<string | null | undefined>;
81
+ /** Find ONE session's project dir (scanSlugCwd), or null. */
82
+ lookupCwd: (sessionId: string) => Promise<string | null | undefined>;
85
83
  }
86
84
  /**
87
85
  * The project directory a session's JSONL resolves under (what `--resume`
88
86
  * needs as cwd): the client's hint if the session really lives there, else
89
- * the current dir, else the session list's routing cwd, else a slug scan.
87
+ * the current dir, else a one-session scan of the project slugs.
90
88
  * null = the session does not exist ("Session not found"). A candidate is
91
89
  * only returned after `exists()` confirms it.
92
90
  */
@@ -122,38 +120,6 @@ export declare function warmParkKey(llm: {
122
120
  * otherwise the agent's boot dir (today's behaviour). Never trusts the param.
123
121
  */
124
122
  export declare function sessionMessagesDir(sessionId: string, requested: string | null | undefined, bootDir: string, exists: (sessionId: string, cwd: string) => boolean): string;
125
- /**
126
- * Working directory the agent boots a CONNECTION in (connect-time, #112).
127
- *
128
- * The resume mismatch bug: a client opens `/chat?session=A&workingDirectory=X`,
129
- * but X is stale/empty (a switch rewrote the URL without a cwd, or the hint was
130
- * never the session's real project). Trusting the raw hint booted the agent in
131
- * the wrong dir — often `/workspace` root — so `--resume A` never found A's
132
- * JSONL and the session silently came up as the wrong one with a generic
133
- * "Workspace" chip. The fix makes the agent AUTHORITATIVE about a pre-selected
134
- * session's cwd: its RESOLVED project dir wins over the client hint.
135
- *
136
- * `resolved` is resolveSessionCwd(preSelectedSessionId, hint, …) — the only dir
137
- * where A's JSONL actually exists (null = found nowhere yet). Pure: the caller
138
- * does the I/O (resolveSessionCwd) and the mkdir when `createIfMissing`.
139
- *
140
- * - pre-selected + resolved → the resolved dir (already exists, no mkdir).
141
- * - pre-selected + unresolved + hint → the hint, created (fresh sprite / new
142
- * project whose JSONL isn't on disk yet, so --resume can still attach there).
143
- * - pre-selected + nothing → the default boot dir.
144
- * - no pre-selected + hint → the hint, created (new project).
145
- * - no pre-selected + nothing → the default boot dir.
146
- */
147
- export declare function pickConnectWorkingDir(args: {
148
- preSelectedSessionId: string | null | undefined;
149
- resolved: string | null | undefined;
150
- hint: string | null | undefined;
151
- defaultDir: string;
152
- }): {
153
- dir: string;
154
- createIfMissing: boolean;
155
- source: 'resolved' | 'hint' | 'default';
156
- };
157
123
  /**
158
124
  * Single-flight guard for performSessionSwitch. Only the critical section
159
125
  * (teardown + arm + session_switched) holds the guard; `after` (the spoken
@@ -176,8 +142,16 @@ export declare function createSwitchGuard(): {
176
142
  * and decoding the slug (the same recovery resume_session has always used).
177
143
  * The decoding is lossy, so only a decoded path that EXISTS is returned — the
178
144
  * switch executor never creates directories for scan-derived paths.
145
+ *
146
+ * The `readCwd` fallback gets that same existence check, because an imported
147
+ * session's JSONL can record a cwd from another machine while sessionExists()
148
+ * only looks at the slug.
179
149
  */
180
150
  export declare function scanSlugCwd(sessionId: string, projectsDir: string, fsx: {
181
151
  readdir: (dir: string) => string[];
182
152
  exists: (path: string) => boolean;
153
+ /** slugToPath(slug) from config.ts: the lossy reverse, '' when it misses. */
154
+ decodeSlug: (slug: string) => string;
155
+ /** extractCwd(filePath) from config.ts: the cwd the JSONL itself records. */
156
+ readCwd: (filePath: string) => Promise<string | null | undefined>;
183
157
  }): Promise<string | null>;
@@ -67,7 +67,7 @@ export function planSwitch(decision, ctx) {
67
67
  /**
68
68
  * The project directory a session's JSONL resolves under (what `--resume`
69
69
  * needs as cwd): the client's hint if the session really lives there, else
70
- * the current dir, else the session list's routing cwd, else a slug scan.
70
+ * the current dir, else a one-session scan of the project slugs.
71
71
  * null = the session does not exist ("Session not found"). A candidate is
72
72
  * only returned after `exists()` confirms it.
73
73
  */
@@ -78,18 +78,14 @@ export async function resolveSessionCwd(sessionId, hint, currentDir, deps) {
78
78
  if (c && deps.exists(sessionId, c))
79
79
  return c;
80
80
  }
81
- for (const lookup of [deps.listCwd, deps.scanCwd]) {
82
- let c = null;
83
- try {
84
- c = await lookup(sessionId);
85
- }
86
- catch {
87
- c = null;
88
- }
89
- if (c && deps.exists(sessionId, c))
90
- return c;
81
+ let c = null;
82
+ try {
83
+ c = await deps.lookupCwd(sessionId);
91
84
  }
92
- return null;
85
+ catch {
86
+ c = null;
87
+ }
88
+ return c && deps.exists(sessionId, c) ? c : null;
93
89
  }
94
90
  /**
95
91
  * chatCtx rebuild on switch (4.13): keep the agent's non-conversation items
@@ -127,42 +123,6 @@ export function sessionMessagesDir(sessionId, requested, bootDir, exists) {
127
123
  }
128
124
  return bootDir;
129
125
  }
130
- /**
131
- * Working directory the agent boots a CONNECTION in (connect-time, #112).
132
- *
133
- * The resume mismatch bug: a client opens `/chat?session=A&workingDirectory=X`,
134
- * but X is stale/empty (a switch rewrote the URL without a cwd, or the hint was
135
- * never the session's real project). Trusting the raw hint booted the agent in
136
- * the wrong dir — often `/workspace` root — so `--resume A` never found A's
137
- * JSONL and the session silently came up as the wrong one with a generic
138
- * "Workspace" chip. The fix makes the agent AUTHORITATIVE about a pre-selected
139
- * session's cwd: its RESOLVED project dir wins over the client hint.
140
- *
141
- * `resolved` is resolveSessionCwd(preSelectedSessionId, hint, …) — the only dir
142
- * where A's JSONL actually exists (null = found nowhere yet). Pure: the caller
143
- * does the I/O (resolveSessionCwd) and the mkdir when `createIfMissing`.
144
- *
145
- * - pre-selected + resolved → the resolved dir (already exists, no mkdir).
146
- * - pre-selected + unresolved + hint → the hint, created (fresh sprite / new
147
- * project whose JSONL isn't on disk yet, so --resume can still attach there).
148
- * - pre-selected + nothing → the default boot dir.
149
- * - no pre-selected + hint → the hint, created (new project).
150
- * - no pre-selected + nothing → the default boot dir.
151
- */
152
- export function pickConnectWorkingDir(args) {
153
- const hint = norm(args.hint);
154
- if (norm(args.preSelectedSessionId)) {
155
- const resolved = norm(args.resolved);
156
- if (resolved)
157
- return { dir: resolved, createIfMissing: false, source: 'resolved' };
158
- if (hint)
159
- return { dir: hint, createIfMissing: true, source: 'hint' };
160
- return { dir: args.defaultDir, createIfMissing: false, source: 'default' };
161
- }
162
- if (hint)
163
- return { dir: hint, createIfMissing: true, source: 'hint' };
164
- return { dir: args.defaultDir, createIfMissing: false, source: 'default' };
165
- }
166
126
  // ── Review minors ────────────────────────────────────────────────────────────
167
127
  /**
168
128
  * Single-flight guard for performSessionSwitch. Only the critical section
@@ -202,6 +162,10 @@ export function createSwitchGuard() {
202
162
  * and decoding the slug (the same recovery resume_session has always used).
203
163
  * The decoding is lossy, so only a decoded path that EXISTS is returned — the
204
164
  * switch executor never creates directories for scan-derived paths.
165
+ *
166
+ * The `readCwd` fallback gets that same existence check, because an imported
167
+ * session's JSONL can record a cwd from another machine while sessionExists()
168
+ * only looks at the slug.
205
169
  */
206
170
  export async function scanSlugCwd(sessionId, projectsDir, fsx) {
207
171
  if (!sessionId || !fsx.exists(projectsDir))
@@ -213,12 +177,24 @@ export async function scanSlugCwd(sessionId, projectsDir, fsx) {
213
177
  catch {
214
178
  return null;
215
179
  }
180
+ let firstMatch = null;
216
181
  for (const slug of slugs) {
217
- if (!fsx.exists(`${projectsDir}/${slug}/${sessionId}.jsonl`))
182
+ const filePath = `${projectsDir}/${slug}/${sessionId}.jsonl`;
183
+ if (!fsx.exists(filePath))
218
184
  continue;
219
- const recovered = slug.replace(/^-/, '/').replace(/--/g, '/.').replace(/-/g, '/');
220
- if (recovered && recovered !== '/' && fsx.exists(recovered))
185
+ if (!firstMatch)
186
+ firstMatch = filePath;
187
+ const recovered = fsx.decodeSlug(slug);
188
+ if (recovered && recovered !== '/')
221
189
  return recovered;
222
190
  }
223
- return null;
191
+ if (!firstMatch)
192
+ return null;
193
+ try {
194
+ const recorded = await fsx.readCwd(firstMatch);
195
+ return recorded && fsx.exists(recorded) ? recorded : null;
196
+ }
197
+ catch {
198
+ return null;
199
+ }
224
200
  }
@@ -0,0 +1,17 @@
1
+ export type StewardMode = 'advise' | 'block' | 'off';
2
+ export type GitAction = 'commit' | 'push' | 'pr';
3
+ export declare const MARKER_FILE = "osborn-steward";
4
+ export declare const TREE_COMMAND: string;
5
+ export declare const SIGNOFF_COMMAND = "T=$(sh -c 'I=$(mktemp -u) && { GIT_INDEX_FILE=$I git read-tree HEAD 2>/dev/null || GIT_INDEX_FILE=$I git read-tree --empty; } && GIT_INDEX_FILE=$I git add -A && GIT_INDEX_FILE=$I git write-tree; S=$?; rm -f \"$I\"; exit $S') && echo \"$T\" > \"$(git rev-parse --git-dir)/osborn-steward\"";
6
+ export declare function stewardMode(env?: Record<string, string | undefined>): StewardMode;
7
+ /** The git action a shell command performs, and the directory it runs in (a leading `cd X &&` or `git -C X`). */
8
+ export declare function gitAction(cmd: string, cwd: string): {
9
+ action: GitAction;
10
+ dir: string;
11
+ } | null;
12
+ export type GateResult = {
13
+ decision: 'allow' | 'advise' | 'deny';
14
+ message?: string;
15
+ };
16
+ /** Check a Bash command against the steward sign-off. Never throws: an unreadable repo is allowed. */
17
+ export declare function stewardGate(cmd: string, cwd: string, mode?: StewardMode): Promise<GateResult>;
@@ -0,0 +1,75 @@
1
+ // Steward sign-off gate (#218). The steward agent records the tree it approved;
2
+ // a commit, push or PR whose tree differs is reported (advise) or refused (block).
3
+ // The marker is a git TREE id, so it covers the content, not a commit sha that
4
+ // does not exist yet when the steward runs (it runs before the commit).
5
+ // Scope: the Osborn agent's own sessions. This repo's dev tooling has its own
6
+ // pre-PR gate (.claude/hooks/pre-pr-gate.py); the two do not share a marker.
7
+ import { execFile } from 'node:child_process';
8
+ import { existsSync } from 'node:fs';
9
+ import { readFile } from 'node:fs/promises';
10
+ import { isAbsolute, join, resolve } from 'node:path';
11
+ import { promisify } from 'node:util';
12
+ const run = promisify(execFile);
13
+ export const MARKER_FILE = 'osborn-steward';
14
+ // Tree of the working tree (tracked + untracked, .gitignore respected), built in a
15
+ // throwaway index so the real index is left alone. Works in a repo with no commits.
16
+ export const TREE_COMMAND = `I=$(mktemp -u) && { GIT_INDEX_FILE=$I git read-tree HEAD 2>/dev/null || GIT_INDEX_FILE=$I git read-tree --empty; } && ` +
17
+ `GIT_INDEX_FILE=$I git add -A && GIT_INDEX_FILE=$I git write-tree; S=$?; rm -f "$I"; exit $S`;
18
+ // Run in the repo root after a CLEAN or REFACTORED verdict.
19
+ export const SIGNOFF_COMMAND = `T=$(sh -c '${TREE_COMMAND}') && echo "$T" > "$(git rev-parse --git-dir)/${MARKER_FILE}"`;
20
+ export function stewardMode(env = process.env) {
21
+ const m = (env.OSBORN_STEWARD_MODE || 'advise').toLowerCase();
22
+ return m === 'block' || m === 'off' ? m : 'advise';
23
+ }
24
+ // Only a command in command position counts: not `grep "git push"` or `echo "... git commit"`.
25
+ const AT = String.raw `(?:^|[;&|(\n]\s*)`;
26
+ const GIT_OPTS = String.raw `(?:\s+-[Cc]\s+\S+)*`;
27
+ /** The git action a shell command performs, and the directory it runs in (a leading `cd X &&` or `git -C X`). */
28
+ export function gitAction(cmd, cwd) {
29
+ const action = new RegExp(`${AT}gh\\s+pr\\s+create\\b`).test(cmd) ? 'pr'
30
+ : new RegExp(`${AT}git${GIT_OPTS}\\s+push\\b`).test(cmd) ? 'push'
31
+ : new RegExp(`${AT}git${GIT_OPTS}\\s+commit\\b`).test(cmd) ? 'commit'
32
+ : null;
33
+ if (!action)
34
+ return null;
35
+ const cd = cmd.match(/^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*&&/);
36
+ const gitC = cmd.match(/\bgit\s+-C\s+("[^"]+"|'[^']+'|\S+)/);
37
+ const raw = (gitC?.[1] ?? cd?.[1])?.replace(/^["']|["']$/g, '');
38
+ const dir = raw ? (isAbsolute(raw) ? raw : resolve(cwd, raw.replace(/^~(?=\/|$)/, process.env.HOME || '~'))) : cwd;
39
+ return { action, dir };
40
+ }
41
+ const git = async (dir, args) => (await run('git', args, { cwd: dir })).stdout.trim();
42
+ const workingTree = async (dir) => (await run('sh', ['-c', TREE_COMMAND], { cwd: dir })).stdout.trim();
43
+ /** Is the content this action ships the content the steward signed off? */
44
+ async function signedFor(dir, action, marker) {
45
+ // A commit ships the working tree (`git add -A && git commit` is checked before the add runs).
46
+ if (action === 'commit')
47
+ return (await workingTree(dir)) === marker;
48
+ // Push / PR ship HEAD: signed if HEAD is exactly the signed tree, or nothing tracked
49
+ // changed since and the working tree still matches (untracked leftovers allowed).
50
+ if ((await git(dir, ['rev-parse', 'HEAD^{tree}'])) === marker)
51
+ return true;
52
+ const trackedClean = await run('git', ['diff', '--quiet', 'HEAD'], { cwd: dir }).then(() => true, () => false);
53
+ return trackedClean && (await workingTree(dir)) === marker;
54
+ }
55
+ /** Check a Bash command against the steward sign-off. Never throws: an unreadable repo is allowed. */
56
+ export async function stewardGate(cmd, cwd, mode = stewardMode()) {
57
+ if (mode === 'off')
58
+ return { decision: 'allow' };
59
+ const hit = gitAction(cmd, cwd);
60
+ if (!hit || !existsSync(hit.dir))
61
+ return { decision: 'allow' };
62
+ try {
63
+ const markerPath = join(await git(hit.dir, ['rev-parse', '--absolute-git-dir']), MARKER_FILE);
64
+ const marker = existsSync(markerPath) ? (await readFile(markerPath, 'utf8')).trim() : '';
65
+ if (marker && await signedFor(hit.dir, hit.action, marker))
66
+ return { decision: 'allow' };
67
+ }
68
+ catch {
69
+ return { decision: 'allow' };
70
+ }
71
+ const what = hit.action === 'pr' ? 'opening this PR' : `this ${hit.action}`;
72
+ const message = `The steward has not signed off on the code in ${what}: run the \`steward\` agent on the change first ` +
73
+ `(it records its sign-off for this exact content; any later edit needs a new sign-off).`;
74
+ return mode === 'block' ? { decision: 'deny', message } : { decision: 'advise', message };
75
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.278",
3
+ "version": "0.9.280",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {