Skip to content

feat: schema-stamp JSON outputs, add labeled archive roots, and extend status monitoring - #30

Closed
Sinity wants to merge 12 commits into
masterfrom
feature/cli/schema-stamps-labeled-roots
Closed

Sinity wants to merge 12 commits into
masterfrom
feature/cli/schema-stamps-labeled-roots

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Every JSON-emitting CLI path now embeds schemaVersion and polylogueVersion via stamp_payload(), making outputs self-describing for downstream consumers and deployment pipelines. Alongside that, the config system gains labeled archive roots for multi-environment setups, and the status command picks up --top and --inbox flags for richer monitoring.

Motivation

JSON outputs from the CLI are consumed by cron jobs, systemd timers, dashboards, and scripts — but nothing in the payload identifies which schema version or polylogue release produced it. When the output format changes, consumers break silently. Stamping every payload with version metadata lets consumers detect format drift and fail explicitly.

The single-root config model also doesn't fit setups where someone archives work and personal conversations separately. Labeled roots (work: ~/archive/work, personal: ~/archive/personal) let each label expand into a full output directory tree without duplicating config files.

The status command, designed for monitoring, was missing two common queries: "which runs consumed the most resources?" and "how many inbox items are pending?" Rather than requiring separate commands, --top N and --inbox fold those answers into the existing status output.

Schema stamping

stamp_payload() is imported from polylogue.schema (introduced in the previous config schema work) and wraps the outermost dict before serialization. For full payloads it adds both schemaVersion and polylogueVersion; for NDJSON streams it uses include_versions=False to keep per-line overhead small.

Touched paths: _record_failure(), config show --json, compare --json, attachment stats/extract, doctor, index check, maintain backup, browse runs.

Before:

payload = {"count": len(rows), "bytes": total_bytes, ...}
print(json.dumps(payload, indent=2))

After:

payload = stamp_payload({"count": len(rows), "bytes": total_bytes, ...})
print(json.dumps(payload, indent=2))

The stamp is always the outermost wrapper so consumers can check payload["schemaVersion"] before parsing the rest.

Labeled archive roots

persist_config() accepts an optional roots: Dict[str, Path] parameter. Each label maps to a base path that expands into the standard six output directories:

roots = {"work": Path("~/archive/work")}
# produces config.json with:
# "paths": { "roots": { "work": {
#   "render": "~/archive/work/render",
#   "sync_drive": "~/archive/work/gemini", ...
# }}}

The init wizard prompts interactively ("Add a labeled archive root?") and config show surfaces roots in both JSON and Rich text output. settings_cli passes roots through when re-persisting so existing labels survive config updates.

Status monitoring extensions

--top N: Sorts all filtered runs by (attachments, tokens) descending, takes the top N, and renders a Rich table in interactive mode. JSON output includes a topRuns / top_runs array.

--inbox: Calls _discover_export_targets() per provider to count pending items, renders an "Inbox Coverage" table, and includes the counts in JSON summaries.

--json-verbose: Added to browse runs, maintain doctor, and maintain index check. For runs, it wraps the output in a stamped envelope with a count field; the non-verbose path remains backward-compatible (bare array).

HTML anchor improvements

Headings and msg-N message anchors in rendered HTML get a 🔗 copy-link button. Clicking copies the full URL with fragment to the clipboard and updates window.location.hash. The search command (run_inspect_search) detects .html results and opens them in the browser with the correct fragment instead of falling through to the editor.

Smaller changes

  • ExamplesHelpFormatter replaces the default argparse formatter, automatically appending examples from COMMAND_EXAMPLES to --help output
  • Watch mode tracks cumulative skipped events during debounce and prints the total on KeyboardInterrupt
  • Inbox CLI tracks totals.pending and totals.quarantined counters in the JSON output
  • README updated to document --top and --inbox flags

Test coverage

  • test_config_roots.py: round-trips labeled roots through persist_config() and verifies the JSON structure
  • test_failure_logging.py: triggers _record_failure() and asserts schemaVersion/polylogueVersion appear in the JSONL record
  • test_inbox_cli.py: updated to verify totals.pending >= 1 in inbox JSON output

Sinity and others added 12 commits December 10, 2025 02:05
Document the new browse inbox command with quarantine support alongside existing browse/sync workflows.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
Switch help formatting to append per-command examples automatically so --help and --examples stay in sync.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
Use the shared schema/casing helper for attachment stats/extract JSON and JSONL outputs to keep version metadata consistent.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
Failure records now use the shared schema helper to include camel/snake keys and version stamps; added a test to ensure failures.jsonl carries schemaVersion/polylogueVersion.
persist_config now accepts optional labeled roots and the init wizard can capture an extra labeled root; settings CLI preserves configured roots. Added coverage to ensure roots are written to config.json.
Runs browse now supports --json-verbose and stamps JSON with schema metadata for consistent machine parsing.
Config show JSON/plain now includes labeled archive roots alongside defaults, using schema stamping for JSON output.
Add json-verbose toggles/stamping to maintain index/doctor, restore, compare, and run outputs while keeping legacy runs JSON shape. Init wizard now supports adding multiple labeled roots. HTML exports gain heading copy-link anchors and search --open can target HTML fragments. Full test suite passes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
Track total skipped file events during watch debounce and print a summary on exit to aid troubleshooting.
Inbox browsing now reports pending/quarantined totals in JSON and plain summaries.
status now accepts --top to show highest-attachment/token runs in JSON summaries and rich tables.
Status can now include inbox pending counts via --inbox, JSON summary includes inbox stats, and HTML exports gain copy-link buttons for per-message anchors. Added --top to status previously to rank runs.
Copilot AI review requested due to automatic review settings April 7, 2026 12:12
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The PR introduces JSON schema stamping across multiple CLI commands, adds labeled archive roots configuration support to init/config/settings, extends status and browse/maintain subcommands with new flags (--top, --inbox, --json-verbose), enhances HTML output with anchor buttons, and improves CLI help formatting with examples.

Changes

Cohort / File(s) Summary
JSON Output Stamping Infrastructure
polylogue/config.py, polylogue/cli/app.py
Added stamp_payload() function and ExamplesHelpFormatter class; integrated stamping into failure logging and CLI output pipelines.
JSON Stamping Applied to Commands
polylogue/cli/attachments.py, polylogue/cli/doctor.py, polylogue/cli/index_cli.py, polylogue/cli/maintain.py, polylogue/cli/runs.py
Wrapped JSON output payloads with stamp_payload() across attachment stats/extract, doctor config hints, index checks, restore metadata, and runs listings; added --json-verbose support to runs for structured payload with count.
Labeled Archive Roots Configuration
polylogue/cli/init.py, polylogue/cli/settings_cli.py, polylogue/config.py
Added interactive labeled roots collection in init wizard; extended persist_config() to accept and serialize labeled root mappings with derived subpaths (render, sync_drive, sync_codex, etc.); updated settings to pass roots from config defaults.
Status Command Enhancements
polylogue/cli/status.py, polylogue/cli/app.py
Added --top and --inbox flags to status subcommand; implemented top runs computation and inbox coverage discovery via dynamic import of export target discovery; added tabular display for top runs and per-provider inbox pending counts in rich output.
CLI Flag Extensions
polylogue/cli/app.py
Added --json-verbose flag to browse runs, browse stats, maintain doctor, and maintain index check subcommands.
Inbox Totals Tracking
polylogue/cli/inbox.py
Introduced pending and quarantined item counters; included totals object in JSON output; updated UI summary display for pending items.
HTML & UI Improvements
polylogue/html.py, polylogue/cli/watch.py, README.md
Added .anchor-btn CSS class and client-side heading/message anchor buttons with clipboard copy functionality; added cumulative skipped event tracking to watch command summary; documented new polylogue browse inbox subcommand.
Test Coverage
tests/test_config_roots.py, tests/test_failure_logging.py, tests/test_inbox_cli.py
Added test for labeled roots persistence, schema stamping validation, and inbox totals in CLI output.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Poem

🐰 A rabbit hops through JSON logs,
Stamping schemas with a grin—
Labeled roots spring from the ground,
Top runs gleam, inbox counts spin,
Anchors click, and breadcrumbs grow! 🔗

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% 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 PR title accurately summarizes the three main changes: schema-stamping JSON outputs, adding labeled archive roots, and extending status monitoring with new flags.
Description check ✅ Passed The PR description is comprehensive and well-structured. It covers all major template sections: summary, problem/motivation, solution with examples, key technical decisions, and test coverage.

✏️ 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/cli/schema-stamps-labeled-roots

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

@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: 9baf2f0d7e

ℹ️ 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 polylogue/config.py Resolved
Comment thread polylogue/cli/app.py Resolved
Comment thread polylogue/cli/status.py Resolved
Sinity added a commit that referenced this pull request Apr 7, 2026
…d status monitoring (#30)

Wire stamp_payload() from polylogue.schema into every CLI command that
emits JSON, so each payload carries schemaVersion and polylogueVersion
fields. Add labeled archive roots to support multi-environment
configurations, and extend the status command with ranked-run and inbox
monitoring.

Schema stamping (polylogue/cli/app.py, attachments.py, doctor.py,
index_cli.py, maintain.py, runs.py):
- _record_failure() wraps failure JSONL records through stamp_payload()
- config show --json, compare --json, attachment stats/extract --json,
  doctor --json, index check --json, maintain backup --json, and
  browse runs --json-verbose all embed version metadata
- NDJSON streams (--json-lines) stamp individual rows with
  include_versions=False to keep per-line overhead minimal

Labeled archive roots (polylogue/config.py, cli/init.py,
cli/settings_cli.py, cli/app.py):
- persist_config() accepts optional roots dict mapping labels to base
  paths; each label expands into a full output directory tree
  (render, sync_drive, sync_codex, etc.)
- init wizard prompts for labeled roots interactively
- config show surfaces roots in both JSON and Rich text output
- settings_cli passes roots through when re-persisting config

Status and monitoring (polylogue/cli/status.py, cli/app.py):
- --top N ranks historical runs by attachments/tokens and renders a
  Rich table in interactive mode
- --inbox discovers pending export targets per provider and renders
  an inbox coverage table
- --json-verbose flag added to browse runs, doctor, and index check
- ExamplesHelpFormatter appends COMMAND_EXAMPLES to --help output

HTML navigation (polylogue/html.py, cli/app.py):
- Heading and message anchors gain copy-link buttons with clipboard
  integration and hash navigation
- run_inspect_search() opens HTML results in browser with fragment
  anchors instead of falling through to editor

Watch mode (polylogue/cli/watch.py):
- Track cumulative skipped events during debounce and report the
  total on exit

Tests:
- test_config_roots.py validates labeled roots round-trip through
  persist_config()
- test_failure_logging.py verifies stamp_payload() presence in
  failure JSONL
- test_inbox_cli.py asserts totals.pending in inbox JSON output

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 makes Polylogue’s CLI JSON outputs self-describing by stamping payloads with schema/app versions, adds support for labeled archive roots in configuration, and extends monitoring/status capabilities (plus some UI/help improvements).

Changes:

  • Stamp machine-readable CLI outputs with schemaVersion and polylogueVersion via stamp_payload() (including NDJSON paths with reduced per-line overhead).
  • Add “labeled archive roots” to config persistence and surface them in config show, plus pass-through in settings/init flows.
  • Extend monitoring UX: browse status gains --top and --inbox; rendered HTML gains copy-link anchor buttons; watch mode reports cumulative debounced events.

Reviewed changes

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

Show a summary per file
File Description
tests/test_inbox_cli.py Asserts new inbox JSON totals.pending field is present/updated.
tests/test_failure_logging.py New test ensuring failure JSONL records include schema/app version stamps.
tests/test_config_roots.py New test verifying labeled roots are written into config JSON structure.
README.md Documents inbox browsing in the “Browse archives” bullet.
polylogue/html.py Adds copy-link buttons for headings and msg-N anchors in rendered HTML.
polylogue/config.py Extends persist_config() to optionally write labeled roots into config payload.
polylogue/cli/watch.py Tracks and prints cumulative skipped events during debounce.
polylogue/cli/status.py Adds --top sorting and --inbox coverage rendering, plus JSON fields for top runs.
polylogue/cli/settings_cli.py Attempts to preserve labeled roots when re-persisting config during settings updates.
polylogue/cli/runs.py Adds --json-verbose mode emitting a stamped envelope with run count.
polylogue/cli/maintain.py Stamps JSON output for restore/backup-like flows.
polylogue/cli/init.py Prompts for labeled roots during interactive init and persists them to config.
polylogue/cli/index_cli.py Stamps JSON output for index check results.
polylogue/cli/inbox.py Adds totals.pending / totals.quarantined counters to inbox JSON and summary output.
polylogue/cli/doctor.py Stamps JSON output for doctor results.
polylogue/cli/attachments.py Stamps JSON outputs for attachment stats/extract (including NDJSON rows).
polylogue/cli/app.py Introduces examples help formatter, stamps multiple JSON outputs, adds status flags + browse runs --json-verbose, and opens HTML search hits in browser with fragment.

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

Comment thread polylogue/config.py
Comment on lines +142 to +146
if roots:
mapped: Dict[str, Dict[str, str]] = {}
for label, base in roots.items():
root_path = Path(base).expanduser()
mapped[label] = {

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.

persist_config() writes labeled roots under payload["paths"]["roots"], but the current config validator (polylogue/core/config_validation.py) forbids extra keys under paths (extra="forbid"). This means any config written with roots= will fail validation on the next run and prevent Polylogue from starting. Update the config schema/validation + loader to accept paths.roots (and actually load it), or store roots in a section that is already permitted by the schema.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli/init.py
Comment on lines +146 to +154
labeled_roots: dict[str, Path] = {}
if not ui.plain:
while ui.confirm("Add a labeled archive root (e.g., work/personal)?", default=False):
label = ui.input(" Label (e.g., work)", default=f"root{len(labeled_roots)+1}") or f"root{len(labeled_roots)+1}"
root_input = ui.input(" Root path", default=str(output_dir))
if root_input:
labeled_roots[label] = Path(root_input).expanduser()
if not ui.confirm("Add another root?", default=False):
break

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.

The init wizard now passes roots=labeled_roots into persist_config(), which currently serializes them as paths.roots. With the current config validation (extra keys forbidden under paths), this can produce a config.json that cannot be loaded on subsequent runs. Either update the config schema/loader first or gate this feature until paths.roots is supported end-to-end.

Suggested change
labeled_roots: dict[str, Path] = {}
if not ui.plain:
while ui.confirm("Add a labeled archive root (e.g., work/personal)?", default=False):
label = ui.input(" Label (e.g., work)", default=f"root{len(labeled_roots)+1}") or f"root{len(labeled_roots)+1}"
root_input = ui.input(" Root path", default=str(output_dir))
if root_input:
labeled_roots[label] = Path(root_input).expanduser()
if not ui.confirm("Add another root?", default=False):
break
#
# Temporarily gated: persist_config() can serialize this as `paths.roots`,
# but current config validation does not yet accept that key. Keep this as
# None so the init wizard does not write a config that cannot be loaded on
# a subsequent run.
labeled_roots: Optional[dict[str, Path]] = None

Copilot uses AI. Check for mistakes.
Comment on lines 84 to 93
persist_config(
input_root=effective_input,
output_root=effective_output,
collapse_threshold=settings.collapse_threshold,
html_previews=settings.html_previews,
html_theme=settings.html_theme,
index=config_obj.index,
path=CONFIG_PATH,
roots=config_obj.defaults.roots if getattr(config_obj.defaults, "roots", None) else 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.

persist_config(..., roots=...) expects a Dict[str, Path] of base root directories, but this call passes config_obj.defaults.roots which is Dict[str, OutputDirs]. At runtime Path(base) in persist_config() will fail (or generate incorrect /render/render paths). Persist roots using the same shape expected by persist_config() (or change persist_config() to accept already-expanded OutputDirs).

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli/app.py
"claude_code": str(defaults.output_dirs.sync_claude_code),
"chatgpt": str(defaults.output_dirs.import_chatgpt),
"claude": str(defaults.output_dirs.import_claude),
"roots": {label: vars(paths) for label, paths in roots_map.items()},

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 config show --json, "roots": {label: vars(paths) ...} will include Path objects (from OutputDirs), but json.dumps(payload) is called without default=str, causing a TypeError: Object of type PosixPath is not JSON serializable when any labeled roots exist. Convert the per-root paths to strings (mirroring the other outputs fields) before dumping.

Suggested change
"roots": {label: vars(paths) for label, paths in roots_map.items()},
"roots": {
label: {name: str(value) for name, value in vars(paths).items()}
for label, paths in roots_map.items()
},

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli/app.py
Comment on lines +110 to +128
class ExamplesHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
"""Formatter that appends command examples from COMMAND_EXAMPLES."""

def format_help(self) -> str: # pragma: no cover - formatting path
help_text = super().format_help()
# Only append when the parser name exists in COMMAND_EXAMPLES
prog = getattr(self, "_prog", None) or getattr(getattr(self, "_parser", None), "prog", "")
# Map parser prog tokens like "polylogue search" to the subcommand key
if prog:
tokens = prog.split()
if len(tokens) >= 2:
cmd = tokens[1]
examples = COMMAND_EXAMPLES.get(cmd)
if examples:
lines = ["\nExamples:"]
for desc, cmdline in examples:
lines.append(f" # {desc}")
lines.append(f" $ {cmdline}")
help_text = help_text.rstrip() + "\n" + "\n".join(lines) + "\n"

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.

ExamplesHelpFormatter.format_help() appends examples based on prog.split()[1], which is incorrect for nested subcommands (e.g., polylogue browse status will pick browse, not status). It can also duplicate examples because _add_command_parser() already injects an examples epilog. Consider deriving the full subcommand path (or using the parser name) and only appending examples when an examples epilog wasn't already set.

Suggested change
class ExamplesHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
"""Formatter that appends command examples from COMMAND_EXAMPLES."""
def format_help(self) -> str: # pragma: no cover - formatting path
help_text = super().format_help()
# Only append when the parser name exists in COMMAND_EXAMPLES
prog = getattr(self, "_prog", None) or getattr(getattr(self, "_parser", None), "prog", "")
# Map parser prog tokens like "polylogue search" to the subcommand key
if prog:
tokens = prog.split()
if len(tokens) >= 2:
cmd = tokens[1]
examples = COMMAND_EXAMPLES.get(cmd)
if examples:
lines = ["\nExamples:"]
for desc, cmdline in examples:
lines.append(f" # {desc}")
lines.append(f" $ {cmdline}")
help_text = help_text.rstrip() + "\n" + "\n".join(lines) + "\n"
def _command_examples_key_from_prog(prog: str) -> Optional[str]:
try:
tokens = shlex.split(prog)
except ValueError:
tokens = prog.split()
if len(tokens) < 2:
return None
command_tokens = tokens[1:]
candidates: List[str] = []
full_path = " ".join(command_tokens).strip()
if full_path:
candidates.append(full_path)
leaf = command_tokens[-1].strip()
if leaf and leaf not in candidates:
candidates.append(leaf)
root = command_tokens[0].strip()
if root and root not in candidates:
candidates.append(root)
for candidate in candidates:
if candidate in COMMAND_EXAMPLES:
return candidate
return None
class ExamplesHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
"""Formatter that appends command examples from COMMAND_EXAMPLES."""
def format_help(self) -> str: # pragma: no cover - formatting path
help_text = super().format_help()
parser = getattr(self, "_parser", None)
if getattr(parser, "epilog", None):
return help_text
prog = getattr(self, "_prog", None) or getattr(parser, "prog", "")
cmd = _command_examples_key_from_prog(prog) if prog else None
if cmd:
examples = COMMAND_EXAMPLES.get(cmd)
if examples:
lines = ["\nExamples:"]
for desc, cmdline in examples:
lines.append(f" # {desc}")
lines.append(f" $ {cmdline}")
help_text = help_text.rstrip() + "\n" + "\n".join(lines) + "\n"

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli/status.py
Comment on lines 132 to +135
"generatedAt": datetime.now(timezone.utc).isoformat(),
"runSummary": run_summary,
"providerSummary": provider_summary,
"topRuns": top_runs,

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.

The --summary payload uses camelCase keys (generatedAt, runSummary, providerSummary, topRuns). stamp_payload() only dualizes snake_case → camelCase, so the summary output will not include snake_case variants (e.g., top_runs). To keep the “both casings” contract consistent, build the summary dict with snake_case keys and let stamp_payload() add camelCase.

Suggested change
"generatedAt": datetime.now(timezone.utc).isoformat(),
"runSummary": run_summary,
"providerSummary": provider_summary,
"topRuns": top_runs,
"generated_at": datetime.now(timezone.utc).isoformat(),
"run_summary": run_summary,
"provider_summary": provider_summary,
"top_runs": top_runs,

Copilot uses AI. Check for mistakes.
Comment on lines +21 to +24
)

data = json.loads(config_path.read_text(encoding="utf-8"))
assert data["paths"]["roots"]["work"]["render"].endswith("/work-archive/render")

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.

This test only asserts the JSON shape written by persist_config(), but it doesn't catch the current end-to-end break where configs containing paths.roots fail validation/loading. Add an assertion that the produced config can be loaded (or that config validation accepts paths.roots) to prevent regressions.

Copilot uses AI. Check for mistakes.
Comment on lines +6 to +8
from polylogue.paths import STATE_HOME
from polylogue.ui import create_ui
from polylogue.commands import CommandEnv

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.

Unused imports: STATE_HOME, create_ui, and CommandEnv aren't referenced in this test. Removing them will keep the test module lint-clean and avoid implying additional setup requirements.

Suggested change
from polylogue.paths import STATE_HOME
from polylogue.ui import create_ui
from polylogue.commands import CommandEnv

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli/app.py
from ..config import CONFIG, CONFIG_PATH, DEFAULT_CREDENTIALS, DEFAULT_TOKEN
from ..local_sync import LOCAL_SYNC_PROVIDER_NAMES, WATCHABLE_LOCAL_PROVIDER_NAMES
from ..paths import STATE_HOME
from ..schema import stamp_payload

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.

stamp_payload is imported twice in this module (from ..schema import stamp_payload near the top and again around line 63). Drop the duplicate import to avoid confusion and keep imports tidy.

Suggested change
from ..schema import stamp_payload

Copilot uses AI. Check for mistakes.
Comment thread polylogue/html.py
anchor.href = `#${h.id}`;
anchor.textContent = '🔗';
anchor.className = 'anchor-btn';
anchor.title = 'Copy link';

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.

The copy-link buttons are rendered as <a> elements with only the '🔗' glyph as text. For accessibility, add an aria-label (and/or visually-hidden text) so screen readers can announce the purpose of the control instead of just reading an emoji/link.

Suggested change
anchor.title = 'Copy link';
anchor.title = 'Copy link';
anchor.setAttribute('aria-label', 'Copy link to this section');

Copilot uses AI. Check for mistakes.
Repository owner deleted a comment from coderabbitai Bot Apr 7, 2026
Repository owner deleted a comment from coderabbitai Bot 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: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
polylogue/html.py (1)

211-231: ⚠️ Potential issue | 🟡 Minor

TOC entries will include the anchor emoji.

The TOC link text is set from h.textContent (line 228) after the anchor button is appended to the heading (line 224). This causes TOC entries to display the "🔗" emoji suffix.

🐛 Proposed fix: capture heading text before appending anchor
       headings.forEach(h => {
         if (!h.id) return;
+        const headingText = h.textContent;
         const anchor = document.createElement('a');
         anchor.href = `#${h.id}`;
         anchor.textContent = '🔗';
         anchor.className = 'anchor-btn';
         anchor.title = 'Copy link';
         anchor.addEventListener('click', evt => {
           evt.preventDefault();
           const url = `${window.location.origin}${window.location.pathname}#${h.id}`;
           navigator.clipboard?.writeText(url).catch(() => {});
           window.location.hash = h.id;
         });
         h.appendChild(anchor);
         const li = document.createElement('li');
         const a = document.createElement('a');
         a.href = `#${h.id}`;
-        a.textContent = h.textContent;
+        a.textContent = headingText;
         li.appendChild(a);
         tocEl.appendChild(li);
       });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/html.py` around lines 211 - 231, The TOC entries include the anchor
emoji because h.textContent is read after appending the anchor; modify the
headings.forEach block to capture the heading text into a local variable (e.g.,
const headingText = h.textContent || '') before calling h.appendChild(anchor),
then use that variable when setting a.textContent for the TOC link (instead of
h.textContent); keep the rest of the logic (anchor creation, clipboard, hash
behavior) unchanged.
polylogue/cli/settings_cli.py (1)

84-93: ⚠️ Potential issue | 🔴 Critical

Fix type mismatch: dict[str, OutputDirs] passed but dict[str, Path] expected.

The code passes config_obj.defaults.roots (type: dict[str, OutputDirs]) to persist_config, which expects roots: Optional[Dict[str, Path]]. Inside persist_config, line 145 attempts Path(base).expanduser() on each value. Since OutputDirs is a dataclass (not a Path or PathLike object), this will raise TypeError at runtime.

Either:

  1. Pass only the base paths: extract the root path from each OutputDirs object before passing, or
  2. Update persist_config to handle OutputDirs objects directly
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/settings_cli.py` around lines 84 - 93, persist_config is being
passed config_obj.defaults.roots which is dict[str, OutputDirs] but it expects
dict[str, Path], causing Path(base).expanduser() to fail; fix by converting the
dict before the call: map each value in config_obj.defaults.roots to its
underlying path string/Path (extract the OutputDirs path field, e.g.,
OutputDirs.base or OutputDirs.root) so you pass dict[str, Path] to
persist_config; alternatively, if you prefer to support OutputDirs directly,
update persist_config to accept OutputDirs values and use the appropriate
attribute when constructing Path, but the quickest fix is to transform
config_obj.defaults.roots into a dict of Paths and pass that to persist_config.
polylogue/cli/status.py (1)

130-157: ⚠️ Potential issue | 🟠 Major

--inbox data is computed but not exported in JSON/summary payloads.

inbox_summary is available, but only used for Rich table output. --json / --summary currently omit inbox counts, so machine-readable consumers miss this feature.

🛠️ Proposed fix
         if summary_requested:
             summary_payload = stamp_payload(
                 {
                     "generatedAt": datetime.now(timezone.utc).isoformat(),
                     "runSummary": run_summary,
                     "providerSummary": provider_summary,
                     "topRuns": top_runs,
+                    "inbox": inbox_summary,
                 }
             )
@@
         if json_mode:
             payload = stamp_payload(
                 {
@@
                     "generated_at": datetime.now(timezone.utc).isoformat(),
                     "top_runs": top_runs,
+                    "inbox": inbox_summary,
                 }
             )

Also applies to: 261-268

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

In `@polylogue/cli/status.py` around lines 130 - 157, The JSON and summary
payloads omit the computed inbox counts: include the existing inbox_summary in
both the summary_payload (used when summary_requested / summary_only) and the
JSON payload (when json_mode) so machine consumers receive inbox data; locate
where summary_payload is built (stamp_payload call that contains
generatedAt/runSummary/providerSummary/topRuns) and add an "inbox_summary":
inbox_summary entry, and likewise add "inbox_summary": inbox_summary to the
payload constructed in the json_mode branch (the dict containing
credentials_present, token_present, run_summary, provider_summary, generated_at,
top_runs) so both outputs expose the inbox counts.
polylogue/cli/app.py (1)

925-928: ⚠️ Potential issue | 🟠 Major

Keep --json-lines hits unwrapped.

The PR contract says NDJSON should omit per-line schema/version fields. Wrapping every search hit with stamp_payload() changes the streaming row shape and will break consumers expecting one hit object per line.

Suggested fix
         if json_lines:
             for row in rows:
-                payload = stamp_payload({k: row.get(k) for k in export_fields} if export_fields else row)
+                payload = {k: row.get(k) for k in export_fields} if export_fields else row
                 print(json.dumps(payload, separators=(",", ":"), ensure_ascii=False))
             return
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/app.py` around lines 925 - 928, When the --json-lines path is
taken (the json_lines branch), do not wrap each hit with stamp_payload because
NDJSON must emit raw hit objects per line; instead for json_lines iterate rows
and print either the raw row or a filtered dict of export_fields (e.g., {k:
row.get(k) for k in export_fields} if export_fields else row) serialized with
json.dumps(..., separators=(",", ":"), ensure_ascii=False). Keep stamp_payload
usage only in the non-json_lines branch so consumers of the json-lines output
receive one hit object per line.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/cli/app.py`:
- Around line 113-129: The format_help method appends Examples unconditionally
and picks the wrong subcommand token; update format_help to (1) determine the
intended subcommand by using the last token (e.g., tokens[-1]) from prog rather
than tokens[1], and (2) skip appending the examples when the help_text already
contains an "Examples:" section (check for the substring) to avoid duplication;
locate and update the format_help function and the use of COMMAND_EXAMPLES,
prog, and _parser accordingly.
- Around line 1030-1039: The HTML-open branch currently assumes success: remove
the unused variable fragment, guard against Path.as_uri() raising ValueError for
relative paths, and only treat opening as successful when webbrowser.open(...)
returns True; specifically, in the code around target_obj, is_html and
anchor_label, wrap the as_uri() call in a try/except to fall back to the editor
if as_uri() fails, call webbrowser.open(target_obj.as_uri() +
f"#{anchor_label}") and check its boolean return value before calling
ui.console.print("Opened...") or returning; if webbrowser.open returns False,
fall through to the existing editor fallback logic.
- Around line 1388-1414: The crash is caused by leaving Path objects in
outputs.roots (built from roots_map) which json.dumps can't serialize; when
constructing payload (around stamp_payload and the "outputs" -> "roots" entry)
convert any Path instances in each paths object to strings instead of using
vars(paths) directly — e.g., replace the {label: vars(paths) for label, paths in
roots_map.items()} with a comprehension that maps each attribute value to str(v)
if isinstance(v, Path) (import Path from pathlib if needed) so outputs.roots
contains only JSON-serializable primitives.

In `@polylogue/config.py`:
- Line 110: The annotation for the roots parameter (roots: Optional[Dict[str,
Path]] ) and other annotations that currently reference typing.Dict should be
changed to use built-in generics (e.g., Optional[dict[str, Path]]); update every
occurrence of Dict[...] to dict[...] (including the other Dict usage around line
143) and remove the now-unused typing.Dict import if present so Ruff F821 is
resolved and CI stays green.

---

Outside diff comments:
In `@polylogue/cli/app.py`:
- Around line 925-928: When the --json-lines path is taken (the json_lines
branch), do not wrap each hit with stamp_payload because NDJSON must emit raw
hit objects per line; instead for json_lines iterate rows and print either the
raw row or a filtered dict of export_fields (e.g., {k: row.get(k) for k in
export_fields} if export_fields else row) serialized with json.dumps(...,
separators=(",", ":"), ensure_ascii=False). Keep stamp_payload usage only in the
non-json_lines branch so consumers of the json-lines output receive one hit
object per line.

In `@polylogue/cli/settings_cli.py`:
- Around line 84-93: persist_config is being passed config_obj.defaults.roots
which is dict[str, OutputDirs] but it expects dict[str, Path], causing
Path(base).expanduser() to fail; fix by converting the dict before the call: map
each value in config_obj.defaults.roots to its underlying path string/Path
(extract the OutputDirs path field, e.g., OutputDirs.base or OutputDirs.root) so
you pass dict[str, Path] to persist_config; alternatively, if you prefer to
support OutputDirs directly, update persist_config to accept OutputDirs values
and use the appropriate attribute when constructing Path, but the quickest fix
is to transform config_obj.defaults.roots into a dict of Paths and pass that to
persist_config.

In `@polylogue/cli/status.py`:
- Around line 130-157: The JSON and summary payloads omit the computed inbox
counts: include the existing inbox_summary in both the summary_payload (used
when summary_requested / summary_only) and the JSON payload (when json_mode) so
machine consumers receive inbox data; locate where summary_payload is built
(stamp_payload call that contains
generatedAt/runSummary/providerSummary/topRuns) and add an "inbox_summary":
inbox_summary entry, and likewise add "inbox_summary": inbox_summary to the
payload constructed in the json_mode branch (the dict containing
credentials_present, token_present, run_summary, provider_summary, generated_at,
top_runs) so both outputs expose the inbox counts.

In `@polylogue/html.py`:
- Around line 211-231: The TOC entries include the anchor emoji because
h.textContent is read after appending the anchor; modify the headings.forEach
block to capture the heading text into a local variable (e.g., const headingText
= h.textContent || '') before calling h.appendChild(anchor), then use that
variable when setting a.textContent for the TOC link (instead of h.textContent);
keep the rest of the logic (anchor creation, clipboard, hash behavior)
unchanged.
🪄 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: 69047f61-9f75-4419-b4cd-2aa4231e1131

📥 Commits

Reviewing files that changed from the base of the PR and between 15eb180 and 9baf2f0.

📒 Files selected for processing (17)
  • README.md
  • polylogue/cli/app.py
  • polylogue/cli/attachments.py
  • polylogue/cli/doctor.py
  • polylogue/cli/inbox.py
  • polylogue/cli/index_cli.py
  • polylogue/cli/init.py
  • polylogue/cli/maintain.py
  • polylogue/cli/runs.py
  • polylogue/cli/settings_cli.py
  • polylogue/cli/status.py
  • polylogue/cli/watch.py
  • polylogue/config.py
  • polylogue/html.py
  • tests/test_config_roots.py
  • tests/test_failure_logging.py
  • tests/test_inbox_cli.py

Comment thread polylogue/cli/app.py
Comment on lines +113 to +129
def format_help(self) -> str: # pragma: no cover - formatting path
help_text = super().format_help()
# Only append when the parser name exists in COMMAND_EXAMPLES
prog = getattr(self, "_prog", None) or getattr(getattr(self, "_parser", None), "prog", "")
# Map parser prog tokens like "polylogue search" to the subcommand key
if prog:
tokens = prog.split()
if len(tokens) >= 2:
cmd = tokens[1]
examples = COMMAND_EXAMPLES.get(cmd)
if examples:
lines = ["\nExamples:"]
for desc, cmdline in examples:
lines.append(f" # {desc}")
lines.append(f" $ {cmdline}")
help_text = help_text.rstrip() + "\n" + "\n".join(lines) + "\n"
return help_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

Examples are duplicated for top-level commands and mis-keyed for nested ones.

super().format_help() already renders the parser epilog, so this appends a second Examples: block for commands that already set one. On nested parsers like polylogue browse status, prog.split()[1] resolves to browse, so the child help picks the parent examples instead of the current subcommand’s.

Also applies to: 132-138

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

In `@polylogue/cli/app.py` around lines 113 - 129, The format_help method appends
Examples unconditionally and picks the wrong subcommand token; update
format_help to (1) determine the intended subcommand by using the last token
(e.g., tokens[-1]) from prog rather than tokens[1], and (2) skip appending the
examples when the help_text already contains an "Examples:" section (check for
the substring) to avoid duplication; locate and update the format_help function
and the use of COMMAND_EXAMPLES, prog, and _parser accordingly.

Comment thread polylogue/cli/app.py
Comment on lines +1030 to +1039
target_obj = Path(target_path)
is_html = target_obj.suffix.lower() == ".html"
if is_html and anchor_label:
fragment = f"#${anchor_label}" if anchor_label else ""
try:
webbrowser.open(target_obj.as_uri() + f"#{anchor_label}")
ui.console.print(f"[dim]Opened {target_obj}#{anchor_label} in browser[/dim]")
return
except Exception:
pass

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:

#!/bin/bash
python - <<'PY'
from pathlib import Path
import inspect, webbrowser

try:
    Path("relative.html").as_uri()
except Exception as exc:
    print("relative Path.as_uri() ->", type(exc).__name__, exc)

print("\nwebbrowser.open implementation:\n")
print(inspect.getsource(webbrowser.open))
PY

Repository: Sinity/polylogue

Length of output: 780


🏁 Script executed:

cd /tmp && git clone --depth 1 https://github.com/Sinity/polylogue.git 2>&1 | head -20

Repository: Sinity/polylogue

Length of output: 141


🏁 Script executed:

sed -n '1020,1050p' /tmp/polylogue/polylogue/cli/app.py | cat -n

Repository: Sinity/polylogue

Length of output: 138


🏁 Script executed:

# Check the broader context around the target lines to understand the function
sed -n '1010,1060p' /tmp/polylogue/polylogue/cli/app.py | cat -n

Repository: Sinity/polylogue

Length of output: 138


🏁 Script executed:

find / -type d -name "polylogue" 2>/dev/null | head -5

Repository: Sinity/polylogue

Length of output: 128


🏁 Script executed:

ls -la polylogue/polylogue/cli/app.py 2>/dev/null || find . -name "app.py" -path "*/cli/*" 2>/dev/null | head -3

Repository: Sinity/polylogue

Length of output: 82


🏁 Script executed:

sed -n '1025,1045p' ./polylogue/cli/app.py | cat -n

Repository: Sinity/polylogue

Length of output: 1342


🏁 Script executed:

# Check context - find the function this code belongs to
sed -n '1000,1050p' ./polylogue/cli/app.py | cat -n

Repository: Sinity/polylogue

Length of output: 2909


Check webbrowser.open() return value before success message and fallback.

webbrowser.open() returns False on failure, and Path.as_uri() raises ValueError for relative paths. The current code prints "Opened…" and skips the editor fallback regardless of whether the browser launched or the path is relative. Additionally, the unused fragment variable should be removed.

Suggested fix
             target_obj = Path(target_path)
             is_html = target_obj.suffix.lower() == ".html"
             if is_html and anchor_label:
-                fragment = f"#${anchor_label}" if anchor_label else ""
-                try:
-                    webbrowser.open(target_obj.as_uri() + f"#{anchor_label}")
-                    ui.console.print(f"[dim]Opened {target_obj}#{anchor_label} in browser[/dim]")
-                    return
-                except Exception:
-                    pass
+                opened = False
+                try:
+                    opened = webbrowser.open(target_obj.resolve().as_uri() + f"#{anchor_label}")
+                except (OSError, ValueError, webbrowser.Error):
+                    opened = False
+                if opened:
+                    ui.console.print(f"[dim]Opened {target_obj}#{anchor_label} in browser[/dim]")
+                    return
🧰 Tools
🪛 Ruff (0.15.9)

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

(TRY300)


[error] 1038-1039: try-except-pass detected, consider logging the exception

(S110)


[warning] 1038-1038: 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 `@polylogue/cli/app.py` around lines 1030 - 1039, The HTML-open branch
currently assumes success: remove the unused variable fragment, guard against
Path.as_uri() raising ValueError for relative paths, and only treat opening as
successful when webbrowser.open(...) returns True; specifically, in the code
around target_obj, is_html and anchor_label, wrap the as_uri() call in a
try/except to fall back to the editor if as_uri() fails, call
webbrowser.open(target_obj.as_uri() + f"#{anchor_label}") and check its boolean
return value before calling ui.console.print("Opened...") or returning; if
webbrowser.open returns False, fall through to the existing editor fallback
logic.

Comment thread polylogue/cli/app.py
Comment on lines +1388 to +1414
roots_map = getattr(env.config.defaults, "roots", {}) or {}
payload = stamp_payload(
{
"configPath": str(CONFIG_PATH) if CONFIG_PATH else None,
"settingsPath": str(SETTINGS_PATH),
"ui": {
"html_previews": settings.html_previews,
"html_theme": settings.html_theme,
"collapse_threshold": settings.collapse_threshold,
},
},
"outputs": {
"render": str(defaults.output_dirs.render),
"gemini": str(defaults.output_dirs.sync_drive),
"codex": str(defaults.output_dirs.sync_codex),
"claude_code": str(defaults.output_dirs.sync_claude_code),
"chatgpt": str(defaults.output_dirs.import_chatgpt),
"claude": str(defaults.output_dirs.import_claude),
},
"inputs": {
"chatgpt": str(CONFIG.exports.chatgpt),
"claude": str(CONFIG.exports.claude),
},
"index": {
"backend": CONFIG.index.backend if CONFIG.index else "sqlite",
"qdrant": {
"url": CONFIG.index.qdrant_url if CONFIG.index else None,
"api_key": CONFIG.index.qdrant_api_key if CONFIG.index else None,
"collection": CONFIG.index.qdrant_collection if CONFIG.index else None,
"vector_size": CONFIG.index.qdrant_vector_size if CONFIG.index else None,
"auth": {
"credentialPath": str(credential_path) if credential_path else None,
"tokenPath": str(token_path) if token_path else None,
"env": {
"POLYLOGUE_CREDENTIAL_PATH": credential_env,
"POLYLOGUE_TOKEN_PATH": token_env,
},
},
},
"statePath": str(env.conversations.state_path),
"runsDb": str(env.database.resolve_path()),
}
"outputs": {
"render": str(defaults.output_dirs.render),
"gemini": str(defaults.output_dirs.sync_drive),
"codex": str(defaults.output_dirs.sync_codex),
"claude_code": str(defaults.output_dirs.sync_claude_code),
"chatgpt": str(defaults.output_dirs.import_chatgpt),
"claude": str(defaults.output_dirs.import_claude),
"roots": {label: vars(paths) for label, paths in roots_map.items()},
},

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
python - <<'PY'
from pathlib import Path
import json

payload = {"outputs": {"roots": {"demo": {"render": Path("/tmp/render")}}}}
try:
    print(json.dumps(payload))
except Exception as exc:
    print(type(exc).__name__, exc)
PY

Repository: Sinity/polylogue

Length of output: 119


🏁 Script executed:

cd /tmp && git clone --depth=1 https://github.com/Sinity/polylogue.git && cd polylogue

Repository: Sinity/polylogue

Length of output: 149


🏁 Script executed:

cat -n polylogue/cli/app.py | sed -n '1380,1440p'

Repository: Sinity/polylogue

Length of output: 3458


🏁 Script executed:

rg "json\.dumps" polylogue/cli/app.py -A 2 -B 2

Repository: Sinity/polylogue

Length of output: 842


🏁 Script executed:

rg "config show" polylogue/cli/ -A 5 -B 5

Repository: Sinity/polylogue

Length of output: 2405


config show --json will crash when labeled roots are configured.

vars(paths) leaves Path instances under outputs.roots, but this serializes with plain json.dumps(payload) at line 1432. Any configured labeled root raises TypeError: Object of type PosixPath is not JSON serializable.

Suggested fix
                 "outputs": {
                     "render": str(defaults.output_dirs.render),
                     "gemini": str(defaults.output_dirs.sync_drive),
                     "codex": str(defaults.output_dirs.sync_codex),
                     "claude_code": str(defaults.output_dirs.sync_claude_code),
                     "chatgpt": str(defaults.output_dirs.import_chatgpt),
                     "claude": str(defaults.output_dirs.import_claude),
-                    "roots": {label: vars(paths) for label, paths in roots_map.items()},
+                    "roots": {
+                        label: {
+                            key: str(value) if isinstance(value, Path) else value
+                            for key, value in vars(paths).items()
+                        }
+                        for label, paths in roots_map.items()
+                    },
                 },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/app.py` around lines 1388 - 1414, The crash is caused by
leaving Path objects in outputs.roots (built from roots_map) which json.dumps
can't serialize; when constructing payload (around stamp_payload and the
"outputs" -> "roots" entry) convert any Path instances in each paths object to
strings instead of using vars(paths) directly — e.g., replace the {label:
vars(paths) for label, paths in roots_map.items()} with a comprehension that
maps each attribute value to str(v) if isinstance(v, Path) (import Path from
pathlib if needed) so outputs.roots contains only JSON-serializable primitives.

Comment thread polylogue/config.py
html_previews: bool,
html_theme: str,
index: Optional[IndexConfig] = None,
roots: Optional[Dict[str, Path]] = None,

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n 'Dict\[' polylogue/config.py
rg -n '^from typing import ' polylogue/config.py

Repository: Sinity/polylogue

Length of output: 189


🏁 Script executed:

# Check Python version requirement
fd -t f setup.py setup.cfg pyproject.toml requirements.txt | head -5 | xargs grep -l "python" 2>/dev/null || echo "No setup files found"

# Look at more context around the problematic lines in config.py
sed -n '1,15p' polylogue/config.py

# Check lines around 110 and 143
sed -n '105,150p' polylogue/config.py

Repository: Sinity/polylogue

Length of output: 2328


🏁 Script executed:

# Check the settings_cli.py context mentioned in the scratchpad
sed -n '80,100p' polylogue/cli/settings_cli.py

Repository: Sinity/polylogue

Length of output: 838


🏁 Script executed:

# Check for Python version in GitHub Actions or tox/pytest configs
fd -type f ".github" "tox.ini" ".python-version" | head -10
find .github -name "*.yml" -o -name "*.yaml" 2>/dev/null | head -5 | xargs head -30

# Check for any Python version specification in commonly used files
fd -type f -e yaml -e yml | head -10

Repository: Sinity/polylogue

Length of output: 1366


🏁 Script executed:

# Check if there's documentation about Python version
head -50 README.md 2>/dev/null || echo "No README found"

Repository: Sinity/polylogue

Length of output: 9622


Dict is undefined in annotations, which breaks Ruff (F821).

Line 110 and Line 143 reference Dict without importing it. Switch to built-in generics to keep CI green.

🛠️ Proposed fix
-    roots: Optional[Dict[str, Path]] = None,
+    roots: Optional[dict[str, Path]] = None,
-        mapped: Dict[str, Dict[str, str]] = {}
+        mapped: dict[str, dict[str, str]] = {}
🧰 Tools
🪛 Ruff (0.15.9)

[error] 110-110: Undefined name Dict

(F821)

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

In `@polylogue/config.py` at line 110, The annotation for the roots parameter
(roots: Optional[Dict[str, Path]] ) and other annotations that currently
reference typing.Dict should be changed to use built-in generics (e.g.,
Optional[dict[str, Path]]); update every occurrence of Dict[...] to dict[...]
(including the other Dict usage around line 143) and remove the now-unused
typing.Dict import if present so Ruff F821 is resolved and CI stays green.

Comment thread polylogue/config.py
Comment on lines +142 to +146
if roots:
mapped: Dict[str, Dict[str, str]] = {}
for label, base in roots.items():
root_path = Path(base).expanduser()
mapped[label] = {

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

persist_config root mapping can crash with settings_cli input shape.

polylogue/cli/settings_cli.py passes config_obj.defaults.roots (values are OutputDirs), but Line 145 assumes each value is path-like (Path(base)), which can raise TypeError. Handle both Path and OutputDirs inputs.

🛠️ Proposed fix
-    roots: Optional[dict[str, Path]] = None,
+    roots: Optional[dict[str, Path | OutputDirs]] = None,
@@
     if roots:
         mapped: dict[str, dict[str, str]] = {}
         for label, base in roots.items():
-            root_path = Path(base).expanduser()
-            mapped[label] = {
-                "render": str(root_path / "render"),
-                "sync_drive": str(root_path / "gemini"),
-                "sync_codex": str(root_path / "codex"),
-                "sync_claude_code": str(root_path / "claude-code"),
-                "import_chatgpt": str(root_path / "chatgpt"),
-                "import_claude": str(root_path / "claude"),
-            }
+            if isinstance(base, OutputDirs):
+                mapped[label] = {
+                    "render": str(base.render),
+                    "sync_drive": str(base.sync_drive),
+                    "sync_codex": str(base.sync_codex),
+                    "sync_claude_code": str(base.sync_claude_code),
+                    "import_chatgpt": str(base.import_chatgpt),
+                    "import_claude": str(base.import_claude),
+                }
+                continue
+            root_path = Path(base).expanduser()
+            mapped[label] = {
+                "render": str(root_path / "render"),
+                "sync_drive": str(root_path / "gemini"),
+                "sync_codex": str(root_path / "codex"),
+                "sync_claude_code": str(root_path / "claude-code"),
+                "import_chatgpt": str(root_path / "chatgpt"),
+                "import_claude": str(root_path / "claude"),
+            }
🧰 Tools
🪛 Ruff (0.15.9)

[error] 143-143: Undefined name Dict

(F821)


[error] 143-143: Undefined name Dict

(F821)

@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/cli/schema-stamps-labeled-roots branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
…d status monitoring (#30)

Wire stamp_payload() from polylogue.schema into every CLI command that
emits JSON, so each payload carries schemaVersion and polylogueVersion
fields. Add labeled archive roots to support multi-environment
configurations, and extend the status command with ranked-run and inbox
monitoring.

Schema stamping (polylogue/cli/app.py, attachments.py, doctor.py,
index_cli.py, maintain.py, runs.py):
- _record_failure() wraps failure JSONL records through stamp_payload()
- config show --json, compare --json, attachment stats/extract --json,
  doctor --json, index check --json, maintain backup --json, and
  browse runs --json-verbose all embed version metadata
- NDJSON streams (--json-lines) stamp individual rows with
  include_versions=False to keep per-line overhead minimal

Labeled archive roots (polylogue/config.py, cli/init.py,
cli/settings_cli.py, cli/app.py):
- persist_config() accepts optional roots dict mapping labels to base
  paths; each label expands into a full output directory tree
  (render, sync_drive, sync_codex, etc.)
- init wizard prompts for labeled roots interactively
- config show surfaces roots in both JSON and Rich text output
- settings_cli passes roots through when re-persisting config

Status and monitoring (polylogue/cli/status.py, cli/app.py):
- --top N ranks historical runs by attachments/tokens and renders a
  Rich table in interactive mode
- --inbox discovers pending export targets per provider and renders
  an inbox coverage table
- --json-verbose flag added to browse runs, doctor, and index check
- ExamplesHelpFormatter appends COMMAND_EXAMPLES to --help output

HTML navigation (polylogue/html.py, cli/app.py):
- Heading and message anchors gain copy-link buttons with clipboard
  integration and hash navigation
- run_inspect_search() opens HTML results in browser with fragment
  anchors instead of falling through to editor

Watch mode (polylogue/cli/watch.py):
- Track cumulative skipped events during debounce and report the
  total on exit

Tests:
- test_config_roots.py validates labeled roots round-trip through
  persist_config()
- test_failure_logging.py verifies stamp_payload() presence in
  failure JSONL
- test_inbox_cli.py asserts totals.pending in inbox JSON output
@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. 3 finding(s) confirmed fixed/stale.

Sinity added a commit that referenced this pull request Aug 31, 2026
…parent indirection (#4460)

## Summary
A worktree resolves sealed verification-graph roots through
`POLYLOGUE_VERIFY_GRAPH_PARENT` (pointing at the main checkout) instead
of needing a seed copy; publication still writes only locally. Also
declares the harvest `publish`/`close` parameters that `agentctl lane
publish` (sinnix #30) passes.

## Problem
Graph roots are immutable content-addressed manifests, but every
worktree needed its own copy of the testmon seed to use affected
selection (polylogue-c2a5l); provisioning never copied one, so every
lane ran static-only. The one-verb publication route needed two bool
parameters the descriptor didn't declare.

## Solution
`_root_bases` adds an optional external roots directory (env var; bare
checkout path or explicit roots dir), local first;
`eligible_root`/`latest_eligible_root` scan both with unchanged
eligibility validation. Writes never touch the indirection. Descriptor
gains `publish`/`close`.

## Verification
`devtools test tests/unit/devtools/test_verification_graph.py` → 6
passed, including the new worktree-resolves-parent-root test (asserts
read-through and local-only publication). `devtools verify --quick`
green (one order-dependent browser-extension flake surfaced on the first
run — `background.test.js` 'holds the job visibly...' — passes in
isolation and on rerun; inherited, not from this diff).

## Residual risk
The indirection trusts the parent path the caller sets; eligibility
checks still gate every manifest read.

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

https://claude.ai/code/session_014BQsaB1NBY8mTR6yZByfMA
Sinity added a commit that referenced this pull request Sep 1, 2026
…parent indirection (#4460)

## Summary
A worktree resolves sealed verification-graph roots through
`POLYLOGUE_VERIFY_GRAPH_PARENT` (pointing at the main checkout) instead
of needing a seed copy; publication still writes only locally. Also
declares the harvest `publish`/`close` parameters that `agentctl lane
publish` (sinnix #30) passes.

## Problem
Graph roots are immutable content-addressed manifests, but every
worktree needed its own copy of the testmon seed to use affected
selection (polylogue-c2a5l); provisioning never copied one, so every
lane ran static-only. The one-verb publication route needed two bool
parameters the descriptor didn't declare.

## Solution
`_root_bases` adds an optional external roots directory (env var; bare
checkout path or explicit roots dir), local first;
`eligible_root`/`latest_eligible_root` scan both with unchanged
eligibility validation. Writes never touch the indirection. Descriptor
gains `publish`/`close`.

## Verification
`devtools test tests/unit/devtools/test_verification_graph.py` → 6
passed, including the new worktree-resolves-parent-root test (asserts
read-through and local-only publication). `devtools verify --quick`
green (one order-dependent browser-extension flake surfaced on the first
run — `background.test.js` 'holds the job visibly...' — passes in
isolation and on rerun; inherited, not from this diff).

## Residual risk
The indirection trusts the parent path the caller sets; eligibility
checks still gate every manifest read.

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

https://claude.ai/code/session_014BQsaB1NBY8mTR6yZByfMA
@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.

  • 60.F065 / P1: stale at the checked revision: The labeled paths.roots configuration writer and its old PathsModel consumer are retired. The replacement starter at polylogue/cli/commands/init.py:92 emits archive.root and daemon.api settings, with detected source locations as comments rather than paths.roots entries.

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

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.

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

Labels

area:cli CLI area:schema Schema area:storage Storage faux-pull-request PR created as part of a history rewrite process type:feat New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants