Skip to content

Commit 0903c34

Browse files
committed
fix: resolve harness labels via ancestry and render explicit session names
OpenCode v1.17.0 removed OPENCODE_RUN_ID with no replacement, so OpenCode sessions degraded to the tty rung and were labeled 'unknown'. Explicit sessions (WEAVER_SESSION=alice) also displayed as 'unknown#hash' instead of the chosen name, contradicting the README. - registry: recognize OPENCODE_SESSION_ID (proposed upstream successor, anomalyco/opencode#12158) ahead of OPENCODE_RUN_ID (still set by ≤1.16.x) - label: when env signals say nothing, walk the process ancestry and match known harness executables (claude, opencode, codex, pi, cursor-agent) - render: explicit sessions display their chosen name everywhere (status, check, preflight, activity, dashboard); JSON outputs gain a 'name' field - docs: correct the identity-ladder pages to match
1 parent c87bfe4 commit 0903c34

10 files changed

Lines changed: 181 additions & 39 deletions

File tree

‎docs/src/content/docs/guides/multiple-agents.md‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,18 @@ Weaver resolves a stable per-session key in this order:
2323

2424
1. **Explicit override** — `--session <id>` or the `WEAVER_SESSION` env var. Always wins;
2525
useful for tests, headless runs, and any harness where the below don't work.
26-
2. **Harness-native session id** — a stable per-session environment variable. Confirmed:
27-
`CLAUDE_CODE_SESSION_ID` (Claude Code), `OPENCODE_RUN_ID` (OpenCode), `CODEX_THREAD_ID`
28-
(Codex). These are per-session UUIDs, so three Codex sessions get three distinct keys.
26+
2. **Harness-native session id** — a stable per-session environment variable. Known:
27+
`CLAUDE_CODE_SESSION_ID` (Claude Code), `CODEX_THREAD_ID` (Codex), and for OpenCode
28+
`OPENCODE_SESSION_ID` or `OPENCODE_RUN_ID` (set by OpenCode ≤1.16.x; v1.17.0 removed it,
29+
so newer OpenCode sessions resolve via the terminal instead). These are per-session
30+
UUIDs, so three Codex sessions get three distinct keys.
2931
3. **Controlling terminal** — the session's TTY, found by walking the process tree (used when
3032
there's no session env var, e.g. Pi, or for a human running `weaver` directly).
3133

34+
The *displayed* harness name resolves separately: environment signals first, then known
35+
harness executables found while walking the process ancestry — so a harness that exposes no
36+
env vars to subprocesses (e.g. OpenCode ≥1.17) is still labeled correctly.
37+
3238
If none resolve, there's **no anonymous fallback**: observer reads still work, but
3339
session-mutating commands fail with a concise hint to set `WEAVER_SESSION`.
3440

‎docs/src/content/docs/guides/using-from-an-agent.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ top of every task without bloating your context.
9595
## Identity & sessions
9696

9797
Each session gets a stable key, resolved as: an explicit `WEAVER_SESSION` / `--session`
98-
override → a harness-native session id (e.g. `CLAUDE_CODE_SESSION_ID`, `OPENCODE_RUN_ID`,
99-
`CODEX_THREAD_ID`) → the controlling terminal. If none can be resolved, observer commands
98+
override → a harness-native session id (e.g. `CLAUDE_CODE_SESSION_ID`, `CODEX_THREAD_ID`)
99+
→ the controlling terminal. If none can be resolved, observer commands
100100
(`status`, `check`, …) still work, but mutating commands fail with a hint to set
101101
`WEAVER_SESSION`. Details: [Coordinating many agents](/weaver/guides/multiple-agents/).
102102

‎docs/src/content/docs/reference/architecture.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ amount of work, and exits. **No daemon, no server, no MCP.**
3131
## Identity ladder
3232

3333
A session's stable key is resolved as: **explicit** (`--session` / `WEAVER_SESSION`) →
34-
**harness-native session id** (`CLAUDE_CODE_SESSION_ID`, `OPENCODE_RUN_ID`, `CODEX_THREAD_ID`)
34+
**harness-native session id** (`CLAUDE_CODE_SESSION_ID`, `OPENCODE_SESSION_ID` /
35+
`OPENCODE_RUN_ID`, `CODEX_THREAD_ID`)
3536
→ **controlling TTY** (self or nearest ancestor). No anonymous fallback. See
3637
[Coordinating many agents](/weaver/guides/multiple-agents/).
3738

‎src/commands/activity.ts‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { flagBool } from "../args.ts";
22
import type { Ctx } from "../context.ts";
3-
import { ago } from "../render.ts";
3+
import { ago, sessionName } from "../render.ts";
44
import { themeFromCtx } from "../terminal/color.ts";
55

66
export function run(ctx: Ctx): number {
@@ -10,13 +10,16 @@ export function run(ctx: Ctx): number {
1010
if (flagBool(ctx.args, "json")) {
1111
ctx.out(
1212
JSON.stringify(
13-
rows.map((a) => ({
14-
kind: a.kind,
15-
target: a.target,
16-
summary: a.summary,
17-
by: ctx.store.getSession(a.sessionId)?.harness ?? null,
18-
tsMsAgo: ctx.now - a.ts,
19-
})),
13+
rows.map((a) => {
14+
const s = ctx.store.getSession(a.sessionId);
15+
return {
16+
kind: a.kind,
17+
target: a.target,
18+
summary: a.summary,
19+
by: s ? sessionName(s) : null,
20+
tsMsAgo: ctx.now - a.ts,
21+
};
22+
}),
2023
) + "\n",
2124
);
2225
return 0;
@@ -29,7 +32,7 @@ export function run(ctx: Ctx): number {
2932
for (const a of rows) {
3033
const s = ctx.store.getSession(a.sessionId);
3134
ctx.out(
32-
`${theme.dim(ago(ctx.now - a.ts).padStart(7))} ${theme.accent((s?.harness ?? "?").padEnd(11))} ${theme.kind(a.kind)} ${a.target ? theme.path(a.target) : ""}${a.summary ? ` ${theme.dim("—")} ${a.summary}` : ""}\n`,
35+
`${theme.dim(ago(ctx.now - a.ts).padStart(7))} ${theme.accent((s ? sessionName(s) : "?").padEnd(11))} ${theme.kind(a.kind)} ${a.target ? theme.path(a.target) : ""}${a.summary ? ` ${theme.dim("—")} ${a.summary}` : ""}\n`,
3336
);
3437
}
3538
return 0;

‎src/commands/preflight.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ import { flagBool, flagStr } from "../args.ts";
33
import type { ConflictHit } from "../conflict.ts";
44
import type { Ctx } from "../context.ts";
55
import { hasBroadClaim, type PreflightResult, type PreflightSeverity, runPreflight } from "../preflight.ts";
6-
import { ago, shortId } from "../render.ts";
6+
import { ago, sessionName, shortId, who } from "../render.ts";
77
import { normalizeTarget } from "../repo/paths.ts";
8-
import type { SessionRow } from "../store/store.ts";
98
import { type TerminalTheme, themeFromCtx } from "../terminal/color.ts";
109
import { terminalWidth, wrapWithPrefix } from "../terminal/format.ts";
1110
import { CliError } from "../validate.ts";
@@ -118,10 +117,6 @@ function shouldFail(severity: PreflightSeverity, failOn: FailOn): boolean {
118117
return severity === "hard" || severity === "soft";
119118
}
120119

121-
function who(session: SessionRow): string {
122-
return `${session.harness}#${shortId(session.id)}`;
123-
}
124-
125120
function hitSummary(hit: ConflictHit, now: number, theme: TerminalTheme): string {
126121
const broad = hasBroadClaim(hit) ? ` ${theme.warn("[broad]")}` : "";
127122
if (hit.claim) {
@@ -222,6 +217,7 @@ function jsonHit(hit: ConflictHit, now: number): unknown {
222217
return {
223218
session: {
224219
shortId: shortId(hit.session.id),
220+
name: sessionName(hit.session),
225221
harness: hit.session.harness,
226222
source: hit.session.idSource,
227223
intent: hit.session.intent,
@@ -275,6 +271,7 @@ function formatJson(result: PreflightResult, opts: RenderOpts, now: number): str
275271
stale: stale.map((c) => ({ path: c.path, tier: c.tier, hits: c.hits.map((h) => jsonHit(h, now)) })),
276272
unrelatedSessions: unrelatedSessions.map((s) => ({
277273
shortId: shortId(s.id),
274+
name: sessionName(s),
278275
harness: s.harness,
279276
source: s.idSource,
280277
intent: s.intent,

‎src/dashboard/page.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export const PAGE = `<!doctype html>
6969
const sessions = d.sessions || [];
7070
$("sessions").className = sessions.length ? "" : "empty";
7171
$("sessions").innerHTML = sessions.length ? sessions.map((s) =>
72-
'<div class="card"><div class="row"><span class="who">' + esc(s.harness) + '</span>' +
72+
'<div class="card"><div class="row"><span class="who">' + esc(s.name || s.harness) + '</span>' +
7373
'<span class="ago">' + ago(s.lastSeenMsAgo) + '</span></div>' +
7474
'<div class="intent">' + esc(s.intent || "(no stated intent)") + '</div>' +
7575
'<div class="meta">' + esc(s.source) + '</div></div>').join("") : "no active sessions";

‎src/identity/session.ts‎

Lines changed: 69 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
/**
2-
* Resolve "which session am I?" — the heart of Weaver, validated by the Phase 0 spike.
3-
* Ladder: explicit override → harness-native session id → controlling TTY (self → ancestry).
4-
* Never returns a shared anonymous key: callers that require identity fail gracefully.
2+
* Resolve "which session am I?" — the heart of Weaver.
3+
* Identity ladder: explicit override → harness-native session id → controlling TTY
4+
* (self → ancestry). Never returns a shared anonymous key: callers that require identity
5+
* fail gracefully.
6+
* The harness *label* resolves separately: env signals first, then known executable names
7+
* in the process ancestry — harness env vars are not a stable API (OpenCode set
8+
* OPENCODE_RUN_ID through v1.16.x and removed it in v1.17.0 with no replacement).
59
*/
610

711
import { execFileSync } from "node:child_process";
812
import os from "node:os";
13+
import path from "node:path";
914
import type { IdSource } from "../store/store.ts";
1015

1116
export interface Identity {
@@ -16,9 +21,14 @@ export interface Identity {
1621

1722
type Env = Record<string, string | undefined>;
1823

19-
/** Per-harness session-id env vars, confirmed in Phase 0. Order = precedence. */
24+
/**
25+
* Per-harness session-id env vars. Order = precedence. These come and go with harness
26+
* releases: OpenCode ≤1.16.x set OPENCODE_RUN_ID (removed in v1.17.0 with no replacement);
27+
* OPENCODE_SESSION_ID is its proposed successor (anomalyco/opencode#12158).
28+
*/
2029
export const HARNESS_SESSION_ENVS: ReadonlyArray<readonly [label: string, env: string]> = [
2130
["claude-code", "CLAUDE_CODE_SESSION_ID"],
31+
["opencode", "OPENCODE_SESSION_ID"],
2232
["opencode", "OPENCODE_RUN_ID"],
2333
["codex", "CODEX_THREAD_ID"],
2434
];
@@ -30,6 +40,8 @@ export interface ResolveOpts {
3040
host?: string;
3141
/** Injection seam for tests; defaults to the real `ps`-based lookup. */
3242
ttyResolver?: (pid: number) => { device: string; viaAncestry: boolean } | null;
43+
/** Injection seam for tests; defaults to the real `ps`-based ancestry walk. */
44+
harnessResolver?: (pid: number) => string | null;
3345
}
3446

3547
function parseSessionArg(argv: string[]): string | undefined {
@@ -51,6 +63,46 @@ function detectLabel(env: Env): string {
5163

5264
const isRealTty = (t: string): boolean => !!t && !/^\?+$/.test(t);
5365

66+
/** Executable basenames that identify a harness when seen in the process ancestry. */
67+
const HARNESS_PROCESS_NAMES: ReadonlyMap<string, string> = new Map([
68+
["claude", "claude-code"],
69+
["opencode", "opencode"],
70+
["codex", "codex"],
71+
["pi", "pi"],
72+
["cursor-agent", "cursor"],
73+
]);
74+
75+
/**
76+
* Walk the process ancestry looking for a known harness executable. Labels harnesses that
77+
* expose no env signal to subprocesses (e.g. OpenCode ≥1.17). Label only — never identity.
78+
*/
79+
export function detectHarnessFromAncestry(pid: number): string | null {
80+
const read = (p: number): { ppid: number; comm: string } | null => {
81+
try {
82+
const raw = execFileSync("ps", ["-o", "ppid=,comm=", "-p", String(p)], {
83+
stdio: ["ignore", "pipe", "ignore"],
84+
})
85+
.toString()
86+
.trim();
87+
const m = /^(\d+)\s+(.*)$/.exec(raw);
88+
return m ? { ppid: Number(m[1]), comm: m[2] ?? "" } : null;
89+
} catch {
90+
return null;
91+
}
92+
};
93+
94+
let cur = pid;
95+
for (let i = 0; i < 8; i++) {
96+
const row = read(cur);
97+
if (!row) return null;
98+
const label = HARNESS_PROCESS_NAMES.get(path.basename(row.comm).toLowerCase());
99+
if (label) return label;
100+
if (!row.ppid || row.ppid <= 1) return null;
101+
cur = row.ppid;
102+
}
103+
return null;
104+
}
105+
54106
/** Controlling terminal of the process, then its nearest ancestor. Returns null if none. */
55107
export function resolveTtyDevice(pid: number): { device: string; viaAncestry: boolean } | null {
56108
const ps = (p: number, field: string): string => {
@@ -83,21 +135,28 @@ export function resolveIdentity(opts: ResolveOpts = {}): Identity | null {
83135
const env = opts.env ?? (process.env as Env);
84136
const host = opts.host ?? os.hostname();
85137
const argv = opts.argv ?? process.argv.slice(2);
138+
const pid = opts.pid ?? process.pid;
139+
140+
// Env signals first; harness executables in the ancestry when the env says nothing.
141+
const label = (): string => {
142+
const fromEnv = detectLabel(env);
143+
if (fromEnv !== "unknown") return fromEnv;
144+
return (opts.harnessResolver ?? detectHarnessFromAncestry)(pid) ?? "unknown";
145+
};
86146

87147
// 1. explicit override
88148
const explicit = (parseSessionArg(argv) ?? env.WEAVER_SESSION)?.trim();
89-
if (explicit) return { key: `explicit:${explicit}@${host}`, source: "explicit", label: detectLabel(env) };
149+
if (explicit) return { key: `explicit:${explicit}@${host}`, source: "explicit", label: label() };
90150

91151
// 2. harness-native session id (most reliable on the tool-call path)
92-
for (const [label, key] of HARNESS_SESSION_ENVS) {
152+
for (const [harness, key] of HARNESS_SESSION_ENVS) {
93153
const value = env[key];
94-
if (value) return { key: `harness:${label}:${value}@${host}`, source: "harness", label };
154+
if (value) return { key: `harness:${harness}:${value}@${host}`, source: "harness", label: harness };
95155
}
96156

97157
// 3. controlling TTY (self → nearest ancestor)
98-
const tty = (opts.ttyResolver ?? resolveTtyDevice)(opts.pid ?? process.pid);
99-
if (tty)
100-
return { key: `tty:${tty.device}@${host}`, source: tty.viaAncestry ? "ancestry" : "tty", label: detectLabel(env) };
158+
const tty = (opts.ttyResolver ?? resolveTtyDevice)(pid);
159+
if (tty) return { key: `tty:${tty.device}@${host}`, source: tty.viaAncestry ? "ancestry" : "tty", label: label() };
101160

102161
// 4. none — caller decides (observer reads ok; mutating commands fail with a hint)
103162
return null;

‎src/render.ts‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,22 @@ interface FormatOptions {
3535
const NOTE_WIDTH = 100;
3636
const NOTE_CONTINUATION_INDENT = " ";
3737

38-
function who(s: SessionRow): string {
39-
return `${s.harness}#${shortId(s.id)}`;
38+
type SessionLike = Pick<SessionRow, "id" | "harness" | "idSource">;
39+
40+
/** Explicit sessions display the name the caller chose (`WEAVER_SESSION=alice` → "alice"). */
41+
export function sessionName(s: SessionLike): string {
42+
if (s.idSource === "explicit" && s.id.startsWith("explicit:")) {
43+
const start = "explicit:".length;
44+
const at = s.id.lastIndexOf("@");
45+
const name = at > start ? s.id.slice(start, at) : s.id.slice(start);
46+
if (name) return name;
47+
}
48+
return s.harness;
49+
}
50+
51+
/** Explicit names are unique per host by construction, so they need no hash suffix. */
52+
export function who(s: SessionLike): string {
53+
return s.idSource === "explicit" ? sessionName(s) : `${s.harness}#${shortId(s.id)}`;
4054
}
4155

4256
function appendWrapped(
@@ -146,7 +160,7 @@ export function formatStatus(
146160
pushSection(out, theme.heading("recent:"));
147161
for (const a of d.activity) {
148162
const holder = store.getSession(a.sessionId);
149-
const prefix = ` ${theme.dim(ago(now - a.ts).padStart(7))} ${padEndVisible(theme.accent(holder?.harness ?? "?"), 11)} ${theme.kind(a.kind)} `;
163+
const prefix = ` ${theme.dim(ago(now - a.ts).padStart(7))} ${padEndVisible(theme.accent(holder ? sessionName(holder) : "?"), 11)} ${theme.kind(a.kind)} `;
150164
const body = `${a.target ? theme.path(a.target) : ""}${a.summary ? `${a.target ? " " : ""}${theme.dim("—")} ${a.summary}` : ""}`;
151165
if (a.kind === "note") {
152166
const maxBody = Math.max(8, width - visibleLength(prefix));
@@ -198,17 +212,23 @@ export function formatStatus(
198212
}
199213

200214
export function statusJson(repoId: string, d: StatusData, now: number, store: Store): unknown {
215+
const byName = (sessionId: string): string | null => {
216+
const s = store.getSession(sessionId);
217+
return s ? sessionName(s) : null;
218+
};
201219
return {
202220
repo: repoId,
203221
sessions: d.sessions.map((s) => ({
204222
shortId: shortId(s.id),
223+
name: sessionName(s),
205224
harness: s.harness,
206225
source: s.idSource,
207226
intent: s.intent,
208227
lastSeenMsAgo: now - s.lastSeen,
209228
})),
210229
completed: d.completed.map((s) => ({
211230
shortId: shortId(s.id),
231+
name: sessionName(s),
212232
harness: s.harness,
213233
source: s.idSource,
214234
intent: s.intent,
@@ -217,14 +237,14 @@ export function statusJson(repoId: string, d: StatusData, now: number, store: St
217237
claims: d.claims.map((c) => ({
218238
pattern: c.pattern,
219239
reason: c.reason,
220-
by: store.getSession(c.sessionId)?.harness ?? null,
240+
by: byName(c.sessionId),
221241
createdMsAgo: now - c.createdAt,
222242
})),
223243
recentActivity: d.activity.map((a) => ({
224244
kind: a.kind,
225245
target: a.target,
226246
summary: a.summary,
227-
by: store.getSession(a.sessionId)?.harness ?? null,
247+
by: byName(a.sessionId),
228248
tsMsAgo: now - a.ts,
229249
})),
230250
notes: d.notes.map((n) => ({ body: n.body, path: n.path, pinned: n.pinned })),

‎test/identity.test.ts‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { test } from "node:test";
33
import { resolveIdentity } from "../src/identity/session.ts";
44

55
const host = "h";
6-
const base = { argv: [] as string[], host };
6+
const base = { argv: [] as string[], host, harnessResolver: () => null };
77

88
test("explicit via WEAVER_SESSION", () => {
99
const id = resolveIdentity({ ...base, env: { WEAVER_SESSION: "abc" } });
@@ -27,6 +27,43 @@ test("harness: claude-code / opencode / codex", () => {
2727
assert.equal(resolveIdentity({ ...base, env: { CODEX_THREAD_ID: "c1" } })?.key, "harness:codex:c1@h");
2828
});
2929

30+
test("opencode: OPENCODE_SESSION_ID recognized, beats OPENCODE_RUN_ID", () => {
31+
assert.equal(resolveIdentity({ ...base, env: { OPENCODE_SESSION_ID: "s1" } })?.key, "harness:opencode:s1@h");
32+
assert.equal(
33+
resolveIdentity({ ...base, env: { OPENCODE_SESSION_ID: "s1", OPENCODE_RUN_ID: "o1" } })?.key,
34+
"harness:opencode:s1@h",
35+
);
36+
});
37+
38+
test("label: env signal wins over ancestry", () => {
39+
const id = resolveIdentity({
40+
...base,
41+
env: { WEAVER_SESSION: "e", CLAUDECODE: "1" },
42+
harnessResolver: () => "opencode",
43+
});
44+
assert.equal(id?.label, "claude-code");
45+
});
46+
47+
test("label: ancestry fills in when env says nothing (explicit rung)", () => {
48+
const id = resolveIdentity({ ...base, env: { WEAVER_SESSION: "e" }, harnessResolver: () => "opencode" });
49+
assert.equal(id?.label, "opencode");
50+
});
51+
52+
test("label: ancestry fills in when env says nothing (tty rung)", () => {
53+
const id = resolveIdentity({
54+
...base,
55+
env: {},
56+
ttyResolver: () => ({ device: "ttys003", viaAncestry: true }),
57+
harnessResolver: () => "opencode",
58+
});
59+
assert.equal(id?.label, "opencode");
60+
});
61+
62+
test("label: unknown when neither env nor ancestry knows", () => {
63+
const id = resolveIdentity({ ...base, env: { WEAVER_SESSION: "e" } });
64+
assert.equal(id?.label, "unknown");
65+
});
66+
3067
test("tty (self) via injected resolver", () => {
3168
const id = resolveIdentity({ ...base, env: {}, ttyResolver: () => ({ device: "ttys003", viaAncestry: false }) });
3269
assert.equal(id?.source, "tty");

0 commit comments

Comments
 (0)