Skip to content

refactor(insights): delete prose-keyword heuristics for terminal state and activity labels - #2960

Merged
Sinity merged 3 commits into
masterfrom
refactor/kill-prose-keyword-heuristics
Jul 16, 2026
Merged

Sinity merged 3 commits into
masterfrom
refactor/kill-prose-keyword-heuristics

Conversation

@Sinity

@Sinity Sinity commented Jul 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

Deletes the two prose-keyword heuristics per the operator-ratified ve9z ladder decision ("kill the terrible heuristics entirely"): the _TEXT_SIGNAL_TABLE activity-type classifier and the _ERROR_MARKERS terminal-state fallback with its clean_finish complement. Net −206 lines. Ref polylogue-h01l.

Problem

9e5.9 measured the _ERROR_MARKERS-family completed/failed prose detection at 50.5% agreement with structural ground truth on 14,377 real runs — a coin flip; the activity keyword table was never measured at all. The ve9z decision makes both illegal: structural facts are canonical, and unknown renders honestly rather than being papered over by a keyword guess.

Solution

  • extraction.py: keyword tables, word-boundary compiler, and text-signal plumbing deleted; _classify_range is action-evidence-only (no-tools → SESSION, weak → coarse IMPLEMENTATION). The write-only normalized_user_text accumulator went too.
  • runtime.py: _terminal_state is structural-only (tool pairing, keystone tool_result_is_error/exit_code, typed event status) plus one new structural rule: an event stream ending on a typed error output is terminal error_left regardless of trailing assistant prose — this preserves the provider-error detection the prose scan used to gate, without prose. A recovered mid-session error stays non-terminal; clean_finish is no longer emitted (no structural signal distinguishes it) — honest unknown instead. All emitted evidence_class values are raw_evidence.
  • rigor.py matrix notes rewritten for the post-deletion contract; generated demo-corpus audit doc regenerated.
  • Read-side compatibility: persisted pre-deletion profiles still carry clean_finish/text_derived; the enrichment goal-outcome mapping keeps those entries, proven by an explicit-variant test.
  • Tests: five expectations moved to honest-unknown/structural semantics; test_work_event_text_signals.py deleted (sole obligation was the deleted mechanism — b0b.1's word-boundary regression tests guard nothing once the matcher is gone); embeddings TERMINAL_PROVIDER_ERROR_MARKERS explicitly classified as kept wire-evidence (live provider HTTP error triage, not content inference).

Verification

devtools test: semantic facts (40), insights (600), archive + refresh (321), delegations/profiles/runtime/resume (43) — all green. devtools verify --quick exit 0. Anti-vacuity: re-adding a keyword match to _classify_range or a prose scan to _terminal_state fails the updated honest-unknown tests; removing the new final-event rule fails test_..._detects_provider_error.

🤖 Generated with Claude Code

https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ

Summary by CodeRabbit

  • Bug Fixes

    • Improved session outcome detection by relying on verifiable runtime signals, avoiding potentially misleading text-based guesses.
    • Work-event labels now use observable actions for more consistent classification.
    • Status reports now show affected components as Unknown with diagnostic details when readiness checks fail, instead of omitting them.
  • Documentation

    • Updated guidance describing session outcomes, work-event classification, and supported provider error handling.
    • Refined demo coverage records to reflect a missing terminal-state verification case.
  • Tests

    • Updated coverage to validate unknown outcomes and visible readiness failures.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 44 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0b2b1354-cc36-4fd0-8d48-7ff47e95837f

📥 Commits

Reviewing files that changed from the base of the PR and between 765a953 and 62a0802.

📒 Files selected for processing (8)
  • docs/plans/demo-corpus-construct-audit.md
  • polylogue/archive/session/extraction.py
  • polylogue/archive/session/runtime.py
  • polylogue/insights/rigor.py
  • polylogue/storage/embeddings/materialization.py
  • tests/unit/archive/test_work_event_text_signals.py
  • tests/unit/core/test_semantic_facts.py
  • tests/unit/storage/test_session_insight_profiles.py
📝 Walkthrough

Walkthrough

Session terminal states and work-event labels now rely on structural evidence instead of archived prose. Direct status readiness reports component computation failures as unknown, with updated tests, rigor notes, and corpus audit records.

Changes

Structural session inference

Layer / File(s) Summary
Terminal-state structural inference
polylogue/archive/session/runtime.py, tests/unit/core/test_semantic_facts.py, polylogue/insights/rigor.py, docs/plans/demo-corpus-construct-audit.md, tests/unit/storage/test_session_insight_profiles.py
Terminal-state fallback keyword scanning and clean_finish classification are removed; missing structural evidence remains unknown, and tests and contract notes reflect raw structural evidence.
Structural work-event classification
polylogue/archive/session/extraction.py, polylogue/insights/rigor.py, tests/unit/core/test_semantic_facts.py
Work-event signals retain only action-category counts, so labels no longer depend on normalized user text or prose keyword matching.
Readiness failure reporting
polylogue/cli/commands/status.py, tests/unit/cli/test_status.py, polylogue/storage/embeddings/materialization.py
Direct readiness computation records failed components as unknown with exception details, while embedding provider error markers are documented as live HTTP-response evidence.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SessionEvents
  participant _terminal_state
  participant SessionProfile
  SessionEvents->>_terminal_state: provide typed tool-result status
  _terminal_state->>_terminal_state: track final typed error state
  _terminal_state-->>SessionProfile: return terminal state and raw evidence
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% 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 refactor: removing prose-keyword heuristics for terminal-state and activity-label classification.
Description check ✅ Passed The description covers Summary, Problem, Solution, and Verification, and the missing Changelog/Risks sections are acceptable for this refactor.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/kill-prose-keyword-heuristics

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.

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

ℹ️ 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/archive/session/runtime.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: 2

🤖 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 `@polylogue/archive/session/runtime.py`:
- Around line 286-294: Terminal block failures must be applied at assistant
boundaries, not merely collected. In
polylogue/archive/session/runtime.py:286-294, update the documented structural
sources to match terminal classification; at :303-320, preserve ordering
evidence distinguishing terminal failures from recovered actions; at :370-381,
classify boundary failed tool results as error_left. Add an unrecovered
block-error regression beside the recovery case in
tests/unit/core/test_semantic_facts.py:714-717, then regenerate
docs/plans/demo-corpus-construct-audit.md:11-12 and restore
error_terminal_state_rows coverage at :75.

In `@polylogue/cli/commands/status.py`:
- Around line 1952-1963: Update the three _component_computation_failure calls
in the embeddings, assertions, and transforms exception handlers to pass scopes
"semantic", "user", and "session-analysis", respectively, instead of relying on
the helper’s default "archive" scope. Preserve the existing component names and
exception propagation behavior.
🪄 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: 7f3227da-9e3c-4d4c-8921-bbef4ff08d00

📥 Commits

Reviewing files that changed from the base of the PR and between a62d2f9 and 765a953.

📒 Files selected for processing (10)
  • docs/plans/demo-corpus-construct-audit.md
  • polylogue/archive/session/extraction.py
  • polylogue/archive/session/runtime.py
  • polylogue/cli/commands/status.py
  • polylogue/insights/rigor.py
  • polylogue/storage/embeddings/materialization.py
  • tests/unit/archive/test_work_event_text_signals.py
  • tests/unit/cli/test_status.py
  • tests/unit/core/test_semantic_facts.py
  • tests/unit/storage/test_session_insight_profiles.py
💤 Files with no reviewable changes (1)
  • tests/unit/archive/test_work_event_text_signals.py

Comment thread polylogue/archive/session/runtime.py Resolved
Comment thread polylogue/cli/commands/status.py Resolved
@Sinity

Sinity commented Jul 16, 2026

Copy link
Copy Markdown
Owner Author

P1 addressed in the follow-up commit: new final-action-outcome rule (structural failure as the session's last tool outcome, cleared only by a later structural success — prose claims count in neither direction). Demo audit regenerated: error_terminal_state_rows 1/1 ok, verification problems cleared. 41 semantic-facts tests + 869 insights/archive/profiles tests + quick gate green.

Sinity and others added 3 commits July 16, 2026 22:19
…e and activity labels

Problem: two never-trusted prose-keyword heuristics survived long past
their measured expiry (polylogue-h01l, operator-directed via the ve9z
ladder decision): the _TEXT_SIGNAL_TABLE activity-type classifier
(accuracy never measured) and the _ERROR_MARKERS terminal-state fallback
plus its clean_finish complement (measured by 9e5.9 at 50.5% agreement
with structural truth on 14,377 real runs — a coin flip).

What changed:
- archive/session/extraction.py: deleted the keyword pattern tables,
  word-boundary compiler, and text-signal collection; WorkEventSignalBundle
  reduces to action-category counts (the write-only normalized_user_text
  accumulator went with it); _classify_range labels from structural action
  evidence only — no-tools ranges label SESSION, weak signals stay coarse
  IMPLEMENTATION instead of a keyword guess.
- archive/session/runtime.py: deleted _ERROR_MARKERS and both prose scans.
  _terminal_state is structural-only: tool-pairing, keystone
  tool_result_is_error/exit_code outcomes, and typed event status — plus
  one new structural rule: an event stream ENDING on a typed error output
  is terminal (error_left) regardless of trailing assistant prose. A
  recovered mid-session error no longer risks becoming error_left, and
  clean_finish is no longer emitted: without a structural terminal signal
  the honest state is unknown. All emitted evidence_class values are now
  raw_evidence.
- insights/rigor.py: both matrix notes rewritten to describe the
  post-deletion contract (regenerated demo-corpus audit doc rides along).
- Tests: five expectations moved to honest-unknown/structural semantics;
  the goal-outcome mapping test keeps clean_finish coverage via an explicit
  variant (persisted pre-deletion profiles still carry it, so the read-side
  mapping stays); tests/unit/archive/test_work_event_text_signals.py
  deleted — its sole obligation was the deleted keyword mechanism.

Verification: devtools test tests/unit/core/test_semantic_facts.py (40),
tests/unit/insights (600), tests/unit/archive + refresh module (321),
delegations/profiles/runtime/resume modules (43) — all passing;
devtools verify --quick exit 0.

Ref polylogue-h01l.

Co-Authored-By: Claude <[email protected]>
Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
CodeRabbit P1 on the heuristic deletion: Codex nonzero exit_codes are
lowered into failed tool-result blocks (not event status strings), so the
final-event rule alone dropped demo error_terminal_state_rows to 0. New
structural rule: a session whose FINAL tool outcome is a structural failure
with no later structural success is error_left — a later successful action
clears the flag (recovery is demonstrated structurally, never by prose, in
either direction). Recovered-error test now proves recovery via a
successful fallback action; new test pins the unrecovered Codex-shape
failure. Demo audit regenerated: error_terminal_state_rows 1/1 ok,
verification problems cleared.

Co-Authored-By: Claude <[email protected]>
Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
@Sinity
Sinity force-pushed the refactor/kill-prose-keyword-heuristics branch from 2db2a1f to 62a0802 Compare July 16, 2026 20:20
@Sinity
Sinity merged commit 682b29b into master Jul 16, 2026
@Sinity
Sinity deleted the refactor/kill-prose-keyword-heuristics branch July 16, 2026 20:20
Sinity added a commit that referenced this pull request Jul 20, 2026
#3226)

## Summary

Adds a session-level **objective-posture** projection — whether a
session's underlying goal remains open — derived from authority-bearing
evidence instead of process-termination text. It is separate from
`SessionInferencePayload.terminal_state` (how the process ended) and is
wired into the existing `INSIGHT_REGISTRY` `session_profiles` entry so
profiles, blocker extraction, resume ranking, and the context preamble
consume the same projection.

## Problem

`terminal_state` describes structural tool/turn evidence at the end of a
session, not whether its objective was resolved. Since polylogue-ve9z
(#2960, landed after this bead was filed) deleted the prose-derived
`clean_finish` heuristic — measured at 50.5% agreement (a coin flip)
with
structural truth — most well-behaved endings now collapse to
`terminal_state="unknown"`: silence, not a completion claim. Two
downstream consumers still effectively read that silence as "probably
done":

- Blocker-text extraction gated on a
`_UNRESOLVED_BLOCKER_TERMINAL_STATES`
  allowlist that never included `"unknown"`, so a session ending on a
  normal reply with an earlier user-reported blocker had that blocker
  text silently suppressed.
- Resume ranking's `_terminal_weight("unknown") == 0.25` (low), with a
  dead `terminal_state == "clean_finish"` exclusion filter that could
  never fire anymore.

## Solution

New `polylogue.insights.objective_posture` module defines
`ObjectivePosture` / `ObjectivePostureAuthority` and an explicit
authority order: `goal_graph` (polylogue-7yk5) > `work_evidence`
(polylogue-1vpm.6) > `assertion` > `structural_inference` > `none`. The
top two tiers are not yet built (both are open epics), so this PR lands
the two that are:

- `structural_objective_posture` — a bounded `terminal_state` mapping,
  `index.db`-only inputs, **never emits `"completed"`** (no structural
  signal available today observes a satisfied effect).
- `derive_objective_posture` — overlays durable `decision`/`blocker`/
  `handoff` `AssertionKind` rows (`user.db`), which outrank structural
  inference. Multiple simultaneous assertion kinds are preserved as
  `contradictions`, not silently collapsed.

The assertion tier is a **read-time overlay**
(`resolve_session_objective_posture`), not baked into the materialized
`session_profiles` row, so `index.db` stays independently rebuildable
from `source.db` without a `user.db` dependency.

**Wiring:**
- `enrichment.objective_posture` field on `SessionProfileInsight`
  (reconciled onto the native `terminal_state` column at read time —
  found and fixed in **both** existing reconciliation sites:
  `insights.archive.SessionProfileInsight.from_record` and the live
  SQL-backed `_session_profile_components_from_archive_row`).
- Blocker-text extraction now gates on the shared posture mapping
  instead of the old parallel allowlist.
- Resume ranking adds a posture-weighted score component and replaces
the dead `clean_finish` exclusion with `objective_posture !=
"completed"`.
- `resume_brief` overlays the full assertion tier for its single session
  and surfaces a durably-declared obligation as the first next-step.
- The context preamble surfaces posture per related session.
- `INSIGHT_REGISTRY` `session_profiles` entry gains `posture` /
  `posture_authority` display fields; FTS enrichment search text
  includes the posture label.

## Scope discrepancy vs. the bead text (honest disclosure)

The bead's AC1 example text ("terminal_state=clean_finish and
objective_posture=awaiting_operator simultaneously") references
`clean_finish`, which PR #2960 deleted the same day the bead was last
updated — that exact literal state no longer exists. The underlying
intent (a session with no structural error/pending signal must not be
silently treated as resolved) is fully addressed via the
`terminal_state="unknown"` case instead, and is directly covered by an
integration test
(`test_session_enrichment_payload_reuses_text_band_outputs`).

The `goal_graph` (polylogue-7yk5) and `work_evidence` (polylogue-1vpm.6)
authority tiers are reserved slots only — both are open epics with no
storage substrate yet. Wiring them in is a bounded follow-on: the
precedence order and `ObjectivePosturePayload` shape do not need to
change.

## AC matrix

1. **Partially satisfied / reframed.** A session with
`terminal_state="unknown"`
(the honest post-#2960 equivalent of the bead's `clean_finish` example)
gets `objective_posture.posture="ambiguous"`, and an active `decision`/
`handoff` assertion on that session elevates it to `"awaiting_operator"`
   — both simultaneously present, and resume ranking includes it
   (`objective_posture != "completed"` filter, plus the posture-weighted
score term). Verified in
`test_objective_posture.py::TestDeriveObjectivePosture::test_assertion_tier_outranks_structural_inference`.
2. **Satisfied** for the two available tiers. Typed `evidence_refs`,
   `authority`, `as_of`, and `contradictions` are all present on
   `ObjectivePosturePayload` and exercised by tests. `completed`,
`blocked`, `abandoned_inactive`, `awaiting_operator`, `awaiting_effect`,
   `ambiguous`, `unknown` are all in the `ObjectivePosture` vocabulary;
   only `abandoned_inactive`/`completed` are not reachable from the two
   currently-wired tiers (deferred to goal_graph/work_evidence).
3. **Satisfied.** `derive_objective_posture` always prefers the
assertion
tier over structural inference;
`test_self_reported_assertion_value_cannot_force_completed`
   proves a freeform assertion `value` claiming resolution cannot force
   `"completed"`.
4. **Satisfied.** `structural_objective_posture` never maps any
   `terminal_state` to `"completed"`; `test_never_emits_completed`
   parametrizes every known state. Removing the authority-order check in
   `derive_objective_posture` (returning structural whenever assertions
   exist) would make `test_assertion_tier_outranks_structural_inference`
   fail — the anti-vacuity anchor for this AC.
5. **Satisfied** for the wired consumers (profiles, blocker extraction,
   resume ranking, context preamble) — one shared function, no parallel
   terminal-state completion heuristic; the old
   `_UNRESOLVED_BLOCKER_TERMINAL_STATES` allowlist is deleted.
6. **Deferred.** No labeled live-sample precision/coverage run — out of
   scope for a single-lane PR without live archive access in this
   sandboxed worktree. Recorded as residual risk below.

## Verification

- `devtools test tests/unit/insights/test_objective_posture.py
tests/unit/storage/test_session_insight_profiles.py
tests/unit/core/test_resume.py
tests/unit/mcp/test_context_resume_intent.py
tests/unit/cli/test_context_view.py
tests/unit/api/test_facade_contracts.py
tests/unit/insights/test_rigor_audit.py` → 381 passed.
- `devtools test` over a broader plausibly-affected set (CLI
insights/check/query-exec-laws, core pricing/registry/readiness, cost
contract suite, devtools rigor-honesty, daemon web reader, storage
archive-tiers/user-state/session-profile-consistency/status-descriptors,
insights registry/no-metadata-cost-reads) → 601 passed, 1 xfailed, **3
pre-existing failures**
(`test_check_runtime_only_skips_archive_readiness`,
`test_exact_session_action_count_bounds_pairing_before_global_ranking`,
`test_operational_web_payloads_redact_configured_archive_paths`) —
reproduced identically on a pristine `origin/master` worktree with none
of this PR's changes present, confirming they are unrelated
pre-existing/environment failures, not regressions from this diff.
- `/realm/project/polylogue/.venv/bin/mypy` on every touched source +
test file → no issues.
- `/realm/project/polylogue/.venv/bin/ruff check` / `ruff format
--check` on every touched file → clean.
- `devtools render topology-projection && devtools render
topology-status` (new module) and `devtools render all --check` → sync
OK, no drift.
- `devtools verify --quick` (format + lint + mypy + render-all-check +
topology/layering/closure-matrix/schema-roundtrip/manifests/ci-workflows/doc-commands/docs-coverage/test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly)
→ exit 0, ran automatically via the pre-push hook too.
- Not run: `devtools verify --all` (full non-integration suite) —
testmon was unseeded in this worktree; seeding was judged out of scope
for a single-lane PR. Not run: `devtools verify --seed-testmon`.

Ref polylogue-37t.23
@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.

  • 58.F041 / P1: fixed-already at the checked revision: polylogue/archive/session/runtime.py:277 reads structural block outcomes, and lines 340-344 retain a final failed action outcome. The assistant-terminal branch at lines 428-437 now emits error_left for that evidence even when the source event omitted a status string.

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.

1 participant