Skip to content

refactor: split CLI into command modules and add HTML preview output - #4

Closed
Sinity wants to merge 4 commits into
masterfrom
feature/refactor/modular-cli-html-previews
Closed

Sinity wants to merge 4 commits into
masterfrom
feature/refactor/modular-cli-html-previews

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Restructures gmd from a single-file CLI into a modular command architecture with typed option/result dataclasses, a UI abstraction over gum and Rich, and optional HTML preview output alongside the existing Markdown. Running python3 gmd.py with no subcommand drops into an interactive menu; all the same functionality is available non-interactively via --plain and --json.

Motivation

The original gmd.py had a ~330-line main() that handled argument parsing, Drive auth, attachment downloading, rendering, and pruning in one function. The render and sync paths duplicated nearly identical attachment-download loops. Adding any new output format (like HTML) would have meant threading more state through that function, and the lack of structured return values made it impossible to compose commands or emit machine-readable output.

I wanted three things:

  1. Testable command functions that accept typed inputs and return typed results — no argparse.Namespace leaking into business logic.
  2. Interactive-first UX that works out of the box (gum menus, skim fuzzy selection) but degrades cleanly for CI/scripts.
  3. HTML previews so rendered conversations can be opened directly in a browser for quick review.

Approach: layered decomposition

The new architecture has four layers:

gmd.py (CLI adapter + interactive menu)
  → geminimd/commands.py (command functions)
    → geminimd/render.py, drive_client.py, html.py (domain)
      → geminimd/models.py, options.py, util.py (data types + helpers)

Each command function takes a dataclass and returns one:

@dataclass
class RenderOptions:
    inputs: List[Path]
    output_dir: Path
    collapse_threshold: int
    download_attachments: bool
    dry_run: bool
    force: bool
    html: bool = False
    html_theme: str = "light"

def render_command(options: RenderOptions, env: CommandEnv) -> RenderResult:
    ...

The CLI adapters in gmd.py translate argparse namespaces into these dataclasses and format the results for display. The interactive menu builds the same dataclasses from gum prompts.

Key changes

UI abstraction (geminimd/ui.py)

UI wraps gum for menus/confirmations and Rich for styled output. When --plain is set (or stdout isn't a TTY), all interactive calls return sensible defaults and formatting is stripped:

def confirm(self, prompt: str, *, default: bool = True) -> bool:
    if self.plain:
        return default
    result = subprocess.run(
        ["gum", "confirm", "--default", "true" if default else "false", prompt],
        check=False,
    )
    return result.returncode == 0

MarkdownDocument return type (geminimd/render.py)

build_markdown_from_chunks() previously returned a raw string. It returns a MarkdownDocument dataclass carrying body, metadata (dict), attachments (list of AttachmentInfo), and stats. This is what makes HTML generation possible — render_html() receives the structured document rather than re-parsing Markdown.

The metadata assembly changed from string concatenation to dict building:

# Before
parts.append(f"title: \"{title}\"\n")
parts.append(f"sourceDriveId: {source_file_id}\n")

# After
metadata: Dict[str, Any] = {"title": title}
if source_file_id:
    metadata["sourceDriveId"] = source_file_id

Content part rendering

A new _render_content_parts() handles structured content types that were previously dropped:

  • code parts → fenced code blocks with language hints
  • list parts → Markdown bullet lists
  • table parts → Markdown tables with header/separator rows
  • text parts → verbatim text (unchanged)

HTML preview (geminimd/html.py)

Uses markdown-it-py to convert the Markdown body to HTML, then wraps it in a themed template via Jinja2. Falls back to string formatting if Jinja2 is unavailable. Two themes (light/dark) with system-font stacks and callout-style blockquotes.

Drive resilience (geminimd/drive.py)

All Drive API calls now go through _retry() with exponential backoff (configurable via GMD_RETRIES and GMD_RETRY_BASE env vars). Auth supports GMD_AUTH_MODE=local for browser-based OAuth alongside the existing console flow.

Fuzzy selection: fzf → skim

Replaced fzf with skim (sk) throughout. The sk_select() helper in cli_common.py supports multi-select, preview commands, custom headers, and key bindings.

Nix dev shell consolidation

shell.nix is removed. flake.nix delegates to nix/devshell.nix, which is the single source of truth for all dependencies — Python libraries and CLI tools alike. New deps: rich, pydantic, python-frontmatter, jinja2, markdown-it-py, skim, gum, bat, delta, fd, ripgrep, glow.

Documentation

  • multi-provider.md documents import formats for ChatGPT, Claude.ai, Codex CLI, and Claude Code exports. This is planning material for the next round of importer work.
  • README.md and AGENTS.md rewritten around the interactive-first workflow.

Test plan

  • python3 gmd.py render data --plain --dry-run processes sample inputs without error
  • python3 gmd.py render data --plain --html --dry-run reports HTML paths in output
  • python3 gmd.py status shows credential and run-log status
  • python3 gmd.py --plain prints help; bare python3 gmd.py shows gum menu when interactive
  • python3 gmd.py sync --plain --dry-run --json emits valid JSON summary

@Sinity Sinity added type:refactor Code restructuring area:cli CLI labels Apr 7, 2026
Copilot AI review requested due to automatic review settings April 7, 2026 11:03
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR restructures the CLI into an interactive-first tool and a modular geminimd package: adds UI abstraction, typed options/results, Drive client + retry logic, chunk validation and structured Markdown/HTML rendering, command orchestration (render/sync/list/status), and consolidates Nix devshells. The main entrypoint delegates to the new command layer.

Changes

Cohort / File(s) Summary
Docs
AGENTS.md, README.md
Replace legacy CLI/config documentation with interactive/menu-first workflow, --plain/--json semantics, simplified auth guidance, and revised development notes.
Entrypoint & CLI
gmd.py
Convert monolithic argparse CLI into interactive menu + thin entrypoint; add --plain, JSON output flags, input resolution, and per-command CLI handlers delegating to command layer.
Command Layer
geminimd/commands.py
New orchestration for render, sync, list, status using typed options/results and a CommandEnv; records runs, aggregates stats, handles pruning and dry-run flows.
Drive Abstraction
geminimd/drive_client.py, geminimd/drive.py
New DriveClient wrapper for auth and common ops; add _retry() exponential-backoff and integrate into Drive API calls; token path and auth-mode env overrides.
UI & UX
geminimd/ui.py, gmd_settings.py
New UI abstraction supporting plain vs interactive (gum) flows; settings for HTML previews/theme and factory to create UI.
Models & Validation
geminimd/models.py, geminimd/options.py
Pydantic models for chunk normalization, and typed dataclasses for all command options and structured results.
Rendering & HTML
geminimd/render.py, geminimd/html.py
MarkdownDocument + AttachmentInfo types; richer content rendering (parts, code, lists, tables); HTML output rendering with themes and optional Jinja usage.
CLI Helpers & Utils
geminimd/cli_common.py, geminimd/util.py
Shared helpers: chat filtering, skim selection, prune-path computation, download decision logic; colorize respects NO_COLOR env.
Nix/devshell
nix/devshell.nix, flake.nix, shell.nix
Introduce nix/devshell.nix and point flake.nix to it; remove legacy shell.nix.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI as gmd.py
    participant UI as UI Layer
    participant Cmd as Command Layer
    participant DriveC as DriveClient
    participant Drive as Google Drive API
    participant Render as Render/HTML
    participant FS as Filesystem

    User->>CLI: run `python3 gmd.py`
    CLI->>UI: create_ui(--plain?)
    alt no subcommand & interactive
        CLI->>UI: interactive_menu()
        UI->>User: prompt action
        User->>UI: choose action (render/sync/list)
        UI->>Cmd: call selected command handler(options)
    else subcommand provided
        CLI->>Cmd: call command handler(options)
    end

    Cmd->>DriveC: resolve folder / list chats (if sync)
    DriveC->>Drive: files().list() / files().get()
    Drive-->>DriveC: metadata / bytes
    DriveC-->>Cmd: chat bytes / metadata

    Cmd->>Render: validate chunks -> build_markdown_from_chunks()
    Render-->>Cmd: MarkdownDocument (body, metadata, attachments)
    alt attachments download enabled
        Cmd->>DriveC: download_attachment(file_id)
        DriveC->>Drive: files().get() / download
        Drive-->>DriveC: bytes
        DriveC->>FS: write _attachments/
    end

    Cmd->>Render: render_html(document, theme) [optional]
    Render-->>FS: write markdown and HTML
    Cmd-->>User: return result (formatted or JSON)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • The gmd CLI monolith is blocking richer render surfaces #3: This PR implements the requested refactor—extracting command functions and typed options, adding UI abstraction with --plain/--json, returning MarkdownDocument for HTML output, adding Drive retries, and consolidating the Nix devshell.

Poem

🐰 I hopped in code, a tidy spree,

Menus gleam where flags once be;
Markdown blooms and HTML sings,
Drive retries mend broken strings,
A warren modular, neat and free.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the two main changes: refactoring the CLI into command modules and adding HTML preview output functionality.
Description check ✅ Passed The PR description thoroughly documents the refactoring, including summary, motivation, architectural approach, key changes across multiple modules, and a test plan.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/modular-cli-html-previews

Comment @coderabbitai help to get the list of available commands and usage tips.

Sinity added a commit that referenced this pull request Apr 7, 2026
)

Decompose the monolithic gmd.py main() into a layered architecture:
typed option/result dataclasses, standalone command functions, CLI
adapter wrappers, and an interactive menu loop. Replace fzf with
skim for fuzzy selection and introduce gum for confirmations and
styled output.

CLI entrypoint (gmd.py):
- build_parser() constructs argparse tree; subcommands are optional
  so bare `python3 gmd.py` enters the interactive gum menu
- Each subcommand delegates to run_{render,sync,list,status}_cli()
  which build option objects and call into geminimd/commands.py
- --plain flag disables all interactive UI; --json emits
  machine-readable summaries for scripting
- Interactive menu offers Render, Sync, List, Status, Settings, Help

Command layer (geminimd/commands.py):
- render_command(), sync_command(), list_command(), status_command()
  accept typed dataclasses and return typed results
- ChatContext groups title, timestamps, and run settings for both
  local and Drive sources
- _build_markdown_output() and _collect_attachments() replace the
  inline attachment-download loops that were duplicated between
  render and sync

Rendering (geminimd/render.py):
- build_markdown_from_chunks() returns MarkdownDocument dataclass
  instead of raw string; metadata dict replaces manual YAML assembly
- New _render_content_parts() handles code, list, and table content
  types that were previously dropped
- AttachmentInfo and remote_attachment_info() give structured
  attachment metadata to both Markdown and HTML outputs
- Attachment summary section appended to document body

HTML preview (geminimd/html.py):
- render_html() converts MarkdownDocument to themed HTML using
  markdown-it-py and Jinja2, with a plain-string fallback when
  Jinja2 is missing
- Light and dark theme palettes; --html and --html-theme flags on
  render and sync commands

UI abstraction (geminimd/ui.py):
- UI dataclass wraps gum (banner, choose, confirm, input) and
  Rich (console, Panel, Table) behind a plain-mode toggle
- detect_plain() auto-disables interactivity when stdout is not a TTY

Supporting modules:
- geminimd/cli_common.py: filter_chats(), sk_select(), prune helpers
- geminimd/drive_client.py: DriveClient class managing credentials
  flow, folder resolution, and attachment downloads
- geminimd/models.py: Pydantic ChunkModel for chunk validation
- geminimd/options.py: Dataclass pairs for each command's options
  and results
- gmd_settings.py: Runtime settings for HTML preview toggle/theme

Drive reliability (geminimd/drive.py):
- _retry() adds exponential backoff to all Drive API calls
- GMD_TOKEN_PATH and GMD_AUTH_MODE env vars for flexible auth

Nix packaging:
- shell.nix removed; flake.nix delegates to nix/devshell.nix
- Dev shell adds rich, pydantic, frontmatter, jinja2, markdown-it-py,
  skim, gum, bat, delta, fd, ripgrep, glow

Documentation:
- multi-provider.md: import format notes for ChatGPT, Claude,
  Codex CLI, and Claude Code exports
- README.md and AGENTS.md rewritten for the interactive-first CLI
@Sinity Sinity closed this Apr 7, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the gmd CLI from a monolithic script into a modular command-based architecture with typed option/result dataclasses, a plain-aware UI abstraction, and optional HTML preview output generated from a structured document model.

Changes:

  • Split CLI responsibilities into gmd.py (adapter + interactive menu) and geminimd/commands.py (typed command functions returning typed results).
  • Introduce a structured MarkdownDocument (metadata/attachments/stats) and add HTML preview generation via geminimd/html.py.
  • Consolidate dev-shell/tooling via Nix and refresh repo docs for the interactive-first workflow.

Reviewed changes

Copilot reviewed 17 out of 17 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
shell.nix Removes legacy non-flake shell in favor of flake-based devshell.
flake.nix Delegates dev shell definition to nix/devshell.nix as a single source of truth.
nix/devshell.nix Adds Python deps + CLI tooling (gum/skim/rich/etc.) for the new interactive UX.
README.md Updates usage/docs to match the new interactive-first CLI and flags.
AGENTS.md Updates contributor guidance to the new module layout and workflows.
gmd.py New CLI adapter: subcommands + interactive menu + settings integration.
gmd_settings.py Adds in-memory settings (HTML preview toggle + theme).
geminimd/ui.py Introduces UI abstraction over gum + Rich with plain-mode fallback.
geminimd/cli_common.py Adds shared helpers (skim selection, filtering, prune path computation).
geminimd/options.py Adds typed option/result dataclasses for commands.
geminimd/commands.py Implements render/list/sync/status command functions using typed inputs/outputs.
geminimd/drive_client.py Wraps Drive auth/service acquisition and interactive credential provisioning.
geminimd/drive.py Adds retry/backoff wrapper + auth mode/token path flexibility.
geminimd/models.py Adds Pydantic validation/normalization for chunk payloads.
geminimd/render.py Produces structured MarkdownDocument, richer content-part rendering, and attachment section/metadata.
geminimd/html.py Adds HTML preview generation from MarkdownDocument (MarkdownIt + optional Jinja2).
geminimd/util.py Adds NO_COLOR/GMD_NO_COLOR support for ANSI color suppression.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread gmd.py
Comment on lines +345 to +348
args.html = SETTINGS.html_previews
args.html_theme = SETTINGS.html_theme
args.html = False
args.html_theme = "light"

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the interactive prompt path, the HTML settings are assigned from SETTINGS and then immediately overwritten (args.html set to False and theme forced to "light"). This makes the Settings menu ineffective for render runs started from the menu. Remove the overriding assignments so prompt_render respects SETTINGS.html_previews / SETTINGS.html_theme (or prompt the user explicitly).

Copilot uses AI. Check for mistakes.
Comment thread gmd.py
Comment on lines +369 to +372
args.html = SETTINGS.html_previews
args.html_theme = SETTINGS.html_theme
args.html = False
args.html_theme = "light"

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue as prompt_render: args.html / args.html_theme are set from SETTINGS and then immediately overwritten (HTML disabled + theme forced to light). This prevents the Settings menu from affecting sync runs launched from the interactive menu.

Copilot uses AI. Check for mistakes.
Comment thread gmd.py
Comment on lines +85 to +87
selection = sk_select(lines, preview="bat --style=plain {}")
if selection is None:
return None

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolve_inputs treats a missing/failed sk invocation as "cancelled" (sk_select returns None on FileNotFoundError), which aborts rendering even though non-interactive fallback could proceed. Consider falling back to candidates (or returning the first file) when sk is unavailable, and reserve None strictly for user-abort when sk actually ran.

Suggested change
selection = sk_select(lines, preview="bat --style=plain {}")
if selection is None:
return None
try:
selection = sk_select(lines, preview="bat --style=plain {}")
except FileNotFoundError:
return candidates
if selection is None:
return candidates

Copilot uses AI. Check for mistakes.
Comment thread geminimd/commands.py
chats = [c for c in chats if c.get("id") in ids]

if not chats:
return SyncResult(0, options.output_dir, options.folder_name, folder_id, [])

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sync_command returns SyncResult without the required total_stats field when there are no chats (options.py defines SyncResult.total_stats as required). This will raise a TypeError at runtime. Return an empty totals dict (or defaultdict coerced to dict) in this early-return path.

Suggested change
return SyncResult(0, options.output_dir, options.folder_name, folder_id, [])
return SyncResult(0, options.output_dir, options.folder_name, folder_id, [], {})

Copilot uses AI. Check for mistakes.
Comment thread geminimd/render.py
Comment on lines +27 to +32
if isinstance(value, (int, float)):
return str(value)
if isinstance(value, (list, dict)):
return json.dumps(value, ensure_ascii=False)
if isinstance(value, bool):
return "true" if value else "false"

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_encode_metadata_value checks (int, float) before bool, but bool is a subclass of int in Python. This causes True/False to be serialized as "True"/"False" instead of YAML-style "true"/"false" in the fallback frontmatter writer. Check bool before int/float to avoid mis-encoding booleans.

Suggested change
if isinstance(value, (int, float)):
return str(value)
if isinstance(value, (list, dict)):
return json.dumps(value, ensure_ascii=False)
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (int, float)):
return str(value)
if isinstance(value, (list, dict)):
return json.dumps(value, ensure_ascii=False)

Copilot uses AI. Check for mistakes.
Comment thread geminimd/html.py
Comment on lines +105 to +110
def render_html(document: MarkdownDocument, options: HtmlRenderOptions) -> str:
theme = THEMES.get(options.theme, THEMES["light"])
md = MarkdownIt("commonmark", {"html": True}).enable("table").enable("strikethrough")
body_html = md.render(document.body)
metadata_rows = {k: v for k, v in document.metadata.items() if k != "attachments"}
metadata_rows["attachments"] = len(document.attachments)

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HTML rendering enables raw HTML passthrough in MarkdownIt ("html": True) and then inserts output into the page. If chat content includes HTML/script tags, opening the preview in a browser could execute it. Consider disabling raw HTML (html=False) and/or sanitizing the rendered HTML before embedding.

