Skip to content

fix(analysis): validate CLI options before sync and honor read-only digest/profile contracts - #265

Closed
saariuslystoned wants to merge 2 commits into
steipete:mainfrom
saariuslystoned:fix/analysis-cli-digest-profile-readonly-pass13
Closed

saariuslystoned wants to merge 2 commits into
steipete:mainfrom
saariuslystoned:fix/analysis-cli-digest-profile-readonly-pass13

Conversation

@saariuslystoned

@saariuslystoned saariuslystoned commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes CLI input validation ordering, digest period/date/count/account-selector contracts, and read-only deployment isolation across src/cli/register-analysis.ts, src/lib/period-digest.ts, and src/lib/profile-analysis.ts (touching zero files overlapped by #257–#264):

  1. Validate CLI options before autoUpdateBeforeRead (src/cli/register-analysis.ts):
    • Builds and validates options before autoUpdateBeforeRead() in today, digest, discuss, profile-analyze, and research, preventing invalid arguments from triggering automatic sync/backup mutations.
    • Shares normalizeProfileHandle inside buildProfileAnalysisOptions so invalid handles (e.g. @bad!handle, blank, >15 chars) fail with CliInputError before writable autoUpdateBeforeRead / maybeAutoUpdateBackup runs.
    • Rejects unknown digest [period] presets (period must be today, 24h, day, yesterday, week, or 7d) instead of silently coercing arbitrary strings to "today".
    • Validates digest --since / --until with Zod ISO date/datetime schemas (z.iso.date() / z.iso.datetime({ offset: true, local: true })) and enforces since <= until before sync.
    • Parses research --limit and --thread-depth via parsePositiveIntegerOption instead of raw Number(...).
  2. Digest window, non-negative counts, canonical account selector propagation, and read-only safety (src/lib/period-digest.ts):
    • Rejects unknown periods, impossible calendar dates (e.g. 2026-02-30), invalid hours (T24:00:00Z), trailing junk, and reversed windows (since > until) while preserving valid aliases (today, 24h, day, yesterday, week, 7d), leap days, equal instants, local ISO timestamps, and timezone offsets.
    • Enforces non-negative safe integers for maxTweets and maxLinks, honors 0 and small caps without clamping to 20/3 or issuing minimum-one read-model queries, and preserves exact cap values in latestDigestCacheKey.
    • Resolves known account selectors (id, username, case-insensitive @handle, surrounding whitespace) once via resolveDigestAccountSelector (findOperationAccount(getReadDb(), trimmed)?.id ?? trimmed), storing the canonical account ID in context.account, latestDigestCacheKey, and enrichContextWithCitedTweets (getTweetsByIds) so outside-window cited tweets belonging to the selected account hydrate for @handle aliases while other accounts stay isolated and unknown selectors stay empty.
    • Prevents live sync, uncached OpenAI generation, and cacheLatestDigest writes in read-only deployments (isReadOnlyDeployment()), while keeping existing cached digests readable.
  3. Profile analysis validation, preserved pacing environment fallback, Effect.either error channel, and read-only safety (src/lib/profile-analysis.ts):
    • Validates normalized handles (^[A-Za-z0-9_]{1,15}$) while preserving URL/@ normalization, rejects fractional/unsafe/negative integers on explicit positive count/page and non-negative pacing/retry options, preserves upstream a147813673ce default fallback for malformed BIRDCLAW_PROFILE_ANALYSIS_* environment overrides (including during cached reads), and wraps synchronous validation + getNativeDb() in trySync so defects surface cleanly through Effect.either before live transport.
    • Refuses uncached profile backfill and uncached report generation in read-only deployments while serving fresh cached backfills/reports without writes.

Real Shipped-CLI Reproduction (bin/birdclaw.mjs, Base 9895445 vs. Head fe99caa)

Executed against an isolated $BIRDCLAW_HOME SQLite store (npm run build:node):

1. Input Validation & Read-Only Guard Table

Command Base (9895445) Head (fe99caa)
birdclaw --json digest invalidpreset {"error":"Unknown account: default"} (coerced invalidpreset to today and entered live sync) {"error":"period must be today, 24h, day, yesterday, week, or 7d"} (exit 1 before sync)
birdclaw --json digest --since 2026-03-10 --until 2026-03-01 {"error":"Unknown account: default"} (accepted reversed window) {"error":"since must be before or equal to until"} (exit 1 before sync)
birdclaw --json digest --since 2026-02-30 {"error":"Unknown account: default"} (rolled impossible date over to March) {"error":"--since must be a valid YYYY-MM-DD or ISO timestamp"} (exit 1 before sync)
BIRDCLAW_DEPLOYMENT_READ_ONLY=1 OPENAI_API_KEY="" birdclaw --json digest --no-live-sync today {"error":"OPENAI_API_KEY is not set"} (attempted uncached generation in read-only mode) {"error":"No cached digest is available in this read-only deployment"} (exit 1, zero writes/requests)
birdclaw --json profile-analyze "@bad!handle" (writable, stale backup.autoSync: true) birdclaw backup auto-sync failed: ... then {"error":"spawn xurl ENOENT"} (attempted backup sync & xurl before handle check) {"error":"Profile handle must contain 1 to 15 letters, digits, or underscores"} (exit 1 before backup sync or transport)
birdclaw --json research --limit 0 topic Exited 0 with empty brief (Number("0") bypassed positive-int check) {"error":"--limit must be at least 1"} (exit 1 before autoUpdateBeforeRead)

2. End-to-End v0.17.0 Upgrade, Cached Read-Only Reads, Alias Hydration, Small Caps & Storage Invariance (Head fe99caa)

Seeded a disposable v0.17.0 archive (birdclaw --json init --demo + cached digest & profile-analyze seeded by base 9895445 bin/birdclaw.mjs against a loopback stub, plus outside-window cited tweet 2065597531644744901 on acct_primary and 2065597531644744902 on acct_secondary, then closed the stub and removed OPENAI_API_KEY and xurl):

=== WRITABLE BACKUP-ENABLED PRE-UPDATE VALIDATION (BASE vs HEAD) ===
$ node <base>/bin/birdclaw.mjs --json profile-analyze '@bad!handle'  # exit=1
stderr:
birdclaw backup auto-sync failed: ENOTDIR: not a directory, lstat '/dev/null/invalid-backup-repo'
{"error":"spawn xurl ENOENT"}
$ node <head>/bin/birdclaw.mjs --json profile-analyze '@bad!handle'  # exit=1
stderr:
{"error":"Profile handle must contain 1 to 15 letters, digits, or underscores"}

=== UPGRADED READ-ONLY CACHED DIGEST + '@STEIPETE' ALIAS + CITATION HYDRATION + SMALL CAPS ===
$ BIRDCLAW_DEPLOYMENT_READ_ONLY=1 node bin/birdclaw.mjs --json digest \
    --since 2026-01-01T00:00:00.000Z --until 2027-01-01T00:00:00.000Z \
    --account ' @STEIPETE ' --no-live-sync  # (v0.17.0 base-seeded cache) exit=0
{
  "cached": true,
  "account": "acct_primary",
  "hydratedPrimaryOutsideWindowCitation": true,
  "leakedSecondaryAccountCitation": false
}

$ BIRDCLAW_DEPLOYMENT_READ_ONLY=1 node bin/birdclaw.mjs --json digest \
    --since 2026-01-01T00:00:00.000Z --until 2027-01-01T00:00:00.000Z \
    --account ' @STEIPETE ' --max-tweets 1 --max-links 1 --no-live-sync  # exit=0
{
  "cached": true,
  "account": "acct_primary",
  "counts": { "home": 1, "mentions": 1, "authored": 0, "likes": 1, "bookmarks": 1, "dms": 0, "links": 1 },
  "tweetIds": ["tweet_001", "2065597531644744901"],
  "hydratedPrimaryOutsideWindowCitation": true,
  "leakedSecondaryAccountCitation": false
}

$ BIRDCLAW_DEPLOYMENT_READ_ONLY=1 node <base>/bin/birdclaw.mjs --json digest \
    --since 2026-01-01T00:00:00.000Z --until 2027-01-01T00:00:00.000Z \
    --account ' @STEIPETE ' --max-tweets 1 --max-links 1 --no-live-sync  # exit=1
stderr: {"error":"attempt to write a readonly database"}

$ BIRDCLAW_DEPLOYMENT_READ_ONLY=1 node bin/birdclaw.mjs --json digest \
    --since 2026-01-01T00:00:00.000Z --until 2027-01-01T00:00:00.000Z \
    --account '@steipete' --max-tweets 0 --max-links 0 --no-live-sync  # exit=0
{"cached":true,"account":"acct_primary","tweets":1,"links":0}

=== UPGRADED READ-ONLY CACHED PROFILE-ANALYZE + MALFORMED PACING ENV FALLBACK ===
$ BIRDCLAW_DEPLOYMENT_READ_ONLY=1 BIRDCLAW_PROFILE_ANALYSIS_CONVERSATION_DELAY_MS=-1 \
    node bin/birdclaw.mjs --json profile-analyze 'https://x.com/alice' \
    --account '@STEIPETE' --max-tweets 1 --max-pages 1 \
    --max-conversations 1 --max-conversation-pages 1  # exit=0
{
  "cached": true,
  "accountId": "acct_primary",
  "handle": "alice",
  "summary": "# @alice Cached v0.17.0 profile report."
}

=== PRESERVED SETTINGS & UNCHANGED STORAGE IN READ-ONLY MODE ===
{
  "configShaBefore": "e2cfdd64f1ae07b0d9b3bc3484388994ae6eab4bf1914758833bc10a66cd6aaa",
  "configShaAfter": "e2cfdd64f1ae07b0d9b3bc3484388994ae6eab4bf1914758833bc10a66cd6aaa",
  "configUnchanged": true,
  "dbShaBefore": "b7b860044f4e3c43f08cac7a0ba4ac169e66c3ba0606ab509c2b882a49014f58",
  "dbShaAfter": "b7b860044f4e3c43f08cac7a0ba4ac169e66c3ba0606ab509c2b882a49014f58",
  "sqliteBytesUnchanged": true,
  "syncCacheRowsBefore": 6,
  "syncCacheRowsAfter": 6,
  "syncCacheIdentical": true,
  "preservedSettings": {
    "accounts": { "default": "acct_primary" },
    "transport": { "preferred": "bird" },
    "backup": { "repoPath": "/dev/null/invalid-backup-repo", "autoSync": true, "staleAfterSeconds": 0 }
  }
}

Verification

Known gaps

GitHub Actions CI has not run on this head. The workflow is waiting for a maintainer to approve it. The verification above is local: unit tests and the shipped CLI against a local archive, not a live X account.

☁️

@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 9, 2026
@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codex review: needs maintainer review before merge.

What this changes

This PR validates analysis inputs before automatic updates, honors digest limits and account aliases, and serves cached analysis safely in read-only deployments.

Example: Run birdclaw --json profile-analyze '@bad!handle' with stale automatic backup sync enabled.

  • Before: Automatic backup updating runs before execution reaches the invalid handle.
  • After: The CLI rejects the handle before backup updating or live transport.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused repairs with shipped-CLI and upgrade evidence, both prior findings resolved, preserved original contracts, and no remaining actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied bin/birdclaw.mjs traces exercise early rejection with automatic backup enabled, read-only digest misses, and cached digest/profile success from a v0.17.0 archive, including canonical aliases, outside-window citation isolation, small caps, and malformed pacing fallback.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Invalid analysis inputs can trigger updates before rejection, explicit digest caps are enlarged, and read-only analysis can attempt live generation or writes.
Reason: These repairs enforce existing input and read-only contracts without introducing configuration or changing the established pacing fallback.

Merge readiness

✅ Ready for maintainer review

This PR fixes current analysis-command defects and resolves both previous findings; no remaining merge blockers were identified.

Priority: P2
Reviewed head: fe99caaafa1b675588495dcb000854ea49bba2ec

Before merge

None.

Findings

None.

Agent review details

How this fits together

Analysis commands consume CLI options and account-scoped SQLite data, optionally fetch live context, and return cached or generated reports.

flowchart TD
 CLI[Analysis commands] --> Validation[Input validation]
 Validation --> Backup[Automatic backup update]
 Backup --> Domain[Digest and profile analysis]
 Domain --> Archive[Account scoped archive]
 Domain --> Guard[Read only guard]
 Guard --> Generation[Live fetching and generation]
 Archive --> Output[Cached report output]
 Generation --> Output
Loading

Technical review

Best possible solution:

Land the focused repairs in the existing analysis owners while preserving pacing fallback and account-scoped cached reads.

Do we have a high-confidence way to reproduce the issue?

Current-main source exposes validation after automatic updates, enlarged digest caps, and unguarded read-only generation; supplied base/head CLI output corroborates those paths, and no target code was executed during this review.

Is this the best way to solve the issue?

The patch repairs the existing CLI and domain boundaries, preserves the shared report lifecycle and environment fallback, and completes the previously missing handle-validation and citation-hydration paths.

AGENTS.md: not found in the target repository.

Codex review notes: model internal, reasoning medium; reviewed against 9895445ba0a2.

Provenance checked

  • Digest periods, dates, and caps changes intended behavior with a stated reason (3b72f11: feat: add streaming period digest #36 introduced streaming digest collection and scoped caching without specifying silent acceptance of invalid presets or enlargement of explicit limits.)
  • Digest freshness and citation hydration keeps the original intent (bcf0d4f: fix: stabilize Today digest reloads #55 preserves fresh reports and hydrates out-of-window citations while enforcing account boundaries.)
  • Profile pacing environment fallback keeps the original intent (a147813: The throttling change added pacing defaults, malformed-environment fallback, and rate-limit retries; the updated head retains that fallback.)
  • Strict input and account contracts keeps the original intent (15f831b: refactor: remove duplicate query and account seams #128 established strict invalid-input handling and centralized account selection.)
  • Analysis report lifecycle ownership keeps the original intent (0a86beb: refactor: centralize analysis report lifecycle #206 centralized generation and persistence while retaining collection, versioned cache identities, freshness, and citation enrichment in domain modules.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production and test changes Production +183/-54 lines; tests +676/-3 lines The larger test contribution covers distinct validation ordering, numeric boundaries, alias hydration, cache behavior, and read-only cases.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.
  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: The PR repairs bounded analysis-command and read-only deployment defects without evidence of an urgent widespread outage.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-09T07:29:01.903Z sha 6f797e7 :: needs real behavior proof before merge. :: [P2] Validate profile inputs before automatic backup updates | [P2] Carry the resolved account ID into digest citation hydration

Reviewed November 9, 2026, 2:48 AM ET / 07:48 UTC (Revision 2).

…lias citations, and preserve pacing env fallback
@saariuslystoned

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 9, 2026
steipete added a commit that referenced this pull request Nov 14, 2026
Consolidate verified fixes from #257, #258, #259, #260, #261, #262, #263, #264, and #265. Repair account selection, cache restoration, search bounds, input validation, and read-only analysis while preserving existing account and data-safety contracts. Also reject unsafe Git indexes before backup publication and keep recovery snapshots private.

Co-authored-by: Bobby Bones <saariuscrypto@gmail.com>
Co-authored-by: sm0ky <smokyproductcompany@gmail.com>
@steipete

Copy link
Copy Markdown
Owner

Thanks for the fixes. I reproduced the reported defects against v0.17.0 and consolidated analysis validation before automatic updates, canonical digest account scoping, and read-only cached report behavior into #266, now landed. The overlapping cache ingestion changes from #257 and #261 are included once.

The consolidation preserves contributor credit in the changelog and squash commit. Synthetic regressions, independent P0–P2 review, and exact-head CI cover the result; no paid X requests were used. Closing this PR as superseded by the landed consolidation.

@steipete steipete closed this Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants