Skip to content

fix(discovery): exclude backpass's own OpenCode sessions safely - #174

Closed
PawanAIT wants to merge 7 commits into
kunchenguid:mainfrom
PawanAIT:pawan/opencode-self
Closed

PawanAIT wants to merge 7 commits into
kunchenguid:mainfrom
PawanAIT:pawan/opencode-self

Conversation

@PawanAIT

@PawanAIT PawanAIT commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Make backpass never analyze its own OpenCode sessions, and never drop a genuine one. acpx drives opencode (on both default ladders), so backpass analysis and synthesis calls land in the opencode SQLite store under the repo cwd; the file-head self check cannot see them and instead reads the database head, where one backpass prompt marks every session in the store as self. Mark self sessions from the store (first user text opens with the sentinel), never read a SQLite database as a transcript head, and do not list the empty sessions each agent probe leaves behind.

What Changed

  • Detect OpenCode self sessions from the first user text in SQLite and exclude their descendants locally and remotely, even when ancestors fall outside --since.
  • Skip transcript-head reads for SQLite stores and omit message-less OpenCode probe sessions while retaining genuine conversations, including attachment-only prompts.
  • Document the filtering behavior and add regression coverage for shared stores, malformed rows, ancestry, CLI scans, and remote probes.

Risk Assessment

✅ Low: The change is limited to OpenCode self-session detection and the SQLite head-read bypass. Both earlier fix rounds are verified correct, the logic fails soft on corrupt rows, and behavioral tests cover the local and remote paths.

Testing

Focused self-session and probe tests passed, followed by six live scenarios using isolated CLI scans and locally executed shipped probes. Captured product outputs confirm self exclusion, genuine-session retention, and the attachment fix. Disposable data was removed; no source changes were needed.

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Scan a shared database containing genuine work and backpass analysis/synthesis sessions ✅ pass live round2-product-transcripts.txt: round2-mixed-store
Exclude self sessions whose prompts lie beyond the database-head window ✅ pass live round2-product-transcripts.txt: round2-self-beyond-head
Retain an image-only conversation while omitting unused agent probes ✅ pass live round2-attachments-and-probes-scan.txt; round2-attachments-and-probes-fetch.frames
Retain genuine conversations that mention or later quote the sentinel ✅ pass live round2-product-transcripts.txt: round2-genuine-sentinel-mentions
Exclude self descendants across the date cutoff without losing genuine descendants ✅ pass live round2-product-transcripts.txt: round2-ancestry-and-cutoff
Scan a store containing malformed message and part records ✅ pass live round2-product-transcripts.txt: round2-malformed-store-rows
Evidence: CLI and shipped-probe responses for all six scenarios
Real backpass CLI and shipped probe output from isolated disposable OpenCode stores.
Each CLI was also run a second time with the same expected result.
The probe was executed locally via its shipped stdin program, without an SSH server.

SCENARIO: round2-mixed-store
$ node bin/backpass.js scan --harness opencode --since all --strict --json
{
  "repo": "repo",
  "scope": "project",
  "perHarness": {
    "opencode": {
      "scanned": 3,
      "matched": 1,
      "cached": 0,
      "skipped": 0,
      "self": 2,
      "error": null
    }
  },
  "perHost": [],
  "mix": {
    "interactive": 0,
    "nonInteractive": 1,
    "total": 1
  },
  "transcripts": [
    {
      "harness": "opencode",
      "id": "opencode-real-release",
      "nativeId": "real-release",
      "path": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/home/.local/share/opencode/opencode.db",
      "cwd": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo",
      "gitBranch": null,
      "title": "real-release",
      "model": null,
      "startedAt": 1790676426392,
      "mtimeMs": 1790676426392,
      "bytes": 0,
      "contentSignature": null,
      "experimental": false,
      "association": {
        "tier": 1,
        "confidence": "exact",
        "reason": "cwd is worktree ~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo",
        "project": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo",
        "projectRoot": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo"
      },
      "extra": {
        "sessionId": "real-release"
      },
      "interactionSignals": {},
      "project": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo",
      "projectRoot": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo",
      "host": null,
      "identity": "847cda048367d6ed08dd01d581c2c24c2df21bd80fbb4897f20e8e9831cfa3bc",
      "interaction": "non-interactive"
    }
  ]
}

