oc-harness-setup 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/.docs/unwired-routing.md +14 -9
  2. package/.gitignore +14 -1
  3. package/AGENTS.md +70 -106
  4. package/README.md +55 -24
  5. package/agents/build.md +10 -12
  6. package/agents/explore.md +14 -8
  7. package/agents/general.md +7 -9
  8. package/agents/orchestrator.md +38 -0
  9. package/agents/plan.md +10 -13
  10. package/agents/reviewer.md +9 -14
  11. package/agents/vault.md +44 -35
  12. package/bin/cli.js +32 -3
  13. package/commands/build.md +2 -8
  14. package/commands/checkpoint.md +3 -1
  15. package/commands/code-simplify.md +3 -9
  16. package/commands/gauntlet.md +7 -0
  17. package/commands/handoff.md +3 -1
  18. package/commands/keeper.md +3 -3
  19. package/commands/kill.md +11 -0
  20. package/commands/plan.md +2 -13
  21. package/commands/retro.md +15 -0
  22. package/commands/review.md +1 -1
  23. package/commands/ship.md +3 -27
  24. package/commands/spec.md +3 -11
  25. package/commands/test.md +2 -9
  26. package/commands/webperf.md +7 -0
  27. package/opencode.jsonc +23 -8
  28. package/package.json +5 -4
  29. package/reference/README.md +14 -14
  30. package/reference/auto-mandate.md +11 -0
  31. package/reference/backup-convention.md +9 -0
  32. package/reference/clean-mandate.md +13 -0
  33. package/reference/editor-parity.md +7 -0
  34. package/reference/gc-scripts.md +8 -0
  35. package/reference/intent-routing.md +14 -0
  36. package/reference/lifecycle.md +15 -0
  37. package/reference/model-keeper.md +30 -10
  38. package/reference/model-test.md +11 -6
  39. package/reference/models.md +25 -14
  40. package/reference/oc-source-map.md +162 -0
  41. package/reference/owner-pin.md +31 -0
  42. package/reference/roster.md +15 -0
  43. package/reference/session-scope.md +9 -0
  44. package/reference/session-state.md +13 -0
  45. package/reference/swarm.md +32 -0
  46. package/scripts/backup-config.ps1 +42 -0
  47. package/scripts/gc-branch.ps1 +196 -0
  48. package/scripts/gc-bump.ps1 +198 -0
  49. package/scripts/gc-clean.ps1 +648 -0
  50. package/scripts/gc-commit.ps1 +143 -0
  51. package/scripts/gc-merge.ps1 +272 -0
  52. package/scripts/gc-pr.ps1 +190 -0
  53. package/scripts/gc-push.ps1 +111 -0
  54. package/scripts/gc-read.ps1 +150 -0
  55. package/scripts/gc-rebase.ps1 +162 -0
  56. package/scripts/gc-release.ps1 +225 -0
  57. package/scripts/gc-stage.ps1 +103 -0
  58. package/scripts/gc-status.ps1 +127 -0
  59. package/scripts/gc-sync.ps1 +65 -0
  60. package/scripts/gc.core.ps1 +715 -0
  61. package/scripts/gc.smoke.ps1 +779 -0
  62. package/scripts/harness-doctor.ps1 +11 -9
  63. package/scripts/interrupt-session.ps1 +65 -0
  64. package/scripts/logbook/README.md +108 -0
  65. package/scripts/logbook/logbook.test.ts +440 -0
  66. package/scripts/logbook/logbook.ts +797 -0
  67. package/scripts/pirep/README.md +147 -0
  68. package/scripts/pirep/pirep.test.ts +735 -0
  69. package/scripts/pirep/pirep.ts +836 -0
  70. package/scripts/testflight/README.md +112 -0
  71. package/scripts/testflight/testflight.test.ts +512 -0
  72. package/scripts/testflight/testflight.ts +806 -0
  73. package/skills/_shared/SOURCES.md +7 -7
  74. package/skills/_shared/references/definition-of-done.md +2 -2
  75. package/skills/_shared/references/orchestration-patterns.md +1 -2
  76. package/skills/_shared/references/security-checklist.md +2 -2
  77. package/skills/api-and-interface-design/SKILL.md +7 -360
  78. package/skills/browser-testing-with-devtools/SKILL.md +303 -0
  79. package/skills/code-simplification/SKILL.md +7 -364
  80. package/skills/creative-writing/SKILL.md +1 -1
  81. package/skills/debugging-and-error-recovery/SKILL.md +8 -309
  82. package/skills/flight-deck/SKILL.md +17 -0
  83. package/skills/frontend-ui-engineering/SKILL.md +8 -320
  84. package/skills/gauntlet/SKILL.md +21 -0
  85. package/skills/git-ceremony/SKILL.md +16 -318
  86. package/skills/grilling/SKILL.md +10 -30
  87. package/skills/observability-and-instrumentation/SKILL.md +9 -229
  88. package/skills/performance-optimization/SKILL.md +8 -488
  89. package/skills/pilot-report/SKILL.md +18 -0
  90. package/skills/planning-and-task-breakdown/SKILL.md +8 -249
  91. package/skills/security-and-hardening/SKILL.md +9 -490
  92. package/skills/source-driven-development/SKILL.md +8 -208
  93. package/skills/spec-driven-development/SKILL.md +15 -234
  94. package/skills/test-driven-development/SKILL.md +8 -388
  95. package/skills/test-flight/SKILL.md +14 -0
  96. package/skills/writing-for-agents/SKILL-MECHANICS.md +3 -3
  97. package/skills/writing-for-agents/SKILL.md +7 -1
  98. package/agents/coder.md +0 -19
  99. package/agents/documenter.md +0 -28
  100. package/agents/keeper.md +0 -22
  101. package/agents/master.md +0 -70
  102. package/agents/researcher.md +0 -21
  103. package/agents/security-auditor.md +0 -20
  104. package/agents/test-engineer.md +0 -20
  105. package/agents/web-performance-auditor.md +0 -19
  106. package/commands/council.md +0 -24
  107. package/commands/doctor.md +0 -19
  108. package/commands/ponytail-audit.md +0 -7
  109. package/commands/ponytail-debt.md +0 -14
  110. package/commands/report.md +0 -13
  111. package/scripts/harness-report.ps1 +0 -695
  112. package/scripts/panic/panic.ts +0 -240
  113. package/skills/code-review-and-quality/SKILL.md +0 -396
  114. package/skills/incremental-implementation/SKILL.md +0 -249
  115. package/skills/swarm-orchestration/SKILL.md +0 -54
@@ -102,14 +102,14 @@ $requiredPaths = @(
102
102
  )
103
103
 
104
104
  # Legacy / remote-catalog top-level keys that must not appear in opencode.jsonc.
105
- # Evidence: <EVIDENCE_ARCHIVE>\.docs\harness-plugin-allowlist.md (the "no remote skill-catalog
106
- # keys" file check). 'plugins' and 'mcp' are legitimate config and are NOT here.
105
+ # Evidence: the package's own .docs (the "no remote skill-catalog keys" file check).
106
+ # 'plugins' and 'mcp' are legitimate config and are NOT here.
107
107
  $remoteCatalogKeys = @('plugin', 'mcpServers', 'mcp_servers', 'skill_catalog', 'skills_catalog', 'remote_skills', 'skills_remote')
108
108
 
109
109
  # Deny gates that must hold as effect=deny (ask is auto-approved under --auto,
110
110
  # so only deny survives). Evidence: the opencode.jsonc inline policy comment
111
- # ("deny is the only gate that holds while you are away"; same text in
112
- # <EVIDENCE_ARCHIVE>\.docs\opencode.jsonc.bak-20260915-pre-harness-guard-removal). Verification is
111
+ # ("deny is the only gate that holds while you are away"; same text in the package's
112
+ # own .docs). Verification is
113
113
  # derived: each gate needs a matching deny rule in the live permissions array.
114
114
  $denyGates = @(
115
115
  @{ Action = 'shell'; Contains = 'Format-Volume' },
@@ -318,10 +318,12 @@ function Get-ModelCatalog {
318
318
  $provider = ''
319
319
  if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return [pscustomobject]@{ Ids = $ids; Provider = $provider; Found = $false } }
320
320
  $text = Get-SafeText -Path $Path
321
- foreach ($m in [regex]::Matches($text, '(?m)^\|\s*\d+\s*\|\s*`([^`]+)`')) { $ids.Add($m.Groups[1].Value.Trim()) }
322
- foreach ($m in [regex]::Matches($text, 'opencode-go/([A-Za-z0-9._-]+)')) { $ids.Add($m.Groups[1].Value.Trim()) }
323
321
  $providerMatch = [regex]::Match($text, 'Model \((?<provider>[A-Za-z0-9._-]+)/<id>\)')
324
- if ($providerMatch.Success) { $provider = $providerMatch.Groups['provider'].Value }
322
+ $provider = if ($providerMatch.Success) { $providerMatch.Groups['provider'].Value } else { '' }
323
+ foreach ($m in [regex]::Matches($text, '(?m)^\|\s*\d+\s*\|\s*`([^`]+)`')) { $ids.Add($m.Groups[1].Value.Trim()) }
324
+ if ($providerMatch.Success) {
325
+ foreach ($m in [regex]::Matches($text, [regex]::Escape($provider) + '/([A-Za-z0-9._-]+)')) { $ids.Add($m.Groups[1].Value.Trim()) }
326
+ }
325
327
  $ids = [System.Collections.Generic.List[string]]::new([string[]](@($ids | Sort-Object -Unique)))
326
328
  return [pscustomobject]@{ Ids = $ids; Provider = $provider; Found = $true }
327
329
  }
@@ -427,7 +429,7 @@ if ($configOk) {
427
429
  Add-Law 'no legacy remote-catalog keys in opencode.jsonc' 'PASS' 'no plugin/mcpServers/skill-catalog keys; plugins[] and mcp come from config + registry only'
428
430
  } else {
429
431
  Add-Law 'no legacy remote-catalog keys in opencode.jsonc' 'FAIL' "legacy keys present: $($badKeys -join ', ')" `
430
- "remove these keys from opencode.jsonc ($($badKeys -join ', ')) — see <EVIDENCE_ARCHIVE>\.docs\harness-plugin-allowlist.md"
432
+ "remove these keys from opencode.jsonc ($($badKeys -join ', ')) — see the package's own .docs"
431
433
  }
432
434
  } else {
433
435
  Add-ConfigDrift 'no legacy remote-catalog keys in opencode.jsonc'
@@ -552,7 +554,7 @@ if (-not $configOk) {
552
554
  }
553
555
  if ($mcpProblems.Count -gt 0) {
554
556
  Add-Law 'configured MCP servers match the registry both directions' 'FAIL' ($mcpProblems -join '; ') `
555
- "run from $root (project configs in cwd merge into the registry); then reconcile the mcp block in opencode.jsonc with ``opencode mcp list`` (see <EVIDENCE_ARCHIVE>\.docs\playwright-mcp-browser-tool.md): $($mcpProblems -join '; ')"
557
+ "run from $root (project configs in cwd merge into the registry); then reconcile the mcp block in opencode.jsonc with ``opencode mcp list`` (see the package's own .docs): $($mcpProblems -join '; ')"
556
558
  } elseif ($undeclaredRegistrations.Count -gt 0) {
557
559
  Add-Law 'configured MCP servers match the registry both directions' 'PASS' "no MCP servers declared in opencode.jsonc; the registry reports machine-global servers it has not adopted: $($undeclaredRegistrations -join ', ') (add an mcp block to adopt them)"
558
560
  } else {
@@ -0,0 +1,65 @@
1
+ param(
2
+ [Parameter(Mandatory = $true, Position = 0)]
3
+ [string]$Target
4
+ )
5
+
6
+ Set-StrictMode -Version Latest
7
+ $ErrorActionPreference = 'Stop'
8
+
9
+ try {
10
+ $stateRoot = if ($env:XDG_STATE_HOME) {
11
+ $env:XDG_STATE_HOME
12
+ } else {
13
+ Join-Path $env:USERPROFILE '.local\state'
14
+ }
15
+
16
+ $servicePath = Join-Path $stateRoot 'opencode\service.json'
17
+ if (-not (Test-Path -LiteralPath $servicePath)) {
18
+ $servicePath = Join-Path $env:USERPROFILE '.config\opencode\service.json'
19
+ }
20
+
21
+ if (-not (Test-Path -LiteralPath $servicePath)) {
22
+ throw 'OpenCode service registration not found'
23
+ }
24
+
25
+ $service = Get-Content -LiteralPath $servicePath -Raw | ConvertFrom-Json
26
+ if (-not $service.password) { throw 'service registration has no password' }
27
+ if (-not $service.url -and -not $service.port) { throw 'service registration has neither url nor port' }
28
+ $baseUrl = if ($service.url) { "$($service.url)" } else { "http://127.0.0.1:$($service.port)" }
29
+ $serviceUri = [uri]$baseUrl
30
+ if ($serviceUri.Scheme -notin @('http', 'https') -or -not $serviceUri.IsLoopback) {
31
+ throw 'service registration URL must be loopback HTTP(S)'
32
+ }
33
+ $token = [Convert]::ToBase64String(
34
+ [Text.Encoding]::UTF8.GetBytes("opencode:$($service.password)")
35
+ )
36
+ $headers = @{ Authorization = "Basic $token" }
37
+ $sessionId = $Target.Trim()
38
+ if (-not $sessionId) { throw 'target must not be empty' }
39
+
40
+ if ($sessionId -notmatch '^ses_') {
41
+ $activeResponse = Invoke-RestMethod "$baseUrl/api/session/active" -Headers $headers -TimeoutSec 8
42
+ $activeIds = if ($null -eq $activeResponse.data) {
43
+ @()
44
+ } else {
45
+ @($activeResponse.data.PSObject.Properties | ForEach-Object { $_.Name })
46
+ }
47
+ $query = [uri]::EscapeDataString(($sessionId -replace '^(the|a|an)\s+', ''))
48
+ $searchResponse = Invoke-RestMethod "$baseUrl/api/session?search=$query&order=desc&limit=20" -Headers $headers -TimeoutSec 8
49
+ $searchItems = if ($null -eq $searchResponse.data) { @() } else { @($searchResponse.data) }
50
+ $matches = @($searchItems | Where-Object { $null -ne $_ -and $activeIds -contains $_.id })
51
+
52
+ if ($matches.Count -ne 1) {
53
+ throw "expected one running match for '$Target'; found $($matches.Count)"
54
+ }
55
+ $sessionId = $matches[0].id
56
+ }
57
+
58
+ if ($sessionId -notmatch '^ses_[A-Za-z0-9]+$') { throw 'target is not a valid session ID' }
59
+ $escapedSessionId = [uri]::EscapeDataString($sessionId)
60
+ $result = Invoke-RestMethod -Method Post -Uri "$baseUrl/api/session/$escapedSessionId/interrupt" -Headers $headers -TimeoutSec 8
61
+ "interrupted=$($result.interrupted)"
62
+ } catch {
63
+ "kill failed: $($_.Exception.Message)"
64
+ exit 1
65
+ }
@@ -0,0 +1,108 @@
1
+ # logbook
2
+
3
+ The readable half of your OpenCode history.
4
+
5
+ Every session you have ever run is still on disk, but it is write-only — nothing
6
+ can search it, so problems get solved for the first time, every time. Logbook
7
+ makes it readable.
8
+
9
+ ```bash
10
+ logbook "lastexitcode" # search everything you have ever run
11
+ logbook --precedent "<error>" # find prior occurrences of a failure
12
+ logbook --precedent # ...reading the error from stdin
13
+ logbook --stats # what is indexed
14
+ logbook --reindex # rebuild from scratch
15
+ logbook --json # machine-readable
16
+ logbook --limit=5 "narrow this"
17
+ ```
18
+
19
+ ## How it is wired
20
+
21
+ - **CLI**, run through `bun`. No plugin, no MCP, no daemon, no server.
22
+ - **Trigger:** `skills/debugging-and-error-recovery/SKILL.md` Step 0 tells the
23
+ agent to run `--precedent` before diagnosing anything.
24
+ - **Shim:** `~/.local/bin/logbook.cmd` (that directory is already on `PATH`).
25
+ - **Source (primary):** the running host's documented V2 HTTP API, called through
26
+ the documented `opencode api` CLI — no token, port, or header handling of our
27
+ own.
28
+ - **Source (fallback):** `~/.local/share/opencode/opencode.db`, opened
29
+ **read-only**. Used automatically when the API is unavailable, errors, or
30
+ returns nothing usable; the switch is recorded and printed, never silent.
31
+ - **Index:** `~/.opencode/logbook/index.db` — deliberately outside the config
32
+ directory, so the config-directory Git mirror never copies it into the repo.
33
+
34
+ ## Design rules
35
+
36
+ 1. **The host database is never written.** The index is a separate file this tool
37
+ owns.
38
+ 2. **The index is derived data.** Deleting it and re-running `--reindex` is always
39
+ safe.
40
+ 3. **Secrets are scrubbed on the way in.** Transcripts contain pasted tokens, and
41
+ an index is a new place for them to leak from. Known credential shapes are
42
+ replaced with `[redacted]`; `key=value` forms keep the key so context survives.
43
+ This is a seatbelt, not a guarantee — unknown formats will get through.
44
+ 4. **Degrade quietly.** A missing index or an unreadable database prints one clear
45
+ line and exits non-zero. It never throws a stack trace at you.
46
+
47
+ ## What is indexed
48
+
49
+ | Kind | Source | Why |
50
+ |---|---|---|
51
+ | `user` | your prompts | the question you asked |
52
+ | `assistant` | the model's prose | the answer, and the reasoning behind it |
53
+ | `note` | synthetic + compaction summaries | context that would otherwise vanish |
54
+ | `error` | **failed** tool calls only | the failure text itself |
55
+
56
+ **Deliberately not indexed: successful tool output** (~52k documents of directory
57
+ listings and command results). It is the bulk of the corpus and almost none of
58
+ the retrieval value, and its short fragments would outrank long explanations
59
+ under bm25. Revisit if you ever want to search for *a command you ran* rather
60
+ than *a problem you solved*. Also skipped: `reasoning` blocks.
61
+
62
+ Long documents are clamped to 8,000 characters **head-and-tail**, because
63
+ failures report at the end of output.
64
+
65
+ ## Schema coupling
66
+
67
+ Ingest prefers the host's **documented V2 HTTP API** — `GET /api/session` for the
68
+ session list and `GET /api/session/{id}/message` for messages — called through
69
+ the documented `opencode api` CLI. The index schema is
70
+ unchanged either way, and only the documented surface is used, so a host schema
71
+ move no longer breaks ingest.
72
+
73
+ The read-only `bun:sqlite` path over `session_message` and `session_v2` remains
74
+ as an automatic **fallback**. It triggers when the API is unavailable or errors
75
+ (missing binary, no running service, non-zero exit, non-JSON) or returns nothing
76
+ usable (an empty or unrecognisable shape). When it triggers, logbook prints one
77
+ line to stderr, records `last_source=db` and the reason in the index `meta`
78
+ table, and `--stats` reports `ingest host database`.
79
+
80
+ Why the split: the API is the host's public contract and survives internal
81
+ schema changes, but it only exists while the host service is running; the
82
+ database is always on disk. Preferring the API and falling back to the table read
83
+ means a host that has moved its tables degrades instead of breaking, and an
84
+ unavailable API still yields a searchable index. The host database is never
85
+ written by either path.
86
+
87
+ Incremental sync from the API is per session — sessions created since the last
88
+ run, plus sessions the host reports as running — because the API exposes no
89
+ global "messages since" cursor and a session's `time.updated` does not move when
90
+ it gains messages. `--reindex` walks every session.
91
+
92
+ The legacy `message`/`part` tables are not indexed: they stop at 2026-08-13 and
93
+ overlap `session_message`, which spans the full range.
94
+
95
+ ## Tests
96
+
97
+ ```bash
98
+ cd ~/.config/opencode/scripts/logbook && bun test
99
+ ```
100
+
101
+ 25 tests: redaction, query building, schema parsing, incremental sync (including
102
+ in-place updates), the API-message adapter, path normalisation, automatic
103
+ fallback with its recorded reason, and the real CLI against a fixture database.
104
+
105
+ The CLI tests point `LOGBOOK_API_BIN` at a binary that cannot exist, so they
106
+ exercise the fixture database deterministically instead of whatever host service
107
+ happens to be running. Add a new test for API behaviour by exporting
108
+ `LOGBOOK_API_BIN` to a fake.
@@ -0,0 +1,440 @@
1
+ // Logbook's behaviour, pinned. The point of these is that the two things that
2
+ // could quietly ruin the index — a leaked secret, and a silent mis-parse of the
3
+ // host schema — both fail loudly here instead.
4
+
5
+ import { describe, expect, test } from "bun:test";
6
+ import { Database } from "bun:sqlite";
7
+ import { mkdtempSync, rmSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { docsFromMessage, ingest, normDir, openIndex, redact, rowFromApiMessage, search, sync, toMatchQuery } from "./logbook.ts";
11
+
12
+ const CLIENT = join(import.meta.dir, "logbook.ts");
13
+
14
+ interface Row {
15
+ id: string;
16
+ session_id: string;
17
+ type: string;
18
+ time_created: number;
19
+ time_updated: number;
20
+ data: string;
21
+ }
22
+
23
+ const message = (over: Partial<Row> & { id: string; type: string; data: unknown }): Row => ({
24
+ session_id: "ses_fixture",
25
+ time_created: 1_700_000_000_000,
26
+ time_updated: 1_700_000_000_000,
27
+ ...over,
28
+ session_id: over.session_id ?? "ses_fixture",
29
+ data: JSON.stringify(over.data),
30
+ });
31
+
32
+ /**
33
+ * A miniature of the real host database: two tables, and only the columns the
34
+ * tool actually reads. If the host schema moves, these tests keep passing while
35
+ * the real run fails loudly — which is the correct asymmetry.
36
+ */
37
+ function fixtureDb(rows: readonly Row[]): Database {
38
+ const db = new Database(":memory:");
39
+ db.exec("create table session_v2(id text, title text, directory text)");
40
+ db.exec("create table session_message(id text, session_id text, type text, seq integer, time_created integer, time_updated integer, data text)");
41
+ db.exec("insert into session_v2 values('ses_fixture', 'Ticker reactivity', 'C:/Users/alice/foo')");
42
+ const insert = db.query(
43
+ "insert into session_message(id, session_id, type, seq, time_created, time_updated, data) values(?, ?, ?, 0, ?, ?, ?)",
44
+ );
45
+ for (const row of rows) {
46
+ insert.run(row.id, row.session_id, row.type, row.time_created, row.time_updated, row.data);
47
+ }
48
+ return db;
49
+ }
50
+
51
+ function tempIndex(): { path: string; indexPath: string } {
52
+ const dir = mkdtempSync(join(tmpdir(), "logbook-test-"));
53
+ return { path: dir, indexPath: join(dir, "index.db") };
54
+ }
55
+
56
+ describe("redact", () => {
57
+ test("removes the credential shapes that actually show up in transcripts", () => {
58
+ expect(redact("token npm_abcdefghijklmnopqrstuvwxyz here")).toContain("[redacted]");
59
+ expect(redact("token npm_abcdefghijklmnopqrstuvwxyz here")).not.toContain("abcdefghijkl");
60
+ // literals are split so the gc secret gate stays clean (it scans for the
61
+ // sk-/AKIA/xoxb- shapes these very fixtures must exercise); runtime
62
+ // strings are identical either way.
63
+ expect(redact("sk-" + "abcdefghijklmnopqrstuvwx")).toBe("[redacted]");
64
+ expect(redact("ghp_abcdefghijklmnopqrstuvwx")).toBe("[redacted]");
65
+ expect(redact("AKIA" + "IOSFODNN7EXAMPLE")).toBe("[redacted]");
66
+ expect(redact("xoxb-" + "1234567890-abcdefghij")).toBe("[redacted]");
67
+ });
68
+
69
+ test("keeps the key so the surrounding context survives", () => {
70
+ const out = redact("//registry.npmjs.org/:_authToken=supersecretvalue123");
71
+ expect(out).toContain("_authToken");
72
+ expect(out).toContain("[redacted]");
73
+ expect(out).not.toContain("supersecretvalue123");
74
+ });
75
+
76
+ test("leaves ordinary prose alone", () => {
77
+ const text = "the spinner wraps rather than running off the end of the frame list";
78
+ expect(redact(text)).toBe(text);
79
+ });
80
+ });
81
+
82
+ describe("toMatchQuery", () => {
83
+ test("quotes every term so error punctuation cannot become FTS syntax", () => {
84
+ expect(toMatchQuery("bun test (fail)", "all")).toBe('"bun" AND "test" AND "fail"');
85
+ expect(toMatchQuery("bun test (fail)", "any")).toBe('"bun" OR "test" OR "fail"');
86
+ });
87
+
88
+ test("drops tokens too short to discriminate anything", () => {
89
+ expect(toMatchQuery("a i the spinner", "all")).toBe('"the" AND "spinner"');
90
+ });
91
+
92
+ test("deduplicates so repetition cannot skew the ranking", () => {
93
+ expect(toMatchQuery("ticker ticker ticker", "all")).toBe('"ticker"');
94
+ });
95
+
96
+ test("returns an empty query rather than throwing on punctuation-only input", () => {
97
+ expect(toMatchQuery("!!! ??? ---", "all")).toBe("");
98
+ expect(toMatchQuery("", "all")).toBe("");
99
+ });
100
+ });
101
+
102
+ describe("docsFromMessage", () => {
103
+ const meta = { title: "T", dir: "D" };
104
+
105
+ test("takes a user prompt as one document", () => {
106
+ const docs = docsFromMessage(
107
+ message({ id: "m1", type: "user", data: { text: "we should check the ticker again" } }),
108
+ meta,
109
+ );
110
+ expect(docs).toHaveLength(1);
111
+ expect(docs[0]?.kind).toBe("user");
112
+ expect(docs[0]?.text).toContain("ticker");
113
+ });
114
+
115
+ test("reads assistant prose but ignores reasoning", () => {
116
+ const docs = docsFromMessage(
117
+ message({
118
+ id: "m2",
119
+ type: "assistant",
120
+ data: {
121
+ content: [
122
+ { type: "reasoning", text: "the internal monologue nobody searches for" },
123
+ { type: "text", text: "the fix is to route the tick through the host store" },
124
+ ],
125
+ },
126
+ }),
127
+ meta,
128
+ );
129
+ expect(docs).toHaveLength(1);
130
+ expect(docs[0]?.kind).toBe("assistant");
131
+ expect(docs[0]?.text).toContain("host store");
132
+ });
133
+
134
+ test("pulls the failure text out of a failed tool call", () => {
135
+ const docs = docsFromMessage(
136
+ message({
137
+ id: "m3",
138
+ type: "assistant",
139
+ data: {
140
+ content: [
141
+ {
142
+ type: "tool",
143
+ name: "shell",
144
+ state: {
145
+ status: "error",
146
+ input: { command: "bun run check" },
147
+ content: [{ type: "text", text: "error TS2345: argument not assignable" }],
148
+ },
149
+ },
150
+ ],
151
+ },
152
+ }),
153
+ meta,
154
+ );
155
+ expect(docs).toHaveLength(1);
156
+ expect(docs[0]?.kind).toBe("error");
157
+ expect(docs[0]?.text).toContain("TS2345");
158
+ });
159
+
160
+ test("skips successful tool output, which is the bulk of the corpus", () => {
161
+ const docs = docsFromMessage(
162
+ message({
163
+ id: "m4",
164
+ type: "assistant",
165
+ data: {
166
+ content: [
167
+ {
168
+ type: "tool",
169
+ name: "shell",
170
+ state: {
171
+ status: "completed",
172
+ input: { command: "ls" },
173
+ content: [{ type: "text", text: "a very long successful directory listing" }],
174
+ },
175
+ },
176
+ ],
177
+ },
178
+ }),
179
+ meta,
180
+ );
181
+ expect(docs).toHaveLength(0);
182
+ });
183
+
184
+ test("scrubs secrets on the way in, not on the way out", () => {
185
+ const docs = docsFromMessage(
186
+ message({ id: "m5", type: "user", data: { text: "my token is npm_abcdefghijklmnopqrstuvwxyz ok" } }),
187
+ meta,
188
+ );
189
+ expect(docs[0]?.text).not.toContain("abcdefghijkl");
190
+ expect(docs[0]?.text).toContain("[redacted]");
191
+ });
192
+
193
+ test("keeps the tail of a long document, where failures are reported", () => {
194
+ const docs = docsFromMessage(
195
+ message({ id: "m6", type: "user", data: { text: `${"x".repeat(20_000)} THE-END-MARKER` } }),
196
+ meta,
197
+ );
198
+ expect(docs[0]?.text.length).toBeLessThan(9_000);
199
+ expect(docs[0]?.text).toContain("THE-END-MARKER");
200
+ });
201
+
202
+ test("survives data that is not valid JSON rather than crashing the sync", () => {
203
+ const docs = docsFromMessage(
204
+ { id: "m7", session_id: "s", type: "user", time_created: 0, data: "{not json" },
205
+ meta,
206
+ );
207
+ expect(docs).toEqual([]);
208
+ });
209
+ });
210
+
211
+ describe("sync and search", () => {
212
+ test("indexes, is incremental, and replaces a row that changed", () => {
213
+ const { path, indexPath } = tempIndex();
214
+ // time_updated moves between syncs; time_created does not. That asymmetry is
215
+ // what makes a tool call that changed from running -> error re-indexable.
216
+ const source = fixtureDb([
217
+ message({ id: "m1", type: "user", data: { text: "first message about the ticker" } }),
218
+ message({
219
+ id: "m2",
220
+ type: "assistant",
221
+ time_created: 1_700_000_001_000,
222
+ time_updated: 1_700_000_001_000,
223
+ data: { content: [{ type: "text", text: "answer mentioning lastexitcode quirks" }] },
224
+ }),
225
+ ]);
226
+ const index = openIndex(indexPath);
227
+
228
+ const first = sync(index, source, false);
229
+ expect(first.indexed).toBe(2);
230
+ expect(search(index, toMatchQuery("ticker", "all"), 10)).toHaveLength(1);
231
+
232
+ // Nothing changed: a second sync must not duplicate anything.
233
+ const second = sync(index, source, false);
234
+ expect(second.indexed).toBe(0);
235
+ expect(search(index, toMatchQuery("ticker", "all"), 10)).toHaveLength(1);
236
+
237
+ // A row that is edited in place must replace its old document, not add one.
238
+ source
239
+ .query("update session_message set data = ?, time_updated = ? where id = 'm1'")
240
+ .run(JSON.stringify({ text: "first message about the ticker, now corrected" }), 1_700_000_002_000);
241
+ const third = sync(index, source, false);
242
+ expect(third.indexed).toBe(1);
243
+ expect(search(index, toMatchQuery("ticker", "all"), 10)).toHaveLength(1);
244
+ expect(search(index, toMatchQuery("corrected", "all"), 10)).toHaveLength(1);
245
+
246
+ index.close();
247
+ source.close();
248
+ rmSync(path, { recursive: true, force: true });
249
+ });
250
+
251
+ test("a forced rebuild produces the same index rather than doubling it", () => {
252
+ const { path, indexPath } = tempIndex();
253
+ const source = fixtureDb([
254
+ message({ id: "m1", type: "user", data: { text: "a searchable sentence about flight decks" } }),
255
+ ]);
256
+ const index = openIndex(indexPath);
257
+
258
+ sync(index, source, false);
259
+ sync(index, source, true);
260
+ expect(search(index, toMatchQuery("flight decks", "all"), 10)).toHaveLength(1);
261
+
262
+ index.close();
263
+ source.close();
264
+ rmSync(path, { recursive: true, force: true });
265
+ });
266
+
267
+ test("carries the session title and date into each hit", () => {
268
+ const { path, indexPath } = tempIndex();
269
+ const source = fixtureDb([
270
+ message({ id: "m1", type: "user", data: { text: "something worth finding later" } }),
271
+ ]);
272
+ const index = openIndex(indexPath);
273
+ sync(index, source, false);
274
+
275
+ const [hit] = search(index, toMatchQuery("finding later", "all"), 10);
276
+ expect(hit?.title).toBe("Ticker reactivity");
277
+ expect(hit?.dir).toBe("C:/Users/alice/foo");
278
+ expect(hit?.snippet).toContain("<<");
279
+ expect(hit?.snippet).toContain(">>");
280
+
281
+ index.close();
282
+ source.close();
283
+ rmSync(path, { recursive: true, force: true });
284
+ });
285
+
286
+ test("--precedent's OR mode still finds a hit when no term appears together", () => {
287
+ const { path, indexPath } = tempIndex();
288
+ const source = fixtureDb([
289
+ message({
290
+ id: "m1",
291
+ type: "assistant",
292
+ data: { content: [{ type: "text", text: "the pipeline swallows the exit code from the native command" }] },
293
+ }),
294
+ ]);
295
+ const index = openIndex(indexPath);
296
+ sync(index, source, false);
297
+
298
+ expect(search(index, toMatchQuery("last-exit-code pipeline", "all"), 10)).toHaveLength(0);
299
+ expect(search(index, toMatchQuery("pipeline exit code", "any"), 10).length).toBeGreaterThan(0);
300
+
301
+ index.close();
302
+ source.close();
303
+ rmSync(path, { recursive: true, force: true });
304
+ });
305
+ });
306
+
307
+ describe("api adapter", () => {
308
+ const meta = { title: "T", dir: "D" };
309
+
310
+ test("maps an API message to the same documents as the host row", () => {
311
+ const dbUser = message({ id: "m1", type: "user", data: { text: "we should check the ticker again" } });
312
+ const apiUser = rowFromApiMessage("ses_fixture", {
313
+ id: "m1",
314
+ time: { created: 1_700_000_000_000 },
315
+ type: "user",
316
+ text: "we should check the ticker again",
317
+ });
318
+ expect(apiUser).toEqual({
319
+ id: "m1",
320
+ session_id: "ses_fixture",
321
+ type: "user",
322
+ time_created: 1_700_000_000_000,
323
+ data: '{"text":"we should check the ticker again"}',
324
+ });
325
+ expect(docsFromMessage(apiUser!, meta)).toEqual(docsFromMessage(dbUser, meta));
326
+
327
+ // The API flattens the payload and moves `time` to the top level; a failed
328
+ // tool call must still extract identically.
329
+ const content = [
330
+ { type: "tool", name: "shell", state: { status: "error", content: [{ type: "text", text: "error TS2345: argument not assignable" }] } },
331
+ ];
332
+ const dbTool = message({ id: "m3", type: "assistant", data: { content } });
333
+ const apiTool = rowFromApiMessage("ses_fixture", { id: "m3", time: { created: 1_700_000_000_000 }, type: "assistant", content });
334
+ expect(docsFromMessage(apiTool!, meta)).toEqual(docsFromMessage(dbTool, meta));
335
+ });
336
+
337
+ test("rejects a message the API returned without an id, type or timestamp", () => {
338
+ expect(rowFromApiMessage("s", { type: "user", time: { created: 1 } })).toBeUndefined();
339
+ expect(rowFromApiMessage("s", { id: "m", time: { created: 1 } })).toBeUndefined();
340
+ expect(rowFromApiMessage("s", { id: "m", type: "user" })).toBeUndefined();
341
+ });
342
+
343
+ test("normalises the API's native path separators to the host table's form", () => {
344
+ expect(normDir("C:\\Users\\alice\\.config\\opencode")).toBe("C:/Users/alice/.config/opencode");
345
+ expect(normDir("/home/user/project")).toBe("/home/user/project");
346
+ expect(normDir(undefined)).toBe("");
347
+ });
348
+
349
+ test("falls back to the database and records why when the API is unavailable", () => {
350
+ const { path, indexPath } = tempIndex();
351
+ const source = fixtureDb([
352
+ message({ id: "m1", type: "user", data: { text: "a fallback sentence about the ticker" } }),
353
+ ]);
354
+ const index = openIndex(indexPath);
355
+ const previous = process.env["LOGBOOK_API_BIN"];
356
+ process.env["LOGBOOK_API_BIN"] = join(path, "no-such-opencode");
357
+ try {
358
+ const result = ingest(index, source, false);
359
+ expect(result.source).toBe("db");
360
+ expect(result.fallbackReason).toBeDefined();
361
+ expect(result.indexed).toBe(1);
362
+ const recorded = index
363
+ .query<{ value: string }, []>("select value from meta where key = 'last_source'")
364
+ .get();
365
+ expect(recorded?.value).toBe("db");
366
+ expect(search(index, toMatchQuery("ticker", "all"), 10)).toHaveLength(1);
367
+ } finally {
368
+ if (previous === undefined) delete process.env["LOGBOOK_API_BIN"];
369
+ else process.env["LOGBOOK_API_BIN"] = previous;
370
+ index.close();
371
+ source.close();
372
+ rmSync(path, { recursive: true, force: true });
373
+ }
374
+ });
375
+ });
376
+
377
+ describe("cli", () => {
378
+ function run(args: readonly string[], indexPath: string, sourcePath: string) {
379
+ return Bun.spawnSync({
380
+ cmd: ["bun", CLIENT, ...args],
381
+ // LOGBOOK_API_BIN points at a binary that cannot exist, so the CLI is
382
+ // exercised against the fixture database deterministically instead of
383
+ // whatever host service happens to be running.
384
+ env: {
385
+ ...process.env,
386
+ LOGBOOK_INDEX: indexPath,
387
+ LOGBOOK_SOURCE: sourcePath,
388
+ LOGBOOK_API_BIN: join(sourcePath, "..", "no-such-opencode"),
389
+ },
390
+ stdout: "pipe",
391
+ stderr: "pipe",
392
+ });
393
+ }
394
+
395
+ test("prints hits with the session, date and a snippet", () => {
396
+ const { path, indexPath } = tempIndex();
397
+ const sourcePath = join(path, "source.db");
398
+ const source = new Database(sourcePath);
399
+ source.exec("create table session_v2(id text, title text, directory text)");
400
+ source.exec("create table session_message(id text, session_id text, type text, seq integer, time_created integer, time_updated integer, data text)");
401
+ source.exec("insert into session_v2 values('ses_fixture', 'Exit codes', 'Q:/P')");
402
+ source
403
+ .query("insert into session_message values(?, 'ses_fixture', 'user', 0, ?, ?, ?)")
404
+ .run(
405
+ "m1",
406
+ 1_700_000_000_000,
407
+ 1_700_000_000_000,
408
+ JSON.stringify({ text: "the last-exit-code after a pipeline is the wrong one" }),
409
+ );
410
+ source.close();
411
+
412
+ const ok = run(["last-exit-code"], indexPath, sourcePath);
413
+ expect(ok.exitCode).toBe(0);
414
+ const out = ok.stdout.toString();
415
+ expect(out).toContain("Exit codes");
416
+ expect(out).toContain("2023-11-14");
417
+ expect(out).toContain("<<");
418
+
419
+ const misses = run(["something-never-said-ever"], indexPath, sourcePath);
420
+ expect(misses.stdout.toString()).toContain("no matches");
421
+
422
+ rmSync(path, { recursive: true, force: true });
423
+ });
424
+
425
+ test("explains itself instead of throwing when there is no history to read", () => {
426
+ const { path, indexPath } = tempIndex();
427
+ const missing = run(["anything"], indexPath, join(path, "does-not-exist.db"));
428
+ expect(missing.exitCode).toBe(1);
429
+ expect(missing.stderr.toString()).toContain("no history found");
430
+ rmSync(path, { recursive: true, force: true });
431
+ });
432
+
433
+ test("--help does not touch an index at all", () => {
434
+ const { path, indexPath } = tempIndex();
435
+ const help = run(["--help"], join(path, "never-created.db"), join(path, "nope.db"));
436
+ expect(help.exitCode).toBe(0);
437
+ expect(help.stdout.toString()).toContain("logbook — search your OpenCode history");
438
+ rmSync(path, { recursive: true, force: true });
439
+ });
440
+ });