Skip to content

Commit f8ddc75

Browse files
Claude Agentclaude
andcommitted
feat(session): add depth/rootID as additive wire fields (nested-agents Issue 3)
Surface the session nesting level (depth) and tree root (rootID) as convenience fields on the wire instead of forcing every client to walk the parentID chain. Both are derived, never client-settable, and purely additive — old clients that ignore them keep working. Core/DB: - Add `depth` (integer, default 1, not null) and `root_id` (text, nullable) columns plus a `session_root_idx` to the session table. - New migration `20260613064154_session_depth_rootid` with a one-shot recursive-CTE backfill over the parent_id chains (root = depth 1, root_id = topmost ancestor; orphans treated as roots; legacy deep chains stamped, never truncated). Backfill UPDATE is idempotent. - Map the fields through the projector, `SessionV1.SessionInfo` event payload, `SessionSchema.Info` and `info.fromRow`. Server/wire: - `createNext` stamps depth/rootID from the lineage walk it already does for the hard-cap check (root: depth 1, no rootID; child: parent chain length + 1, rootID = root.rootID ?? root.id). fromRow/toRow round-trip them and the Session.Info schema exposes them. - `GET /session/:id/children?recursive=true` returns the whole descendant subtree (via Session.descendants); the default stays direct-children only. SDK: - Regenerated the v2 SDK (depth/rootID on Session, recursive query param). - Patched the v1 (`src/gen`) SDK additively by hand (it is produced by a separate stainless pipeline not runnable in this worktree). Tests: - Migration backfill over a 3-level tree + orphan, with idempotency. - createNext depth/rootID stamping (root, 3-level tree, orphaned parent). - HTTP children recursive vs direct + depth/rootID on the wire. - Updated existing wire-shape fixtures for the now-required depth field. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 81ea40c commit f8ddc75

22 files changed

Lines changed: 813 additions & 22 deletions

‎packages/core/schema.json‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{
22
"version": "7",
33
"dialect": "sqlite",
4-
"id": "4afa16d2-a0b8-4cf9-9b05-a04364ee5ec9",
4+
"id": "0083c7c4-806f-47a7-b5f8-e560f97ec51f",
55
"prevIds": [
6-
"abd2f920-b822-49af-b8a7-2e48367d424f"
6+
"4afa16d2-a0b8-4cf9-9b05-a04364ee5ec9"
77
],
88
"ddl": [
99
{
@@ -1126,6 +1126,26 @@
11261126
"entityType": "columns",
11271127
"table": "session"
11281128
},
1129+
{
1130+
"type": "integer",
1131+
"notNull": true,
1132+
"autoincrement": false,
1133+
"default": "1",
1134+
"generated": null,
1135+
"name": "depth",
1136+
"entityType": "columns",
1137+
"table": "session"
1138+
},
1139+
{
1140+
"type": "text",
1141+
"notNull": false,
1142+
"autoincrement": false,
1143+
"default": null,
1144+
"generated": null,
1145+
"name": "root_id",
1146+
"entityType": "columns",
1147+
"table": "session"
1148+
},
11291149
{
11301150
"type": "text",
11311151
"notNull": true,
@@ -2360,6 +2380,20 @@
23602380
"entityType": "indexes",
23612381
"table": "session"
23622382
},
2383+
{
2384+
"columns": [
2385+
{
2386+
"value": "root_id",
2387+
"isExpression": false
2388+
}
2389+
],
2390+
"isUnique": false,
2391+
"where": null,
2392+
"origin": "manual",
2393+
"name": "session_root_idx",
2394+
"entityType": "indexes",
2395+
"table": "session"
2396+
},
23632397
{
23642398
"columns": [
23652399
{

‎packages/core/src/database/migration.gen.ts‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { Effect } from "effect"
2+
import type { DatabaseMigration } from "../migration"
3+
4+
export default {
5+
id: "20260613064154_session_depth_rootid",
6+
up(tx) {
7+
return Effect.gen(function* () {
8+
yield* tx.run(`ALTER TABLE \`session\` ADD \`depth\` integer DEFAULT 1 NOT NULL;`)
9+
yield* tx.run(`ALTER TABLE \`session\` ADD \`root_id\` text;`)
10+
yield* tx.run(`CREATE INDEX \`session_root_idx\` ON \`session\` (\`root_id\`);`)
11+
// One-shot recursive backfill for existing rows (nested-agents Issue 3).
12+
// Walks every parent_id chain from its roots, stamping depth (root = 1)
13+
// and root_id (the topmost ancestor's id; NULL for roots/orphans, matching
14+
// the create-time convention). SQLite cannot reference a WITH RECURSIVE CTE
15+
// from UPDATE ... FROM, so the CTE lives in correlated subqueries instead.
16+
// Idempotent: re-running stamps the same values; orphans (parent_id points
17+
// at a deleted session, so the row never appears in `tree`) are left at the
18+
// depth=1/root_id=NULL defaults and treated as roots — the safest reading.
19+
// Existing chains deeper than the new limit are stamped, never truncated:
20+
// the spawn limit only gates NEW spawns, legacy deep sessions stay readable.
21+
yield* tx.run(`
22+
WITH RECURSIVE tree(id, root_id, depth) AS (
23+
SELECT id, id, 1 FROM session WHERE parent_id IS NULL
24+
UNION ALL
25+
SELECT s.id, t.root_id, t.depth + 1
26+
FROM session s JOIN tree t ON s.parent_id = t.id
27+
)
28+
UPDATE session SET
29+
depth = (SELECT depth FROM tree WHERE tree.id = session.id),
30+
root_id = CASE WHEN session.parent_id IS NULL THEN NULL
31+
ELSE (SELECT root_id FROM tree WHERE tree.id = session.id) END
32+
WHERE EXISTS (SELECT 1 FROM tree WHERE tree.id = session.id)
33+
`)
34+
})
35+
},
36+
} satisfies DatabaseMigration.Migration

‎packages/core/src/database/schema.gen.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,8 @@ export default {
186186
\`project_id\` text NOT NULL,
187187
\`workspace_id\` text,
188188
\`parent_id\` text,
189+
\`depth\` integer DEFAULT 1 NOT NULL,
190+
\`root_id\` text,
189191
\`slug\` text NOT NULL,
190192
\`directory\` text NOT NULL,
191193
\`path\` text,
@@ -276,6 +278,7 @@ export default {
276278
yield* tx.run(`CREATE INDEX \`session_project_idx\` ON \`session\` (\`project_id\`);`)
277279
yield* tx.run(`CREATE INDEX \`session_workspace_idx\` ON \`session\` (\`workspace_id\`);`)
278280
yield* tx.run(`CREATE INDEX \`session_parent_idx\` ON \`session\` (\`parent_id\`);`)
281+
yield* tx.run(`CREATE INDEX \`session_root_idx\` ON \`session\` (\`root_id\`);`)
279282
yield* tx.run(`CREATE INDEX \`todo_session_idx\` ON \`todo\` (\`session_id\`);`)
280283
yield* tx.run(`CREATE INDEX \`workflow_run_started_at_idx\` ON \`workflow_run\` (\`started_at\`);`)
281284
yield* tx.run(`CREATE INDEX \`workflow_run_status_started_at_idx\` ON \`workflow_run\` (\`status\`,\`started_at\`);`)

‎packages/core/src/session/info.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ export function fromRow(row: typeof SessionTable.$inferSelect): SessionSchema.In
1515
projectID: ProjectV2.ID.make(row.project_id),
1616
title: row.title,
1717
parentID: row.parent_id ? SessionSchema.ID.make(row.parent_id) : undefined,
18+
depth: row.depth,
19+
rootID: row.root_id ? SessionSchema.ID.make(row.root_id) : undefined,
1820
agent: row.agent ? AgentV2.ID.make(row.agent) : undefined,
1921
model: row.model
2022
? {

‎packages/core/src/session/projector.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ function sessionRow(info: SessionV1.SessionInfo): typeof SessionTable.$inferInse
4848
project_id: info.projectID,
4949
workspace_id: info.workspaceID ?? null,
5050
parent_id: info.parentID,
51+
// Derived wire fields (nested-agents Issue 3). depth falls back to the
52+
// table default (1) when an older event omits it; root_id is null for
53+
// roots/orphans.
54+
depth: info.depth ?? 1,
55+
root_id: info.rootID ?? null,
5156
slug: info.slug,
5257
directory: info.directory,
5358
path: info.path,

‎packages/core/src/session/schema.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ export type ID = typeof ID.Type
2525
export class Info extends Schema.Class<Info>("SessionV2.Info")({
2626
id: ID,
2727
parentID: ID.pipe(optionalOmitUndefined),
28+
// Convenience wire fields derived from the parentID chain (nested-agents
29+
// Issue 3, additive). `depth` is the 1-based nesting level (root = 1, always
30+
// present); `rootID` is the topmost ancestor, omitted for roots/orphans
31+
// (callers read `rootID ?? id`).
32+
depth: Schema.Finite,
33+
rootID: ID.pipe(optionalOmitUndefined),
2834
projectID: ProjectV2.ID,
2935
agent: AgentV2.ID.pipe(Schema.optional),
3036
model: ModelV2.Ref.pipe(Schema.optional),

‎packages/core/src/session/sql.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ export const SessionTable = sqliteTable(
2828
.references(() => ProjectTable.id, { onDelete: "cascade" }),
2929
workspace_id: text().$type<WorkspaceV2.ID>(),
3030
parent_id: text().$type<SessionSchema.ID>(),
31+
// Convenience wire fields derived from the parent_id chain (nested-agents
32+
// Issue 3). `depth` is the 1-based nesting level (root = 1, never null —
33+
// legacy rows backfilled by migration, new rows stamped at create time).
34+
// `root_id` is the topmost ancestor's id; null for roots/orphans (a root is
35+
// its own root, so callers read `root_id ?? id`). These are additive: the
36+
// wire format stays backward compatible and clients that ignore them break
37+
// nothing. Depth is derived, never client-settable.
38+
depth: integer().notNull().default(1),
39+
root_id: text().$type<SessionSchema.ID>(),
3140
slug: text().notNull(),
3241
directory: DatabasePath.directoryColumn().notNull(),
3342
path: DatabasePath.pathColumn(),
@@ -61,6 +70,7 @@ export const SessionTable = sqliteTable(
6170
index("session_project_idx").on(table.project_id),
6271
index("session_workspace_idx").on(table.workspace_id),
6372
index("session_parent_idx").on(table.parent_id),
73+
index("session_root_idx").on(table.root_id),
6474
],
6575
)
6676

‎packages/core/src/v1/session.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,12 @@ export const SessionInfo = Schema.Struct({
552552
directory: Schema.String,
553553
path: optionalOmitUndefined(Schema.String),
554554
parentID: optionalOmitUndefined(SessionSchema.ID),
555+
// Convenience wire fields derived from the parentID chain (nested-agents
556+
// Issue 3, additive). `depth` is the 1-based nesting level (root = 1, always
557+
// present). `rootID` is the topmost ancestor; omitted for roots/orphans
558+
// (a root is its own root, so callers read `rootID ?? id`).
559+
depth: optionalOmitUndefined(NonNegativeInt),
560+
rootID: optionalOmitUndefined(SessionSchema.ID),
555561
summary: optionalOmitUndefined(SessionSummary),
556562
cost: optionalOmitUndefined(Schema.Finite),
557563
tokens: optionalOmitUndefined(SessionTokens),

‎packages/core/test/database-migration.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import sessionMessageProjectionOrderMigration from "@opencode-ai/core/database/m
1414
import eventSourcedSessionInputMigration from "@opencode-ai/core/database/migration/20260604172448_event_sourced_session_input"
1515
import contextEpochAgentMigration from "@opencode-ai/core/database/migration/20260605042240_add_context_epoch_agent"
1616
import simplifyIntegrationCredentialsMigration from "@opencode-ai/core/database/migration/20260611192811_lush_chimera"
17+
import sessionDepthRootMigration from "@opencode-ai/core/database/migration/20260613064154_session_depth_rootid"
1718
import { ProjectV2 } from "@opencode-ai/core/project"
1819
import { ProjectTable } from "@opencode-ai/core/project/sql"
1920
import { AbsolutePath } from "@opencode-ai/core/schema"
@@ -310,6 +311,60 @@ describe("DatabaseMigration", () => {
310311
)
311312
})
312313

314+
test("backfills depth/root_id over a parent chain and treats orphans as roots", async () => {
315+
await run(
316+
Effect.gen(function* () {
317+
const db = yield* makeDb
318+
// Minimal pre-migration session table (no depth/root_id yet).
319+
yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, parent_id text)`)
320+
// A three-level tree: root -> child -> grandchild, plus a second child
321+
// under root, plus an orphan whose parent row never existed.
322+
yield* db.run(sql`INSERT INTO session (id, parent_id) VALUES ('ses_root', NULL)`)
323+
yield* db.run(sql`INSERT INTO session (id, parent_id) VALUES ('ses_child_a', 'ses_root')`)
324+
yield* db.run(sql`INSERT INTO session (id, parent_id) VALUES ('ses_child_b', 'ses_root')`)
325+
yield* db.run(sql`INSERT INTO session (id, parent_id) VALUES ('ses_grandchild', 'ses_child_a')`)
326+
yield* db.run(sql`INSERT INTO session (id, parent_id) VALUES ('ses_orphan', 'ses_gone')`)
327+
328+
yield* DatabaseMigration.applyOnly(db, [sessionDepthRootMigration])
329+
330+
const rows = yield* db.all<{ id: string; depth: number; root_id: string | null }>(
331+
sql`SELECT id, depth, root_id FROM session ORDER BY id`,
332+
)
333+
expect(rows).toEqual([
334+
{ id: "ses_child_a", depth: 2, root_id: "ses_root" },
335+
{ id: "ses_child_b", depth: 2, root_id: "ses_root" },
336+
{ id: "ses_grandchild", depth: 3, root_id: "ses_root" },
337+
// Orphan (parent row missing) is treated as a root: depth 1, no root_id.
338+
{ id: "ses_orphan", depth: 1, root_id: null },
339+
// Root is its own root: root_id stays NULL (callers read root_id ?? id).
340+
{ id: "ses_root", depth: 1, root_id: null },
341+
])
342+
343+
// Idempotent backfill: re-running the recursive CTE stamps the same
344+
// values (the migration runner already guards replay via the migration
345+
// table; this proves the UPDATE itself converges).
346+
yield* db.run(sql`
347+
WITH RECURSIVE tree(id, root_id, depth) AS (
348+
SELECT id, id, 1 FROM session WHERE parent_id IS NULL
349+
UNION ALL
350+
SELECT s.id, t.root_id, t.depth + 1
351+
FROM session s JOIN tree t ON s.parent_id = t.id
352+
)
353+
UPDATE session SET
354+
depth = (SELECT depth FROM tree WHERE tree.id = session.id),
355+
root_id = CASE WHEN session.parent_id IS NULL THEN NULL
356+
ELSE (SELECT root_id FROM tree WHERE tree.id = session.id) END
357+
WHERE EXISTS (SELECT 1 FROM tree WHERE tree.id = session.id)
358+
`)
359+
expect(
360+
yield* db.all<{ id: string; depth: number; root_id: string | null }>(
361+
sql`SELECT id, depth, root_id FROM session ORDER BY id`,
362+
),
363+
).toEqual(rows)
364+
}),
365+
)
366+
})
367+
313368
test("normalizes Windows storage paths and leaves POSIX paths untouched", async () => {
314369
await run(
315370
Effect.gen(function* () {

0 commit comments

Comments
 (0)