$ node - < buildProbeProgram({op:"discover", harnesses:["opencode"], cutoffMs})
{"protocol":1,"node":"v24.21.0","platform":"linux","hostname":"CPC-kumar-Y38I8","home":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/home","harnesses":{"opencode":{"scanned":3,"classified":3,"self":2,"error":null}},"transcripts":[{"harness":"opencode","kind":"events","key":"opencode:real-release","id":"real-release","path":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/home/.local/share/opencode/opencode.db","cwd":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo","gitRoot":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo","gitBranch":null,"remotes":[],"title":"real-release","startedAt":1790676426392,"mtimeMs":1790676426392,"bytes":0,"contentSignature":"488580f42ea0abce4146cb356372f24bf0b9df2ebc32a91497ef6a109881dc0e","model":null,"extra":{"sessionId":"real-release"},"interactionSignals":{},"rawPath":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/home/.local/share/opencode/opencode.db"}],"paths":{"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo":{"real":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo","exists":true,"toplevel":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-mixed-store/repo","remotes":[]}},"warnings":[]}

SCENARIO: round2-self-beyond-head
$ node bin/backpass.js scan --harness opencode --since all --strict --json
{
  "repo": "repo",
  "scope": "project",
  "perHarness": {
    "opencode": {
      "scanned": 3,
      "matched": 1,
      "cached": 0,
      "skipped": 0,
      "self": 2,
      "error": null
    }
  },
  "perHost": [],
  "mix": {
    "interactive": 0,
    "nonInteractive": 1,
    "total": 1
  },
  "transcripts": [
    {
      "harness": "opencode",
      "id": "opencode-real-release",
      "nativeId": "real-release",
      "path": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/home/.local/share/opencode/opencode.db",
      "cwd": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo",
      "gitBranch": null,
      "title": "real-release",
      "model": null,
      "startedAt": 1790676426392,
      "mtimeMs": 1790676426392,
      "bytes": 0,
      "contentSignature": null,
      "experimental": false,
      "association": {
        "tier": 1,
        "confidence": "exact",
        "reason": "cwd is worktree ~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo",
        "project": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo",
        "projectRoot": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo"
      },
      "extra": {
        "sessionId": "real-release"
      },
      "interactionSignals": {},
      "project": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo",
      "projectRoot": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo",
      "host": null,
      "identity": "4f66af84d779180356c8cb7de342ead8166a9bb2984ec1f41c9c744e1a729abc",
      "interaction": "non-interactive"
    }
  ]
}

$ node - < buildProbeProgram({op:"discover", harnesses:["opencode"], cutoffMs})
{"protocol":1,"node":"v24.21.0","platform":"linux","hostname":"CPC-kumar-Y38I8","home":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/home","harnesses":{"opencode":{"scanned":3,"classified":3,"self":2,"error":null}},"transcripts":[{"harness":"opencode","kind":"events","key":"opencode:real-release","id":"real-release","path":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/home/.local/share/opencode/opencode.db","cwd":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo","gitRoot":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo","gitBranch":null,"remotes":[],"title":"real-release","startedAt":1790676426392,"mtimeMs":1790676426392,"bytes":0,"contentSignature":"488580f42ea0abce4146cb356372f24bf0b9df2ebc32a91497ef6a109881dc0e","model":null,"extra":{"sessionId":"real-release"},"interactionSignals":{},"rawPath":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/home/.local/share/opencode/opencode.db"}],"paths":{"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-beyond-head/repo":{"real":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-self-bey

... [41668 bytes truncated] ...

   },
    {
      "harness": "opencode",
      "id": "opencode-real-malformed-prefix",
      "nativeId": "real-malformed-prefix",
      "path": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home/.local/share/opencode/opencode.db",
      "cwd": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
      "gitBranch": null,
      "title": "real-malformed-prefix",
      "model": null,
      "startedAt": 1790676426392,
      "mtimeMs": 1790676426392,
      "bytes": 0,
      "contentSignature": null,
      "experimental": false,
      "association": {
        "tier": 1,
        "confidence": "exact",
        "reason": "cwd is worktree ~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
        "project": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
        "projectRoot": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo"
      },
      "extra": {
        "sessionId": "real-malformed-prefix"
      },
      "interactionSignals": {},
      "project": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
      "projectRoot": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
      "host": null,
      "identity": "f8e6c25a00bb258c4d26fb6deaeae7bce40a006f1a931467b5a47b061784da29",
      "interaction": "non-interactive"
    },
    {
      "harness": "opencode",
      "id": "opencode-real-malformed-part",
      "nativeId": "real-malformed-part",
      "path": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home/.local/share/opencode/opencode.db",
      "cwd": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
      "gitBranch": null,
      "title": "real-malformed-part",
      "model": null,
      "startedAt": 1790676426392,
      "mtimeMs": 1790676426392,
      "bytes": 0,
      "contentSignature": null,
      "experimental": false,
      "association": {
        "tier": 1,
        "confidence": "exact",
        "reason": "cwd is worktree ~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
        "project": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
        "projectRoot": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo"
      },
      "extra": {
        "sessionId": "real-malformed-part"
      },
      "interactionSignals": {},
      "project": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
      "projectRoot": "~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo",
      "host": null,
      "identity": "a5e424a9d7a1ef1f41caf5f987f43774b2c08db8724a530d3e4c67fb87a8733d",
      "interaction": "non-interactive"
    }
  ]
}

$ node - < buildProbeProgram({op:"discover", harnesses:["opencode"], cutoffMs})
{"protocol":1,"node":"v24.21.0","platform":"linux","hostname":"CPC-kumar-Y38I8","home":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home","harnesses":{"opencode":{"scanned":4,"classified":4,"self":1,"error":null}},"transcripts":[{"harness":"opencode","kind":"events","key":"opencode:real-release","id":"real-release","path":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home/.local/share/opencode/opencode.db","cwd":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo","gitRoot":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo","gitBranch":null,"remotes":[],"title":"real-release","startedAt":1790676426392,"mtimeMs":1790676426392,"bytes":0,"contentSignature":"488580f42ea0abce4146cb356372f24bf0b9df2ebc32a91497ef6a109881dc0e","model":null,"extra":{"sessionId":"real-release"},"interactionSignals":{},"rawPath":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home/.local/share/opencode/opencode.db"},{"harness":"opencode","kind":"events","key":"opencode:real-malformed-prefix","id":"real-malformed-prefix","path":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home/.local/share/opencode/opencode.db","cwd":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo","gitRoot":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo","gitBranch":null,"remotes":[],"title":"real-malformed-prefix","startedAt":1790676426392,"mtimeMs":1790676426392,"bytes":0,"contentSignature":"b956e805255f2b6eb23a66bde8e8a6a001d41452e5bcf5e666b4f60465ad6d71","model":null,"extra":{"sessionId":"real-malformed-prefix"},"interactionSignals":{},"rawPath":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home/.local/share/opencode/opencode.db"},{"harness":"opencode","kind":"events","key":"opencode:real-malformed-part","id":"real-malformed-part","path":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home/.local/share/opencode/opencode.db","cwd":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo","gitRoot":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo","gitBranch":null,"remotes":[],"title":"real-malformed-part","startedAt":1790676426392,"mtimeMs":1790676426392,"bytes":0,"contentSignature":"c046e39aab12d92a7b0d687aaf389ac6eeb8270b33f22013eed6aa3014841372","model":null,"extra":{"sessionId":"real-malformed-part"},"interactionSignals":{},"rawPath":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/home/.local/share/opencode/opencode.db"}],"paths":{"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo":{"real":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo","exists":true,"toplevel":"~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-malformed-store-rows/repo","remotes":[]}},"warnings":[]}

Image-only conversation: shipped probe fetch response
{"key":"opencode:image-conversation","harness":"opencode","kind":"events","bytes":150,"mtimeMs":1790676426392,"contentSignature":"08acf4adb32cec2ba2a9a8ee95017624be6d921c6ba6f741b9d021399bb65ea2","model":null}
{"events":[{"kind":"message","role":"assistant","text":"The screenshot shows a missing release tag. Create the tag before publishing."}],"model":null}{"end":true}
Evidence: Human-readable scan retaining attachment conversations
repo · 1 worktree(s) · since all

HOST   HARNESS   SCANNED  MATCHED  SELF  CACHED  NOTE
local  opencode  4        3        1     0
  SELF = backpass's own loss / gradient-descent sessions, excluded from the corpus

3 transcript(s) associated with this repo · tier1 3 (exact) · tier1.5 0 (sibling clone) · tier2 0 (remote) · tier3 0 (best-effort) · interactive 0 · non-interactive 3

HOST   HARNESS   SESSION       KIND             WHEN   SIZE  TIER  HOW
local  opencode  image-conver  non-interactive  today  -     t1    cwd is worktree ~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-attachments-and-probes/repo
local  opencode  recorded-use  non-interactive  today  -     t1    cwd is worktree ~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-attachments-and-probes/repo
local  opencode  assistant-on  non-interactive  today  -     t1    cwd is worktree ~/.no-mistakes/worktrees/9ce30939faf7/01M3P941F9VZ62N5WCGSNVDGGW/.test-opencode-live/manual/round2-attachments-and-probes/repo
Evidence: Image-only conversation fetched through the shipped probe
{"key":"opencode:image-conversation","harness":"opencode","kind":"events","bytes":150,"mtimeMs":1790676426392,"contentSignature":"08acf4adb32cec2ba2a9a8ee95017624be6d921c6ba6f741b9d021399bb65ea2","model":null}
{"events":[{"kind":"message","role":"assistant","text":"The screenshot shows a missing release tag. Create the tag before publishing."}],"model":null}{"end":true}
Evidence: Focused regression-test output
✔ the probe runs from a directory holding only the manifest, so no hidden import can break a host (61.6496ms)
✔ path facts preserve path names that match prototype keys (0.412126ms)
✔ the locate command and shipped probe execute through the supported remote shell path (273.253727ms)
✔ a fetch frame is read back byte for byte, and a torn stream is reported rather than parsed (2.23996ms)
✔ an oversized declared body is discarded and the next frame remains readable (1.29225ms)
✔ malformed fetch headers are rejected instead of becoming empty transcripts (1.272725ms)
✔ every prompt backpass sends begins with the self-session sentinel (0.920275ms)
✔ discovery excludes backpass-originated sessions from every acpx-backed harness (13.166608ms)
✔ the exclusion survives the scan cache (a cached descriptor is still checked) (6.982013ms)
▶ OpenCode attachment-only conversations survive CLI scans and shipped probes
  ✔ CLI retains the conversation but not the empty probe or self session (328.421553ms)
  ✔ shipped probe retains the conversation but not the empty probe or self session (102.058764ms)
✔ OpenCode attachment-only conversations survive CLI scans and shipped probes (542.22665ms)
▶ malformed OpenCode rows do not suppress valid sessions locally or remotely
  ✔ message corruption in ses_opencode_real (72.648611ms)
  ✔ message corruption in ses_opencode_self (77.275901ms)
  ✔ message corruption in ses_other (100.373101ms)
  ✔ part corruption in ses_opencode_real (125.488352ms)
  ✔ part corruption in ses_opencode_self (135.29207ms)
  ✔ part corruption in ses_other (122.777495ms)
✔ malformed OpenCode rows do not suppress valid sessions locally or remotely (681.778142ms)
✔ OpenCode self ancestry excludes descendants locally and remotely regardless of cutoff (1463.841174ms)
✔ isSelfSession is fail-soft on a missing or directory path (0.57245ms)
ℹ tests 21
ℹ suites 0
ℹ pass 21
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2997.81923
Evidence: Reproducible isolated live-test driver
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { DatabaseSync } from 'node:sqlite';
import { pathToFileURL } from 'node:url';

const cwd = process.cwd();
const evidence = '~/.no-mistakes/evidence/01M3P941F9VZ62N5WCGSNVDGGW';
const root = path.join(cwd, '.test-opencode-live', 'manual');
const { renderPrompt, SELF_SESSION_SENTINEL: sentinel } = await import(pathToFileURL(path.join(cwd, 'src/prompts.js')));
const { buildProbeProgram, createFrameReader } = await import(pathToFileURL(path.join(cwd, 'src/discovery/remote/bundle.js')));
const analysis = renderPrompt('analysis', { MEMORY_PATH: 'AGENTS.md', INSTRUCTION_INDEX: 'Run targeted tests.', TRACE: 'user: fix the release' });
const synthesis = renderPrompt('synthesis', { REPO_NAME: 'demo', MEMORY_PATH: 'AGENTS.md' });
const text = value => ({ type: 'text', text: value });
const user = value => ({ role: 'user', parts: [text(value)] });
const assistant = value => ({ role: 'assistant', parts: [text(value)] });
const now = Date.now();
const old = now - 3 * 86400000;
const reply = 'The screenshot shows a missing release tag. Create the tag before publishing.';
const results = [];

function run(command, args, env, repo, input) {
  const result = spawnSync(command, args, { cwd: repo, env, input, encoding: 'utf8', timeout: 30000, maxBuffer: 8 * 1024 * 1024 });
  assert.equal(result.status, 0, `${command} ${args.join(' ')}\n${result.stderr}\n${result.error || ''}`);
  return result;
}

function scenario(name, sessions, expected, self, options = {}) {
  const dir = path.join(root, name);
  const repo = path.join(dir, 'repo');
  const home = path.join(dir, 'home');
  const config = path.join(dir, 'config');
  const tmp = path.join(dir, 'tmp');
  const store = path.join(home, '.local/share/opencode/opencode.db');
  for (const d of [repo, config, tmp, path.dirname(store)]) fs.mkdirSync(d, { recursive: true });
  const env = { PATH: process.env.PATH, HOME: home, TMPDIR: tmp, XDG_CONFIG_HOME: config, XDG_DATA_HOME: path.join(home, '.local/share'), GIT_CONFIG_NOSYSTEM: '1', NO_COLOR: '1' };
  run('git', ['init', '-q', repo], env, repo);
  const db = new DatabaseSync(store);
  if (options.padding) {
    db.exec('CREATE TABLE padding (data TEXT)');
    db.prepare('INSERT INTO padding VALUES (?)').run('x'.repeat(400000));
  }
  db.exec(`CREATE TABLE project (id TEXT PRIMARY KEY, worktree TEXT NOT NULL);
    CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT NOT NULL, parent_id TEXT, directory TEXT NOT NULL, title TEXT NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL);
    CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, time_created INTEGER NOT NULL, data TEXT NOT NULL);
    CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL, time_created INTEGER NOT NULL, data TEXT NOT NULL);`);
  db.prepare('INSERT INTO project VALUES (?, ?)').run('project', repo);
  for (const s of sessions) {
    const at = s.at ?? now;
    db.prepare('INSERT INTO session VALUES (?, ?, ?, ?, ?, ?, ?)').run(s.id, 'project', s.parent ?? null, repo, s.id, at, at);
    for (const [i, m] of (s.turns ?? [user(s.text ?? 'Fix the release'), assistant('Implemented and tested the fix')]).entries()) {
      const mid = `${s.id}-m${i}`;
      db.prepare('INSERT INTO message VALUES (?, ?, ?, ?)').run(mid, s.id, at + i, m.raw ?? JSON.stringify({ role: m.role, time: { created: at + i } }));
      for (const [j, p] of (m.parts ?? []).entries()) db.prepare('INSERT INTO part VALUES (?, ?, ?, ?, ?)').run(`${mid}-p${j}`, mid, s.id, at + i, typeof p === 'string' ? p : JSON.stringify(p));
    }
  }
  db.close();
  const headHasSentinel = fs.readFileSync(store).subarray(0, 256 * 1024).includes(Buffer.from(sentinel));
  if (options.head !== undefined) assert.equal(headHasSentinel, options.head, 'adversarial database head arrangement');
  const inputDescription = { name, expected, self, headHasSentinel, sessions };
  fs.writeFileSync(path.join(evidence, `${name}-inputs.json`), JSON.stringify(inputDescription, null, 2));
  const cliArgs = [path.join(cwd, 'bin/backpass.js'), 'scan', '--harness', 'opencode', '--since', options.since ?? 'all', '--strict', '--json'];
  const cutoffMs = options.since ? now - 86400000 : null;
  const scanned = sessions.filter(s => (s.turns?.length !== 0) && (!cutoffMs || (s.at ?? now) >= cutoffMs)).length;
  for (let pass = 1; pass <= 2; pass++) {
    const cli = run(process.execPath, cliArgs, env, repo);
    fs.writeFileSync(path.join(evidence, `${name}-cli-${pass}.json`), cli.stdout);
    const output = JSON.parse(cli.stdout);
    assert.deepEqual(output.transcripts.map(t => t.nativeId).sort(), [...expected].sort());
    assert.equal(output.perHarness.opencode.self, self);
    assert.equal(output.perHarness.opencode.scanned, scanned);
    assert.equal(output.perHarness.opencode.error, null);
  }
  const request = { op: 'discover', harnesses: ['opencode'], cutoffMs };
  const remote = run(process.execPath, ['-'], env, repo, buildProbeProgram(request));
  fs.writeFileSync(path.join(evidence, `${name}-probe.json`), remote.stdout);
  const output = JSON.parse(remote.stdout);
  assert.deepEqual(output.transcripts.map(t => t.id).sort(), [...expected].sort());
  assert.equal(output.harnesses.opencode.self, self);
  assert.equal(output.harnesses.opencode.scanned, scanned);
  assert.equal(output.harnesses.opencode.error, null);
  if (options.fetch) {
    const item = output.transcripts.find(t => t.id === options.fetch);
    assert.ok(item);
    const result = run(process.execPath, ['-'], env, repo, buildProbeProgram({ op: 'fetch', items: [item] }));
    fs.writeFileSync(path.join(evidence, `${name}-fetch.frames`), result.stdout);
    const reader = createFrameReader();
    const frames = reader.push(Buffer.from(result.stdout));
    assert.equal(reader.ended, true);
    assert.deepEqual(JSON.parse(frames[0].body).events, [{ kind: 'message', role: 'assistant', text: reply }]);
  }
  if (options.human) {
    const human = run(process.execPath, cliArgs.filter(arg => arg !== '--json'), env, repo);
    fs.writeFileSync(path.join(evidence, `${name}-scan.txt`), human.stdout);
  }
  const result = { name, result: 'pass', live: true, retained: expected, excludedSelf: self, scanned, databaseHeadContainsSentinel: headHasSentinel, surfaces: ['CLI scan twice', 'shipped probe discover', ...(options.fetch ? ['shipped probe fetch'] : [])] };
  results.push(result);
  console.log(JSON.stringify(result));
}

try {
  scenario('round2-mixed-store', [
    { id: 'real-release' }, { id: 'self-analysis', text: analysis }, { id: 'self-synthesis', text: synthesis }
  ], ['real-release'], 2, { head: true, human: true });
  scenario('round2-self-beyond-head', [
    { id: 'real-release' }, { id: 'self-analysis', text: analysis }, { id: 'self-synthesis', text: synthesis }
  ], ['real-release'], 2, { padding: true, head: false });
  scenario('round2-attachments-and-probes', [
    { id: 'empty-probe', turns: [] }, { id: 'self-analysis', text: analysis },
    { id: 'image-conversation', turns: [ { role: 'user', parts: [{ type: 'file', mime: 'image/png', filename: 'failure.png', url: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=' }] }, assistant(reply) ] },
    { id: 'recorded-user-without-parts', turns: [{ role: 'user', parts: [] }] },
    { id: 'assistant-only', turns: [assistant('Restored conversation history')] }
  ], ['image-conversation', 'recorded-user-without-parts', 'assistant-only'], 1, { fetch: 'image-conversation', human: true });
  scenario('round2-genuine-sentinel-mentions', [
    { id: 'mentions-sentinel', text: `Why does backpass prepend ${sentinel} to its prompts?` },
    { id: 'later-user-quotes-prompt', turns: [user('Explain this prompt'), assistant('Please paste it'), user(analysis)] },
    { id: 'assistant-quotes-prompt', turns: [user('Show me the prompt'), assistant(synthesis)] },
    { id: 'second-text-part-quotes-prompt', turns: [{ role: 'user', parts: [text('Explain this prompt:'), text(analysis)] }] },
    { id: 'self-analysis', text: analysis }
  ], ['mentions-sentinel', 'later-user-quotes-prompt', 'assistant-quotes-prompt', 'second-text-part-quotes-prompt'], 1);
  scenario('round2-ancestry-and-cutoff', [
    { id: 'old-self', at: old, text: analysis },
    { id: 'self-child', parent: 'old-self' }, { id: 'self-grandchild', parent: 'self-child' },
    { id: 'empty-self-child', parent: 'old-self', turns: [] }, { id: 'self-via-empty', parent: 'empty-self-child' },
    { id: 'old-real', at: old }, { id: 'real-child', parent: 'old-real' }, { id: 'real-grandchild', parent: 'real-child' },
    { id: 'self-under-real', parent: 'old-real', text: synthesis }, { id: 'self-under-real-child', parent: 'self-under-real' },
    { id: 'orphan', parent: 'nonexistent' }, { id: 'cycle-a', parent: 'cycle-b' }, { id: 'cycle-b', parent: 'cycle-a' }
  ], ['real-child', 'real-grandchild', 'orphan', 'cycle-a', 'cycle-b'], 5, { since: '1d' });
  scenario('round2-malformed-store-rows', [
    { id: 'real-release' }, { id: 'self-analysis', turns: [{ raw: '{broken', parts: ['{broken'] }, user(analysis)] },
    { id: 'real-malformed-prefix', turns: [{ raw: '{broken', parts: [text('Unreadable role')] }, user('Fix the release')] },
    { id: 'real-malformed-part', turns: [{ role: 'user', parts: ['{broken', text('Fix the parser')] }] },
    { id: 'empty-probe', turns: [] }
  ], ['real-release', 'real-malformed-prefix', 'real-malformed-part'], 1);
} finally {
  fs.writeFileSync(path.join(evidence, 'round2-live-results.json'), JSON.stringify(results, null, 2));
  fs.rmSync(root, { recursive: true, force: true });
}
- Outcome: 🔧 2 issues found → auto-fixed ✅ across 2 runs (7m21s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (2) ✅
  • ⚠️ src/discovery/adapters/opencode.js:60 - The new listing subquery uses json_extract(m.data, &#39;$.role&#39;) (line 60) and json_extract(pt.data, &#39;$.type&#39;) (line 61). In SQLite, json_extract on text that is not valid JSON throws malformed JSON instead of returning NULL. I checked this with node:sqlite: the error comes through a correlated scalar subquery too. So a single corrupt message.data or part.data row in any session inside the cutoff window, including a session belonging to a different repo, makes discover() throw. discoverTranscripts then catches the error, logs opencode: transcript store unreadable ... - harness skipped and drops every genuine opencode session. The remote probe does the same through its per-harness catch. Before this change the listing never parsed JSON, and read() still parses safely with safeJsonParse. This breaks the AGENTS.md rule that adapters stay fail-soft, and the intent's 'never drop a genuine one'. Fix: guard both calls so a bad row only drops itself, for example CASE WHEN json_valid(m.data) THEN json_extract(m.data, &#39;$.role&#39;) END = &#39;user&#39; and the same for pt.data. Use CASE rather than a separate json_valid(...) AND term, because SQLite does not guarantee the order in which WHERE terms are evaluated.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ src/discovery/adapters/opencode.js:60 - The new listing subquery uses json_extract(m.data, &#39;$.role&#39;) (line 60) and json_extract(pt.data, &#39;$.type&#39;) (line 61). In SQLite, json_extract on text that is not valid JSON throws malformed JSON instead of returning NULL. I checked this with node:sqlite: the error comes through a correlated scalar subquery too. So a single corrupt message.data or part.data row in any session inside the cutoff window, including a session belonging to a different repo, makes discover() throw. discoverTranscripts then catches the error, logs opencode: transcript store unreadable ... - harness skipped and drops every genuine opencode session. The remote probe does the same through its per-harness catch. Before this change the listing never parsed JSON, and read() still parses safely with safeJsonParse. This breaks the AGENTS.md rule that adapters stay fail-soft, and the intent's 'never drop a genuine one'. Fix: guard both calls so a bad row only drops itself, for example CASE WHEN json_valid(m.data) THEN json_extract(m.data, &#39;$.role&#39;) END = &#39;user&#39; and the same for pt.data. Use CASE rather than a separate json_valid(...) AND term, because SQLite does not guarantee the order in which WHERE terms are evaluated.
  • ⚠️ src/discovery/adapters/opencode.js:102 - A session is marked self only when its own first user text part starts with the sentinel. OpenCode's task tool creates a child session. That child has parent_id set to the calling session and the same directory, and its first user text is the task prompt the model wrote, which does not carry the sentinel. Concrete sequence: backpass analysis or consolidation runs acpx opencode with cwd set to the repo root (src/analyze.js:207, src/consolidate.js:85). The model delegates a read or exploration step to a subagent. The child session is then listed under the repo root with self: false. discoverDirect (src/discovery/index.js:300) finds no self match, because readHead is false and the cwd is not under stateDir, so the child is classified non-interactive through parent_id and analyzed. That breaks the intent's requirement "never analyze its own OpenCode sessions". Synthesis children are still caught, because their cwd sits under the stateDir staging copy. The query already selects parent_id, so the fix stays inside discover: carry self down to every descendant of a self row (for example with an id-to-self map resolved through parent_id, or a recursive CTE, so a parent outside the cutoff window still counts). One sibling site must hold the same rule: the remote probe calls descriptorFrom (src/discovery/remote/probe.js:72-74), which works out self separately from each session's own read() events and ignores row.self. It should also honor row.self from the adapter so remote child sessions are dropped too.

🔧 Fix applied.
✅ Re-checked - no issues remain.

🔧 **Test** - 2 issues found → auto-fixed ✅
  • 🚨 src/discovery/adapters/opencode.js:98 - The empty-session filter silently drops genuine OpenCode sessions whose user message contains only an attachment. Reproduced with an image-only user message followed by a substantive assistant reply: the base CLI retains the session, but the changed CLI and shipped remote probe both return zero scanned sessions. The real probe fetch confirms that the session contains a nonempty assistant event. Absence of a user text part is not equivalent to an unused probe session. Separate empty-session detection from sentinel detection, preserve recorded attachment conversations, and add a behavioral regression test.
  • 🚨 live validation verdict: no-go (6 of 6 scenarios were driven live against the product); failed: Scan a genuine image-only user conversation with a substantive assistant reply
  • Live validation: ❌ no-go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Scan a shared OpenCode database and retain genuine sessions while excluding backpass analysis and synthesis ✅ pass live base-mixed.json, fixed-mixed.json, fixed-mixed-repeat.json, and probe-mixed.json in the evidence directory; consolidated in live-results.json.
Scan after agent probing without listing unused empty sessions ✅ pass live fixed-mixed.json and probe-mixed.json.
Discuss or quote the sentinel without losing a genuine conversation ✅ pass live marker-boundaries.json and probe-marker-boundaries.json.
Scan recent descendants when their backpass ancestor predates the cutoff ✅ pass live ancestry-all.json, ancestry-1d.json, repeat scans, and corresponding probe outputs.
Scan a store containing malformed message and part JSON ✅ pass live malformed-rows.json and probe-malformed-rows.json.
Scan a genuine image-only user conversation with a substantive assistant reply ❌ fail live attachment-persisted-state.json, base-attachment-only.json, fixed-attachment-only-clean.json, probe-attachment-only-clean.json, and attachment-fetch.json.
  • TMPDIR=&#34;$PWD/.test-opencode-live/tmp&#34; node --import ./test/helpers/hermetic-config.js --test test/self-session.test.js test/remote-bundle.test.js passed.
  • git archive ddf8a7b06a9d191ee696d2ae9a10683c8b1ca872 bin src package.json extracted a disposable base version for before/after CLI comparisons.
  • node .test-opencode-live/drive.mjs ran the real backpass scan --harness opencode --since all --strict --json CLI against isolated SQLite stores, including repeated scans and --since 1d ancestry checks.
  • The same driver executed actual buildProbeProgram discovery payloads through node -, checking mixed stores, sentinel boundaries, ancestry, corrupt JSON, and attachment-only sessions.
  • Ran backpass scan without --json and captured its end-user table and SELF explanation.
  • node .test-opencode-live/verify-attachment.mjs executed the shipped probe fetch protocol and verified that the omitted attachment session contains a substantive assistant event.
  • Corrected the clean-store baseline setup with SQLite VACUUM to remove residual sentinel bytes, then reran the complete driver.
  • Removed .test-opencode-live/ after evidence collection; the worktree is unchanged.

🔧 Fix applied.
✅ Re-checked - no issues remain.

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Scan a shared database containing genuine work and backpass analysis/synthesis sessions ✅ pass live round2-product-transcripts.txt: round2-mixed-store
Exclude self sessions whose prompts lie beyond the database-head window ✅ pass live round2-product-transcripts.txt: round2-self-beyond-head
Retain an image-only conversation while omitting unused agent probes ✅ pass live round2-attachments-and-probes-scan.txt; round2-attachments-and-probes-fetch.frames
Retain genuine conversations that mention or later quote the sentinel ✅ pass live round2-product-transcripts.txt: round2-genuine-sentinel-mentions
Exclude self descendants across the date cutoff without losing genuine descendants ✅ pass live round2-product-transcripts.txt: round2-ancestry-and-cutoff
Scan a store containing malformed message and part records ✅ pass live round2-product-transcripts.txt: round2-malformed-store-rows
  • node --import ./test/helpers/hermetic-config.js --test test/self-session.test.js test/remote-bundle.test.js with isolated HOME, config, and temporary directories.
  • node ~/.no-mistakes/evidence/01M3P941F9VZ62N5WCGSNVDGGW/round2-live-driver.mjs created disposable OpenCode SQLite stores and exercised six scenarios.
  • node bin/backpass.js scan --harness opencode --since all --strict --json twice per applicable scenario, plus --since 1d for ancestry and cutoff validation.
  • Executed the actual shipped probe through node - for discovery in every scenario and fetched the image-only conversation through its framed protocol.
  • Captured and inspected human-readable CLI scan output, JSON responses, and the attachment conversation's fetched assistant reply.
  • Corrected the disposable database padding setup, reran all live scenarios successfully, removed test data, and confirmed a clean worktree.
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ test/self-session.test.js:354 - Prettier requires multiline formatting for assert.deepEqual. Left unchanged because this phase explicitly prohibits test edits. ESLint and TypeScript checks pass; all other checked files pass formatting.

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

acpx drives opencode, and opencode is on both default ladders, so every
analysis and synthesis call backpass makes through it is filed in the
opencode store under the repo's cwd - a tier-1 exact match on the next
run. Self-session detection only reads transcript files, and an
opencode store is one SQLite database, so three things went wrong:

- The file-head check read the database's first 256 KiB. Its pages hold
  every session's text, so a backpass prompt stored near the start of
  the file marked every session in the store as backpass's own, and a
  prompt stored further in was missed.
- With the head check unable to see them, backpass's own opencode
  sessions were analyzed as corpus - backpass auditing itself, which the
  self-session sentinel exists to prevent.
- Each agent probe (`acpx opencode sessions new`) leaves an empty
  session under the repo's cwd, which was listed and matched at tier 1.

The opencode listing query now reads each session's first user text
part, the part an acpx prompt lands in, and marks the row `self` when it
opens with the sentinel; discovery drops those rows and counts them in
SELF. A session with no user text at all recorded nothing and is not
listed. Discovery never reads a SQLite database as a transcript head.
The new cases in `test/self-session.test.js` put a genuine session, a
self session and a probe's empty session in one small opencode store;
they fail on all three counts before this change.
@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Changes how the discovery system identifies and excludes its own sessions.

The PR appears safe to merge; no outstanding findings or new actionable issues remain.

Reviews (2) · Last reviewed commit: "no-mistakes(ci): Fixed both findings. Op..."

Comment thread src/discovery/adapters/opencode.js Resolved
Comment thread src/discovery/adapters/opencode.js Resolved
…cks the first user message, preserving attachment-opening conversations and their descendants when later messages quote backpass prompts. Remote probes respect the adapter's explicit classification. Self ancestry is computed once per discovery instead of querying ancestors per child. Both regressions failed before the fixes and pass afterward. Verification passed: 103 relevant tests, targeted ESLint and Prettier checks, TypeScript checking, and git diff --check. The hosted Greptile check was not rerun in this phase
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Closing as subsumed by #181 (squash-merged as 04ac5efa, now on main d8b2c8a / 0.1.31).

Main's OpenCode adapter already detects self from the first user text in SQLite (selfSessions / opensWithSentinel), excludes descendants, skips unused message-less probes, keeps attachment-only openings, fails soft on malformed rows, and covers this in test/self-session.test.js (including the attachment + malformed regressions this PR added). This branch is CONFLICTING against that stack; re-opening a competing fix is not needed.

Thank you @PawanAIT — really appreciate you taking the time on the safe self-exclusion path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants