supercode-core 0.2.1

A lightweight, fully-customizable AI coding agent SDK in Rust. Talks to any model via OpenRouter or any OpenAI-compatible endpoint.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#!/usr/bin/env python3
"""Deterministic generator for `opencode_fixture/opencode.db` (PARITY-1/3/4
reopen — D1-D8 fix verification).

This does NOT hand-author a CREATE TABLE schema. The DDL below is copied
VERBATIM from the real, generated `packages/core/src/database/schema.gen.ts`
in `sst/opencode@fd9ee43` (the authoritative schema source pinned for this
work) — i.e. exactly what a fresh real `opencode` install's first-run
migration produces for the `project`/`session`/`message`/`part`/`todo`
tables. Only the tables our loader actually reads are included (plus
`project`, an FK dependency of `session`). Row *content* (ids, JSON `data`
payloads) is hand-built to match the real `SessionV1.{Info,Part,...}` field
shapes in `packages/schema/src/v1/session.ts` at the same pin, chosen to
exercise the hard cases from the Fable-5 review of parity/opencode-native:

  - a session with every LEGITIMATELY-nullable `session` column actually
    NULL (workspace_id, path, share_url, summary_*, metadata, permission,
    agent, model, time_compacting, time_archived) — D1's re-confirmed scope.
    (NOTE: `cost`/`tokens_*` are NOT NULL DEFAULT 0 in the real schema — see
    the D1 write-up in the build report — so this fixture does NOT attempt a
    NULL `cost` row; that would violate the real DB's own constraint and
    stop being "genuine".)
  - a `session.revert` column carrying the V2 `Revert.State` shape's extra
    `files` field (S9c: the upstream row→V1 reconstruction drops it; the
    envelope must carry the raw column value).
  - a `todo` row (real schema: has `time_created`/`time_updated`, contra the
    review's D1 claim).
  - a non-image `file` part (https URL) AND a `data:`-URI image `file` part,
    side by side, so audit can be checked against both (D5).
  - an `ignored:true` text part (must never be replayed — D5).
  - a `tool` part reaching `state.completed` (paired output) and a second
    `tool` part reaching `state.error` (paired error), both same-shape
    call+result records as upstream stores them (§2.1).
  - a second, OLDER session in the same store, to exercise multi-session
    detection (D6) — the newer session (below) is the auto-picked "primary".
  - a `session_diff` JSON sidecar file at
    `<dir>/storage/session_diff/<session_id>.json`, mirroring the real
    `packages/opencode/src/storage/storage.ts` write path (D3).

Run: `python3 gen_opencode_fixture.py` from this directory (or any cwd —
paths are relative to this script). Regenerates
`opencode_fixture/opencode.db` and the `session_diff` sidecar in place.
"""
import json
import os
import sqlite3

HERE = os.path.dirname(os.path.abspath(__file__))
FIXTURE_DIR = os.path.join(HERE, "opencode_fixture")
DB_PATH = os.path.join(FIXTURE_DIR, "opencode.db")
STORAGE_DIR = os.path.join(FIXTURE_DIR, "storage")

PROJECT_ID = "prj_fixture000000000000001"
SESSION_A = "ses_fixtureAAAAAAAAAAAAAAA1"  # primary (newer, has the hard cases)
SESSION_B = "ses_fixtureBBBBBBBBBBBBBBB1"  # secondary (older, plain) — D6 multi-session
MSG_USER_A1 = "msg_fixtureUser0000000001"
MSG_ASST_A1 = "msg_fixtureAsst0000000001"
MSG_USER_B1 = "msg_fixtureUser0000000002"
MSG_ASST_B1 = "msg_fixtureAsst0000000002"

T0 = 1750000000000  # fixed base ms epoch — deterministic fixture

# --- DDL copied verbatim from schema.gen.ts @ sst/opencode@fd9ee43 ---------
DDL = [
    """
    CREATE TABLE `project` (
      `id` text PRIMARY KEY,
      `worktree` text NOT NULL,
      `vcs` text,
      `name` text,
      `icon_url` text,
      `icon_url_override` text,
      `icon_color` text,
      `time_created` integer NOT NULL,
      `time_updated` integer NOT NULL,
      `time_initialized` integer,
      `sandboxes` text NOT NULL,
      `commands` text
    );
    """,
    """
    CREATE TABLE `message` (
      `id` text PRIMARY KEY,
      `session_id` text NOT NULL,
      `time_created` integer NOT NULL,
      `time_updated` integer NOT NULL,
      `data` text NOT NULL,
      CONSTRAINT `fk_message_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE
    );
    """,
    """
    CREATE TABLE `part` (
      `id` text PRIMARY KEY,
      `message_id` text NOT NULL,
      `session_id` text NOT NULL,
      `time_created` integer NOT NULL,
      `time_updated` integer NOT NULL,
      `data` text NOT NULL,
      CONSTRAINT `fk_part_message_id_message_id_fk` FOREIGN KEY (`message_id`) REFERENCES `message`(`id`) ON DELETE CASCADE
    );
    """,
    """
    CREATE TABLE `session` (
      `id` text PRIMARY KEY,
      `project_id` text NOT NULL,
      `workspace_id` text,
      `parent_id` text,
      `slug` text NOT NULL,
      `directory` text NOT NULL,
      `path` text,
      `title` text NOT NULL,
      `version` text NOT NULL,
      `share_url` text,
      `summary_additions` integer,
      `summary_deletions` integer,
      `summary_files` integer,
      `summary_diffs` text,
      `metadata` text,
      `cost` real DEFAULT 0 NOT NULL,
      `tokens_input` integer DEFAULT 0 NOT NULL,
      `tokens_output` integer DEFAULT 0 NOT NULL,
      `tokens_reasoning` integer DEFAULT 0 NOT NULL,
      `tokens_cache_read` integer DEFAULT 0 NOT NULL,
      `tokens_cache_write` integer DEFAULT 0 NOT NULL,
      `revert` text,
      `permission` text,
      `agent` text,
      `model` text,
      `time_created` integer NOT NULL,
      `time_updated` integer NOT NULL,
      `time_compacting` integer,
      `time_archived` integer,
      CONSTRAINT `fk_session_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE
    );
    """,
    """
    CREATE TABLE `todo` (
      `session_id` text NOT NULL,
      `content` text NOT NULL,
      `status` text NOT NULL,
      `priority` text NOT NULL,
      `position` integer NOT NULL,
      `time_created` integer NOT NULL,
      `time_updated` integer NOT NULL,
      CONSTRAINT `todo_pk` PRIMARY KEY(`session_id`, `position`),
      CONSTRAINT `fk_todo_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE
    );
    """,
]


def user_message(msg_id, session_id, t_created, system=None):
    data = {
        "role": "user",
        "time": {"created": t_created},
        "agent": "build",
        "model": {"providerID": "anthropic", "modelID": "claude-fixture"},
    }
    if system is not None:
        data["system"] = system
    return data


def assistant_message(msg_id, session_id, parent_id, t_created, t_completed):
    return {
        "role": "assistant",
        "time": {"created": t_created, "completed": t_completed},
        "parentID": parent_id,
        "modelID": "claude-fixture",
        "providerID": "anthropic",
        "mode": "build",
        "agent": "build",
        "path": {"cwd": "/tmp/fixture-project", "root": "/tmp/fixture-project"},
        "cost": 0.0123,
        "tokens": {
            "input": 100,
            "output": 200,
            "reasoning": 0,
            "cache": {"read": 10, "write": 5},
        },
        "finish": "stop",
    }


def text_part(part_id, text, ignored=None):
    d = {"type": "text", "text": text}
    if ignored is not None:
        d["ignored"] = ignored
    return d


def file_part(part_id, mime, url, filename=None):
    d = {"type": "file", "mime": mime, "url": url}
    if filename:
        d["filename"] = filename
    return d


def tool_part_completed(part_id, call_id, tool, t_start, t_end):
    return {
        "type": "tool",
        "callID": call_id,
        "tool": tool,
        "state": {
            "status": "completed",
            "input": {"command": "cat file.txt"},
            "output": "file contents: hello world\n",
            "title": tool,
            "metadata": {},
            "time": {"start": t_start, "end": t_end},
        },
    }


def tool_part_error(part_id, call_id, tool, t_start, t_end):
    return {
        "type": "tool",
        "callID": call_id,
        "tool": tool,
        "state": {
            "status": "error",
            "input": {"path": "file.txt"},
            "error": "permission denied",
            "time": {"start": t_start, "end": t_end},
        },
    }


TINY_PNG_DATA_URI = (
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4"
    "2mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
)


def main():
    os.makedirs(FIXTURE_DIR, exist_ok=True)
    os.makedirs(os.path.join(STORAGE_DIR, "session_diff"), exist_ok=True)
    if os.path.exists(DB_PATH):
        os.remove(DB_PATH)

    conn = sqlite3.connect(DB_PATH)
    conn.execute("PRAGMA foreign_keys = ON")
    for stmt in DDL:
        conn.execute(stmt)

    # --- project (session's FK dependency) ---
    conn.execute(
        "INSERT INTO project (id, worktree, vcs, name, icon_url, icon_url_override, "
        "icon_color, time_created, time_updated, time_initialized, sandboxes, commands) "
        "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
        (
            PROJECT_ID,
            "/tmp/fixture-project",
            "git",
            "fixture-project",
            None,
            None,
            None,
            T0,
            T0,
            None,
            "[]",
            None,
        ),
    )

    # --- session A: primary, newer, carries every hard case ---
    revert_with_files = {
        "messageID": MSG_ASST_A1,
        "snapshot": "snap_fixture0001",
        "diff": "@@ -1 +1 @@\n-old\n+new\n",
        # S9c: `files` is the V2 `Revert.State` extra field the CLI's own
        # row->V1 reconstruction drops — the envelope must carry it raw.
        "files": [
            {"path": "src/a.txt", "additions": 3, "deletions": 1, "patch": "@@ -1,1 +1,3 @@\n"}
        ],
    }
    conn.execute(
        "INSERT INTO session (id, project_id, workspace_id, parent_id, slug, directory, "
        "path, title, version, share_url, summary_additions, summary_deletions, "
        "summary_files, summary_diffs, metadata, cost, tokens_input, tokens_output, "
        "tokens_reasoning, tokens_cache_read, tokens_cache_write, revert, permission, "
        "agent, model, time_created, time_updated, time_compacting, time_archived) "
        "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        (
            SESSION_A,
            PROJECT_ID,
            None,  # workspace_id: nullable — NULL
            None,  # parent_id: top-level session
            "fixture-session-a",
            "/tmp/fixture-project",
            None,  # path: nullable — NULL
            "Fixture Session A (hard cases)",
            "1.0.0",
            None,  # share_url: nullable — NULL
            None,
            None,
            None,  # summary_*: nullable — NULL
            None,  # summary_diffs: nullable — NULL
            None,  # metadata: nullable — NULL
            0.0421,  # cost: NOT NULL DEFAULT 0 in the real schema — nonzero here
            120,
            340,
            0,
            50,
            10,
            json.dumps(revert_with_files),
            None,  # permission: nullable — NULL
            None,  # agent: nullable — NULL
            None,  # model: nullable — NULL
            T0 + 60_000,
            T0 + 120_000,
            None,  # time_compacting: nullable — NULL
            None,  # time_archived: nullable — NULL
        ),
    )

    # user message + parts (ignored text, non-image file, image data-URI file)
    u1 = user_message(MSG_USER_A1, SESSION_A, T0 + 60_000, system="You are a helpful coding agent.")
    conn.execute(
        "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?,?,?,?,?)",
        (MSG_USER_A1, SESSION_A, T0 + 60_000, T0 + 60_500, json.dumps(u1)),
    )
    user_parts = [
        ("prt_userA_text1", text_part("prt_userA_text1", "Please check this file and fix the bug.")),
        (
            "prt_userA_ignored",
            text_part("prt_userA_ignored", "internal scratch note — not shown to the model", ignored=True),
        ),
        (
            "prt_userA_pdf",
            file_part("prt_userA_pdf", "application/pdf", "https://example.com/report.pdf", "report.pdf"),
        ),
        (
            "prt_userA_img",
            file_part("prt_userA_img", "image/png", TINY_PNG_DATA_URI, "screenshot.png"),
        ),
    ]
    for i, (pid, pdata) in enumerate(user_parts):
        conn.execute(
            "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?,?,?,?,?,?)",
            (pid, MSG_USER_A1, SESSION_A, T0 + 60_000 + i, T0 + 60_000 + i, json.dumps(pdata)),
        )

    # assistant message + parts (text, tool/completed, tool/error)
    a1 = assistant_message(MSG_ASST_A1, SESSION_A, MSG_USER_A1, T0 + 61_000, T0 + 90_000)
    conn.execute(
        "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?,?,?,?,?)",
        (MSG_ASST_A1, SESSION_A, T0 + 61_000, T0 + 90_000, json.dumps(a1)),
    )
    asst_parts = [
        ("prt_asstA_text1", text_part("prt_asstA_text1", "I'll check the file now.")),
        (
            "prt_asstA_tool_ok",
            tool_part_completed("prt_asstA_tool_ok", "call_1", "bash", T0 + 62_000, T0 + 63_000),
        ),
        (
            "prt_asstA_tool_err",
            tool_part_error("prt_asstA_tool_err", "call_2", "edit", T0 + 64_000, T0 + 65_000),
        ),
    ]
    for i, (pid, pdata) in enumerate(asst_parts):
        conn.execute(
            "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?,?,?,?,?,?)",
            (pid, MSG_ASST_A1, SESSION_A, T0 + 62_000 + i, T0 + 62_000 + i, json.dumps(pdata)),
        )

    # todo row (real schema HAS time_created/time_updated — D1 re-confirmed)
    conn.execute(
        "INSERT INTO todo (session_id, content, status, priority, position, time_created, time_updated) "
        "VALUES (?,?,?,?,?,?,?)",
        (SESSION_A, "Fix the bug in file.txt", "in_progress", "high", 0, T0 + 61_500, T0 + 61_500),
    )

    # --- session B: secondary, OLDER, plain (D6 multi-session detection) ---
    conn.execute(
        "INSERT INTO session (id, project_id, workspace_id, parent_id, slug, directory, "
        "path, title, version, share_url, summary_additions, summary_deletions, "
        "summary_files, summary_diffs, metadata, cost, tokens_input, tokens_output, "
        "tokens_reasoning, tokens_cache_read, tokens_cache_write, revert, permission, "
        "agent, model, time_created, time_updated, time_compacting, time_archived) "
        "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        (
            SESSION_B,
            PROJECT_ID,
            None,
            None,
            "fixture-session-b",
            "/tmp/fixture-project",
            None,
            "Fixture Session B (plain, older)",
            "1.0.0",
            None,
            None,
            None,
            None,
            None,
            None,
            0.0,
            0,
            0,
            0,
            0,
            0,
            None,
            None,
            "build",
            json.dumps({"id": "claude-fixture", "providerID": "anthropic"}),
            T0,  # created BEFORE session A — so A is picked as primary
            T0 + 1_000,
            None,
            None,
        ),
    )
    ub1 = user_message(MSG_USER_B1, SESSION_B, T0)
    conn.execute(
        "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?,?,?,?,?)",
        (MSG_USER_B1, SESSION_B, T0, T0 + 100, json.dumps(ub1)),
    )
    conn.execute(
        "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?,?,?,?,?,?)",
        ("prt_userB_text1", MSG_USER_B1, SESSION_B, T0, T0, json.dumps(text_part("prt_userB_text1", "hi"))),
    )
    ab1 = assistant_message(MSG_ASST_B1, SESSION_B, MSG_USER_B1, T0 + 200, T0 + 500)
    conn.execute(
        "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?,?,?,?,?)",
        (MSG_ASST_B1, SESSION_B, T0 + 200, T0 + 500, json.dumps(ab1)),
    )
    conn.execute(
        "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?,?,?,?,?,?)",
        (
            "prt_asstB_text1",
            MSG_ASST_B1,
            SESSION_B,
            T0 + 200,
            T0 + 200,
            json.dumps(text_part("prt_asstB_text1", "hello back")),
        ),
    )

    conn.commit()
    conn.close()

    # --- session_diff sidecar (D3): `<dir>/storage/session_diff/<id>.json`,
    # mirroring `packages/opencode/src/storage/storage.ts`'s
    # `JSON.stringify(diffs, null, 2)` write shape. Only session A gets one
    # (mirrors a real revert having just happened on that session).
    diffs = [
        {"file": "src/a.txt", "additions": 3, "deletions": 1, "patch": "@@ -1,1 +1,3 @@\n"}
    ]
    with open(os.path.join(STORAGE_DIR, "session_diff", f"{SESSION_A}.json"), "w") as f:
        json.dump(diffs, f, indent=2)

    print(f"wrote {DB_PATH}")
    print(f"wrote {os.path.join(STORAGE_DIR, 'session_diff', SESSION_A + '.json')}")
    print(f"SESSION_A (primary) = {SESSION_A}")
    print(f"SESSION_B (secondary) = {SESSION_B}")


if __name__ == "__main__":
    main()