Skip to content

feat(portal): add durable private connector - #839

Closed
skeng77 wants to merge 6 commits into
kunchenguid:mainfrom
skeng77:fm/portal-connector-8c5
Closed

skeng77 wants to merge 6 commits into
kunchenguid:mainfrom
skeng77:fm/portal-connector-8c5

Conversation

@skeng77

@skeng77 skeng77 commented Jul 22, 2026

Copy link
Copy Markdown

What Changed

  • Adds a durable private portal connector: new bin/fm-portal-* scripts (shared lib plus config, poll, request, reply, followup, and link commands) that let the watcher poll a private portal for captain messages and deliver replies, with body-free durable records, token redaction in state, lock-guarded replay-safe state transitions, and wiring into bootstrap, session-start, guards, and fm-watch.sh.
  • Includes follow-up hardening from review: claimed portal work is never re-offered, record scans consolidated to a single jq pass, stale portal task links cleared after deferred-ack poller completion, and watcher identity fixed for X polls.
  • Adds a hermetic test harness — tests/fixtures/fake-portal.py and a 12-scenario tests/fm-portal-connector.test.sh end-to-end suite — plus a new portal-respond skill and updated configuration, architecture, and supervision-protocol docs.

Risk Assessment

✅ Low: The fix round resolves the claimed-request duplicate-execution error and the poll-cost warning exactly as instructed, with behavior-parity in the rewritten scan paths, deterministic regression tests that fail under the old behavior, and only one minor defense-in-depth nuance remaining; the feature stays opt-in and inert by default.</risk_rationale>

Testing

Ran the new fm-portal-connector end-to-end suite (12/12 scenarios pass with a real loopback HTTP fake portal) plus the six other test suites modified by this change (all pass), and captured a manual CLI transcript demonstrating the complete connector lifecycle — install, poll signal, claimed-work no-re-offer, read, idempotent reply verified server-side by body hash and acknowledgement, durable body-free records, token redaction, and disable back to inert.

Evidence: End-to-end portal connector CLI transcript (install → message → poll → read → reply → server-verified ack → redaction → disable)

$ fm-portal-poll.sh portal-message 1 $ fm-portal-request.sh mark-queued 1 $ fm-portal-poll.sh (no output — queued work is not re-offered) $ fm-portal-request.sh read 1 {"id":1,"body":"Please summarize the deploy status for me.","created_at":"2026-07-21T00:00:01.000Z"} $ fm-portal-reply.sh 1 --text-file reply.txt 1 $ GET /_test/stats { "reply_count": 1, "reply_hashes": ["c8e364aa…"], "acknowledged_ids": [1] } reply body hash matches sha256 of the agent's reply text: VERIFIED captain message 1 acknowledged as delivered: VERIFIED token absent from all connector state files (config file mode 600)

### 1. Unconfigured connector is a hard no-op (no output, no state written)

$ FM_HOME=$HOME fm-portal-poll.sh
(exit 0; state dir created: no)

### 2. Install connector config (token passed on stdin, never argv)

$ fm-portal-config.sh install --token-stdin --base-url $BASE_URL
portal connector: configuration installed for http://127.0.0.1:35357; run the next locked session start to activate polling

$ fm-portal-config.sh status
portal connector: enabled (http://127.0.0.1:35357, config mode 0600)

### 3. Captain sends a message through the portal
portal now holds captain message id=1

### 4. Watcher poll surfaces the message as a body-free signal line

$ fm-portal-poll.sh
portal-message 1

### 5. Watcher queues it durably; a queued/claimed request is never re-offered

$ fm-portal-request.sh mark-queued 1
$ fm-portal-poll.sh
(no output — queued work is not re-offered: '')

### 6. Agent claims and reads the request (the only place the body prints)

$ fm-portal-request.sh read 1
{"id":1,"body":"Please summarize the deploy status for me.","created_at":"2026-07-21T00:00:01.000Z"}


### 7. Agent replies durably (idempotent transaction; prints only the id)

$ fm-portal-reply.sh 1 --text-file reply.txt
1

### 8. Portal server confirms: reply stored and captain message acknowledged
$ GET /_test/stats
{
  "reply_count": 1,
  "reply_hashes": [
    "c8e364aaee539173f237002e3519a3ae28f5ccfa3a99752e8c86480c43135bb0"
  ],
  "acknowledged_ids": [
    1
  ]
}
reply body hash matches sha256 of the agent's reply text: VERIFIED
captain message 1 acknowledged as delivered: VERIFIED

### 9. Durable local record reaches terminal state (no message body stored)

$ cat state/portal/records/1.json
{
  "schema": "fm-portal-record.v1",
  "request_id": 1,
  "request_sha256": "ff7b5d81a46e48906ff411e1489177bf4bbbc0a66e6716f195190bbc745d79c7",
  "state": "complete",
  "task_id": "",
  "received_at": 1784692703,
  "updated_at": 1784692708,
  "claimed_at": 0
}

### 10. Redaction: the bearer token never appeared above or in any state file
token absent from all connector state files (config file mode 600)

### 11. Disable returns the connector to inert

$ fm-portal-config.sh disable
portal connector: disabled; run the next locked session start to remove polling artifacts
$ fm-portal-poll.sh
(no output after disable: '')
Evidence: fm-portal-connector test suite output (12/12 scenarios pass)
ok - portal connector is a hard no-op until explicitly configured
ok - config install, validation, permissions, and redaction are guarded
ok - poll, cursor, duplicate, restart, and durable wake behavior converge
ok - poll errors, retries, response bounds, and batch bounds are deterministic
ok - reply idempotency, malformed responses, crash windows, and acknowledgement order converge
ok - cumulative portal acknowledgements are serialized oldest-first
ok - idempotency-key conflicts stop without duplicate reply or acknowledgement
ok - long-running work returns exactly once to its originating portal channel
ok - credentials and message bodies stay out of output, wakes, and logs
ok - portal wake integration is shared across all harnesses, backends, and away mode
ok - expired leases re-offer stale queued notifications but never claimed work
ok - completed retention is bounded and disablement returns to inert behavior

Pipeline

Updates from git push no-mistakes

⏭️ **intent** - skipped

✅ No issues found.

🔧 **Rebase** - 2 issues found → auto-fixed ✅
  • ⚠️ docs/configuration.md - merge conflict rebasing onto origin/main
  • ⚠️ docs/scripts.md - merge conflict rebasing onto origin/main

🔧 Fix applied.
✅ Re-checked - no issues remain.

⚠️ **Review** - 1 info
  • ⚠️ bin/fm-portal-lib.sh:531 - Every poll cycle spawns O(records) jq processes while holding FMP_LOCK: the resume scan (fm-portal-poll.sh:60) runs fmp_record_load (~4 jq calls) per record, and fmp_prune_completed re-validates and re-reads state for every record up to three more times (age loop, count pipeline, removal pipeline). At the default retention cap of 256 completed records this is roughly 2,000+ jq invocations per 30-second cycle, and the whole poll runs under the watcher's timeout $CHECK_TIMEOUT (default 30s, fm-watch.sh:467). On a slow or loaded host a full retention window can push the poll past the timeout, in which case it is killed before printing anything — notifications stall silently with no portal-error emitted. Consolidating each directory scan into a single jq pass (or caching validation results within one run) would remove the risk without changing behavior.
  • ℹ️ bin/fm-bootstrap.sh:757 - Dead code in portal_mode_setup's invalid-config branch: [ &#34;$had_artifacts&#34; -eq 0 ] || return 0 immediately followed by return 0 — both paths return 0, so the conditional (and the had_artifacts bookkeeping feeding it) has no effect and can be dropped.
  • ℹ️ bin/fm-portal-followup.sh:40 - A task's portal_request= meta link can be stranded when the reply completes via the poller's resume path instead of a fm-portal-followup.sh retry: followup exits 5 when an earlier request blocks the cumulative ack (fm-portal-reply.sh:181-184), leaving the link in place; if the poller later completes the record, nothing re-notifies the agent to retry followup, and fm-portal-link.sh then refuses to link any new request to that task ("task is already linked to another portal request") until the meta is manually cleaned. Consider having the poller's linked/replying recovery, or recover-unclaimed, clear meta links whose record is already complete.
  • ℹ️ bin/fm-portal-reply.sh:90 - fm-portal-reply.sh holds FMP_LOCK across all network I/O (acquired at line 90, released only by the EXIT trap): the POST can take up to ~24s (max-time 8s x 3 attempts) plus the ack round-trip. A concurrent watcher poll spins on the lock for that whole time and can itself be killed by CHECK_TIMEOUT. The state is durable so this self-heals on the next cycle, but releasing the lock around the two HTTP calls (state transitions are already replay-safe) would avoid the wasted watcher cycles.
  • ℹ️ bin/fm-portal-poll.sh:8 - fm-portal-poll.sh's header documents the output contract as portal-message &lt;id&gt; [&lt;id&gt; ...] (and fm-watch.sh's mark-queued handler parses multiple ids), but the implementation only ever prints the single oldest pending id (line 209-221). Harmless — the consumer handles both — but the contract comment overstates what is emitted.

🔧 Fix: Never re-offer claimed portal work; single-pass record scans
1 info still open:

  • ℹ️ bin/fm-portal-lib.sh:346 - fmp_records_scan's || return 1 on the jq invocation does not fire for an invalid record in the middle of the directory: verified on both jq 1.6 and 1.7, error(&#34;invalid record&#34;) on a non-final input prints to stderr and jq still exits 0 (only a failing final input yields exit 5). The fail-closed contract therefore rests entirely on the line-count backstop, which a contrived compensating corruption (one record file holding two schema-valid concatenated JSON values plus one invalid file) could balance out. Practical impact is negligible — records/ is owner-only 0600/0700 state and anyone able to craft such files could simply write a fully valid record instead — but replacing error(&#34;invalid record&#34;) with halt_error would make jq abort with a nonzero status at the first invalid record, making the documented "any invalid payload fails the whole scan" guarantee unconditional.
✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-portal-connector.test.sh — all 12 end-to-end scenarios pass against the hermetic fake portal
  • bash tests/fm-bootstrap.test.sh (exit 0)
  • bash tests/fm-session-start.test.sh (exit 0)
  • bash tests/fm-turnend-guard.test.sh (exit 0)
  • bash tests/fm-x-mode.test.sh (exit 0)
  • bash tests/fm-arm-pretool-check.test.sh (exit 0)
  • bash tests/fm-supervision-instructions.test.sh (exit 0)
  • Manual end-to-end CLI walkthrough: started tests/fixtures/fake-portal.py, ran fm-portal-config.sh install/status, injected a captain message, fm-portal-poll.sh emitted the body-free portal-message 1 signal, mark-queued suppressed re-offer (head-commit behavior), fm-portal-request.sh read printed the body, fm-portal-reply.sh delivered the reply — verified on the server via sha256 body hash and acknowledged_ids — then confirmed body-free durable record, token redaction in state, and inert behavior after disable
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 warning
  • ⚠️ linter found issues (exit code 127)

🔧 Fix: suppress SC2016 false positive on portal record schema jq
1 warning still open:

  • ⚠️ linter found issues (exit code 127)

🔧 Fix: clear stale portal task links after deferred-ack poller completion
1 warning still open:

  • ⚠️ linter found issues (exit code 127)
✅ **Push** - passed

✅ No issues found.

@skeng77
skeng77 force-pushed the fm/portal-connector-8c5 branch from 3c45b00 to d2273b8 Compare July 22, 2026 05:29
@kunchenguid

kunchenguid commented Jul 23, 2026 •

Copy link
Copy Markdown
Owner

Automated reminder: thanks for the PR! This branch currently has a merge conflict with the base branch.

When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again.

Noted for firstmate#839 at 830627ee.

@kunchenguid

Copy link
Copy Markdown
Owner

Automated reminder: this PR still looks blocked on a rebase or merge conflict fix.

If you are still interested, please rebase onto the current base branch, resolve the conflict, and push.

If I do not hear back, I may close this as inactive.

@kunchenguid

Copy link
Copy Markdown
Owner

I am closing this because it has been waiting on a rebase or merge-conflict fix since 2026-07-23, and I have not seen a comment or push since then.

If you still want to keep working on this, please reopen it or open a new PR and mention this one.

Happy to take another look when there is an update.

@kunchenguid kunchenguid closed this Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants