Skip to content

fix(daemon): align loopback definitions across daemon and browser_capture (#1005) - #1011

Merged
Sinity merged 3 commits into
masterfrom
feature/fix/loopback-coherence-1005
May 11, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/fix/loopback-coherence-1005

Conversation

@Sinity

@Sinity Sinity commented May 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes #1005. Two near-duplicate loopback helpers across the daemon HTTP API and the browser-capture receiver disagreed on RFC compliance; consolidates them into one shared helper, removes two dead helpers in daemon/http.py, and brings every consumer (bind enforcement, cross-origin allowlist, security tests, security docs) onto the shared definition.

The first commit (chore) restores the pytest baseline by fixing three pre-existing master failures encountered during verification — split out from the loopback work because it is unrelated.

Problem

polylogue/daemon/http.py::_is_localhost rejected 127.0.0.2, 127.1.2.3, and the rest of the 127.0.0.0/8 block, while polylogue/browser_capture/server.py::_is_loopback accepted the full block. polylogue/daemon/cli.py then hardcoded the same narrow tuple for --api-host enforcement, so polylogued run --api-host 127.0.0.2 was refused as a remote bind even though it is a loopback per RFC 5735. The cross-origin allowlist in _check_cross_origin had the same narrow set hard-coded.

Two dead helpers in daemon/http.py (_advertised_cors_headers returning {} in every branch, and an unread _auth_required property whose docstring contradicted _check_auth_logic) remained as leftovers from earlier iterations and confused adversarial review on PR #1004.

Solution

  • polylogue/core/loopback.py (new) — is_loopback_host(host) defers to ipaddress.ip_address(host).is_loopback so the full 127.0.0.0/8 block plus ::1 plus the localhost name are accepted; is_loopback_origin(origin) parses scheme/host/port from a browser Origin header, including bracketed IPv6 per RFC 3986.
  • daemon/http.py — re-routes _is_localhost and _check_cross_origin through the shared helpers; removes _advertised_cors_headers and _auth_required.
  • daemon/cli.py — --api-host enforcement uses is_loopback_host.
  • browser_capture/server.py — defers to the shared helper.
  • tests/unit/core/test_loopback.py (new) — RFC 5735 contract tests covering broad range plus malformed inputs.
  • tests/unit/daemon/test_daemon_http_security.py::TestIsLocalhost — parametrization extended to assert the broader range.
  • docs/security.md — cross-origin allowlist statement now points at the shared helper and names RFC 5735.

The earlier chore: restore master pytest baseline commit fixes three orphan failures present on master:

  1. terminal snapshot drift after new context-pack/maintenance commands shifted column padding;
  2. test_artifact_graph expected list missing message_type_backfill (added in 5b5dc1e);
  3. test_cwd_prefix_filter's direct-write helper bypassed prepare_enrichment so the typed working_directories_json column was never populated; added a symmetric fallback in conversations_writes.save_conversation_record that promotes provider_meta.working_directories/cwd when the typed column is absent.

Verification

  • nix develop -c pytest -q tests/unit/core/test_loopback.py tests/unit/daemon tests/unit/browser_capture → 174 passed.
  • nix develop -c devtools verify --quick → all checks passed (mypy, ruff, render-all, topology, layering, file budgets, witness lifecycle, proof-pack check).
  • Full nix develop -c pytest -q --ignore=tests/integration → green (one xdist worker had a transient long stall on test_api_facets_scoped_to_provider ~10min; final run completed cleanly).

Summary by CodeRabbit

  • Documentation

    • Enhanced security documentation with clearer descriptions of loopback-only default behavior and CSRF/origin boundary protections.
  • Bug Fixes

    • Improved working directory handling with fallback logic for better data serialization.
  • Refactor

    • Centralized loopback detection logic for more consistent security boundary enforcement across modules.
  • Tests

    • Added comprehensive test coverage for loopback host and origin detection.
    • Updated existing tests to validate expanded loopback address range support.

Review Change Stack

Sinity and others added 2 commits May 11, 2026 01:21
Three failures had landed on master in unrelated commits:

1. ``tests/unit/cli/test_terminal_snapshots.py::TestHelpOutput::test_help_output_snapshot``
   — snapshot drifted after new ``context-pack`` and ``maintenance``
   subcommands shifted column padding and changed ``tags`` help text.
   Regenerated via ``pytest --snapshot-update``.

2. ``tests/unit/devtools/test_artifact_graph.py::test_render_artifact_graph_json_is_machine_readable``
   — expected ``uncovered_maintenance_targets`` list missed the
   ``message_type_backfill`` target added by 5b5dc1e
   (``feat(maintenance): add message_type backfill``). Added the entry
   to both the JSON-mode list and the rendered-text assertion.

3. ``tests/unit/core/test_cwd_prefix_filter.py::test_cwd_prefix_sql_filter_is_path_component_bounded``
   — direct ``backend.save_conversation_record`` callers (test
   helpers, ad-hoc backfills) bypassed the ``prepare_enrichment``
   stage that promotes ``provider_meta.working_directories`` (or
   ``cwd``) into the typed ``working_directories_json`` column the
   ``cwd_prefix`` SQL filter reads. Mirrored the existing
   ``source_name`` fallback in ``conversations_writes.py``: derive
   ``working_directories_json`` from ``provider_meta`` when not
   explicitly set, so the canonical materialization rule from #864
   holds for direct write callers too.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ture (#1005)

## Problem

Two near-duplicate loopback helpers diverged on RFC compliance:

- ``polylogue/daemon/http.py::_is_localhost`` rejected
  ``127.0.0.2``, ``127.1.2.3``, and the rest of the
  ``127.0.0.0/8`` block.
- ``polylogue/browser_capture/server.py::_is_loopback`` accepted
  the full block.

``polylogue/daemon/cli.py`` then hardcoded the same narrow
tuple, so ``polylogued run --api-host 127.0.0.2`` was refused
as a remote bind even though it is a loopback address per
RFC 5735. The cross-origin allowlist in
``http.py::_check_cross_origin`` had the same narrow set hard-coded.

Two dead helpers in ``daemon/http.py`` (``_advertised_cors_headers``
returning ``{}`` in every branch, and an unread ``_auth_required``
property whose docstring contradicted ``_check_auth_logic``)
remained as leftovers from earlier iterations and confused
adversarial review.

## Solution

- ``polylogue/core/loopback.py`` — new shared module exposing
  ``is_loopback_host(host)`` (defers to ``ipaddress.ip_address(host).is_loopback``
  so the full ``127.0.0.0/8`` block plus ``::1`` plus the
  ``localhost`` name are accepted) and ``is_loopback_origin(origin)``
  (parses scheme/host/port from a browser ``Origin`` header,
  including bracketed IPv6 per RFC 3986).
- ``daemon/http.py`` — re-routes ``_is_localhost`` and
  ``_check_cross_origin`` through the shared helpers. Removed
  ``_advertised_cors_headers`` and ``_auth_required``.
- ``daemon/cli.py`` — replaced the hardcoded tuple at the
  ``--api-host`` enforcement site with ``is_loopback_host``.
- ``browser_capture/server.py`` — dropped local
  ``_LOOPBACK_HOSTS``/``_is_loopback`` body, defers to the shared
  helper.
- ``tests/unit/core/test_loopback.py`` — new contract tests
  covering the RFC 5735 range and several malformed inputs.
- ``tests/unit/daemon/test_daemon_http_security.py::TestIsLocalhost``
  — extended parametrization to assert the broader range
  (``127.0.0.2``, ``127.1.2.3``, ``127.255.255.254``).
- ``docs/security.md`` — explicit cross-origin allowlist statement
  now points at the shared helper and names RFC 5735 so a future
  regression is recognized as a policy change.

## Verification

- ``nix develop -c pytest -q tests/unit/core/test_loopback.py
  tests/unit/daemon tests/unit/browser_capture`` — 174 passed.
- ``nix develop -c devtools verify --quick`` — all checks
  passed (mypy, ruff, render-all, topology, layering, file
  budgets, witness lifecycle, proof-pack check).

Closes #1005

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 10, 2026 23:24
@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 16 minutes and 27 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: df213209-349b-4f8f-a779-d71c244e72fd

📥 Commits

Reviewing files that changed from the base of the PR and between d51b469 and f7ef9f1.

📒 Files selected for processing (3)
  • docs/security.md
  • polylogue/core/loopback.py
  • polylogue/storage/sqlite/queries/conversations_writes.py
📝 Walkthrough

Walkthrough

This PR consolidates loopback detection logic from duplicated and RFC-incomplete implementations across daemon and browser_capture into a shared RFC 5735-compliant module, updates all consumers, removes dead code helpers, and adds working directory JSON derivation in conversation storage with corresponding topology and documentation updates.

Changes

Loopback Predicate Consolidation

Layer / File(s) Summary
Core Loopback Predicates
polylogue/core/loopback.py
New module exports LOOPBACK_HOST_NAMES (set to {"localhost"}), LOOPBACK_ORIGIN_PREFIXES (HTTP/HTTPS for localhost and [::1]), is_loopback_host(host) covering full 127.0.0.0/8 plus ::1 plus localhost, and is_loopback_origin(origin) for origin header validation.
Daemon Loopback Integration
polylogue/daemon/cli.py, polylogue/daemon/http.py
run_daemon_services replaces hardcoded loopback tuple with is_loopback_host(api_host) call. _is_localhost(host) delegates to same predicate. _check_cross_origin() uses is_loopback_origin(origin) instead of ad-hoc string prefixes. Dead helpers _advertised_cors_headers() and _auth_required property removed.
Browser Capture Loopback Integration
polylogue/browser_capture/server.py
Removes local _LOOPBACK_HOSTS constant and delegates _is_loopback(host) to centralized is_loopback_host.
Test Coverage
tests/unit/core/test_loopback.py, tests/unit/daemon/test_daemon_http_security.py
New comprehensive test module for is_loopback_host and is_loopback_origin with RFC 5735 range coverage. Existing daemon tests expanded to cover 127.0.0.2, 127.1.2.3, 127.255.255.254 alongside original 127.0.0.1.
Documentation & Topology
docs/security.md, docs/plans/topology-target.yaml, docs/topology-status.md
Security docs reference new is_loopback_host and is_loopback_origin predicates with explicit RFC 5735 scope. Topology files updated to track new core/loopback.py module (65 loc, core-primitive owner); core-primitive cells increased 12→13 and totals increased 712→713.

Storage Working Directories & Topology Updates

Layer / File(s) Summary
Working Directories JSON Derivation
polylogue/storage/sqlite/queries/conversations_writes.py
New _derive_working_directories_json(provider_meta) helper converts provider_meta.working_directories list or cwd string to JSON string (or None). save_conversation_record computes local working_directories_json value with fallback to derivation when record.working_directories_json is not set before upsert write.
CLI & Topology Snapshots
tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr, tests/unit/devtools/test_artifact_graph.py
CLI help text reflowed to accommodate new message_type_backfill in doctor --target allowed targets; Commands sections rewrapped for main/narrow/wide terminal widths. Artifact graph tests updated to expect message_type_backfill in uncovered maintenance targets.

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Sinity/polylogue#438: Topology projection YAML generation and tooling; this PR's docs/plans/topology-target.yaml and docs/topology-status.md are inputs/outputs to that system.
  • Sinity/polylogue#455: Topology status dashboard rendering and devtools artifact graph; this PR updates the expected maintenance targets tracked by those features.

Suggested labels

type:refactor, area:security, area:daemon

🐰 A loopback truth, at last aligned,
Five-seven-three-five, RFC-defined,
No more scattered strings, no tangled skein,
One predicate to rule, from core domain!
Dead helpers gone—the daemon breathes clean again. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.48% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: consolidating divergent loopback definitions and removing dead helpers across daemon and browser_capture modules.
Description check ✅ Passed The PR description is comprehensive, covering Summary, Problem, Solution, Verification, and a Risks/Follow-ups section; all required sections per the template are present and substantially filled.
Linked Issues check ✅ Passed All acceptance criteria from #1005 are met: shared loopback helpers created, RFC 5735 compliance achieved, daemon/cli.py updated, dead helpers removed, tests extended to broader range, cross-origin allowlist updated, and security docs updated.
Out of Scope Changes check ✅ Passed All changes are in scope: loopback helper consolidation, dead helper removal, test updates, documentation updates, and the separate chore commit for pytest baseline restoration are all related to the stated objectives.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/loopback-coherence-1005

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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: d51b469b46

ℹ️ 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/core/loopback.py Resolved

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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/security.md`:
- Around line 67-75: Doc text incorrectly claims the browser-capture receiver
shares loopback definition via is_loopback_origin; instead reference the actual
helper used for bind validation. Update the paragraph to state that
browser-capture/server.py uses is_loopback_host() for bind validation and that
the CSRF boundary check in polylogue/daemon/http.py uses
polylogue/core/loopback.py:is_loopback_origin; adjust wording so it doesn't
overstate that the receiver and CSRF check share the same helper name.

In `@polylogue/core/loopback.py`:
- Around line 55-60: When parsing bracketed IPv6 hosts in the host-handling
block (the host.startswith("[") branch), reject malformed cases by ensuring the
closing ']' is present and that any characters after ']' are either empty or a
valid port prefixed by ':' containing only digits; specifically: find end =
host.find("]"), return False if end == -1, set tail = host[end+1:], if tail ==
"" then call is_loopback_host(host[1:end]) as before, else if tail startswith
":" verify tail[1:].isdigit() and only then call is_loopback_host(host[1:end]),
otherwise return False to avoid treating inputs like "[::1].evil.com" or
"[::1]:bad" as loopback.

In `@polylogue/storage/sqlite/queries/conversations_writes.py`:
- Around line 34-35: In _derive_working_directories_json, validate that when
working_directories (wds) is a list you only serialize it if every element is a
string: replace the unconditional return of _json.dumps(wds) with a check like
all(isinstance(x, str) for x in wds) and either filter/convert non-strings or
raise a ValueError (consistent with project error handling); apply the same
element-type validation to the other branch handling working_directories (the
second list-handling branch referenced around the same area) so only lists of
path strings are persisted.
- Line 54: The line that sets working_directories_json uses a truthy fallback
which overwrites intentional falsey values; replace the boolean-or pattern with
an explicit None check so working_directories_json =
record.working_directories_json if record.working_directories_json is not None
else _derive_working_directories_json(record.provider_meta), ensuring you
reference record.working_directories_json and the helper
_derive_working_directories_json to locate and update the assignment in
conversations_writes.py.

In `@tests/unit/core/test_loopback.py`:
- Around line 70-80: Add an extra malformed-origin test string "http://::1:8765"
to the same list in tests/unit/core/test_loopback.py (near the existing
"http://[::1" malformed bracket case) to cover unbracketed IPv6 with port;
ensure the test follows the same assertion pattern as the other malformed
entries so the origin is treated as invalid/rejected by the code under test.
- Around line 54-63: Update the origin test cases list used in the
loopback/origin unit test to include examples that omit explicit ports (to cover
default-port behavior): add "http://localhost", "https://localhost",
"http://127.0.0.1", "https://127.0.0.1", "http://127.0.0.2", "http://[::1]", and
"https://[::1]/path/segment" alongside the existing ported entries so the test
for origin parsing/matching (the array literal of allowed origins in the test)
validates default-port handling for HTTP (80) and HTTPS (443).

In `@tests/unit/daemon/test_daemon_http_security.py`:
- Around line 369-378: The POST origin security tests only check Origin values
for 127.0.0.1, so they would miss regressions if _check_cross_origin() reverted
to canonical-only matching; update the test matrix in
tests/unit/daemon/test_daemon_http_security.py to mirror the broader 127.0.0.0/8
coverage you added for _is_localhost(): replace or parametrize the Origin hosts
used in the POST security matrix to include multiple addresses from 127.* (e.g.,
127.0.0.1, 127.0.0.2, 127.1.2.3, 127.255.255.254) and also include ::1 and
localhost where relevant so that _check_cross_origin() is validated against the
same set of loopback variants.
🪄 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: ab4a12a1-b045-4744-87d4-371343ef6e7f

📥 Commits

Reviewing files that changed from the base of the PR and between 50f23b3 and d51b469.

📒 Files selected for processing (12)
  • docs/plans/topology-target.yaml
  • docs/security.md
  • docs/topology-status.md
  • polylogue/browser_capture/server.py
  • polylogue/core/loopback.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/http.py
  • polylogue/storage/sqlite/queries/conversations_writes.py
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/core/test_loopback.py
  • tests/unit/daemon/test_daemon_http_security.py
  • tests/unit/devtools/test_artifact_graph.py

Comment thread docs/security.md Resolved
Comment thread polylogue/core/loopback.py Resolved
Comment on lines +54 to +63
[
"http://localhost:8765",
"https://localhost:8766",
"http://127.0.0.1:8765",
"https://127.0.0.1:8765",
"http://127.0.0.2:8765",
"http://127.1.2.3:9999",
"http://[::1]:8765",
"https://[::1]:8765/path/segment",
],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add test coverage for origins without explicit ports.

All current test cases include explicit ports, but real-world HTTP/HTTPS origins frequently omit ports when using defaults (80 for http, 443 for https). This is a common scenario in browser Origin headers.

✅ Suggested test cases to add
         [
             "http://localhost:8765",
             "https://localhost:8766",
+            "http://localhost",
+            "https://localhost",
             "http://127.0.0.1:8765",
             "https://127.0.0.1:8765",
+            "https://127.0.0.1",
             "http://127.0.0.2:8765",
             "http://127.1.2.3:9999",
             "http://[::1]:8765",
             "https://[::1]:8765/path/segment",
+            "http://[::1]",
         ],
📝 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
[
"http://localhost:8765",
"https://localhost:8766",
"http://127.0.0.1:8765",
"https://127.0.0.1:8765",
"http://127.0.0.2:8765",
"http://127.1.2.3:9999",
"http://[::1]:8765",
"https://[::1]:8765/path/segment",
],
[
"http://localhost:8765",
"https://localhost:8766",
"http://localhost",
"https://localhost",
"http://127.0.0.1:8765",
"https://127.0.0.1:8765",
"https://127.0.0.1",
"http://127.0.0.2:8765",
"http://127.1.2.3:9999",
"http://[::1]:8765",
"https://[::1]:8765/path/segment",
"http://[::1]",
],
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/core/test_loopback.py` around lines 54 - 63, Update the origin
test cases list used in the loopback/origin unit test to include examples that
omit explicit ports (to cover default-port behavior): add "http://localhost",
"https://localhost", "http://127.0.0.1", "https://127.0.0.1",
"http://127.0.0.2", "http://[::1]", and "https://[::1]/path/segment" alongside
the existing ported entries so the test for origin parsing/matching (the array
literal of allowed origins in the test) validates default-port handling for HTTP
(80) and HTTPS (443).

Comment on lines +70 to +80
[
"",
"http://example.com",
"https://192.168.1.1:8765",
"http://0.0.0.0:8765",
"ftp://localhost:8765",
"chrome-extension://abcdef",
"http://[fe80::1]:8765",
"http://[::]:8765",
"http://[::1", # malformed bracket
],

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 | ⚡ Quick win

Consider adding test for unbracketed IPv6 in origin.

The malformed bracket test at line 79 is excellent. Adding a test for IPv6 without brackets (e.g., "http://::1:8765") would strengthen coverage of malformed origins, as the colons in an unbracketed IPv6 address conflict with port delimiters.

🧪 Suggested additional test case
             "http://[fe80::1]:8765",
             "http://[::]:8765",
             "http://[::1",  # malformed bracket
+            "http://::1:8765",  # unbracketed IPv6
         ],
📝 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
[
"",
"http://example.com",
"https://192.168.1.1:8765",
"http://0.0.0.0:8765",
"ftp://localhost:8765",
"chrome-extension://abcdef",
"http://[fe80::1]:8765",
"http://[::]:8765",
"http://[::1", # malformed bracket
],
[
"",
"http://example.com",
"https://192.168.1.1:8765",
"http://0.0.0.0:8765",
"ftp://localhost:8765",
"chrome-extension://abcdef",
"http://[fe80::1]:8765",
"http://[::]:8765",
"http://[::1", # malformed bracket
"http://::1:8765", # unbracketed IPv6
],
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/core/test_loopback.py` around lines 70 - 80, Add an extra
malformed-origin test string "http://::1:8765" to the same list in
tests/unit/core/test_loopback.py (near the existing "http://[::1" malformed
bracket case) to cover unbracketed IPv6 with port; ensure the test follows the
same assertion pattern as the other malformed entries so the origin is treated
as invalid/rejected by the code under test.

Comment on lines +369 to +378
@pytest.mark.parametrize(
"host",
["127.0.0.1", "127.0.0.2", "127.1.2.3", "127.255.255.254", "::1", "localhost"],
)
def test_loopback_addresses(self, host: str) -> None:
assert _is_localhost(host) is True

@pytest.mark.parametrize(
"host",
["0.0.0.0", "192.168.1.1", "10.0.0.1", "8.8.8.8", "::", ""],
["0.0.0.0", "192.168.1.1", "10.0.0.1", "8.8.8.8", "128.0.0.1", "::", ""],

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 | ⚡ Quick win

Mirror the broader 127.0.0.0/8 contract in the origin-gate tests.

These _is_localhost() additions are good, but this file’s POST security matrix still only exercises Origin: http://127.0.0.1:.... A regression in _check_cross_origin() back to canonical-only matching would still pass here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/daemon/test_daemon_http_security.py` around lines 369 - 378, The
POST origin security tests only check Origin values for 127.0.0.1, so they would
miss regressions if _check_cross_origin() reverted to canonical-only matching;
update the test matrix in tests/unit/daemon/test_daemon_http_security.py to
mirror the broader 127.0.0.0/8 coverage you added for _is_localhost(): replace
or parametrize the Origin hosts used in the POST security matrix to include
multiple addresses from 127.* (e.g., 127.0.0.1, 127.0.0.2, 127.1.2.3,
127.255.255.254) and also include ::1 and localhost where relevant so that
_check_cross_origin() is validated against the same set of loopback variants.

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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

…s validation

Address review feedback on PR #1011 (#1005):

- ``polylogue/core/loopback.py::is_loopback_origin`` now rejects
  malformed bracketed IPv6 origins (``http://[::1].evil.com``,
  ``http://[::1]evil.com``, ``http://[::1]:bad``, ``http://127.0.0.1:bad``).
  RFC 3986 only allows ``:port`` after a closed bracket; anything else
  is treated as a non-loopback origin.
- ``tests/unit/core/test_loopback.py`` — added 4 negative cases pinning
  the malformed-bracket and non-numeric-port contracts.
- ``docs/security.md`` — corrected the helper attribution: the
  browser-capture receiver uses ``is_loopback_host`` for bind
  validation; the daemon HTTP API additionally uses ``is_loopback_origin``
  for the ``Origin`` header. Documented the malformed-bracket
  rejection so the policy is auditable.
- ``polylogue/storage/sqlite/queries/conversations_writes.py``:
  - ``_derive_working_directories_json`` filters out non-string entries
    so a malformed ``provider_meta.working_directories=[123, "ok"]``
    payload yields ``["ok"]`` instead of corrupting the column.
  - ``save_conversation_record`` uses an explicit ``is not None``
    check before falling back to the derivation, so a deliberate
    empty-string column value is no longer silently overwritten.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity
Sinity merged commit 3b4f556 into master May 11, 2026
4 checks passed
@Sinity
Sinity deleted the feature/fix/loopback-coherence-1005 branch May 11, 2026 01:46
Sinity added a commit that referenced this pull request May 11, 2026
…865) (#1014)

## Summary

Closes #865. Replaces the original #865 scaffolding with a real reader
smoke harness that boots the production ``DaemonAPIHTTPServer`` against
a synthetic archive and exercises the live HTTP surface end-to-end.
Fixes two structural bugs that masked or blocked coverage: workers hung
forever because the harness never started ``serve_forever()`` in a
thread, and ``/api/conversations/{id}/messages`` was unreachable because
of an off-by-one in the dispatcher.

## Problem

- ``DaemonAPIHTTPServer`` is a ``ThreadingHTTPServer``, but the original
harness instantiated it without spinning ``serve_forever`` in a thread.
The very first ``urlopen`` request blocked indefinitely until pytest
workers were SIGKILLed (observed during PR #1011 and #1013
verification).
- The dispatch in ``polylogue/daemon/http.py`` checked ``len(path) ==
5`` for the ``messages`` route, so the four-segment URL the JS bundle
hits (``/api/conversations/c1/messages``) returned 404. The reader UI
works because the JS hits a different path; this lane catches the gap.

## Solution

- ``polylogue/daemon/http.py`` — fixed the messages-route length check
to ``len(path) == 4 and path[3] == "messages"``.
- ``tests/unit/daemon/test_web_reader.py`` — rewritten as a real visual
smoke harness with five test classes covering search, conversation,
degraded, privacy, and auth states; documented in module docstring and
per-class docstrings.
- ``_running_server`` context manager spins ``serve_forever`` in a
daemon thread, joins on teardown, and routes the daemon at the
``workspace_env`` temp archive so the seeded synthetic DB is what the
daemon reads.
  - 21 tests total (19 passing, 2 skipped pending FTS priming).
- Exercises the documented artefact ids the MK2 design pack uses:
``polylogue.local_reader.search`` and
``polylogue.local_reader.conversation``.
- Privacy lane audits the unauthenticated web shell and ``/api/facets``
JSON for absolute local-path leaks across the standard POSIX prefixes;
``/api/sources`` and ``/api/raw_artifacts/:id`` deliberately surface
absolute paths under the operator-level token (see ``docs/security.md``)
and are out of scope.
- Hang-protection budget: each route asserted to return within 10 s — a
future "endpoint hangs forever" regression fails the suite instantly
instead of taking down xdist workers.
- ``docs/visual-evidence.md`` — new doc describing the lane, its
artefact ids (so #848 can reference them), what is and isn't checked,
the explicit non-goal of blessing pixel snapshots, and the FTS
follow-up.

## Verification

- ``nix develop -c pytest tests/unit/daemon/test_web_reader.py`` → 19
passed, 2 skipped.
- ``nix develop -c devtools verify --quick`` → all checks passed.

## Acceptance criteria

- [x] Documented command runs the lane from the devshell against
synthetic data — `pytest tests/unit/daemon/test_web_reader.py` (also
runs as part of `devtools verify`).
- [x] Drives the real daemon-served reader and HTTP API, not a frontend
mock.
- [x] DOM/text-level coverage for search/list and conversation/detail
reader states.
- [x] Empty/no-results/degraded/privacy states have at least DOM-level
coverage with sanitized messaging assertions.
- [x] Actionable failure output for blank rendering, missing region
hooks, contract drift, hung endpoints, and absolute-path leakage.
- [x] Documents whether the lane runs in `devtools verify` (yes — part
of the standard pytest unit run, no separate browser binary).
- [ ] Pixel/screenshot evidence — explicit non-goal for this iteration
(see ``docs/visual-evidence.md``); a Playwright lane can layer on later
as a separate gate without changing this lane's contract.
- [ ] FTS-dependent query routes — two assertions skipped pending the
priming follow-up.

## Notes

- Built directly on master (not stacked on the loopback or envelope
PRs); merges cleanly in any order.

---------

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

## Summary

Closes #1007. Twelve registry-driven insight MCP tools historically
returned ``{count: N, <key>: [...]}`` while every other paginated MCP
surface returned ``{items|hits|messages|...: [...], total: N, ...}``.
This PR flips the field name in the registry's payload factory
(``insight_items_payload``) and reclassifies the 12 affected tools in
the registry-wide ``TOOL_CONTRACT`` matrix so they share the standard
envelope shape.

The first commit picks up the same baseline-restore from PR #1011
(#1005); the second commit xfails 5 additional pre-existing master
failures uncovered while verifying this work and tracks them at #1012.

## Problem

The drift was visible to every consumer generalising over MCP list
responses — they had to special-case insight tools.
``test_envelope_contracts.py::test_insight_envelope_uses_count_not_total``
(added during the #819 closure) pinned the inconsistency in code so it
would not silently regress, with an explicit pointer to this issue for
the coordinated rename.

## Solution

- ``polylogue/insights/registry.py::insight_items_payload`` now emits
``total``. Doc comment names the rename and references #1007.
- ``tests/unit/mcp/test_envelope_contracts.py``:
- All 12 insight tools' rows reclassified from ``"insight_envelope"`` to
``("envelope", frozenset({"items", "total"}))``.
- The class-based parametrize is restricted to envelope tools backed by
typed payload classes; insight tools wrap a ``MCPRootPayload[dict]`` so
their envelope shape is pinned by a new
``TestInsightEnvelopeRuntimeSerialisation`` runtime smoke (covers both
the default ``json_key`` and the explicit ``item_key="items"`` paths).
- The inverted pin (``test_insight_envelope_uses_count_not_total``) is
removed in favour of positive ``total``-asserting tests.
- Test sweep: ``payload["count"]`` → ``payload["total"]`` in
``tests/unit/cli/test_insights.py``,
``tests/unit/core/test_insight_registry_runtime.py``,
``tests/unit/mcp/test_tool_contracts.py``. Non-insight ``count``
references (provider ranges, FTS index status, export results)
untouched.

No production reader of ``insight_items_payload`` outside the registry
itself read the legacy ``"count"`` field — verified by grep across
``polylogue/cli``, ``polylogue/api``, ``polylogue/daemon``. The MCP
insight tool registration already passes ``item_key="items"`` so the MCP
envelope shape is now uniformly ``{items: [...], total: N}`` across
every tool.

## Verification

- ``pytest -q tests/unit/cli/test_insights.py
tests/unit/core/test_insight_registry_runtime.py
tests/unit/mcp/test_envelope_contracts.py`` → 65 passed.
- ``pytest tests/unit/cli tests/unit/mcp tests/unit/core
tests/unit/devtools`` → 3015 passed, 3 xfailed (pre-existing, #1012).
- ``devtools verify --quick`` → all checks passed.

## Notes on stacked work

This branch picks up the baseline-restore commit from PR #1011 (#1005)
and adds 5 more xfails in a second baseline commit referencing #1012.
Once #1011 merges to master, a rebase removes the duplicate baseline
commit; the xfail commit and the actual envelope-rename commit are
independent of #1011.

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

## Summary by CodeRabbit

## Release Notes

* **New Features**
* Introduced `message_type_backfill` maintenance target for enhanced
system diagnostics.

* **Bug Fixes**
* Improved conversation working directory handling with automatic
fallback logic for better data persistence.

* **Changes**
* Updated API response schema: paginated result envelopes now use
`"total"` field instead of `"count"` for aggregate counts.

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Sinity/polylogue/pull/1013)

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@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.

  • 63.F016 / P2: fixed-already at the checked revision: The bracketed-host parser validates the suffix after ] at polylogue/core/loopback.py:80 and rejects anything other than an optional numeric port. The cited http://[::1]evil.com:8765 input therefore fails before loopback-host acceptance.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(daemon): align loopback definitions across daemon and browser_capture; remove dead helpers

2 participants