Copilot uses AI. Check for mistakes.
Comment thread geminimd/html.py
Comment on lines +142 to +149
env = Environment(loader=BaseLoader(), autoescape=False)
template = env.from_string(HTML_TEMPLATE)
return template.render(
title=document.metadata.get("title", "Conversation"),
metadata=metadata_rows,
body_html=body_html,
theme=theme,
)

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Jinja rendering uses autoescape=False and prints metadata values directly into the HTML template. This can allow HTML injection via metadata fields (e.g., title) in local previews. Enable autoescaping for HTML templates (or explicitly escape values) and avoid marking untrusted content as safe unless it has been sanitized.

Copilot uses AI. Check for mistakes.
Comment thread geminimd/cli_common.py
Comment on lines +65 to +74
try:
proc = subprocess.run(
cmd,
input="\n".join(lines).encode("utf-8"),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
)
except (subprocess.CalledProcessError, FileNotFoundError):
return None

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sk_select returns None for both user-abort and tool-missing/command failure (FileNotFoundError / CalledProcessError). Callers treat None as "cancelled", which can break interactive flows when skim isn't installed. Consider distinguishing "not available" from "aborted" (e.g., return [] or raise a specific exception on missing binary) so callers can fall back sensibly.

Copilot uses AI. Check for mistakes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6561e961e7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread geminimd/commands.py Resolved
Comment thread gmd.py Resolved
Comment thread gmd.py Resolved
@Sinity Sinity reopened this Apr 7, 2026
@Sinity

Sinity commented Apr 7, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Apr 7, 2026

Copy link
Copy Markdown
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 17

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@AGENTS.md`:
- Around line 3-24: The MD022 lint fails because several top-level headings in
AGENTS.md are not followed by a blank line; add a single blank line immediately
after each heading title ("Project Structure & Modules", "Development Workflow",
"Automation & Testing", "Style & Naming", and "Credentials & Security") so each
heading is separated from the subsequent paragraph/list, ensuring Markdown
linting passes.

In `@geminimd/cli_common.py`:
- Around line 26-35: The epoch bound checks currently treat 0 as falsy and skip
valid timestamps; update the conditional logic in the loop that processes out
(where tmp is built and parse_rfc3339_to_epoch is used) to check s_epoch and
u_epoch explicitly with "is not None" (e.g., use "if s_epoch is not None and mt
< s_epoch:" and "if u_epoch is not None and mt > u_epoch:") so zero/epoch-0
bounds are honored while still skipping None.
- Line 105: The current predicate uses "int(local_path.stat().st_mtime) !=
int(mt)" which triggers downloads when timestamps merely differ (including when
local is newer); change the logic so it only returns True when the remote
timestamp is strictly newer than the local one (e.g., compare int(mt) >
int(local_path.stat().st_mtime)), preserving any necessary int casts and
handling missing local files as before.

In `@geminimd/commands.py`:
- Around line 340-342: compute_prune_paths currently only targets .md and
*_attachments dirs, leaving generated HTML previews like "<name>.html" behind;
update compute_prune_paths to also consider and return paths for matching
".html" preview files (and any associated preview attachment dirs if applicable)
for deletion when options.prune is set so the sync directory mirrors Drive.
Locate compute_prune_paths and the call site around the options.prune block
(where sanitize_filename and wanted are built) and extend the pruning logic to
include sanitized_name + ".html" (and related preview attachment folders) in the
set of paths to remove.
- Around line 219-247: The code computes local_path only from fname (sanitized
display name), causing different attachments with the same display name to
collide; change to generate a unique on-disk filename for each attachment (e.g.,
derive file_name from sanitize_filename(meta_att.get("name", att_id)) then, if
that file already exists for a different att_id, append a stable unique suffix
derived from att_id or an incrementing counter) before creating local_path; keep
the original sanitized display name (fname) for per_index_links entries but use
the unique file_name/local_path for download, drive.touch_mtime, size checks and
AttachmentInfo.local_path; update any dedupe logic that uses key = (fname,
att_id) to ensure it references the unique on-disk filename where appropriate so
downloads are not skipped or overwritten (adjust variables: fname, file_name,
local_path, att_id, seen, attachments, per_index_links).
- Around line 384-400: status_command currently checks DEFAULT_TOKEN.exists()
which hard-codes token.json; update it to check the actual configured token path
used by auth (the GMD_TOKEN_PATH-aware token path helper or variable used
elsewhere) instead of DEFAULT_TOKEN so gmd status reflects the env-configured
token location; modify the token_present computation in status_command to use
that configured token path (the same symbol/function your auth code uses to
resolve the token path) and leave the rest of the function unchanged.

In `@geminimd/drive_client.py`:
- Around line 20-21: DEFAULT_CREDENTIALS and DEFAULT_TOKEN currently use
cwd-relative Paths; change them to be application-relative by resolving this
module's directory and joining the filenames so the defaults point to the
geminimd package location (use the resolved parent directory of this file to
build the paths for DEFAULT_CREDENTIALS and DEFAULT_TOKEN and apply the same
change to the other default path constants on lines ~30-31). Ensure the new
defaults still produce Path objects and preserve existing behavior when absolute
paths are passed in.

In `@geminimd/drive.py`:
- Around line 51-52: Normalize the custom token path and ensure its parent
directory exists before saving the OAuth token: when reading GMD_TOKEN_PATH
(token_env) construct token_path with Path(token_env).expanduser().resolve() (or
equivalent normalization) and, wherever the token is written (references to
token_path and the token save block around lines ~80-84), call
token_path.parent.mkdir(parents=True, exist_ok=True) before writing the file so
a custom path won't fail silently; if token_env is not set keep using
(credentials_path.parent / TOKEN_FILE) as fallback.
- Around line 24-43: The _retry function should clamp environment overrides
before the loop so callers (e.g., list_children(), download_file()) always
invoke fn(); after parsing GMD_RETRIES and GMD_RETRY_BASE, ensure retries is at
least 1 (if parsed value <= 0 set to 1) and base_delay is non-negative (if
parsed value < 0 set to 0.0 or the original default); keep the existing last_err
logic and exponential backoff but avoid letting negative retries prevent any
call or a negative base_delay cause time.sleep() to raise.
- Around line 120-124: The Drive query interpolates folder_name into
service.files().list(...) which allows single quotes or backslashes to break the
query; before building the q string in the code that calls _retry(...
service.files().list(... name='{folder_name}' ...)), escape backslashes and
single quotes in folder_name (replace "\" with "\\\\" and "'" with "\\'") or add
a small helper (e.g., escape_drive_query or escape_folder_name) and use that
escaped value when interpolating into the q parameter so the resulting Google
Drive query is always syntactically safe and not subject to injection.

In `@geminimd/html.py`:
- Around line 105-149: render_html currently allows raw HTML from untrusted
Gemini content and disables template autoescaping, leading to stored XSS; fix by
disabling HTML in the Markdown parser (call MarkdownIt with "html": False and
keep table/strikethrough enables), enable Jinja autoescaping when constructing
Environment (Environment(..., autoescape=True)), and escape all metadata and
title used in the fallback f-string path (use html.escape on document.metadata
values and document.metadata.get("title", ...) before building rows and the
<title>/<h1>). Reference symbols: render_html, MarkdownIt, Environment,
HTML_TEMPLATE, document.body, document.metadata, metadata_rows, title.

In `@geminimd/models.py`:
- Around line 41-42: Wrap the ChunkModel.model_validate(chunk) call in a
try/except that catches pydantic.ValidationError (import ValidationError from
pydantic), log a warning including identifying info (e.g., chunk id/index and
the exception message) and skip that chunk rather than letting the exception
propagate; update both call sites that build the validated list (the code that
appends model.to_dict() to validated) to apply the same guard so one bad chunk
won’t abort processing the whole file.

In `@geminimd/render.py`:
- Around line 26-36: The fallback front-matter serializer in
_encode_metadata_value currently emits invalid YAML by wrapping strings with
naive quotes and checks int/float before bool; change it to use a proper YAML
scalar serializer (e.g., yaml.safe_dump) to produce correctly escaped scalars
and preserve types, and reorder the isinstance checks so bool is detected before
int/float; replace the manual string-quoting branch with a call to the YAML
dumper that strips document markers/newlines so the output is a single scalar.

In `@geminimd/ui.py`:
- Around line 78-88: The confirm() method currently returns the default on any
gum subprocess exception which treats failures as consent; instead, update
confirm(self, ...) to return False on Exception. Also update the other
interactive methods (choose(...) and input(...)) to return None on any gum
subprocess exception so gum failures are treated as explicit cancellation rather
than accepting defaults; locate and modify the exception handlers in confirm,
choose, and input methods to return these cancellation values.

In `@geminimd/util.py`:
- Around line 21-22: The NO_COLOR/GMD_NO_COLOR check currently uses
os.environ.get(...) which treats empty strings as falsey and won't respect a key
set to an empty value; change the presence test to check keys in the environment
(e.g., use "if 'NO_COLOR' in os.environ or 'GMD_NO_COLOR' in os.environ:") in
the function containing that snippet so the function (in geminimd/util.py)
returns text when either env var is present regardless of its value.

In `@gmd_settings.py`:
- Around line 16-18: The reset_settings function currently hardcodes values;
instead instantiate a fresh default Settings (e.g., default = Settings()) and
copy the default attribute values into the global SETTINGS for the fields you
need (e.g., html_previews, html_theme) so defaults come from the dataclass
definition; update reset_settings to use that default instance rather than
literal values to avoid drift if Settings defaults change.

In `@gmd.py`:
- Around line 345-348: The code loads SETTINGS.html_previews and
SETTINGS.html_theme into args (args.html = SETTINGS.html_previews;
args.html_theme = SETTINGS.html_theme) and then immediately overwrites them with
fixed values; remove the overwriting assignments (the later args.html = False
and args.html_theme = "light") or make them conditional so they only set
defaults when args.* is unset, ensuring the interactive helpers (render/sync)
respect SETTINGS.html_previews and SETTINGS.html_theme; apply the same change
for the duplicated block at the other location (the block at lines ~369-372).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f83ead7f-8ac3-4024-8bcc-bc92d4d36e59

📥 Commits

Reviewing files that changed from the base of the PR and between e68c4ab and 6561e96.

📒 Files selected for processing (17)
  • AGENTS.md
  • README.md
  • flake.nix
  • geminimd/cli_common.py
  • geminimd/commands.py
  • geminimd/drive.py
  • geminimd/drive_client.py
  • geminimd/html.py
  • geminimd/models.py
  • geminimd/options.py
  • geminimd/render.py
  • geminimd/ui.py
  • geminimd/util.py
  • gmd.py
  • gmd_settings.py
  • nix/devshell.nix
  • shell.nix
💤 Files with no reviewable changes (1)
  • shell.nix

Comment thread AGENTS.md
Comment on lines +3 to +24
## Project Structure & Modules
- `gmd.py`: interactive CLI entrypoint for rendering local Gemini JSON and syncing Drive chats.
- `geminimd/`: implementation modules (commands, Drive helpers, rendering, UI utilities).
- `nix/devshell.nix`: dev shell defining Python deps plus gum, skim, rich, bat, glow, etc.
- `gemini/`, `sinex_md/`: sample inputs and generated Markdown artifacts.

## Build, Test, and Development Commands
- Enter dev shell (recommended): `nix develop` (flakes) or `nix-shell`.
- Convert a JSON chat log (no downloads):
`python3 convert_gemini_chatlog.py ai_sinity_analysis_gemini_2_5_flash.json --output-dir out --attachment-summary --no-download`
- Convert with Drive downloads (first run triggers OAuth):
`python3 convert_gemini_chatlog.py INPUT.json --output-dir out --credentials credentials.json --download-dir attachments --force-download`
- Preview without writing files: `python3 convert_gemini_chatlog.py INPUT.json --dry-run -v`
- Format an agent JSONL log: `cat log.jsonl | jq -f format_log.jq -r > log.md`
## Development Workflow
- Use `nix develop` to enter the environment with all required tools.
- Launch `python3 gmd.py` for the interactive menu (render, sync, list, status, help).
- First Drive action will ask for a Google OAuth client JSON and perform auth automatically; token is cached locally.

## Coding Style & Naming Conventions
- Python: follow PEP 8, 4-space indentation, type hints where practical.
- Naming: modules and functions in `snake_case`; CLI flags use kebab-case (e.g., `--no-download`).
- Formatting/Linting: no enforced tool in repo; if used locally, keep diffs minimal.
## Automation & Testing
- Non-interactive paths use `--plain` to disable gum/skim/Rich; combine with `--json` for machine-readable summaries.
- Smoke test with `python3 gmd.py render data --plain --dry-run` and `python3 gmd.py sync --plain --dry-run`.
- If you add automated tests, place them under `tests/` and use `pytest`.

## Testing Guidelines
- No formal unit tests yet. Validate changes by running the converter against a real file (e.g., `ai_sinity_analysis_gemini_2_5_flash.json`) with `--dry-run` and with downloads disabled/enabled.
- If adding tests, place them under `tests/` with `test_*.py` and use `pytest`.

## Commit & Pull Request Guidelines
- Commit messages: prefer Conventional Commits style (e.g., `feat: add --link-text-attachments flag`, `fix: robust token file handling`).
- Pull requests: include a short description, example command(s) showing the change in action, and any before/after Markdown snippets.
- Link related issues or notes; add screenshots only when the change affects Markdown rendering.

## Security & Configuration Tips
- Keep `credentials.json` and generated `token.json` out of version control. Store them locally and reference with `--credentials`.
- Google Drive: ensure the account has access to linked files; if downloads fail, try `--force-download` and verify tester permissions.
## Style & Naming
- Python code follows PEP 8, 4-space indentation, snake_case identifiers.
- CLI flags are kebab-case (e.g., `--links-only`, `--dry-run`).
- Keep inline comments concise and purposeful.

## Credentials & Security

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix markdown heading spacing to satisfy lint (MD022).

Headings at Line 3, Line 9, Line 14, Line 19, and Line 24 need a blank line below each heading.

📝 Proposed fix
 ## Project Structure & Modules
+
 - `gmd.py`: interactive CLI entrypoint for rendering local Gemini JSON and syncing Drive chats.
 - `geminimd/`: implementation modules (commands, Drive helpers, rendering, UI utilities).
 - `nix/devshell.nix`: dev shell defining Python deps plus gum, skim, rich, bat, glow, etc.
 - `gemini/`, `sinex_md/`: sample inputs and generated Markdown artifacts.
 
 ## Development Workflow
+
 - Use `nix develop` to enter the environment with all required tools.
 - Launch `python3 gmd.py` for the interactive menu (render, sync, list, status, help).
 - First Drive action will ask for a Google OAuth client JSON and perform auth automatically; token is cached locally.
 
 ## Automation & Testing
+
 - Non-interactive paths use `--plain` to disable gum/skim/Rich; combine with `--json` for machine-readable summaries.
 - Smoke test with `python3 gmd.py render data --plain --dry-run` and `python3 gmd.py sync --plain --dry-run`.
 - If you add automated tests, place them under `tests/` and use `pytest`.
 
 ## Style & Naming
+
 - Python code follows PEP 8, 4-space indentation, snake_case identifiers.
 - CLI flags are kebab-case (e.g., `--links-only`, `--dry-run`).
 - Keep inline comments concise and purposeful.
 
 ## Credentials & Security
+
 - Never commit `credentials.json` or `token.json`.
 - The CLI guides users through supplying an OAuth client; ensure documentation reflects this.
 - Drive access errors should surface clear, actionable prompts.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## Project Structure & Modules
- `gmd.py`: interactive CLI entrypoint for rendering local Gemini JSON and syncing Drive chats.
- `geminimd/`: implementation modules (commands, Drive helpers, rendering, UI utilities).
- `nix/devshell.nix`: dev shell defining Python deps plus gum, skim, rich, bat, glow, etc.
- `gemini/`, `sinex_md/`: sample inputs and generated Markdown artifacts.
## Build, Test, and Development Commands
- Enter dev shell (recommended): `nix develop` (flakes) or `nix-shell`.
- Convert a JSON chat log (no downloads):
`python3 convert_gemini_chatlog.py ai_sinity_analysis_gemini_2_5_flash.json --output-dir out --attachment-summary --no-download`
- Convert with Drive downloads (first run triggers OAuth):
`python3 convert_gemini_chatlog.py INPUT.json --output-dir out --credentials credentials.json --download-dir attachments --force-download`
- Preview without writing files: `python3 convert_gemini_chatlog.py INPUT.json --dry-run -v`
- Format an agent JSONL log: `cat log.jsonl | jq -f format_log.jq -r > log.md`
## Development Workflow
- Use `nix develop` to enter the environment with all required tools.
- Launch `python3 gmd.py` for the interactive menu (render, sync, list, status, help).
- First Drive action will ask for a Google OAuth client JSON and perform auth automatically; token is cached locally.
## Coding Style & Naming Conventions
- Python: follow PEP 8, 4-space indentation, type hints where practical.
- Naming: modules and functions in `snake_case`; CLI flags use kebab-case (e.g., `--no-download`).
- Formatting/Linting: no enforced tool in repo; if used locally, keep diffs minimal.
## Automation & Testing
- Non-interactive paths use `--plain` to disable gum/skim/Rich; combine with `--json` for machine-readable summaries.
- Smoke test with `python3 gmd.py render data --plain --dry-run` and `python3 gmd.py sync --plain --dry-run`.
- If you add automated tests, place them under `tests/` and use `pytest`.
## Testing Guidelines
- No formal unit tests yet. Validate changes by running the converter against a real file (e.g., `ai_sinity_analysis_gemini_2_5_flash.json`) with `--dry-run` and with downloads disabled/enabled.
- If adding tests, place them under `tests/` with `test_*.py` and use `pytest`.
## Commit & Pull Request Guidelines
- Commit messages: prefer Conventional Commits style (e.g., `feat: add --link-text-attachments flag`, `fix: robust token file handling`).
- Pull requests: include a short description, example command(s) showing the change in action, and any before/after Markdown snippets.
- Link related issues or notes; add screenshots only when the change affects Markdown rendering.
## Security & Configuration Tips
- Keep `credentials.json` and generated `token.json` out of version control. Store them locally and reference with `--credentials`.
- Google Drive: ensure the account has access to linked files; if downloads fail, try `--force-download` and verify tester permissions.
## Style & Naming
- Python code follows PEP 8, 4-space indentation, snake_case identifiers.
- CLI flags are kebab-case (e.g., `--links-only`, `--dry-run`).
- Keep inline comments concise and purposeful.
## Credentials & Security
## Project Structure & Modules
- `gmd.py`: interactive CLI entrypoint for rendering local Gemini JSON and syncing Drive chats.
- `geminimd/`: implementation modules (commands, Drive helpers, rendering, UI utilities).
- `nix/devshell.nix`: dev shell defining Python deps plus gum, skim, rich, bat, glow, etc.
- `gemini/`, `sinex_md/`: sample inputs and generated Markdown artifacts.
## Development Workflow
- Use `nix develop` to enter the environment with all required tools.
- Launch `python3 gmd.py` for the interactive menu (render, sync, list, status, help).
- First Drive action will ask for a Google OAuth client JSON and perform auth automatically; token is cached locally.
## Automation & Testing
- Non-interactive paths use `--plain` to disable gum/skim/Rich; combine with `--json` for machine-readable summaries.
- Smoke test with `python3 gmd.py render data --plain --dry-run` and `python3 gmd.py sync --plain --dry-run`.
- If you add automated tests, place them under `tests/` and use `pytest`.
## Style & Naming
- Python code follows PEP 8, 4-space indentation, snake_case identifiers.
- CLI flags are kebab-case (e.g., `--links-only`, `--dry-run`).
- Keep inline comments concise and purposeful.
## Credentials & Security
🧰 Tools
🪛 markdownlint-cli2 (0.22.0)

[warning] 3-3: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 9-9: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 14-14: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 19-19: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 24-24: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@AGENTS.md` around lines 3 - 24, The MD022 lint fails because several
top-level headings in AGENTS.md are not followed by a blank line; add a single
blank line immediately after each heading title ("Project Structure & Modules",
"Development Workflow", "Automation & Testing", "Style & Naming", and
"Credentials & Security") so each heading is separated from the subsequent
paragraph/list, ensuring Markdown linting passes.

Comment thread geminimd/cli_common.py
Comment on lines +26 to +35
if s_epoch or u_epoch:
tmp: List[Dict[str, Any]] = []
for c in out:
mt = parse_rfc3339_to_epoch(c.get("modifiedTime"))
if mt is None:
continue
if s_epoch and mt < s_epoch:
continue
if u_epoch and mt > u_epoch:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Use explicit is not None checks for time bounds.

Line 26, Line 32, and Line 34 treat epoch 0 as false, so valid bounds like 1970-01-01 are ignored.

🐛 Proposed fix
-    if s_epoch or u_epoch:
+    if s_epoch is not None or u_epoch is not None:
@@
-            if s_epoch and mt < s_epoch:
+            if s_epoch is not None and mt < s_epoch:
                 continue
-            if u_epoch and mt > u_epoch:
+            if u_epoch is not None and mt > u_epoch:
                 continue
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if s_epoch or u_epoch:
tmp: List[Dict[str, Any]] = []
for c in out:
mt = parse_rfc3339_to_epoch(c.get("modifiedTime"))
if mt is None:
continue
if s_epoch and mt < s_epoch:
continue
if u_epoch and mt > u_epoch:
continue
if s_epoch is not None or u_epoch is not None:
tmp: List[Dict[str, Any]] = []
for c in out:
mt = parse_rfc3339_to_epoch(c.get("modifiedTime"))
if mt is None:
continue
if s_epoch is not None and mt < s_epoch:
continue
if u_epoch is not None and mt > u_epoch:
continue
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@geminimd/cli_common.py` around lines 26 - 35, The epoch bound checks
currently treat 0 as falsy and skip valid timestamps; update the conditional
logic in the loop that processes out (where tmp is built and
parse_rfc3339_to_epoch is used) to check s_epoch and u_epoch explicitly with "is
not None" (e.g., use "if s_epoch is not None and mt < s_epoch:" and "if u_epoch
is not None and mt > u_epoch:") so zero/epoch-0 bounds are honored while still
skipping None.

Comment thread geminimd/cli_common.py
if mt is None:
return False
try:
return int(local_path.stat().st_mtime) != int(mt)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Download predicate should check freshness, not mere inequality.

Line 105 causes re-download whenever timestamps differ, including cases where local is newer; this creates churn and can overwrite local changes unnecessarily.

🧭 Proposed fix
     try:
-        return int(local_path.stat().st_mtime) != int(mt)
+        local_mtime = local_path.stat().st_mtime
+        return mt > (local_mtime + 1.0)
     except Exception:
         return True
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return int(local_path.stat().st_mtime) != int(mt)
try:
local_mtime = local_path.stat().st_mtime
return mt > (local_mtime + 1.0)
except Exception:
return True
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@geminimd/cli_common.py` at line 105, The current predicate uses
"int(local_path.stat().st_mtime) != int(mt)" which triggers downloads when
timestamps merely differ (including when local is newer); change the logic so it
only returns True when the remote timestamp is strictly newer than the local one
(e.g., compare int(mt) > int(local_path.stat().st_mtime)), preserving any
necessary int casts and handling missing local files as before.

Comment thread geminimd/commands.py
Comment on lines +219 to +247
fname = sanitize_filename(meta_att.get("name", att_id))
local_path = attachments_dir / fname
if not dry_run:
if force or not local_path.exists():
ok = drive.download_attachment(att_id, local_path)
if not ok:
continue
drive.touch_mtime(local_path, meta_att.get("modifiedTime"))
try:
rel = local_path.relative_to(out_dir)
except Exception:
rel = local_path
per_index_links[idx].append((fname, rel))
size = None
if not dry_run and local_path.exists():
try:
size = local_path.stat().st_size
except OSError:
size = None
key = (fname, att_id)
if key not in seen:
seen.add(key)
attachments.append(
AttachmentInfo(
name=fname,
link=f"attachment://{att_id}",
local_path=None if dry_run else rel,
size_bytes=size,
remote=False,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Disambiguate attachments that share the same filename.

local_path is derived only from the sanitized display name. Two different Drive files called image.png will therefore share one target path; with force=False the second link points at the first file, and with force=True it overwrites it.

Proposed fix
             fname = sanitize_filename(meta_att.get("name", att_id))
-            local_path = attachments_dir / fname
+            stem = Path(fname).stem
+            suffix = Path(fname).suffix
+            local_path = attachments_dir / f"{stem}_{att_id}{suffix}"
🧰 Tools
🪛 Ruff (0.15.9)

[warning] 229-229: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@geminimd/commands.py` around lines 219 - 247, The code computes local_path
only from fname (sanitized display name), causing different attachments with the
same display name to collide; change to generate a unique on-disk filename for
each attachment (e.g., derive file_name from
sanitize_filename(meta_att.get("name", att_id)) then, if that file already
exists for a different att_id, append a stable unique suffix derived from att_id
or an incrementing counter) before creating local_path; keep the original
sanitized display name (fname) for per_index_links entries but use the unique
file_name/local_path for download, drive.touch_mtime, size checks and
AttachmentInfo.local_path; update any dedupe logic that uses key = (fname,
att_id) to ensure it references the unique on-disk filename where appropriate so
downloads are not skipped or overwritten (adjust variables: fname, file_name,
local_path, att_id, seen, attachments, per_index_links).

Comment thread geminimd/commands.py
Comment on lines +340 to +342
if options.prune:
wanted = {sanitize_filename(item.name or item.id or "") for item in items}
to_delete = compute_prune_paths(options.output_dir, wanted)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

--prune still leaves stale HTML previews behind.

compute_prune_paths() only deletes .md files and *_attachments directories, so once previews are enabled a removed chat leaves <name>.html behind and the sync directory stops mirroring Drive.

Companion change in `geminimd/cli_common.py`
 def compute_prune_paths(out_dir: Path, wanted_basenames: Set[str]) -> List[Path]:
     to_delete: List[Path] = []
     for p in out_dir.iterdir():
-        if p.is_file() and p.suffix.lower() == ".md":
+        if p.is_file() and p.suffix.lower() in {".md", ".html"}:
             base = p.stem
             if base not in wanted_basenames:
                 to_delete.append(p)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@geminimd/commands.py` around lines 340 - 342, compute_prune_paths currently
only targets .md and *_attachments dirs, leaving generated HTML previews like
"<name>.html" behind; update compute_prune_paths to also consider and return
paths for matching ".html" preview files (and any associated preview attachment
dirs if applicable) for deletion when options.prune is set so the sync directory
mirrors Drive. Locate compute_prune_paths and the call site around the
options.prune block (where sanitize_filename and wanted are built) and extend
the pruning logic to include sanitized_name + ".html" (and related preview
attachment folders) in the set of paths to remove.

Comment thread geminimd/render.py
Comment on lines +26 to +36
def _encode_metadata_value(value: Any) -> str:
if isinstance(value, (int, float)):
return str(value)
if isinstance(value, (list, dict)):
return json.dumps(value, ensure_ascii=False)
if isinstance(value, bool):
return "true" if value else "false"
if value is None:
return "null"
text = str(value).replace("\n", " ")
return f'"{text}"'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

The fallback front matter serializer can emit invalid YAML.

When python-frontmatter is unavailable, _encode_metadata_value() wraps strings in quotes without escaping embedded quotes/backslashes. Common titles like He said "hi" will therefore produce malformed front matter. Using a real scalar encoder also fixes the current bool/int ordering bug.

Proposed fix
 def _encode_metadata_value(value: Any) -> str:
-    if isinstance(value, (int, float)):
-        return str(value)
+    if isinstance(value, bool):
+        return "true" if value else "false"
+    if isinstance(value, (int, float)):
+        return str(value)
     if isinstance(value, (list, dict)):
         return json.dumps(value, ensure_ascii=False)
-    if isinstance(value, bool):
-        return "true" if value else "false"
     if value is None:
         return "null"
-    text = str(value).replace("\n", " ")
-    return f'"{text}"'
+    return json.dumps(str(value).replace("\n", " "), ensure_ascii=False)

Also applies to: 58-66

🧰 Tools
🪛 Ruff (0.15.9)

[warning] 26-26: Dynamically typed expressions (typing.Any) are disallowed in value

(ANN401)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@geminimd/render.py` around lines 26 - 36, The fallback front-matter
serializer in _encode_metadata_value currently emits invalid YAML by wrapping
strings with naive quotes and checks int/float before bool; change it to use a
proper YAML scalar serializer (e.g., yaml.safe_dump) to produce correctly
escaped scalars and preserve types, and reorder the isinstance checks so bool is
detected before int/float; replace the manual string-quoting branch with a call
to the YAML dumper that strips document markers/newlines so the output is a
single scalar.

Comment thread geminimd/ui.py
Comment on lines +78 to +88
def confirm(self, prompt: str, *, default: bool = True) -> bool:
if self.plain:
return default
try:
result = subprocess.run(
["gum", "confirm", "--default", "true" if default else "false", prompt],
check=False,
)
return result.returncode == 0
except Exception:
return default

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n geminimd/ui.py

Repository: Sinity/polylogue

Length of output: 5162


Treat gum failures as cancellation, not as user consent.

In interactive mode, a gum failure currently falls back to the same default values used for plain mode: True in confirm(), options[0] in choose(), and the default value in input(). On a machine where gum is missing or crashes during a TTY session, the CLI can immediately enter the first menu item, accept downloads, and operate on Path.cwd() without any user choice.

Return False, None, and None respectively on exception to treat gum failures as explicit cancellation.

Proposed fix
@@ -85,7 +85,7 @@ class UI:
                 ["gum", "confirm", "--default", "true" if default else "false", prompt],
                 check=False,
             )
             return result.returncode == 0
         except Exception:
-            return default
+            return False
 
     def choose(self, prompt: str, options: List[str]) -> Optional[str]:
@@ -102,7 +102,7 @@ class UI:
             choice = result.stdout.strip()
             return choice or None
         except Exception:
-            return options[0]
+            return None
 
     def input(self, prompt: str, *, default: Optional[str] = None) -> Optional[str]:
@@ -117,7 +117,7 @@ class UI:
             if not value:
                 return default
             return value
         except Exception:
-            return default
+            return None
🧰 Tools
🪛 Ruff (0.15.9)

[error] 82-82: subprocess call: check for execution of untrusted input

(S603)


[error] 83-83: Starting a process with a partial executable path

(S607)


[warning] 86-86: Consider moving this statement to an else block

(TRY300)


[warning] 87-87: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@geminimd/ui.py` around lines 78 - 88, The confirm() method currently returns
the default on any gum subprocess exception which treats failures as consent;
instead, update confirm(self, ...) to return False on Exception. Also update the
other interactive methods (choose(...) and input(...)) to return None on any gum
subprocess exception so gum failures are treated as explicit cancellation rather
than accepting defaults; locate and modify the exception handlers in confirm,
choose, and input methods to return these cancellation values.

Comment thread geminimd/util.py
Comment on lines +21 to +22
if os.environ.get("NO_COLOR") or os.environ.get("GMD_NO_COLOR"):
return text

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Respect NO_COLOR by key presence, not truthy value.

Line 21 misses cases where NO_COLOR/GMD_NO_COLOR is set to an empty string.

🎨 Proposed fix
-    if os.environ.get("NO_COLOR") or os.environ.get("GMD_NO_COLOR"):
+    if "NO_COLOR" in os.environ or "GMD_NO_COLOR" in os.environ:
         return text
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@geminimd/util.py` around lines 21 - 22, The NO_COLOR/GMD_NO_COLOR check
currently uses os.environ.get(...) which treats empty strings as falsey and
won't respect a key set to an empty value; change the presence test to check
keys in the environment (e.g., use "if 'NO_COLOR' in os.environ or
'GMD_NO_COLOR' in os.environ:") in the function containing that snippet so the
function (in geminimd/util.py) returns text when either env var is present
regardless of its value.

Comment thread gmd_settings.py
Comment on lines +16 to +18
def reset_settings() -> None:
SETTINGS.html_previews = False
SETTINGS.html_theme = "light"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Reset logic should derive from dataclass defaults, not duplicated literals.

Line 17 and Line 18 hardcode values already defined in Settings, which can drift if defaults change.

♻️ Proposed refactor
 def reset_settings() -> None:
-    SETTINGS.html_previews = False
-    SETTINGS.html_theme = "light"
+    defaults = Settings()
+    SETTINGS.html_previews = defaults.html_previews
+    SETTINGS.html_theme = defaults.html_theme
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def reset_settings() -> None:
SETTINGS.html_previews = False
SETTINGS.html_theme = "light"
def reset_settings() -> None:
defaults = Settings()
SETTINGS.html_previews = defaults.html_previews
SETTINGS.html_theme = defaults.html_theme
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gmd_settings.py` around lines 16 - 18, The reset_settings function currently
hardcodes values; instead instantiate a fresh default Settings (e.g., default =
Settings()) and copy the default attribute values into the global SETTINGS for
the fields you need (e.g., html_previews, html_theme) so defaults come from the
dataclass definition; update reset_settings to use that default instance rather
than literal values to avoid drift if Settings defaults change.

Comment thread gmd.py
Comment on lines +345 to +348
args.html = SETTINGS.html_previews
args.html_theme = SETTINGS.html_theme
args.html = False
args.html_theme = "light"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Stop overwriting the HTML settings you just loaded.

Both interactive helpers read SETTINGS.html_previews / SETTINGS.html_theme and then immediately replace them with False / "light". That makes the new Settings menu a no-op for interactive render and sync.

Proposed fix
-    args.html = SETTINGS.html_previews
-    args.html_theme = SETTINGS.html_theme
-    args.html = False
-    args.html_theme = "light"
+    args.html = SETTINGS.html_previews
+    args.html_theme = SETTINGS.html_theme

Also applies to: 369-372

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gmd.py` around lines 345 - 348, The code loads SETTINGS.html_previews and
SETTINGS.html_theme into args (args.html = SETTINGS.html_previews;
args.html_theme = SETTINGS.html_theme) and then immediately overwrites them with
fixed values; remove the overwriting assignments (the later args.html = False
and args.html_theme = "light") or make them conditional so they only set
defaults when args.* is unset, ensuring the interactive helpers (render/sync)
respect SETTINGS.html_previews and SETTINGS.html_theme; apply the same change
for the duplicated block at the other location (the block at lines ~369-372).

@Sinity Sinity closed this Apr 9, 2026
@Sinity Sinity added the faux-pull-request PR created as part of a history rewrite process label Apr 9, 2026
@Sinity
Sinity deleted the feature/refactor/modular-cli-html-previews branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
)

Decompose the monolithic gmd.py main() into a layered architecture:
typed option/result dataclasses, standalone command functions, CLI
adapter wrappers, and an interactive menu loop. Replace fzf with
skim for fuzzy selection and introduce gum for confirmations and
styled output.

CLI entrypoint (gmd.py):
- build_parser() constructs argparse tree; subcommands are optional
  so bare `python3 gmd.py` enters the interactive gum menu
- Each subcommand delegates to run_{render,sync,list,status}_cli()
  which build option objects and call into geminimd/commands.py
- --plain flag disables all interactive UI; --json emits
  machine-readable summaries for scripting
- Interactive menu offers Render, Sync, List, Status, Settings, Help

Command layer (geminimd/commands.py):
- render_command(), sync_command(), list_command(), status_command()
  accept typed dataclasses and return typed results
- ChatContext groups title, timestamps, and run settings for both
  local and Drive sources
- _build_markdown_output() and _collect_attachments() replace the
  inline attachment-download loops that were duplicated between
  render and sync

Rendering (geminimd/render.py):
- build_markdown_from_chunks() returns MarkdownDocument dataclass
  instead of raw string; metadata dict replaces manual YAML assembly
- New _render_content_parts() handles code, list, and table content
  types that were previously dropped
- AttachmentInfo and remote_attachment_info() give structured
  attachment metadata to both Markdown and HTML outputs
- Attachment summary section appended to document body

HTML preview (geminimd/html.py):
- render_html() converts MarkdownDocument to themed HTML using
  markdown-it-py and Jinja2, with a plain-string fallback when
  Jinja2 is missing
- Light and dark theme palettes; --html and --html-theme flags on
  render and sync commands

UI abstraction (geminimd/ui.py):
- UI dataclass wraps gum (banner, choose, confirm, input) and
  Rich (console, Panel, Table) behind a plain-mode toggle
- detect_plain() auto-disables interactivity when stdout is not a TTY

Supporting modules:
- geminimd/cli_common.py: filter_chats(), sk_select(), prune helpers
- geminimd/drive_client.py: DriveClient class managing credentials
  flow, folder resolution, and attachment downloads
- geminimd/models.py: Pydantic ChunkModel for chunk validation
- geminimd/options.py: Dataclass pairs for each command's options
  and results
- gmd_settings.py: Runtime settings for HTML preview toggle/theme

Drive reliability (geminimd/drive.py):
- _retry() adds exponential backoff to all Drive API calls
- GMD_TOKEN_PATH and GMD_AUTH_MODE env vars for flexible auth

Nix packaging:
- shell.nix removed; flake.nix delegates to nix/devshell.nix
- Dev shell adds rich, pydantic, frontmatter, jinja2, markdown-it-py,
  skim, gum, bat, delta, fd, ripgrep, glow

Documentation:
- multi-provider.md: import format notes for ChatGPT, Claude,
  Codex CLI, and Claude Code exports
- README.md and AGENTS.md rewritten for the interactive-first CLI
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 4 finding(s) confirmed still present → tracked in #550. 10 finding(s) confirmed fixed/stale.

Sinity added a commit that referenced this pull request May 10, 2026
 follow-on) (#1010)

## Summary

Eliminates the read-amplification storm that produced ~65 MB/s sustained
reads attributed to ``polylogued`` during a single active Claude Code
session. The watcher's ``_needs_work_from_state`` slowpath was rehashing
the entire file on every mtime drift, even when (dev, ino, size,
content_fingerprint) all agreed with the cursor.

The fix is one branch in one function: trust the cursor when those four
fields agree, regardless of mtime. The investigation was evidence-driven
— see "Adversarial-loop methodology" below.

Refs #1003 (follow-on; #1003 itself closed the schema-preflight loop).

## Problem

Symptom (on sinnix-prime, NixOS, btrfs):

- 65 MB/s read attributed to polylogued's PID
- 114 MB/s + 12 044 IOPS on sda (where ``~/.claude/projects/`` lives)
- 9.5 KB/op (metadata-heavy small-read pattern — many ``stat`` +
``openat`` + small ``read`` rather than sequential scanning)
- System-wide ``/proc/pressure/io`` peaked at avg10=73.6%
- Single active Claude Code session being written to

## Investigation

Traced every source-file read site in ``polylogue/sources/live/``:

| Site | Trigger |
|---|---|
| ``fingerprint_file`` in ``_needs_work_from_state`` | size unchanged +
mtime drifted + content_fingerprint exists |
| ``fingerprint_file`` in ``_record_failed_cursor`` | any failed ingest
|
| ``fingerprint_file`` in ``_cursor_state_after_full_ingest`` | only
when ``_latest_raw_fingerprint`` returns None too |
| ``path.read_bytes`` in ``_ingest_full_paths_sync`` | full re-ingest, <
8 MiB |
| ``blob_store.write_from_path`` | full re-ingest, ≥ 8 MiB |
| ``_append_plan`` open+seek+read | append path, delta only |

Two hypotheses fit the symptom:
- **H1** Watcher fingerprint-on-mtime-drift: rehashes whole file when
mtime drifts but content didn't.
- **H2** Claude Code append-fallback to full ingest: tail-identity check
rejects benign appends.

Per the prompt's instruction to fix what data implicates, I built a
regression harness
(``tests/integration/test_live_read_amplification.py``) that wraps every
read site with a counter and runs four scenarios. Result:

- **H1 confirmed**: a single mtime drift on an otherwise-unchanged file
produced one ``fingerprint_file`` call of 690 bytes. A 50-file catch-up
with universal mtime drift produced 50 calls.
- **H2 refuted**: all three Claude Code append scenarios
(sessionId-bearing append, tool_result-only append without sessionId,
subagent file with parent sessionId) take the append path correctly. No
full reread.

The user's prompt hypothesis #4 ("Tighten append-fallback condition") is
wrong for this codebase as-is — that path already handles benign
rotation correctly. H1 was the storm.

## Solution

One-line semantic change in
``polylogue/sources/live/watcher.py:_needs_work_from_state``: drop
``cursor.mtime_ns == stat.st_mtime_ns`` from the early-return
AND-condition. Trust ``(dev, ino, size, content_fingerprint)`` as
authoritative.

```diff
-    if (
-        same_inode
-        and size == cursor.byte_size
-        and cursor.mtime_ns == stat.st_mtime_ns
-        and cursor.content_fingerprint is not None
-    ):
-        return False
+    if same_inode and size == cursor.byte_size and cursor.content_fingerprint is not None:
+        return False
```

Mtime drift alone is not a reliable content-change signal — filesystem
touches, hardlink ops, fsync rounding, nanosecond-resolution drift all
advance mtime without changing content.

### Cost and tracked follow-up

**Same-size in-place content rewrites** (rare: ``echo 'new' >
file.jsonl`` where new content happens to be the same length as old) are
no longer auto-detected. Realistic production cases:
- vim edits with ``backupcopy=yes`` — uncommon default
- manual test/dev rewrites
- restoring an old version from same-size backup

Operators can force re-ingest with ``polylogue ingest <path>`` or
``polylogue reset``.

The pre-existing test ``test_same_size_rewrite_triggers_reingest`` is
renamed to ``test_same_size_rewrite_is_not_auto_detected`` and rewritten
to document the new contract.

Tail-hash chunk check would restore auto-detection without the storm
cost; tracked at **#1009**.

## Acceptance criteria

Verbatim from the original prompt:

- [x] **Under steady-state load, polylogued's process-attributable read
rate stays below ~5 MB/s sustained.** Regression test S1 pins
``bytes_read ≤ 8 × bytes_appended + 64 KB`` per batch; in practice ≪ 1
because only the tail-newline scan happens.
- [x] **Catch-up after daemon restart over a 1000-session archive reads
each file at most once (modulo failure-retry).** Test S4 runs catch-up
against 50 files with universally-drifted mtimes and asserts zero
``fingerprint_file`` calls. Behaviour is per-file; 50 = 1000 here.
- [x] **No regression in ingest latency for the first-ever ingestion of
a new session.** First-ingest path is unchanged;
``_needs_work_from_state`` returns True for ``cursor is None``.
- [x] **Unit/integration tests added for each cache invariant
introduced.** Five new tests in ``test_live_read_amplification.py`` plus
the renamed contract-pin in ``test_live_watcher.py``.
- [x] **Every JSONL change still produces ingestion, including
resumption of years-dormant files.** Existing
``test_year_old_file_resumed_triggers_reingest``
(test_live_watcher.py:1210) still passes — dormant resumption produces
``size > cursor.byte_offset`` → True via the fast path, regardless of
mtime drift during dormancy.

## Files changed

- ``polylogue/sources/live/watcher.py``: the surgical fix (-3 / +5
lines).
- ``tests/integration/test_live_read_amplification.py``: NEW; five
regression scenarios.
- ``tests/infra/io_counter.py``: NEW; read-counter infrastructure
wrapping the production read sites.
- ``tests/unit/sources/test_live_watcher.py``: renames
``test_same_size_rewrite_triggers_reingest`` →
``test_same_size_rewrite_is_not_auto_detected`` with documented
contract.
- ``docs/plans/file-size-budgets.yaml``: exception for the kitchen-sink
test file (1517 > 1500), with split candidate noted.

## Verification

```
$ pytest tests/integration/test_live_read_amplification.py \
         tests/unit/sources/test_live_watcher.py \
         tests/unit/sources/test_live_batch_support.py \
         tests/unit/sources/test_cursor_adversary.py -q
74 passed in 6.42s

$ devtools verify --quick
verify: all checks passed
```

Before/after for the read-counter scenarios:

| Scenario | Before fix | After fix |
|---|---|---|
| S1 active append (3 records to 1 KB file) | (already passed) | 0
``fingerprint_file``, 0 full-stream |
| S2 single-file mtime drift | 1 ``fingerprint_file`` (690 B) | 0 |
| S3 subagent append | (already passed) | 0 |
| S4 50-file catch-up mtime drift | 50 ``fingerprint_file`` (~35 KB) | 0
|

On a ~1000-session archive (the user's), the same fix eliminates ~1000
``fingerprint_file`` calls per drifted-mtime event.

## Adversarial review notes

Loop ran 2 iterations, both clean.

**Iteration 1**: independent reviewer walked through inverting the fix
mentally — re-adding the mtime check would make test S2 (line 314-316)
fail loud on the zero-fingerprint assertion. AC4 ("dormant resumption
still ingests") confirmed via existing
``test_year_old_file_resumed_triggers_reingest`` at
``test_live_watcher.py:1210``. Verdict: "No legitimate gaps found across
all ACs after iteration 1 review."

**Iteration 2**: independent reviewer specifically attacked:
inode-rotation edge case (atomic-write-rename), cursor non-advance
loops, test S1's ×8 multiplier, convergence path indirect reads. All
dismissed with evidence: Claude Code is append-only (no inode rotation
in primary use case), partial batch failure path uses
``_record_failed_cursor`` (no infinite loops), ×8 is generous because
append reads delta+tail only, convergence stages are pure DB. Verdict:
"No legitimate gaps found across all ACs after iteration 2 review."

## What I decided NOT to fix and why

| Hypothesis | Verdict | Evidence |
|---|---|---|
| #1 ``fingerprint_file`` repeats from
``_cursor_state_after_full_ingest`` | Not the storm | Only fires when
``_latest_raw_fingerprint`` ALSO returns None, which requires no
raw_conversations row for the path. In steady state, the row exists from
first ingest. |
| #2 raw_fingerprint cache on cursor row | Not needed | The existing
``_latest_raw_fingerprint`` already prevents repeat fingerprinting after
first full ingest. |
| #3 Convergence re-reads source/blob | Not the storm | Verified in
``polylogue/daemon/convergence_stages.py``: all stages are pure DB
operations. No file or blob reads. |
| #4 ``_append_payload_for_provider`` returns None too often | Not the
storm | Regression tests S1, S3 confirm benign Claude Code appends
(sessionId-bearing, tool_result-only, subagent) all take the append
path. |
| #5 Codex append SELECT is expensive | Not the storm | Bounded by
``LIMIT 1`` on indexed ``source_path``. |
| #6 ``stop_requested`` / ``is_degraded`` busy-loop | Not the storm |
Checked once per source group in ``_full_parse_progress_groups``, not in
a tight loop. |

## Follow-up

- **#1009** — tail-hash chunk check to restore same-size in-place
rewrite detection without storm cost.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request Jul 18, 2026
…outes (#3140)

## Summary
Lands the genuinely-new-coverage slice of polylogue-jtwu (route-latency
observation) and closes polylogue-20d.17's AC #4 (randomized CLI/MCP
status sampling with per-component timing, product budgets from measured
distributions).

## Problem
- jtwu wants one unified route-observation contract projected into
p50/p95 analysis, but the ops-tier telemetry that already exists
(`mcp_call_log`, `query_runs`) has no reader at all —
`list_mcp_calls`/`list_otlp_spans` are defined and never called anywhere
in the codebase.
- 20d.17's AC #4 wants randomized CLI/MCP status sampling with
per-component timing and budgets set from measured distributions — no
substrate existed for this.

## Scope decision (recorded on both beads)
jtwu's own AC #1 wants literal write-path unification across every route
including HTTP, query, and embed/convergence work. Two things make
attempting that whole in one pass unsafe:
- jtwu's own stated dependency (**polylogue-1xc.14**, WorkloadReceipt)
is itself still open.
- This lane's own prompt explicitly excludes `daemon/http.py` (Lane E's
active six-tool/webui-v2 territory this cycle — confirmed still hot via
`git log` on that file before starting: most recent touch was hours
before this PR).

This PR lands the genuinely new coverage that needed neither: **CLI
invocation** and **MCP sub-route detail**. `query_runs`/`mcp_call_log`
stay separate, federated at the read layer rather than migrated — named
explicitly as remaining jtwu scope in the bead notes, not silently
dropped.

## Solution
- New ops-tier table `route_observations` (disposable, additive DDL —
`ops.db` reapplies its DDL idempotently, no migration needed). Bounded
by a 7-day retention window and a 20k-row cap, mirroring
`mcp_call_log`'s existing pattern.
- `polylogue/operations/route_observation.py`: `observe_route()` — a
context manager that times a block and records a best-effort receipt
(never raises on telemetry failure, never blocks the operation being
observed). `compute_latency_percentiles()` federates
`route_observations` with `mcp_call_log` into grouped p50/p95 buckets,
flagging buckets under 5 samples as `low_confidence` rather than
presenting an unreliable percentile as a real budget number.
- Wired into three call sites: the MCP six-tool
`status(scope=coordination)` handler (records archive-evidence-degraded
state from the envelope's own advisories), `polylogue agents <view>`
(all coordination CLI views), and `polylogue status` (records
daemon-reachable vs direct fallback).
- New `polylogue analyze latency` CLI command reads and renders the
federated p50/p95 view.
- New benchmark `tests/benchmarks/test_cli_cold_start.py` backs a new
informational `cli_status_cold` SLO row: measured baseline p50 ~1.80s (5
rounds) — this is polylogue-8s70's own cProfile finding restated as a
runnable number instead of a one-off manual measurement. The row's
target (500/800ms) is the aspirational post-8s70-fix budget, not today's
passing bar.

## Verification
- `devtools test tests/unit/operations/test_route_observation.py
tests/unit/storage/test_archive_tiers_ops_write.py
tests/unit/cli/test_status.py tests/unit/cli/test_status_diagnostics.py
tests/unit/cli/commands/test_status.py
tests/unit/cli/test_agents_command.py
tests/unit/mcp/test_status_scope_coordination.py` — 202 passed.
- `tests/unit/cli/test_diagnostics.py -k latency` — 3 passed (the file's
other 8 `test_tools_*` failures are pre-existing and unrelated —
confirmed via `git stash` comparison against the same baseline before
this change).
- Manual end-to-end proof: real CLI invocations against an
initialized-but-empty archive produced real `route_observations` rows
that `analyze latency` then read back with correct p50/p95.
- `mypy --strict` across all touched/added source files — clean.
- `devtools verify --quick` — exit 0 (required adding
`record_route_observation` to `docs/plans/layering.yaml`'s
`ops_write.py` entrypoint declaration, and
`tests/unit/cli/test_diagnostics.py` to
`docs/plans/test-clock-allowlist.yaml` for its `--since-hours` window
fixture construction, which legitimately reads real wall time to match
the production command's own `time.time()` usage).

Ref polylogue-jtwu, polylogue-20d.17
Sinity added a commit that referenced this pull request Jul 20, 2026
## Summary

`record_revision_application_sync` now permits a raw-revision replay to
supersede its own previous accepted head when the incoming receipt is
derived from the same `accepted_raw_id` — a re-derivation from identical
raw evidence, not a genuine conflict. Every raise in the function now
carries diagnostic context (logical source key, existing vs incoming raw
ids/session ids/frontiers, content-hash prefixes).

This unblocks resume #4 of operation ab5bad1f: resume #3 failed fast
after the #3191 parser fix because ~466 already-committed sessions'
raw evidence now reparses to a different content hash (and in some cases
a different `session_id` after identity-law fixes), and the CAS was
treating that as an unauthorized conflict.

## Problem

`polylogue/storage/sqlite/archive_tiers/revision_application.py`'s
equal-frontier CAS branch rejected any incoming receipt whose derived
semantics (`accepted_content_hash`, `session_id`) differed from the
existing `raw_revision_heads` row at the same frontier, unless a
`FullSnapshotFoldAuthorization` was present — even when the receipt's
`accepted_raw_id` was *identical* to the existing head's. The raw blob
is content-addressed and unchanged after a parser fix; only the
*derivation* (parsed content, and possibly the session_id it resolves
to) changed. Blocking same-raw re-derivation contradicts the repo's
derived-tier doctrine ("derived content re-derives from source",
`docs/architecture.md`) and means every parser or identity-law
improvement poisons already-committed archives on the next rebuild.

While reproducing this at fixture scale, a second, earlier gate with
the identical failure mode turned up: `raw_revision_applications`'
immutable-ledger check uses `decision_id` as its natural key, and
`decision_id` deliberately excludes `accepted_content_hash` from its
hash payload. So a receipt that is identical to an existing ledger row
in every decision-defining field except `accepted_content_hash` (the
pure "same raw, reparsed to a different hash" case) hit "conflicting
raw revision application receipt" *before* ever reaching the heads
CAS — same root cause, one call earlier.

## Solution

Both in
`polylogue/storage/sqlite/archive_tiers/revision_application.py`:

- **Ledger check** (`raw_revision_applications`): when an existing row
  found by `decision_id` differs from the incoming receipt *only* in
  `accepted_content_hash` (the only field `decision_id`'s hash doesn't
  cover), `UPDATE` the row's `accepted_content_hash` in place instead of
  raising. Any other field actually differing is unreachable without a
  `decision_id` hash collision and still raises defensively.
- **Heads CAS** (`raw_revision_heads`, equal-frontier branch): added a
  `same_raw_supersede = receipt.accepted_raw_id == existing_head[1]`
  exemption alongside the existing fold-authorization exemption. Falls
  through to the same `UPSERT` that fold-authorized folds already use.
  **Cross-raw conflicts** (different `accepted_raw_id`, same frontier,
  differing semantics, no fold authorization) are unaffected and still
  reject — that guard protects real divergence. Older-frontier and
  incomparable-frontier-kind rejections are unaffected.
- **Error context**: all six raises in the function now include
  `logical_source_key`, existing vs incoming `accepted_raw_id`/
  `session_id`/frontier, and content-hash prefixes. A 10-hour rebuild
  died on a context-free `RuntimeError` twice this weekend.

**Async twin audit**: grepped the repo for a second CAS implementation
(`record_revision_application` without `_sync`, an `async_sqlite` tree,
etc.) — none exists. `record_revision_application_sync` is the sole
writer of `raw_revision_heads` across every call site
(`storage/sqlite/archive_tiers/archive.py`, `storage/repair.py`).

## Verification

- `devtools test tests/unit/storage/test_revision_application.py` — 12
  passed. Extended (not duplicated) with: same-raw content-hash
  supersede, same-raw session_id supersede (identity-law fix case),
  cross-raw conflict without fold authorization (asserts the message
  names both `accepted_raw_id`s), idempotent same-everything
  re-application, and a frontier-mismatch case split out of the old
  parametrized test whose other two cases this PR intentionally
  changes the expected outcome of.
- `devtools test tests/unit/sources/test_live_batch_support.py` — 63
  passed, 5 failed. Reproduced the identical 5 failures on unmodified
  master (`08cd41b34`) via a throwaway `git worktree`, confirming they
  are pre-existing and unrelated to this change (removed the worktree
  after comparison).
- `devtools test tests/unit/storage/test_repair.py
  tests/unit/storage/test_raw_revision_authority.py
  tests/unit/storage/test_duplicate_raw_identity_repair.py` — 95
  passed (broader affected-area check for the touched CAS surface).
- `devtools verify --quick` — all steps green (ruff format/check, mypy
  --strict, render all, topology/layering/closure-matrix/manifests/
  ci-workflows/doc-commands/docs-coverage/test-infra-currency/
  test-clock-hygiene/pytest-timeout-overrides/degrade-loudly).

Not run: `devtools verify --all` (full non-integration suite) — the
targeted + affected-area runs above cover the touched surface; the
per-PR CI `test` job runs post-merge on master per repo convention.

Ref ab5bad1f resume #4
Sinity added a commit that referenced this pull request Jul 20, 2026
Ref polylogue-gd6v (parse-stage seam performance; surfaced by the resume
#4 parallel-warm probe).

## Summary
The parse-prefetch inflight budget default becomes adaptive: physical
RAM / 16 clamped to [64 MiB, 2 GiB], env override unchanged.

## Problem
Measured live on the 50K-raw archive (2026-07-20): under the fixed 64
MiB default, a 2000-raw bulk warm did 139 raws in 376s (0.37 raws/s) —
the thread pool was stalled on cache admission, not parsing. With an
adequate budget the same host warms 500 raws in 8.8s (56.7 raws/s), ~10x
the sequential engine pace. The budget exists to bound transient memory
beside a live daemon; a one-size constant starves capable machines and
is exactly what made the daemon bulk path (#3189) parallelism
theoretical.

## Solution
`daemon_parse_stage_max_inflight_bytes()` computes RAM/16 clamped to [64
MiB, 2 GiB]; unknown RAM → 64 MiB floor;
`POLYLOGUE_DAEMON_PARSE_STAGE_MAX_INFLIGHT_BYTES` still always wins.

## Verification
`devtools test tests/unit/daemon/test_parse_prefetch.py` → 7 passed (new
test covers ceiling/floor/proportional/unknown/override). `devtools
verify --quick` → exit 0. Live probe numbers above.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Performance**
* Improved background session prefetching by adapting its memory usage
to the available system RAM.
* Added safeguards to prevent prefetch operations from waiting
indefinitely.

* **Reliability**
* If prefetching times out, uncached data is processed normally without
interrupting the workflow.
* Added support for configuring the prefetch memory limit, including
safe fallback limits.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sinity added a commit that referenced this pull request Jul 21, 2026
…tion (#3235)

## Summary

Adds a `messages_fts_identity` shadow ledger that binds each
`messages_fts` rowid to its `block_id`, exact reconciliation that joins
on rowid AND identity (not rowid alone), bounded ops.db drift-magnitude
history, and a Prometheus drift-magnitude gauge. Real-trigger
metamorphic property tests (Hypothesis `RuleBasedStateMachine`) plus
focused anti-vacuity unit tests prove the check has teeth.

## Problem

`messages_fts` is a **contentless** FTS5 table (`content=''`): its
`block_id` UNINDEXED column is write-only and never retrievable by a
later `SELECT` (verified empirically). SQLite reuses freed rowids —
deleting the highest-rowid block then inserting a new one commonly gets
the **same rowid back**, exactly what a full-session-replace does.
Count-only reconciliation (`source_rows == indexed_rows`) is blind to
this: a stale rowid can silently rebind to a different block while both
sides still balance, and the existing `fts_freshness_state` ledger only
ever tracked counts (missing/excess/duplicate), never identity.

## Solution

- **`polylogue/storage/fts/sql.py`**: `FTS_MESSAGES_IDENTITY_TABLE_SQL`
(`messages_fts_identity(rowid PK, block_id UNIQUE, source_hash,
recipe_id)`), `FTS_MESSAGES_IDENTITY_RECIPE_ID` (versioned recipe
token), and `message_identity_mismatch_sql()` — an exact join across
`blocks`/`messages_fts_docsize`/`messages_fts_identity` that flags a
**present-but-wrong** ledger entry (rowid-reuse, changed-text,
changed-recipe). A missing entry is deliberately NOT counted (see
below).
- Trigger bodies (`messages_fts_ai`/`ad`/`au`) gain a paired identity
write in the SAME body as their `messages_fts` write, so the two can
never diverge for one event. `source_hash` reuses the existing
`blocks.content_hash` evidence hash; `recipe_id` is the versioned
constant — the same subject/source/recipe split
`storage/derivation_identity.py` formalizes for polylogue-wmsc's
`DerivationKey`, applied here as a lightweight per-row ledger (never a
shared cross-domain table).
- `storage/fts/fts_lifecycle.py`: every bulk rebuild/repair path (full
rebuild, batched missing/excess repair, session-scoped repair) pairs its
`messages_fts` write with the matching identity companion SQL;
`FtsSurfaceInvariant`/`FtsInvariantSnapshot` gain
`identity_mismatch_rows` and fold it into `.ready`.
- `storage/fts/freshness.py`: `fts_freshness_state` gains an
`identity_mismatch_rows` column (backward-compatible `ALTER ... DEFAULT
0`), threaded through `freshness_ready_record_trusted` and every
read/record path.
- `storage/sqlite/archive_tiers/ops.py` + `ops_write.py`: bounded
`fts_drift_samples` table (30d / 5k-row retention, same shape as
`cursor_lag_samples`),
`record_fts_drift_sample`/`list_fts_drift_samples`.
`storage/fts/drift_sampling.py::sample_fts_drift_to_ops_sync` reads the
just-recorded `fts_freshness_state` row(s) and appends a sample to the
sibling `ops.db`; wired into daemon startup and every
`record_fts_invariant_snapshot_sync` call site.
- `daemon/metrics.py`: `polylogue_fts_drift_rows` gauge — labels
`surface`, `kind` (missing/excess/duplicate/identity_mismatch) — read
O(1) from `fts_freshness_state`, no scan on scrape.
- `INDEX_SCHEMA_VERSION` 42→43 with a declared clone-safe fast-forward
(`IndexDeltaDeclaration` v43 in `storage/sqlite/lifecycle.py`,
`FTS_REINDEX` class) since every ledgered field derives from
already-persisted `blocks` columns — no raw reparse needed.

### Design decision: coverage gap vs. conflict

`message_identity_mismatch_sql()` counts only a **present-but-wrong**
ledger entry, never a missing one. Rationale, discovered empirically
(see Verification): `storage/sqlite/archive_tiers/write.py`'s non-bulk
full-session-replace fast path calls
`delete_session_rows_sql`/`insert_session_rows_sql` directly (bypassing
the suspended block triggers) and does **not** populate the identity
ledger inline — this is the dominant real-world re-ingest path. Counting
a missing entry as a mismatch made `messages_ready` permanently false on
any ordinarily-written archive, which defeats the point of a readiness
signal. A missing entry is provably safe on its own: nothing reads block
identity *from* the ledger except this reconciliation query, and the
next trigger-fired mutation at that rowid always writes a correct fresh
row regardless of prior absence. Only a present-but-wrong entry is the
actual danger signature.

### STOP-and-report: `write.py` gap (not fixed here, per task boundary)

`storage/sqlite/archive_tiers/write.py` is on this lane's do-not-touch
list. Its non-bulk full-session-replace path (`_full_replace_...`, four
call sites) calls
`delete_session_rows_sql(1)`/`insert_session_rows_sql(1)` directly and
would need one additional paired
`delete_session_identity_rows_sql`/`insert_session_identity_rows_sql`
call at each site to keep the ledger inline-fresh instead of relying on
the next repair pass. Both companion functions already exist in
`storage/fts/sql.py`. Until that lands, a freshly-written session is
coverage-incomplete (not conflicting) until `dangling_repair.py`'s
missing-row repair backfills it — the same eventually-consistent
contract `missing_rows`/`excess_rows` already had.

## Verification

- `mypy --strict` on all touched modules: `Success: no issues found in
12 source files`
- `devtools verify --quick`: exit 0 (format, lint, mypy,
render-all-check, layering, degrade-loudly, closure-matrix,
schema-roundtrip, manifests, ci-workflows, doc-commands, docs-coverage,
test-infra-currency, test-clock-hygiene, pytest-timeout-overrides)
- `devtools test tests/unit/storage/test_fts_identity_ledger.py
tests/property/test_fts_identity_state_machine.py
tests/unit/daemon/test_metrics_endpoint.py
tests/unit/daemon/test_daemon_cli.py
tests/unit/daemon/test_fts_readiness_fallback.py`: **157 passed**
- Broader FTS-adjacent sweep (`test_dangling_fts_derived_surfaces`,
`test_fts_global_repair`, `test_convergence_stages`,
`test_bulk_build_lifecycle`, `test_fts_bloat_invariants`, `test_index`,
`test_fts_repair_sql`, `test_write_gateway`, `test_write_effects`,
`test_ingest_batch_fts_repair`, `test_pl_fold`, `test_schema_safety`):
**all green except one pre-existing failure**
(`test_reset_and_repair_fts_rows_recovers_excess_message_rows`,
confirmed failing identically on baseline `master` before this branch —
`no such table: main.derived_refresh_guard`, unrelated to this change)
- `devtools lab policy schema-versioning`: v43 correctly declared; the
one reported gap (`missing: [40]`) is confirmed pre-existing on baseline
- `devtools render topology-projection && devtools render
topology-status`: regenerated for the new
`storage/fts/drift_sampling.py` module

Not run: full `devtools verify` (testmon-seeded pytest) — testmon wasn't
seeded in this fresh worktree and seeding is a full-suite-equivalent
cost; the targeted sweep above plus mypy --strict cover every touched
surface.

## AC matrix (polylogue-1xc.12)

| # | AC | Status |
| --- | --- | --- |
| 1 | `messages_fts_identity(rowid PK, block_id UNIQUE, source_hash,
recipe_id)` + exact freshness fields | **Satisfied** |
| 2 | Production triggers + full rebuild maintain FTS, docsize, ledger,
O(1) state atomically across
empty/text/delete/replace/rollback/recipe-change | **Satisfied** for
triggers and bulk rebuild/repair paths in `fts_lifecycle.py`;
**deferred** for `write.py`'s non-bulk fast path (see STOP-and-report
above) |
| 3 | Exact reconciliation compares identity/source/recipe; rowid-reuse,
changed-text, changed-recipe all fail before repair | **Satisfied**
(proven by `test_fts_identity_ledger.py::TestIdentityMismatchDetection`
and the metamorphic state machine) |
| 4 | Periodic convergence detects drift in FTS or ledger, rebuilds
both, records before/after, converges idempotently | **Partially
satisfied**: exact reconciliation + bounded repair self-heal on every
rebuild/repair call and daemon startup; a dedicated periodic *scheduled*
convergence stage (vs. today's startup/rebuild-triggered cadence) is not
added — no existing `ConvergenceStage` was extended, out of scope for
this lane's effort budget |
| 5 | Metrics/readiness never scan blocks/FTS; ops history is bounded |
**Satisfied** (`polylogue_fts_drift_rows` reads O(1) from the ledger;
`fts_drift_samples` is time+row-bounded) |
| 6 | Real-trigger Hypothesis state machine covers rowid reuse, full
replace, rollback, empty text, source change, recipe change |
**Satisfied** — `tests/property/test_fts_identity_state_machine.py`
(recipe change proven via the corrupt-then-repair rule since the recipe
constant is compiled into trigger SQL, not runtime-configurable) |
| 7 | Removing any trigger arm, block_id/source/recipe check, or exact
audit fails | **Satisfied by construction**: tests exercise the real
trigger DDL and real reconciliation SQL, never a mock; anti-vacuity
docstrings on each test name the exact mutation that would flip it red |
| 8 | FTS consumes shared DerivationKey value semantics without sharing
embedding storage/scheduling/lifecycle | **Satisfied** —
`source_hash`/`recipe_id` mirror the subject/source/recipe split
conceptually; no table/module shared with polylogue-wmsc's embedding
freshness work |

Ref polylogue-1xc.12 (do not close — AC #4 and the `write.py` gap in AC
#2 remain open follow-up work)

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 21, 2026
…te detection (#3247)

## Summary

`ingest_record` (the live daemon's per-raw ingest worker) previously
decoded
every raw as text/JSON before any provider dispatch, so Hermes raws
whose
payload is SQLite database bytes failed to parse -- while the rebuild
path
(historical backfill / census / replay) parsed the identical bytes fine.
This
PR routes ingest_record's decode step through the same binary-capable
detection the rebuild path uses, and fixes two related parse-route
divergences
found while proving parity.

## Problem

Live failure (2026-07-21, discovered during a targeted Hermes
reprocess):
`parse_from_raw` -> `process_ingest_batch` -> `ingest_record`
(`polylogue/pipeline/services/ingest_worker.py`) fails all 3 Hermes
verification raws (`source_path ~/.hermes/verification_evidence.db`,
SQLite
database bytes) with:

```
decode: str is not valid UTF-8: surrogates not allowed: line 1 column 1
```

The REBUILD path (`sources.revision_backfill._parse_retained_raw` /
`_parse_one`) parses these same raws fine -- the v42 walk materialized
verification sessions from them via `looks_like_sqlite_bytes` + the
parser
modules' own `looks_like_*_path` structural probes, bypassing
`build_raw_payload_envelope`/`classify_artifact` entirely.

Root cause is two-layered:

1. **`polylogue/archive/raw_payload/decode.py`**:
`build_raw_payload_envelope`
(the function `ingest_record` calls to decode every raw) only
special-cased
`state.db` via `_looks_like_hermes_state_db` --
`verification_evidence.db`
   had no equivalent marker branch, so it fell through to the generic
   JSON/JSONL decode path and was rejected as invalid UTF-8.
2. **`polylogue/archive/artifact_taxonomy/runtime.py`**: even after
building
the correct marker payload, `classify_artifact()` consulted the
path-only
`classify_artifact_path()` *first*. That function's "Hermes SQLite
evidence
   sidecar" filename rule for `verification_evidence.db` unconditionally
   returns `parse_as_session=False` (intended for pre-decode, path-only
callers like schema sampling) -- and since `classify_artifact()` returns
early on a non-`None` path classification, it shadowed the marker
payload's
   positive session classification for the identical filename.

## Solution

- **`polylogue/archive/raw_payload/decode.py`**: generalized the
state.db-only
`_looks_like_hermes_state_db` branch into
`_hermes_sqlite_marker_payload`,
  which now recognizes both `state.db` and `verification_evidence.db` by
calling `hermes_state.marker_payload()` /
`hermes_verification.marker_payload()`
  directly (previously the state.db marker dict was hand-built inline,
duplicating what `hermes_state.marker_payload` already does).
Binary-capable
detection now runs before any text decode, in the same order the rebuild
path's `_parse_one` already uses (`looks_like_sqlite_bytes` ->
per-artifact
  `looks_like_*_path` probes).
- **`polylogue/archive/artifact_taxonomy/runtime.py`**: extracted the
two
Hermes SQLite marker checks (state.db / verification_evidence.db) out of
`_classify_dict` into a shared `_classify_hermes_sqlite_marker` helper,
and
  call it from `classify_artifact()` *before* consulting
`classify_artifact_path()`. The raw `*.db` path itself still classifies
as a
non-session sidecar when passed alone (schema sampling and other
path-only
callers are unaffected); only a decoded marker *payload* now wins over
the
  path-only sidecar rule.
- **`polylogue/sources/revision_backfill.py`**: while building the
parity
  test, found `_parse_one`'s `verification_evidence.db` branch omitted
`profile_root=` (unlike the adjacent `state.db` branch, which already
passes
  `profile_root=Path(source_path).parent`). This meant the rebuild route
produced an *unqualified* `verification:<raw_id>` session id while the
fixed
  ingest route (via dispatch, which already threads `profile_root` from
`spec.source_path`) produces a *profile-qualified* id -- a second,
narrower
  parse-route disagreement in the exact same area. Fixed to match.

**Ownership note:** `polylogue/sources/dispatch.py` is owned by a
concurrent
lane (OriginSpec work). This PR does not touch it -- the marker-payload
dispatch route (`detect_provider` / `_lower_payload_specs` /
`_parse_lowered_spec`) already fully supported
`verification_evidence.db`
markers; the gap was entirely upstream of dispatch, in the envelope
decode and
artifact classification steps.

## Other binary-payload providers (AC #4)

Grepped every parser module under `polylogue/sources/parsers/` for
direct
`sqlite3` reads. Only `hermes_state.py` (`state.db`) and
`hermes_verification.py` (`verification_evidence.db`) read raw SQLite
bytes;
both are covered by the new parity test. Antigravity's "brain-metadata"
artifact (`looks_like_brain_metadata`) is JSON, not binary -- not
exposed to
this bug class. No other provider needs coverage.

## Acceptance-criteria matrix

| # | AC | Status |
| --- | --- | --- |
| 1 | Diagnose exact divergence point; reuse the rebuild path's helper
instead of forking logic | Satisfied -- `_hermes_sqlite_marker_payload`
calls the same `hermes_state`/`hermes_verification`
`looks_like_*_path`/`marker_payload` functions `_parse_one` uses |
| 2 | Fix lives in `pipeline/services/ingest_worker.py` and/or
`sources/decoders.py`; `dispatch.py` untouched or minimally flagged |
Satisfied -- fix lives in `archive/raw_payload/decode.py` (the module
`ingest_record` calls into) and `archive/artifact_taxonomy/runtime.py`;
`dispatch.py` not touched at all |
| 3 | Contract test: raw parseable via rebuild route also parseable via
`ingest_record`, comparing session native ids; anti-vacuity stated |
Satisfied -- `tests/unit/pipeline/test_binary_payload_parse_parity.py`,
two tests (verification_evidence.db + state.db regression guard);
anti-vacuity verified live (see Verification) |
| 4 | Check other binary-payload providers | Satisfied -- only Hermes
exposed; documented above |

## Verification

```
devtools test tests/unit/pipeline/test_binary_payload_parse_parity.py \
  tests/unit/pipeline/test_ingest_worker_assembly.py \
  tests/unit/sources/parsers/test_hermes_verification.py \
  tests/unit/sources/parsers/test_hermes_state.py \
  tests/unit/sources/test_revision_backfill.py \
  tests/unit/core/test_raw_payload_decode.py tests/unit/core/test_models.py \
  tests/unit/sources/test_parsers_local_agent.py tests/unit/sources/test_artifact_taxonomy.py
```
-> 270 passed, 1 pre-existing failure unrelated to this change

(`test_build_raw_payload_envelope_prefers_claude_subagent_path_over_codex_like_shape`,
reproduces identically against unmodified `master` -- Claude Code
subagent
JSONL classification, no file this PR touches is involved).

```
mypy --strict polylogue/archive/raw_payload/decode.py \
  polylogue/archive/artifact_taxonomy/runtime.py \
  polylogue/sources/revision_backfill.py \
  polylogue/pipeline/services/ingest_worker.py
```
-> `Success: no issues found in 4 source files`

```
devtools verify --quick
```
-> all 16 steps `ok`, exit 0.

**Anti-vacuity**: stashed the `decode.py` routing change and re-ran the
new
parity test -- it fails with the exact live error string:
`decode: str is not valid UTF-8: surrogates not allowed: line 1 column
1`.

Ref polylogue-zoc3
Sinity added a commit that referenced this pull request Jul 21, 2026
…pairing (polylogue-yyvg.7 + 3v1 + gnie) (#3260)

## Summary

Delivers the browser-capture receiver+extension pairing-bootstrap and
capture-health-telemetry slice of the extension trust-surface cluster
(Ref polylogue-yyvg.7, Ref polylogue-3v1, Ref polylogue-gnie). Two
commits:
receiver/CLI infrastructure (Python), then the extension-side pairing UI
that consumes it (JS).

## Problem

- **polylogue-gnie**: a fresh extension install had no way to adopt the
  receiver's auto-minted bearer token except the operator running
  `polylogued browser-capture token show` and pasting the 43-character
secret into the popup. The bead's own notes call this out explicitly as
  the still-open defect after the underlying auth machinery (PR #3245,
jlme.5) shipped: "the prior close treated CLI copy/paste as equivalent
to
  automatic token adoption. It is not."
- **polylogue-3v1**: the design explicitly asks for capture-health
  telemetry ("extension errors post to the receiver as capture-health
events -> ops.db -> daemon /metrics + status ... the extension becomes
an
observable component") so that capture gaps/errors are queryable archive
history rather than only visible transiently in the popup. This did not
  exist.
- **polylogue-yyvg.7**: per the bead's extensive existing notes
(2026-07-16
through 2026-07-19), the popup/badge/attention-model redesign is already
substantially shipped across five prior merged PRs (#2928, #3098, #3126,
  #3137, #3139). What remains open per the bead's own AC-by-AC record is
  either blocked on a data model that does not exist yet (explicit-
  approval/destructive-conflict attention categories) or requires live
  installed-browser proof the bead's notes say was already attempted and
  partially completed by a prior session.

## Solution

**polylogue-gnie — one-time pairing code (compatibility fallback per the
bead's own design text)**: the bead's recommended primary design is an
installer-managed native-messaging host; this repo cannot install an
OS-level
native-messaging manifest or exercise a real, stable
`chrome-extension://`
identity headlessly, so that path is genuinely out of scope for an
unattended session. The design text names an explicit fallback instead —
"a user-presence one-time pairing approval/code that transfers the
secret
without copy/paste" — and that is what this PR implements:

- `polylogue/browser_capture/pairing.py` (new): mints an 8-character,
40-bit-entropy, single-use, 180s-default-TTL code; only its SHA-256 hash
  is ever persisted (`browser-capture-pairing` file under the archive
  root, same 0600-atomic-write pattern as the bearer token). 5 wrong
  guesses burn the pending code even before its TTL expires.
- `POST /v1/pairing/redeem` (new route,
`polylogue/browser_capture/server.py`):
deliberately unauthenticated — bootstrapping the token *is* its job —
but
still origin-checked (`_reject_origin`), so an arbitrary webpage cannot
  forge the extension's `chrome-extension://` origin to redeem a code it
  somehow observed.
- `polylogued browser-capture pairing start [--ttl-seconds]` CLI prints
the
code; the extension's new popup "Pairing code" field (inside the
existing
collapsed diagnostics section, next to the manual bearer-token field it
  complements rather than replaces) exchanges it automatically via
  `background.js`'s new `pairWithCode`/`redeemPairingCode`.
- **Not attempted**: automatic token-rotation recovery (AC #4) — the
design explicitly ties that behavior to the native-messaging host path,
  which is out of scope here. Manual re-pairing (paste the token, or run
  `pairing start` again) remains the break-glass/recovery route.

**polylogue-3v1 — capture-health telemetry, producer side deferred**:

- `POST /v1/capture-health` (bearer-gated like every other route) and
`GET /v1/capture-health` (new routes): events are stored in the existing
  ops.db `daemon_events` ledger under `kind="browser_capture_health"`,
reusing
`polylogue.daemon.events.emit_daemon_event`/`query_daemon_events`
  rather than adding a new table (`ops.db` is a freeform-additive
  disposable tier — see `fts_drift_samples` precedent).
- `polylogued browser-capture capture-health [--limit]` CLI lists recent
  events without an HTTP round trip.
- **Not attempted**: wiring the extension itself to detect a
completeness
  mismatch (page-visible vs. archived message count) and call this new
endpoint automatically. The receiver-side ledger, query surface, and CLI
are real and tested; the producer that would make gaps self-report is a
  distinct, still-open chunk of work (the extension has no existing
  visible-vs-captured comparison to hook — a genuine follow-up, not a
  trivial wire-up). Gemini bridge coverage (`gemini.google.com` host
  permission + content-script bridge) is likewise not attempted — a full
  new provider bridge is out of scope for this slice.

**polylogue-yyvg.7 — no additional code in this PR.** Verified the
bead's
own AC-by-AC record against current `main` (popup.js/operator_status.js/
popup.html) and confirmed the prior sessions' claims hold: compact
always-visible surface, single-attention-item model, shared status
module,
DOM/action budget test, and the F1/F6 visual convergence are all present
in the current tree. What the bead's notes list as still open —
explicit-
approval/destructive-conflict attention categories (blocked on a data
model ptx does not yet expose) and literal live-installed
offline-recovery
proof — are unchanged by this PR; both require capability or environment
this session does not have (a real backing data model for the former, a
disposable second receiver + real browser for the latter).

## Verification

- Python: `devtools test tests/unit/browser_capture/` — 146 passed
(18 new: `tests/unit/browser_capture/test_pairing.py`, real HTTP against
  the threaded `BrowserCaptureHTTPServer`, plus CLI round-trips via
  `CliRunner`). `mypy` clean on touched files. `devtools verify --quick`
  exit 0 (`.cache/verify/runs/20260721T234119Z-quick-765869-deca05d8`).
`devtools render all --check` exit 0 (new `pairing.py` module required a
  topology-projection regen, included).
- JS: `npx vitest run` — 347 passed / 1 failed. The 1 failure
  (`build.test.js` service-worker-fixture timing) is **pre-existing and
unrelated** — reproduced identically with this branch's diff stashed out
(`git stash && npx vitest run tests/build.test.js` fails the same way).
  `npm run lint` and `npm run validate` (manifest) both clean.
- **Anti-vacuity**:
`test_pairing_redeem_route_pairs_without_a_preexisting_token`
  exercises the real `write_capture_envelope`-adjacent HTTP stack end to
  end — mutating `redeem_pairing_code` to skip the origin check, or
  removing the `_reject_origin()` call ahead of the pairing route in
`server.py`, makes `test_pairing_redeem_route_rejects_disallowed_origin`
  fail; mutating the single-use clear-on-success behavior makes
`test_pairing_redeem_route_is_single_use_over_http` fail. On the JS
side,
  deleting the `polylogue.pairWithCode` handler or the `Content-Type`
  header in `redeemPairingCode` fails
`background.test.js`'s "exchanges a valid pairing code" test (asserts no
  `Authorization` header is sent and the body round-trips exactly).

## What only manual/live browser testing can prove

- The popup's new "Pairing code" field actually rendering and being
  reachable/styled correctly in a real installed Chrome/Firefox profile
(jsdom-based `popup.test.js` proves the click → message → storage
wiring,
  not visual layout).
- End-to-end pairing against a real `polylogued` daemon + real
  `chrome-extension://<id>` origin (the test fixtures use a synthetic
  `chrome-extension://polylogue-test` origin, which is the same pattern
  every other receiver-route test in this repo already uses).
- Token-rotation recovery UX and the native-messaging path — both
  explicitly out of scope for this PR (see Solution above).

## Per-bead AC matrix

**polylogue-gnie** ("Automate secure browser-to-receiver pairing"):
1. Fresh install pairs without viewing/copying/pasting a bearer secret —
**partially satisfied**: the one-time-code fallback delivers this; the
design's *primary* recommendation (native messaging) is not attempted.
2. Receiver stays deny-by-default; hostile origin/process can't retrieve
the token via pairing — **satisfied** for the origin axis (tested); the
short-lived/single-use/rate-limited code is the stated defense against a
   same-host process without native-messaging-grade isolation.
3. Pairing binds real extension+receiver identities, fails visibly on
   mismatch, logs no secret — **satisfied**: the response includes
`receiver_id`; rejections log only the exception type, never the code or
   token (verified by reading the log call sites).
4. Token rotation invalidates old token, extension recovers
automatically —
**deferred**: this AC clause is explicitly tied to the native-messaging
path in the bead's design text; manual re-pairing remains the recovery
   route with this fallback.
5. Real browser-extension-to-loopback fixture proving first pairing,
authenticated reads, rotation recovery, profile reseed, hostile-origin
   rejection, receiver-offline recovery — **partially satisfied**: first
pairing and hostile-origin rejection are proven over real HTTP; rotation
recovery, profile reseed, and receiver-offline recovery are not (need a
   live browser or are explicitly deferred per AC #4).

**polylogue-3v1** ("Capture extension reliability + status UX"):
- Badge shows current/spooled/error per tab — **unchanged by this PR**
  (already substantially shipped per the bead's prior-session notes;
  independently verified present in the current tree).
- Receiver-down spooling drains with no loss/dup — **unchanged by this
PR**
(prior sessions' notes claim this is already implemented; not
re-verified
  here — out of this slice's scope).
- `gemini.google.com` capture end-to-end — **not attempted** (full new
provider bridge, out of scope for this slice; named as residual above).
- Capture-gap events queryable in the archive — **satisfied for the
  receiver/CLI side** (`GET /v1/capture-health`,
  `polylogued browser-capture capture-health`); **not satisfied for the
  producer side** — the extension does not yet detect and report gaps
  automatically (residual, needs a follow-up bead for the visible-vs-
  captured comparison + wiring).
- Bridge DOM fixtures in CI — **unchanged by this PR**.

**polylogue-yyvg.7** ("Make extension UX automatic and
exception-driven"):
- AC1-AC7 — **no change from the bead's existing 2026-07-19 record**,
independently spot-checked against current `main` and found consistent.
Still-open items per that record (explicit-approval/destructive-conflict
  attention categories blocked on a missing data model; literal
  live-installed offline-recovery proof) are unchanged residuals, not
  addressed by this PR.

## Residuals (named follow-ups, not silently dropped)

1. Extension-side capture-health *producer* wiring (visible-vs-captured
   comparison → `POST /v1/capture-health` on detected gap/error/spool-
backlog/provider-auth-broken) — the receiver/CLI/query side landed here,
   the extension-side detection+call did not.
2. Gemini (`gemini.google.com`) capture bridge — not attempted.
3. Native-messaging installer bootstrap for gnie AC #1/#4's full
automatic
   path — not attempted (this repo cannot install/test it headlessly).
4. yyvg.7's explicit-approval/destructive-conflict attention categories
—
   blocked on a ptx-side data model that does not exist yet (per the
   bead's own notes, unchanged by this PR).
Sinity added a commit that referenced this pull request Jul 27, 2026
## Summary

Live-ingest SSE events (`session.appended` / `message.appended`) now
carry
the real session id they describe instead of firing once per batch with
`session_id: null`. Added a real production emitter for
`session.updated`.
Retired three advertised-but-unwired topics (`insight.updated`,
`progress.update`, `progress.complete`) that had zero production
callers.

## Problem

`polylogue-20d.13` names an evidence-identity defect: the daemon emitted
one
aggregate `session.appended`/`message.appended` event per live-ingest
batch
with `session_id=None`. The web reader's live-tail handler already had
correct session-scoping logic (`if (convId && convId !== selectedId)
return;`
in `web_shell_realtime.py`), but since the producer never sent a real
`session_id`, the guard never fired — every successful ingest batch
refreshed whichever session the browser happened to have open,
regardless
of which session actually changed.

Separately, `session.updated` was advertised in `GRANULAR_EVENT_KINDS`
and
subscribed to by the client, but had no emitter at all. Grepping the
whole
codebase for `emit_insight_updated`/`emit_progress_update`/
`emit_progress_complete` turned up zero production callers — only their
own
unit tests — and the docstring's claimed CLI consumer
(`status --convergence --watch`) does not exist.

## Solution

- `polylogue/sources/live/append_ingest.py`: capture the `session_id`
that
  `archive.apply_raw_revision_replay` already returns (previously
  discarded) into a new `_AppendResult.session_ids_by_path`.
- `polylogue/sources/live/batch_support.py`: add
  `_FullIngestResult.changed_session_ids` (threaded from
  `_IngestBatchSummary.changed_session_ids`, which existed but was only
  ever reduced to a count).
- `polylogue/sources/live/batch.py`: accumulate `(source_name,
session_id)`
  touches from both routes during `ingest_files` and attach them to
  `LiveBatchMetrics` as `new_sessions` (full-ingest route — first
materialization) and `updated_sessions` (append route — the append path
  only ever grows a file whose session already exists, by construction).
- `polylogue/sources/live/metrics.py`: serialize the two new fields in
  `to_payload()`.
- `polylogue/daemon/cli.py`: `_emit_live_batch_event` now fans out one
  `session.appended`/`session.updated`/`message.appended` event **per
distinct touched session**, each carrying its real `session_id`, instead
of one aggregate event. Falls back to the old unscoped emission only
when
  no identity was resolved for a succeeded batch (an explicit, logged
  degrade rather than silent loss — covers source families this pass
  doesn't thread identity through yet).
- `polylogue/daemon/events.py`: added `emit_session_updated` (the first
real
  producer for `session.updated`); added `session_id` to
  `emit_session_appended`. Removed `EVENT_INSIGHT_UPDATED`,
`EVENT_PROGRESS_UPDATE`, `EVENT_PROGRESS_COMPLETE` and their emitters —
  per this bead's own design text ("remove topics with no production
  semantics or wire their actual producers"), zero-producer advertised
  topics are a completeness defect, not a feature worth preserving.
- `polylogue/daemon/web_shell_realtime.py` / `events_http.py`: dropped
the
  matching client-side subscriptions/handlers and doc references.

**Not done (honest residual):**
- No formal per-topic `EventSpec` registry (design section 1 of this
bead)
  — that's a larger structural addition (ids, refs, cursor/frame, phase,
  authorization contract per topic) beyond identity-scoping the two
  existing wired topics.
- New-vs-updated classification uses the ingestion **route** (full vs
append) as a proxy for new-vs-existing session. This is accurate for the
common case (a brand-new file vs. an already-cursor-tracked file
growing)
but a full reparse of an *already-existing* session id (e.g. a rewritten
  file) would still surface as `session.appended` rather than
  `session.updated`. Documented, not silently claimed solved.
- Multi-session bundle raws (browser-capture snapshots, ChatGPT exports)
  get correct per-session identity for every touched session, but no
  per-session message-count split (the underlying membership-census
application only returns an aggregate message count across all sessions
  in one raw).
- Ring-gap resync, subscriber cap, and privacy/auth policy (AC #4 and
#5)
  were already in place before this change (bounded replay ring, `Last-
Event-ID`, subscriber controls in `events_http.py`) and are untouched by
  this PR.

## Verification

```
devtools test tests/unit/sources/test_live_watcher.py \
  tests/unit/sources/test_live_metrics.py \
  tests/unit/daemon/test_daemon_events_endpoint.py \
  tests/unit/sources/test_live_batch_support.py
# 193 passed, 1 pre-existing failure unrelated to this change
# (test_live_full_ingest_over_ambiguous_membership_fails_closed_with_diagnostic,
# reproduced identically against master before this branch existed)

uv run mypy polylogue          # Success: no issues found in 1087 source files
uv run ruff check . / format --check .   # all clean
devtools render all --check    # exit 0
devtools verify --quick        # exit_code 0
```

Anti-vacuity: reverted the `session_ids_by_path` assignment in
`append_ingest.py` and confirmed
`test_live_ingest_metrics_carry_real_session_identity` fails
(`assert () == (('claude-code', ...),)`), then restored it — proving the
test exercises the real production wiring, not a self-authorized mock.

Ref polylogue-20d.13

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
#3535)

## Summary

Completes the remaining query-path gap from polylogue-2qx.4 and lands
the first real dependent-column derivation for polylogue-cuxz.8:
`messages.stop_reason` now survives the bulk query-execution path (not
just single-session reads), and `session_profiles.terminal_state` (plus
the two delegation_facts columns that are SQL views over it) derives
from it instead of falling back to `unknown` for a refused or truncated
turn.

## Problem

polylogue-cuxz.8 found the archive can't say how most sessions ended:

```
delegation_facts.result_status          'unknown'   99%  of 11,692
delegation_facts.parent_terminal_state  'unknown'   96%  of 11,692
session_profiles.terminal_state         'unknown'   85%  of 18,871
delegation_facts.child_terminal_state   'unknown'   56%  of 11,692
```

Meanwhile Claude's wire carries `message.stop_reason` on 608,608
assistant messages, including 70 `refusal` and 17 `max_tokens` cases
that are otherwise invisible in any surface. A prior partial fix
(polylogue-2qx.4) persisted `stop_reason` to `messages.stop_reason` and
threaded it into the single-session `repository.get()` read path
(`storage/hydrators.py::message_from_record`), but its own bd note
flagged two explicit gaps: the bulk query-execution path
(`archive/query/archive_execution.py`, behind `SessionFilter.list()` /
the CLI-MCP `find`/`sessions where ...` query grammar) still dropped the
field entirely, and no consumer derived `terminal_state`/`result_status`
from it yet.

## Solution

- `ArchiveMessageRow`/`ArchiveBlockRow`
(`storage/sqlite/archive_tiers/write.py`) gain `stop_reason` /
`tool_result_outcome_unknown_reason` fields, threaded through all four
read sites that construct them: the full-session envelope read, the
paged-window read (`_fetch_message_window`), and the two block/message
SQL `SELECT`s underneath them.
- `archive/query/archive_execution.py::_message_to_domain` — the exact
function the prior fix's bd note named as the missing link — now copies
`stop_reason` onto the domain `Message` and the companion unknown-reason
onto block dicts.
- `MessageSemanticFacts` (`archive/semantic/models.py`) gains a
`stop_reason` field, threaded from the domain `Message` in
`archive/semantic/facts.py`, so
`archive/session/runtime.py::_terminal_state` can see it on the last
meaningful turn.
- `_terminal_state` now consults the last assistant turn's `stop_reason`
before falling back to `unknown`: `REFUSAL` -> `"refused"`, `MAX_TOKENS`
-> `"truncated"`. `TOOL_USE`/`STOP_SEQUENCE` are deliberately **not**
claimed: `TOOL_USE` is already fully covered by the existing
pending-tool/action-outcome structural checks, and `STOP_SEQUENCE` alone
doesn't distinguish a clean stop from truncation the way `MAX_TOKENS`
unambiguously does.
- Because
`delegation_facts.parent_terminal_state`/`child_terminal_state` are SQL
views joining `session_profiles.terminal_state` (not
independently-guessed columns — confirmed by reading
`storage/sqlite/archive_tiers/index.py`'s `delegation_facts` view
definition), this one change improves those two columns for free,
without touching them directly.

Schema classification: no schema change. `messages.stop_reason` and
`blocks.tool_result_outcome_unknown_reason` already exist (schema v46,
landed by polylogue-2qx.4); this PR only threads already-stored values
through previously-lossy read paths and adds a new (Python-only)
derivation branch.

## Deferred (follow-up)

- `delegation_facts.result_status`/`result_is_error` derive from a
different signal (the Task tool's own returned artifact block outcome,
i.e. `blocks.tool_result_is_error` on the delegation's result block —
not the assistant turn's `stop_reason`) and are out of scope for this
PR.
- AC #4 (refusal/max_tokens queryable via the CLI/MCP query grammar,
e.g. `find "stop_reason:refusal"`) is not done: the field now reaches
the domain `Message` object end-to-end, but wiring a new fielded
predicate through the Lark grammar (`archive/query/expression.py`), the
field-descriptor registry (`archive/query/fields.py`), SQL pushdown, and
the runtime post-filter is a comparably-sized follow-up in its own
right.
- AC #5 (re-measure the percentages) needs a live-archive rebuild +
rerun of the original sweep query, not something this PR's unit tests
can produce.

Recommend filing a Beads follow-up for the deferred scope (query-grammar
wiring for `stop_reason`,
`delegation_facts.result_status`/`result_is_error` derivation, and the
AC#5 re-measurement) — not filed from this worktree per its
no-`bd`-writes constraint.

## AC matrix (polylogue-cuxz.8)

1. stop_reason persisted per assistant message — **satisfied** (was
already partially done by polylogue-2qx.4 for the single-session path;
this PR completes it for the bulk query path).
2. terminal_state/result_status derive from persisted evidence or are
deleted — **partially satisfied**: `terminal_state` (and its two
view-derived siblings) now derive from `stop_reason` for the
refusal/max_tokens cases; `result_status`/`result_is_error` untouched
(deferred, different signal).
3. 'unknown' ceases to be dominant — **partially satisfied**: reduces
(does not eliminate) `terminal_state` unknowns; needs a live
re-measurement to quantify.
4. refusal/max_tokens queryable — **deferred**: reaches the domain
model, not yet the query grammar.
5. Re-measure percentages — **deferred**: needs a live archive rebuild,
out of scope for a unit-tested PR.

## Verification

- `devtools verify --quick` (ruff format/check, mypy --strict, `render
all --check`) — exit 0, both pre-commit and pre-push hook runs.
- `devtools test tests/unit/core/test_semantic_facts.py
tests/unit/storage/test_session_insight_profiles.py
tests/unit/storage/test_delegations_view.py
tests/unit/storage/test_stop_reason_queryable.py
tests/unit/storage/test_title_source_queryable.py
tests/unit/cli/test_archive_query.py
tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_models.py
tests/unit/insights/test_delegation_work_evidence.py
tests/unit/storage/test_session_insight_refresh.py` — 419 passed.
- Anti-vacuity: manually reverted the `stop_reason=message.stop_reason`
line in `archive_execution.py::_message_to_domain` and confirmed
`test_session_filter_query_path_exposes_stop_reason` fails (`assert None
== 'max_tokens'`) — the production mutation this test exercises is
exactly that line — then restored it and reconfirmed green.
- Not run: `devtools verify` full testmon suite (testmon isn't seeded in
this worktree; seeding requires a full baseline run out of scope for
this change) and a live-archive rebuild/re-measurement (AC #5).

Ref polylogue-cuxz.8

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
…3554)

## Summary

Fixes two of the four observability defects audited in polylogue-7eo7
(alert-count/verdict contradiction, silent heartbeat staleness) plus the
schema-blocked health-loop gap, and scopes the fourth (dead cursor-lag
SLO check) as a documented follow-up rather than a silent no-op.

## Problem

An audit of the daemon health/status pipeline (polylogue-7eo7) found:

1. `polylogued status` printed `"Health: ok (6 alerts)"` while
`hook_flow [error]` fires in the journal -- because `alert_count`
counted every FAST-tier check run (including OK ones), not actual
problems. A fully healthy daemon always shows exactly `len(fast checks)`
"alerts", making "ok (N alerts)" read as a contradiction regardless of
N.
2. `"Status: running (heartbeat 1369.8s ago)"` on a 15-minute (900s)
interval produced no staleness signal at all -- the only existing
threshold was the 2x-interval (1800s) "vanished" floor, so anything
short of that read as flat "running".
3. `ops.db.cursor_lag_samples` has 0 rows ever: the SLO check reads a
table whose only producer runs inside a MEDIUM-tier check, and
`health_check_tiers` defaults to `"fast"` -- so the producer never
executes under default daemon operation.
4. When the watcher is schema-blocked, `_periodic_health_check()` only
started inside the `if not watcher_blocked:` branch in
`run_daemon_services`, so the daemon ran with zero periodic health
checks/notifications for the entire blocked duration -- exactly when an
operator most needs to see "archive tier layout is not ready".

## Solution

- **#1**: `alert_count` in `daemon_status_payload()`'s `"health"` dict
now counts only non-OK alerts; a new `checks_run` field carries the
previous "every check" total for anyone who still wants it
(`polylogue/daemon/status.py`).
- **#2**: New FAST-tier `heartbeat_staleness` check plus
`DAEMON_HEARTBEAT_STALE_WARN_SECONDS` (1.5x
`DAEMON_HEARTBEAT_INTERVAL_SECONDS`, derived, not hardcoded) fills the
gap between "fresh" and the pre-existing 2x "vanished" floor with a
WARNING-severity `"stale"` lifecycle state
(`polylogue/daemon/lifecycle.py`, `polylogue/daemon/health.py`).
`format_daemon_status_lines` renders a `[STALE]` marker on the
plain-text status line so the signal is visible without reading alerts
separately.
- **#4**: `_periodic_health_check()` moved into the unconditional
`maintenance_tasks` list in `run_daemon_services`
(`polylogue/daemon/cli.py`), so it now starts regardless of
`watcher_blocked`. All FAST-tier checks are read-only (schema_version
via `mode=ro` connections, disk/WAL space stats, hook flow, source
availability, heartbeat staleness), so this does not reintroduce the
archive-write concern the schema-block guard exists for.
- **#3 (deferred, findings recorded)**: `record_cursor_lag_sample` is
only ever called from `_check_cursor_lag_anomaly_layer`, invoked by
`_check_cursor_lag_medium` (MEDIUM tier). `health_check_tiers` defaults
to `"fast"` (`polylogue/config.py`), and `docs/daemon.md` already
documents MEDIUM/EXPENSIVE as deliberate "explicit operator diagnostics"
-- not accidentally disabled. So the check is not dead code in the sense
of being unreachable, but its only producer never runs under default
daemon operation, making the table permanently empty in practice. Two
real options for a follow-up: (a) decouple sample recording from the
MEDIUM gate since it's a cheap read+write, not an expensive scan, or (b)
make the gap explicit in status output (e.g. surface "0 samples,
producer not scheduled" rather than silence). Left to a follow-up bead
since either choice is a behavior decision, not a pure bug fix, and out
of the "prioritize #1/#2" scope this bead itself calls for.

## Verification

```
devtools test tests/unit/daemon/test_health_check_paths.py tests/unit/daemon/test_health_contract.py \
  tests/unit/daemon/test_daemon_lifecycle.py tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_daemon_cli.py
# 241 passed
```

New tests added: `test_health_alert_count_excludes_ok_severity_checks`
and `test_health_alert_count_reflects_a_real_problem_not_ok` (proves a
nonzero-alert scenario no longer reports "ok" and an all-OK scenario
reports `(0 alerts)` instead of `(6 alerts)`),
`test_heartbeat_staleness_warning_between_warn_and_vanished_floors` and
`test_lifecycle_status_reports_stale_between_warn_and_vanished_floors`
(proves the exact observed 1369.8s/900s scenario now produces a WARNING
alert and a `"stale"` lifecycle state),
`test_cli_status_marks_a_stale_but_still_running_heartbeat` (proves the
`[STALE]` marker renders), and
`test_run_daemon_services_schema_block_skips_write_but_starts_health_check`
(renamed/rewritten from the old `..._skips_db_background_work` test,
which previously asserted the opposite -- that health checks must NOT
start when blocked).

Also fixed an unrelated pre-existing drift in the same
pinned-check-inventory test: `capture_coverage` (added in #3541) was
missing from `EXPECTED_MEDIUM_CHECKS`, causing
`test_medium_tier_inventory_pinned` to fail independent of this change.

`devtools verify --quick` passes (ruff format/check, mypy --strict,
render all --check, layering, degrade-loudly, closure-matrix, and the
rest of the static gate set) -- also ran automatically via the pre-push
hook.

A broader `devtools test tests/unit/daemon/` run (2010 tests) shows 2009
passing; the one remaining failure
(`test_no_token_in_log_or_print_calls` in
`test_daemon_http_security.py`, about `polylogue/daemon/api_auth.py`) is
unrelated and pre-existing -- this PR does not touch that file.

Not run: full `devtools verify` (seed-testmon, non-slow suite) --
started once, killed per operator instruction to avoid cross-turn
backgrounding; the focused command above covers every file this PR
touches.

Ref polylogue-7eo7

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 3, 2026
## Summary
Ports cycle detection + quarantine into the sole production writer of
`session_links` rows, so a genuine cycle in the parent chain is now
detected and recorded with evidence instead of silently relying on
recursion-guard short-circuits.

## Problem
`session_links.status`/`.method` are declared vocabulary
(`TopologyEdgeStatus`), but a live-archive measurement (2026-07-28,
index v43, 18,871 sessions) found every one of 9,179 topology edges had
empty `status`/`method`. `method` is already populated as of #3390
(2026-07-30, landed before this bead's structural audit); `status`
stayed NULL on every row because nothing in the live write path ever
detects or records a cycle.

A 2026-08-03 structural audit
(`polylogue-structural-audit-2026-08-03.html`) found the real gap is
worse than an unwritten column: a full cycle-detection + quarantine
engine already exists at `storage/sqlite/queries/session_links.py`
(`_would_create_cycle`, `_quarantine_link`, `status='quarantined'` +
evidence JSON) but has **zero production callers** — it is exercised
only by `tests/unit/insights/test_topology_cycle_rejection.py`, a
test-only surface certifying behavior production code cannot exhibit.
The live writer (`write_parsed_session_to_archive` ->
`_resolve_session_graph` / `_resolve_outbound_session_links`,
`storage/sqlite/archive_tiers/write.py`) resolves every matching parent
edge unconditionally; a real cycle is only ever avoided by
`_refresh_session_projection`'s seen-set short-circuit and
`_composed_db_signatures`' visited-set truncation, which silently pick
an arbitrary root/branch point on a real cycle instead of persisting
evidence of the rejected edge, making root/branch projections
order-dependent and arbitrary.

Given `polylogue-5dfu` already narrowed `TopologyEdgeStatus` to just
`REPAIRED`/`QUARANTINED` (NULL = ordinary resolved/unresolved, not
"missing data"), the correct fix is not "every row must carry a non-NULL
status" — it's "when a cycle actually occurs, the closing edge must be
quarantined with evidence, and this must happen in the live path, not
only in dead test-only code."

## Solution
- Ported `_would_create_cycle` (walks `sessions.parent_session_id`
upward from a proposed parent, bounded by a 1024-step budget, matching
the dead engine's algorithm) and `_quarantine_link`
(`_quarantine_session_link` here) as synchronous `sqlite3`-based helpers
in `storage/sqlite/archive_tiers/write.py`, next to the functions they
protect.
- Wired cycle checking into both live resolution entry points:
- `_resolve_outbound_session_links` (a session resolving its own parent
reference) now evaluates each unresolved candidate individually instead
of one blanket UPDATE, cycle-checking before resolving.
- The inbound-child loop inside `_resolve_session_graph` (a session
resolving pending children that reference it as their parent) does the
same per child.
- A candidate whose resolution would close a loop is quarantined
(`status='quarantined'`, `evidence_json` recording `{reason, cycle_path,
detected_at_ms}`) instead of resolved; its `parent_session_id`
projection stays NULL, so composition/ancestry walks degrade visibly
(the session surfaces as its own root) rather than silently entering the
cycle.
- Both entry points now also filter on `status IS NULL` (in addition to
`resolved_dst_session_id IS NULL`), so a quarantined edge is never
reconsidered on a later write — idempotent by construction.

## Alternatives rejected
- Retargeting `tests/unit/insights/test_topology_cycle_rejection.py`
(621 lines) and the `session_links`-dependent slice of
`tests/unit/storage/test_delegations_view.py` off the dead async engine,
and deleting `storage/sqlite/queries/session_links.py`, is explicitly
**not** done in this PR. That's a large, separable retarget-and-delete
step (both files currently pass, unchanged, because this PR only adds
behavior to the live path and does not touch the dead module) and is
called out as follow-up scope below rather than rushed into this PR.

## Verification
- New tests: `tests/unit/storage/test_topology_cycle_quarantine_live.py`
— reproduces a genuine cross-ingest two-node cycle (A lands root, B
lands as A's child and resolves immediately, A is then re-ingested
claiming B as its parent), a self-referential edge, and a non-cyclic
diamond-DAG control case (B and C both point at D — a legitimate shared
parent, must resolve cleanly, not be mistaken for a cycle), all through
the real `write_parsed_session_to_archive` path.
- Confirmed red without the `write.py` change: 2 of 3 new tests failed
with `assert None == 'quarantined'` (stashed the fix out, reran,
restored it).
- `devtools test
tests/unit/storage/test_topology_cycle_quarantine_live.py
tests/unit/storage/test_lineage_normalization.py
tests/unit/storage/test_session_topology.py
tests/unit/storage/test_topology_edges.py
tests/unit/storage/test_archive_tiers_write.py
tests/unit/storage/test_bulk_fts_prefix_reextract.py` — 142 passed.
- `ruff check` / `ruff format --check` / `mypy --strict` clean on both
touched files.
- `devtools verify --quick` — exit 0.

## Acceptance criteria (polylogue-4ts.10)
1. "Every session_links row written by resolve_session_links_for_session
carries a TopologyEdgeStatus value and a method token" — **misframed by
`polylogue-5dfu`'s prior narrowing**: `method` is satisfied (populated
since #3390); `status` legitimately stays NULL for ordinary
resolved/unresolved edges (that's the narrowed vocabulary's intent) and
is now populated (`quarantined`) exactly when a cycle is detected, which
is the actual gap this bead's own structural-audit note identified.
2. "Existing rows acquire status through ordinary derived-tier rebuild,
not a bespoke backfill script" — satisfied: this is a derived-tier
(`index.db`) behavior change with no migration; a `polylogue ops reset
--index && polylogued run` naturally re-derives status/method for every
row through the now-fixed live path.
3. "A reader can filter edges by status, and composition refuses (or
degrades visibly) on a non-resolved parent rather than silently
composing" — satisfied for composition (a quarantined child's
`parent_session_id` stays NULL, so it surfaces as its own root); a
dedicated reader/insight surface for quarantined-edge counts is deferred
(the dead engine's `count_quarantined_session_links` is one candidate to
port, left for the follow-up retarget work below).
4. "Live re-measure shows zero empty status/method rows and a status
distribution consistent with the 222 unresolved-destination rows" — not
independently re-measured against the live archive in this PR (no access
to `/realm/db/polylogue` from this worktree); the mechanism this AC
depends on is now live, so a follow-up index rebuild + re-measure is the
natural next step, not additional code here.

## Remaining polylogue-4ts.10 scope (follow-up)
- Retarget `tests/unit/insights/test_topology_cycle_rejection.py` and
the `session_links`-dependent parts of
`tests/unit/storage/test_delegations_view.py` at the live path (this
PR's new test file demonstrates the pattern), then delete
`storage/sqlite/queries/session_links.py` (dead code, zero production
callers) once nothing references it.
- A read surface to filter/count quarantined edges (AC #3's "reader can
filter" half).
- Live-archive re-measure after an index rebuild (AC #4).

Ref polylogue-4ts.10
Sinity added a commit that referenced this pull request Aug 19, 2026
…4019)

## Summary

A Codex rollout that grows in place accumulates both `full` snapshots
and
`append` fragments under one logical source. Append fragments are
deliberately
never parsed for identity, and the parser-census receipt written for
them was
`failed` — a status that satisfies neither branch of the census-complete
gate.
Every raw-materialization pass therefore re-selected the fragment,
rewrote the
same receipt, and reported "paused until the persisted parser census
completes"
forever, which stopped raw-replay planning for **every** `full` snapshot
sharing
the authority component. This receipts a byte-governed fragment as the
complete
observation it is, so those components converge.

## Problem

`polylogue-39kcs` (bucket B7 of the dyica classification — the only
genuine gap
in the 111-failure population): codex session
`019f49d8-0185-7c43-8793-db6e57db13e1` is acquired, parsed, and censused
but
absent from `index.db`. It is the only codex logical source with a
parsed raw
missing from the index out of 1448 checked.

The `parse_error` the bead quotes — `RuntimeError: membership replay
cannot
replace an unconvertible byte head` — is **not** the live cause. That
wording no
longer exists in the codebase (PR #3646 replaced it with the typed,
retry-eligible
`MembershipReplayConflictError`); it is a legacy string frozen on one
raw row.
Two measurements ruled the membership-replay hypothesis out entirely:

- Running `classify_historical_full_revision_streams` over the 22 real
full
blobs resolves a **clean, unambiguous byte-prefix chain** — every
revision
`byte_proven`, head `dd0cbb34b9` (90,822,451 bytes, the current on-disk
file).
  Nothing about this cohort is "unconvertible" today.
- Reconstructing the cohort in a scratch archive from the real blobs and
driving
`backfill_historical_revision_evidence` materializes the session with
29,280
messages, even with the live archive's 21 stale
`raw_session_memberships`
rows (`decision IS NULL`, `revision_authority='quarantined'`) staged
first.

The actual blocker is upstream of replay, in the census/planning
handshake:

- `_persist_revision_census` routes every `source_index < 0` raw
straight to the
byte-authority membership receipt (`BYTE_AUTHORITY_CENSUS_DETAIL`)
without
  parsing it — correct, appends are governed by byte revision authority.
- `record_current_parser_source_census` then computed `complete=False`
for that
raw (no parsed sessions, no membership rows, not a typed non-session
artifact)
  and wrote `status='failed'` carrying the byte-authority detail.
- `uncensused_historical_revision_raw_ids` accepts only `complete` +
  `detail LIKE 'parser-observed:%'`, or `failed` at the current
resource-blocked fingerprint. The fragment's receipt matches neither, so
it is
  reported uncensused on every pass, forever.

Reproduced against the real shape: with the component rebuilt from the
live
blobs, six consecutive whale-escalation passes each returned
`success=False`
with `Raw replay planning paused until the persisted parser census
completes for
22 relevant raw(s)` and zero progress. The live source has 767 such
fragments.

This is the "converged or explicitly blocked" invariant failing in the
silent
direction: the pass claims unfinished census work for a raw the census
can never
say anything more about, instead of typing it as the authority debt it
is.

## Solution

`polylogue/storage/sqlite/archive_tiers/revision_governance.py` —
`record_current_parser_source_census` now treats an append-position raw
(`source_index < 0`) whose membership census is the byte-authority
governance
receipt as having an authoritative empty identity set, exactly like the
existing
`typed_non_session` branch it sits beside. The receipt becomes
`complete` / `parser-observed: append fragment governed by byte revision
authority`.

The fragment's `revision_authority` is untouched — it stays
`quarantined`, still
counted as durable authority debt. Only the census receipt changes, from
"we
have not finished looking at this" to "we looked, and byte governance
owns it".
The `source_index < 0` guard keeps the branch off full snapshots even if
one
somehow carried the marker, matching how `storage/repair.py` already
reads the
same detail.

Alternative rejected: special-casing the byte-authority detail inside
`uncensused_historical_revision_raw_ids` instead. That leaves the
durable
receipt lying about its own status and makes every other consumer of
`raw_authority_parser_census` disagree with the gate.

Nothing in revision-authority refusal semantics changed: the byte-chain
classifier, the polylogue-52l2 retired-sibling guard, the polylogue-eqnv
source-path guard, and both `MembershipReplayConflictError` refusals are
untouched.

Two existing tests asserted the old receipt shape and were updated with
the
reason recorded inline — they were encoding the livelock, not protecting
an
invariant.
`test_raw_materialization_reports_uncensused_append_fragments_as_pending_debt`
now asserts the census reaches quiescence while the fragment is still
reported
as `append authority quarantine` debt; its three authority-bucket
transitions
(pending → quarantined → fragment) are unchanged and still pass.

## Verification

Red first.
`test_raw_materialization_converges_component_with_byte_governed_append_fragment`
drives the real `repair_raw_materialization` entry point and failed on
the
parent commit at the census gate:

```
E   AssertionError: assert ('80be922c7b2...62bf34ee473',) == ()
      Left contains one more item: '80be922c7b289e66fa7776dad5efc1f6f4c7dae4e92e0521cff9a62bf34ee473'
```

Green after the fix, and the whole affected surface with it:

```
devtools test tests/unit/storage/test_repair.py tests/unit/storage/test_revision_replay.py
  → 140 passed in 19.02s
devtools test tests/unit/sources/test_revision_backfill.py tests/unit/storage/test_raw_authority_ledger.py tests/unit/storage/test_archive_readiness.py
  → 167 passed in 27.49s
devtools test tests/unit/cli/test_status.py tests/unit/cli/commands/test_status.py tests/unit/core/test_readiness_capability.py tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_parse_prefetch.py tests/unit/daemon/test_raw_materialization_parse_stage_equivalence.py tests/unit/maintenance/test_raw_authority_reset.py tests/unit/maintenance/test_inactive_candidate_durable_barrier.py tests/unit/pipeline/test_archive_ingest_shared_raw.py tests/unit/storage/test_incremental_rebuild_equivalence.py tests/unit/storage/test_durable_migrations.py
  → 400 passed in 41.93s
devtools test tests/unit/scenarios/test_codex_804_live_proof.py -k red_mutation
  → 3 passed
devtools verify --quick
  → exit=0, no "out of sync"
```

That set is every test file in the repo that references
`raw_authority_parser_census` or `parser-observed`.

Against the real 019f49d8 shape, in a scratch archive built from the
live blobs
(21 distinct full revisions + append fragments bound as the live rows
are bound,
live blob store read-only, live archive never written):

- before: six whale passes, `success=False`, `index sessions: (0,)`
- after: `attempt 0: success=True repaired=1`, `index sessions: (1,)`,
  `('codex-session:019f49d8-0185-7c43-8793-db6e57db13e1', 29280)`

At the daemon's ordinary 64 MiB envelope the component is still
explicitly
resource-blocked (`plan_deferred_count 1.0`, "retry through bounded
stream-safe
whale pass"). That is the correct typed blocked state and is what routes
it to
the whale pass — the invariant now holds at both envelopes.

**Gate substitution (deliberate, per lane policy).** The final plain
`devtools verify` was skipped. Policy is to run `devtools why` first and
skip
the full run when it predicts a bootstrap; it did:

```
devtools why
  selection: bootstrap (absent)
  reason: native environment 'polylogue-e962f60d05f5eb...' is absent
```

Re-provisioning this lane's venv changed the testmon environment digest,
so no
graph exists for it and a plain verify becomes a full-corpus bootstrap
(~45 min
measured median) rather than a warm affected-selection run. The focused
`devtools test` selections above plus `devtools verify --quick` are this
PR's
gate in its place. The coordinator records the merge receipt centrally
at head.

**Also not run:**

`test_codex_804_live_proof.py::test_sanitized_codex_804_revision_recovery_proof`
(900s timeout, `storage_scale`). It is provably unaffected —
`tests/infra/whale_fixtures.py` never sets `source_index` or
`revision_kind`, so
every raw it acquires is `source_index=0`, and the new branch is gated
on
`source_index < 0`. Its three fast red-mutation guards do pass.

## Bead disposition matrix

| Bead | Disposition | Evidence |
| --- | --- | --- |
| `polylogue-39kcs` | satisfied | Root cause identified and fixed
(`67ab67c52`); red-first production-route regression test (`9ccfaa893`);
the real 019f49d8 cohort converges to 29,280 messages where it
previously livelocked. |

`Ref polylogue-dyica` — AC#2 ("parser or lifecycle defects have
production-route
regression tests that fail when the original failure is reintroduced")
is
satisfied for this defect by the new test. The rest of dyica (the
backup-gated
live reclassification pass for the 110 benign rows, AC#1/#4) is
untouched and
stays open.

<!-- polylogue-pr-scope:v2
{
  "assigned_beads": [
    "polylogue-39kcs"
  ],
  "dispositions": [
    {
      "bead_id": "polylogue-39kcs",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "test",
"ref":
"tests/unit/storage/test_repair.py::test_raw_materialization_converges_component_with_byte_governed_append_fragment"
        },
        {
          "kind": "commit",
          "ref": "9ccfaa893"
        },
        {
          "kind": "commit",
          "ref": "67ab67c52"
        },
        {
          "kind": "command",
"ref": "devtools test tests/unit/storage/test_repair.py
tests/unit/storage/test_revision_replay.py"
        }
      ],
      "successors": []
    }
  ],
  "mutated_beads": [],
"scope_digest":
"778a5991c2362d6487d63c578af293dbd1722d2bb82e5fa4fcb5ce425cedac4d",
  "scope_kind": "bead",
  "version": 2
}
-->
@Sinity

Sinity commented Sep 30, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

Sinity added a commit that referenced this pull request Nov 8, 2026
…e examples (#6729)

Deletes apparatus found by the 11-08 audit
(`analysis/audits-20261108/apparatus.md` A1–A3): the planned-pages
reference index for a docs generator that was never built, a committed
bundle schema whose only reader compared it with the code, unreferenced
schema snapshots and examples, an environment override nothing set,
seven ignored measurement tests and three probe programs outside `xtask
bench`, and byte-identical Morrow copies (the parents set now reuses
sessions #1–#4). The render README becomes the crate's module docs.

Not included: removing the crate-dependency allow-list and the
hand-written formatting list in xtask; both wait for #6724, which
rewrites the same file.

Verification: agentctl `fmt` passed; `compile --tests --examples` for
model, sources, store, render, engine, testkit and polylogue passed with
no warnings. Nothing deleted had a non-test caller.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01AcQETkbTfFMr1hgNJ8A3em

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sinity added a commit that referenced this pull request Nov 12, 2026
…der (#6905)

Root and depth queries currently walk only spawn links and silently stop
at depth 1,000. This change derives them from explicit spawn, fork,
continuation and resume ancestry through one indexed store-owned
traversal, shared by the stored product, current reader and query
fields.

Missing or stub parents return unknown root/depth with root_pending;
conflicting parent identities and cycles return typed issues without
choosing a parent or cycle root. Different anchors to one parent remain
recorded alternatives and have the same structural depth. References and
physical copied-prefix facts do not create ancestry. Transactional marks
invalidate only affected descendants, and reads compute the current
value through the same traversal while derivation is behind.

The product declaration, generated reference and owning session/measure
docs are updated together. The stale Morrow example now keeps copy-only
session #4 separate from provider ancestry. Default logical listings,
family/successor consumers, shared message composition and assertion
target-state behavior remain subsequent parts of the existing lineage
task.

Validation: focused187/polylogue-focused-140c2ec8 passed78/78 lineage,
derivation and existing unknown-value controls on
exact9a54ce9ceb469fb276e56a1a9d18a3a65cb4edfb (build76.5s, tests4.0s).
Strict metadata180 passed both configurations/all targets in52s before
the final reference-predicate correction; the current-head focused
compile passed, and required hosted verification follows. This changes
the derived index schema. Runtime adoption is separate from this source
change.
Sinity added a commit that referenced this pull request Nov 18, 2026
Session listings currently test the root session's directory and dates
and omit work done by a related session elsewhere. Match visible
physical sessions first, then return each current logical root once.
`physical:true`, structure fields and exact references keep the physical
view. The fold uses the existing lineage owner, including unresolved and
stale-root behavior.

Follow spawn, fork, continuation and resume links consistently for
measurement, search ranking and snippets; reference links remain
separate. Measurement text prints in its logical-day zone while billing
windows remain UTC. Failed-command data retains its array shape and gets
its text zone from the existing resolved answer context.

The default count changes follow [the logical-session
design](docs/sessions.md#logical-sessions). The row-wise test fixture
records spawn #2→#3, resume #2→#4 and fork #5→#6, yielding five logical
roots from eight physical sessions. The separately imported example
golden retains its actual resolved-edge population (six roots).
Generated sessions have no link evidence and remain independent roots
even when marked subagent. Physical Boolean/complement tests and the
abstract shared-language adapter now declare their physical outer
population explicitly; a new control proves that distinct physical
matches can place one logical root in both a condition and its physical
complement.

Keep the existing indexed physical-selection path for bound predicates,
including cwd, similarity and the ranked FTS prefix. Bare default pages
only compare each row to its current root, so they stop at the keyset
boundary without scanning all matches or descendants. Both paths apply
the same outer root visibility rules. No stored state or extra planner
is added. Authenticated pre-change query cursors are refused through the
existing compiler-version guard.

Individual `why` conditions count physical rows; the logical default
reports its folded count through the existing counter. Hidden sessions
remain included in measurement populations.

Validation: pinned formatting and commit hooks pass. Native Store 841
passed all six existing controls: flat default page work (100→2,000
sessions), bounded ranked prefix, cwd index access without session scan,
similarity work tied to the selected rows, page stability across a newly
linked child, and one rank score per identity across differing sorts.
The coherent required exact-head check remains pending; live
query/day-zone and synthetic-session actions remain release-stage work.
No native deployment acceptance is claimed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli CLI faux-pull-request PR created as part of a history rewrite process type:refactor Code restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants