Skip to content

feat(bin): add slack-captain process-event-source adapter - #4

Merged
digbycampbell merged 3 commits into
mainfrom
fm/fm-slack-adapter
Aug 16, 2026
Merged

digbycampbell merged 3 commits into
mainfrom
fm/fm-slack-adapter

Conversation

@digbycampbell

Copy link
Copy Markdown
Owner

Intent

Build the slack-captain process-event-source adapter for firstmate, so messages the captain posts in the Slack #captain channel wake the primary firstmate. This changes firstmate's SHARED TRACKED material, so the firstmate-coding-guidelines skill applies throughout: one-owner rule (every contract stated in full exactly once, other mentions are one-line cross-references), the knowledge-placement decision tree, shellcheck clean via bin/fm-lint.sh, the bin script header owns exact mechanics rather than prose elsewhere, and one full sentence per line in tracked Markdown.

Deliverables, all in this one PR:

  1. bin/fm-procevent-slack-captain.sh - an adapter for the generic runner in bin/fm-procevent.sh, which registers sources whose adapter must exist at bin/fm-procevent-.sh. It owns: arm (register plus its own poll child), classify (returns messages / untrusted-messages / empty / api-error / unknown, and is NEVER terminal - the source re-arms indefinitely), handle guidance in --help, and a retire passthrough. It follows the arm/handle/retire command shapes of the existing bin/fm-procevent-lavish.sh and bin/fm-procevent-remote-reply.sh adapters. The poll child has cursor-file continuity (no message loss across restarts within Slack's retention; a cursor break surfaces loudly rather than silently rebasing), bounded runtime with silent exit on no traffic so the runner's reconcile re-arms, curl --max-time, and no shell interpretation of message text anywhere (every byte is data, per the process-event-sources SKILL's input-never-instruction rule).
  2. Security invariants, enforced not just documented: the token never appears in argv or in captured output; messages from any user OTHER than the configured allowed_user are marked untrusted in the result and distinguished by classify; result files inherit the runner's 0600.
  3. Tests: colocated tests/fm-procevent-slack-captain.test.sh per existing tests/ patterns, with a fake curl via PATH shim so CI makes no network call, covering new-message capture plus cursor advance, bot-post filtering, non-allowed-user marking, cursor-break loud failure, and token-absent refusal. bin/fm-lint.sh clean.
  4. Docs: the adapter header owns mechanics; one line in .agents/skills/process-event-sources/SKILL.md's arming section naming the new adapter; the config keys in docs/configuration.md following its existing per-key section style.

Explicit constraints the captain set, which a reviewer reading only the diff would not know:

  • The Slack channel id and bot user id MUST be configuration, never hardcoded: they are read from an optional config/slack-captain file with channel=, bot_user=, allowed_user= lines, documented in the adapter header and in docs/configuration.md.
  • The bot token comes from the home's gitignored .env as SLACK_BOT_TOKEN, and must never appear in argv and never be logged. It is therefore passed to curl through --config - on stdin.
  • NO AGENTS.md change was required, and that was checked deliberately: section 13's process-event-sources trigger already covers procevent wakes generically, so a new adapter needs no new inline entry. The absence of an AGENTS.md change is intentional, not an oversight.
  • A working prototype poll loop existed at the primary home's state/slack-captain-poll.sh and was used only as reference; it is not part of this repo and was not copied.

Deliberate design decisions I made while implementing, which differ from that prototype on purpose:

  • The poll child NEVER advances the stored cursor. It reports from_ts and to_ts in the result header instead, and the read position advances only in handle/autohandle, strictly after the runner has durably captured the result. The prototype advanced the cursor before printing, which loses messages if the process dies before the runner reads its output; this ordering removes that pre-capture loss window. A result that does not continue the stored cursor is refused loudly and the cursor is never silently rebased.
  • autohandle deliberately reports failure after advancing the cursor, so the runner leaves the result unacknowledged. Unlike a remote-reply delta that is applied into durable state, the captured Slack result IS the deliverable and only firstmate can read it, so it must stay eligible for re-announcement until firstmate acknowledges it. handle is the firstmate-facing command that advances the read position and records the acknowledgement together. This intentional nonzero exit is documented in the adapter header and asserted in the tests; it is not a bug.
  • On a quiet channel the poll exits NONZERO with empty output rather than exiting 0 silently as the prototype did. The runner only treats a result as absent when the child exits nonzero AND produces no output, so exiting 0 with empty output would publish an empty wake on every cycle. Nonzero-and-empty makes the runner record no-result and leave the source armed.
  • terminal always exits 1: the captain can always post again, so this source is never terminal.
  • An absent allowed_user marks every author untrusted, because trust is granted only by configuration.
  • Fatal Slack errors (invalid_auth, missing_scope, channel_not_found and similar) become an api-error result so they reach the captain, while transient errors such as ratelimited are simply retried within the bounded loop.
  • The adapter reuses fmx_env_get from bin/fm-x-lib.sh as the repo's single .env reader rather than duplicating that parser, with a comment noting the fmx_ prefix records where it was first needed rather than a Relay-only scope.
  • POLL_TMP is deliberately a global rather than a local because the EXIT trap runs outside function scope; a local there leaked the staging directory and printed an unbound-variable error under set -u on every poll. That was a real bug found by live verification and fixed, with a regression check that the poll is silent and leaves nothing behind.

Verification performed beyond the unit tests: the full path was exercised against the real Slack API read-only in a throwaway home, proving arm, runner start, real conversations.history call, 0600 capture, wake publication, classify reporting messages with the configured captain trusted, handle advancing the cursor and recording the acknowledgement, and the source remaining armed afterwards.

What Changed

  • Add bin/fm-procevent-slack-captain.sh, a process-event-source adapter that polls the Slack #captain channel and wakes the primary firstmate: arm registers the source and spawns a bounded poll child with cursor-file continuity (cursor advances only in handle/autohandle after the runner captures the result; cursor breaks fail loudly), classify distinguishes messages / untrusted-messages / empty / api-error / unknown and is never terminal, and the token is read from .env via fmx_env_get and passed to curl on stdin so it never appears in argv or logs. Messages from anyone other than the configured allowed_user are marked untrusted, and message text is treated purely as data.
  • Add tests/fm-procevent-slack-captain.test.sh with a fake-curl PATH shim (no network in CI), covering new-message capture with cursor advance, bot-post filtering, non-allowed-user untrusted marking, cursor-break loud failure, and token-absent refusal.
  • Document the adapter: channel/bot_user/allowed_user config keys and the FM_SLACK_CAPTAIN_MAX_PAGES tuning variable in docs/configuration.md, and a one-line arming entry in the process-event-sources SKILL.md.

Risk Assessment

✅ Low: All three authorized round-1 fixes are correctly implemented with behavioral regression tests, the pagination invariant and security constraints (token on stdin only, bounded runtime) are preserved, and the only residuals are a one-line doc omission and a deliberate bounded-refusal trade-off.

Testing

Ran the adapter's colocated behavior suite (16/16 pass, network replaced by a PATH curl shim) covering capture with cursor advance, bot filtering, untrusted marking, cursor-break loud refusal, token-absent refusal, pagination, api-error handling, and a runner round-trip; then performed a manual end-to-end demonstration through the generic runner and recorded a transcript showing arm, capture with 0600 perms, wake publication, classify, token confinement to stdin, handle advancing the cursor, and the source remaining armed. No screenshot applies — this is a CLI/daemon change with no rendered surface; the CLI transcript is the end-user surface.

Evidence: End-to-end CLI transcript: arm → runner capture → classify → handle
$ fm-procevent-slack-captain.sh arm   (FM_HOME points at a demo home; Slack replaced by a PATH curl shim)
registered: slack-captain-C0DEMO (slack-captain)
armed: slack-captain-C0DEMO

$ fm-procevent.sh start slack-captain-C0DEMO   (generic runner polls, captures, publishes wake)
not-autohandled: slack-captain-C0DEMO (left for the handler; still unacknowledged)
captured: /tmp/tmp.KIZfKTLGXE/home/state/procevent-inbox/slack-captain-C0DEMO.1.result

$ ls -l captured result (0600 expected)
-rw------- 1 digby digby 223 Aug 16 09:20 /tmp/tmp.KIZfKTLGXE/home/state/procevent-inbox/slack-captain-C0DEMO.1.result

$ cat result
schema=fm-slack-captain.v1
status=messages
channel=C0DEMO
from_ts=0
to_ts=1755300000.000100
count=1
untrusted=0
reason=

{"ts":"1755300000.000100","user":"U0CAPTAIN","trusted":true,"text":"ahoy firstmate, please check CI"}

$ classify result
messages

$ wake queue entry
1786839614	1	check	procevent:slack-captain-C0DEMO:1	check: procevent slack-captain slack-captain-C0DEMO 1

$ grep token in curl argv and result (must be absent; token travels via --config - on stdin)
/tmp/tmp.KIZfKTLGXE/home/state/procevent-inbox/slack-captain-C0DEMO.1.result:0
/tmp/tmp.KIZfKTLGXE/argv:0
token absent from argv and result: OK
token seen on curl stdin (times): 1

$ handle slack-captain-C0DEMO 1 (acknowledges and advances read position)
handled: slack-captain-C0DEMO 1
applied: slack-captain-C0DEMO read-position=1755300000.000100

$ cursor after handle
schema=fm-slack-captain-cursor.v1
ts=1755300000.000100

$ source still armed:
slack-captain-C0DEMO.source

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 2 infos
  • ⚠️ bin/fm-procevent-slack-captain.sh:273 - cmd_poll issues a single conversations.history call with limit=$PAGE_LIMIT (default 200) and ignores has_more. Slack returns newest-first, so a burst of more than PAGE_LIMIT messages past the cursor drops the oldest ones while to_ts commits the newest timestamp; handle then advances the cursor past the never-captured messages — silent loss within retention, contradicting the intent's cursor-continuity/no-loss-within-retention requirement. Fix at the poll boundary: detect has_more (or count == PAGE_LIMIT) and paginate to exhaustion, or cap to_ts at the oldest fetched message so the next poll captures the remainder.
  • ⚠️ bin/fm-procevent-slack-captain.sh:392 - An api-error result can never be acknowledged through the adapter: apply_result dies for any class other than messages/untrusted-messages, yet the new SKILL.md line names the adapter's handle as "the required handling command". An api-error wake therefore re-announces indefinitely unless firstmate bypasses the adapter with raw fm-procevent.sh handled. Either let handle acknowledge api-error (the cursor advance is already a no-op since from_ts == to_ts) or document the intended retirement path in the header/SKILL — this challenges a deliberate design choice, so asking the author.
  • ℹ️ bin/fm-procevent-slack-captain.sh:290 - When the ok:true jq extraction pipeline fails (e.g., a malformed message ts breaks tonumber), || : > "$payload" treats the page as empty and the bounded loop silently retries until no-traffic exit. No cursor advance occurs so nothing is lost, but a persistently malformed page degrades into quiet no-result cycles with no diagnostic; a one-line stderr note or die on repeated jq failure would surface it.

🔧 Fix: paginate poll windows, acknowledge api-error, surface jq failures
2 infos still open:

  • ℹ️ docs/configuration.md:503 - docs/configuration.md's Slack captain section enumerates the tuning variables FM_SLACK_CAPTAIN_MAX_LOOPS, INTERVAL, MAX_TIME, and PAGE_LIMIT, but omits FM_SLACK_CAPTAIN_MAX_PAGES introduced by the pagination fix (referenced in the adapter header). Add it to the list to keep the enumeration complete.
  • ℹ️ bin/fm-procevent-slack-captain.sh:317 - When a window past the cursor exceeds FM_SLACK_CAPTAIN_MAX_PAGES (default 25 pages, ~5000 messages), every poll dies loudly and the source re-arms into the same refusal until an operator intervenes. No message is lost and the intent forbids an unbounded fetch, so this is a deliberate bounded-runtime trade-off, not a defect.
✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-procevent-slack-captain.test.sh (16/16 pass, fake curl PATH shim, no network)
  • manual e2e: arm → fm-procevent.sh start → captured 0600 result → classify=messages → wake-queue entry → handle advances cursor → source still armed
  • token confinement check: token absent from curl argv and captured result, present once on curl stdin via --config -
  • docs presence check: SKILL.md arming line and docs/configuration.md config/slack-captain section
  • git status clean after cleanup of temp home and shim
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Register a bounded long-poll of a configured Slack channel as a
process-event source, so a message the captain posts there reaches
firstmate as an ordinary check wake.

The source is never terminal, so a quiet channel exits nonzero with no
output and the runner's reconcile re-arms it without publishing an empty
wake. The poll child never advances the stored read position; that
happens only after the result is durably captured, so a crash cannot
skip messages, and a result that does not continue the stored position
is refused loudly rather than rebased.

The bot token is read from the home's .env inside the poll child and
handed to curl on stdin, so it never reaches argv, a registration
record, a captured result, or a diagnostic. Channel and identities are
configuration, and any author other than the configured captain is
marked untrusted in the result and distinguished by classify.
@digbycampbell
digbycampbell merged commit 44c386d into main Aug 16, 2026
13 checks passed
@digbycampbell
digbycampbell deleted the fm/fm-slack-adapter branch August 23, 2026 04:06
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