Skip to content

feat(extensions): bind trusted external process-event adapters - #3192

Closed
M00NLIG7 wants to merge 17 commits into
kunchenguid:mainfrom
M00NLIG7:fm/firstmate-private-overlay-extension-architecture-v1-t7
Closed

M00NLIG7 wants to merge 17 commits into
kunchenguid:mainfrom
M00NLIG7:fm/firstmate-private-overlay-extension-architecture-v1-t7

Conversation

@M00NLIG7

Copy link
Copy Markdown
Contributor

Intent

Implement the smallest ergonomic, upstream-reviewable, vision-aligned Firstmate extension binding contribution on the exact fetched default-branch HEAD of github.com/kunchenguid/firstmate, and open a public PR against that exact repository without merging it. The first contribution must be a genuinely usable end-to-end vertical slice for trusted external process-event-adapter/1 adapters—not framework scaffolding: an external adapter must be registerable, configurable, discoverable from an explicit home-local registry, strictly validated, invokable, and safely retired, with a minimal runnable example, concise operator documentation, and executable-interface conformance/integration tests. Keep it narrow to this one extension type and aligned with Firstmate's explicit opt-in, flat, inspectable, deterministic, vendor-independent operating model; do not add lifecycle sinks, delivery-provider plugins, dynamic runtime backends, worker-launch grants, arbitrary before/after hooks, brief or instruction injection, project-local discovery, or any private names, paths, credentials, policy, behavioral constants, packages, or code.

An absent binding registry must remain permanently inert and state-free, preserve all built-in process-event behavior, and impose only a bounded cheap absence check. Discovery must read only explicit home-local bindings under the repository's configuration ownership conventions; project files, current directories, worker text, task copies, environment variables, and Pi packages must not register extensions. Separate a package manifest from a per-home enabled binding, pinning exact extension identity/version, host protocol, process-event-adapter/1 capability/version, allowed adapter names, canonical package root, complete code-tree digest, enabled capability subset, and required explicit consent facts. Provide repository-native setup, verification, inspection, registration, invocation, and retirement commands so operators do not hand-author opaque hashes or duplicate generated state.

Never source, eval, or shell-expand extension code. Invoke one exact executable without a shell using strict bounded UTF-8 JSON on stdin/stdout, bounded stderr, exact request identity, deterministic version negotiation, and a fixed handshake/invocation contract. Before accepting evidence, validate package-root confinement, same-user ownership and safe modes, canonical paths, symlink and hard-link hazards, manifest and complete-tree integrity, executable identity, protocol/capability agreement, response schema and size, timeout, process cleanup, and request-id matching. State honestly that this is trusted same-user code, not an OS sandbox. Keep lifecycle and authority transitions in existing Firstmate core owners: extension bytes are untrusted evidence and never authorize captain decisions, merges, destinations, force, discard, cleanup, credential use, or stronger operations.

Extend process-event registration to pin extension identity, capability version, package digest, and an owner identity, and require owner-matched conditional retirement so a stale owner cannot retire a replacement. Preserve built-in adapter behavior and compatibility during the documented migration window. Put each contract in exactly one current owner: docs/configuration.md for home-local layout, a focused maintainer architecture document for manifest/envelope/capability contracts, script headers and --help for mechanics, concise process-event supervision cross-references, and current repository verification evidence. Do not inflate AGENTS.md with conditional procedure.

Conformance coverage must exercise absent-registry parity; manifest, path, mode, owner, link, and full-tree digest checks; handshake and deterministic negotiation; malformed, invalid-UTF-8, unknown, duplicate-key, and oversized JSON; bounded stderr; timeout and process-tree cleanup; crashes, nonzero exits, and missing executables; replay/idempotence and request identity; owner-matched retirement; unhandled captured output; authority-injection attempts; and independent local and remote-home paths. Tests must validate executable interfaces, not implementation-source bytes. Inspect every supported primary worker runtime and session-provider integration ownership boundary and mark an axis not applicable only after real inspection. Run the current repository's lint, documentation-audience checks, focused tests, broad tests, and maintainer verification, reviewing the complete final branch diff after every automated correction. Use GitHub author/committer M00NLIG7 [email protected]. The PR title should be "feat(extensions): bind trusted external process-event adapters" unless current upstream conventions require a clearer equivalent. The authorized PR base is exactly github.com/kunchenguid/firstmate; do not merge the PR.

What Changed

  • Add explicit home-local binding, inspection, verification, invocation, remote transfer, and safe retirement workflows for trusted external process-event-adapter/1 packages.
  • Integrate extension-backed sources with process-event registration, supervision, classification, and owner-matched retirement while preserving built-in adapters and inert absent-registry behavior.
  • Document the extension contracts and operator workflow, provide a runnable file-signal adapter, and add executable conformance coverage plus a foreign-owner CI check.

Risk Assessment

⚠️ Medium: Captain, no material source defect remains substantiated, but the change introduces a sizable trusted-code, remote-transfer, and concurrent-retirement lifecycle surface that warrants medium residual risk.

Testing

Scoped the supplied diff and CLI contracts, ran the focused executable-interface suite, and completed a fresh-home bind-to-retirement flow captured in the attached transcript; all exercised behavior passed, but the suite skipped its foreign-owner fixture because chown privilege was unavailable.

Evidence: Fresh-home extension-binding end-to-end CLI transcript

Source: Fresh-home extension-binding end-to-end CLI transcript

Firstmate trusted external process-event adapter: fresh-home operator flow
=======================================================================

$ FM_HOME=<fresh-home> bin/fm-extension.sh list
no extension bindings
OBSERVED: absent registry remained absent after discovery.

$ FM_HOME=<fresh-home> bin/fm-extension.sh bind <external-package> --adapter file-signal --trust-same-user-code --consent artifact-references
bound: [email protected]
binding: /private/var/folders/9w/r64y1hss78j7h843gtlnls6r0000gn/T/no-mistakes-evidence/01M128D0HQD1H14TY216SB4VP2/manual-extension-e2e-canonical/home/config/extensions.d/org.firstmate.example.file-signal.json
binding-digest: sha256:e625df011f6ae64af49c9cdb87ab9e3d97f6b0704e1f88b5b4ae818609a629e2
package: /private/var/folders/9w/r64y1hss78j7h843gtlnls6r0000gn/T/no-mistakes-evidence/01M128D0HQD1H14TY216SB4VP2/manual-extension-e2e-canonical/home/data/extensions/packages/org.firstmate.example.file-signal/1.0.0/a670d3f1353bbfa659564b86f6af7783cd47d32ae9a04e7962b28aedf5bc0e76
package-digest: sha256:a670d3f1353bbfa659564b86f6af7783cd47d32ae9a04e7962b28aedf5bc0e76
verified: process-event-adapter/1 (file-signal)

$ FM_HOME=<fresh-home> bin/fm-extension.sh list
EXTENSION VERSION CAPABILITY ADAPTERS PACKAGE_DIGEST
org.firstmate.example.file-signal 1.0.0 process-event-adapter/1 file-signal sha256:a670d3f1353bbfa659564b86f6af7783cd47d32ae9a04e7962b28aedf5bc0e76

$ FM_HOME=<fresh-home> bin/fm-extension.sh inspect org.firstmate.example.file-signal
{
  "capabilities": [
    {
      "adapter_names": [
        "file-signal"
      ],
      "name": "process-event-adapter",
      "version": 1
    }
  ],
  "consents": {
    "artifact_references": true,
    "credential_store": false,
    "network": false,
    "task_metadata": false,
    "trusted_same_user_code": true
  },
  "entrypoint": "file-signal.mjs",
  "entrypoint_sha256": "sha256:fa90eeea9f90e84afe07cd44797216fdd6196c0aefd9f0d3add25f2354eff82a",
  "extension_id": "org.firstmate.example.file-signal",
  "extension_version": "1.0.0",
  "host_protocol": 1,
  "manifest_sha256": "sha256:bc8f76ad0cb19e6d9e492eb3cab4c983938f57f40ea75def895d184274f7e32c",
  "package_digest": "sha256:a670d3f1353bbfa659564b86f6af7783cd47d32ae9a04e7962b28aedf5bc0e76",
  "package_root": "/private/var/folders/9w/r64y1hss78j7h843gtlnls6r0000gn/T/no-mistakes-evidence/01M128D0HQD1H14TY216SB4VP2/manual-extension-e2e-canonical/home/data/extensions/packages/org.firstmate.example.file-signal/1.0.0/a670d3f1353bbfa659564b86f6af7783cd47d32ae9a04e7962b28aedf5bc0e76",
  "schema": "firstmate.extension-binding.v1",
  "source": {
    "kind": "local-directory",
    "path": "/private/var/folders/9w/r64y1hss78j7h843gtlnls6r0000gn/T/no-mistakes-evidence/01M128D0HQD1H14TY216SB4VP2/manual-extension-e2e-canonical/package/file-signal"
  },
  "timeout_ms": 300000
}

$ FM_HOME=<fresh-home> bin/fm-extension.sh verify org.firstmate.example.file-signal
verified: [email protected] sha256:a670d3f1353bbfa659564b86f6af7783cd47d32ae9a04e7962b28aedf5bc0e76

$ FM_HOME=<fresh-home> bin/fm-procevent.sh register-extension file-signal manual-signal --config-ref file:<absolute-result-path>
registered: manual-signal (file-signal from [email protected])
owner-token: sha256:cc3b1af2a0af58a41bd53288d3c8522ebd423b2788b1a39c8bfec094f79a5958
retire: bin/fm-procevent.sh retire manual-signal --if-owner sha256:cc3b1af2a0af58a41bd53288d3c8522ebd423b2788b1a39c8bfec094f79a5958

$ FM_HOME=<fresh-home> bin/fm-procevent.sh start manual-signal  # supervised runner
retired: manual-signal (adapter classified the captured result terminal)
not-autohandled: manual-signal (left for the handler; still unacknowledged)
captured: /private/var/folders/9w/r64y1hss78j7h843gtlnls6r0000gn/T/no-mistakes-evidence/01M128D0HQD1H14TY216SB4VP2/manual-extension-e2e-canonical/home/state/procevent-inbox/manual-signal.1.result

OBSERVED captured result (state/procevent-inbox/manual-signal.1.result):
build 108 completed successfully

$ FM_HOME=<fresh-home> bin/fm-procevent.sh classify <captured-result>
file-signal

$ FM_HOME=<fresh-home> bin/fm-procevent.sh list
no sources registered

$ FM_HOME=<fresh-home> bin/fm-procevent.sh handled manual-signal 1
handled: manual-signal 1
$ FM_HOME=<fresh-home> bin/fm-procevent.sh retire manual-signal --if-owner <owner-token>
retired: manual-signal
$ FM_HOME=<fresh-home> bin/fm-extension.sh retire-binding org.firstmate.example.file-signal --if-binding-digest <binding-digest>
retired-binding: org.firstmate.example.file-signal sha256:e625df011f6ae64af49c9cdb87ab9e3d97f6b0704e1f88b5b4ae818609a629e2
retained-at: /private/var/folders/9w/r64y1hss78j7h843gtlnls6r0000gn/T/no-mistakes-evidence/01M128D0HQD1H14TY216SB4VP2/manual-extension-e2e-canonical/home/data/extensions/retired-bindings/org.firstmate.example.file-signal/e625df011f6ae64af49c9cdb87ab9e3d97f6b0704e1f88b5b4ae818609a629e2.json

$ FM_HOME=<fresh-home> bin/fm-extension.sh list
no extension bindings
OBSERVED: exact binding retired; discovery is disabled while retained package bytes remain inspectable.
- Outcome: ⚠️ 1 warning across 1 run (6m56s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (7) ✅
  • 🚨 tests/fm-extension-binding.test.sh:448 - Required criterion: “Conformance coverage must exercise ... owner ... checks.” This test reports a pass when chown is unavailable, so normal unprivileged CI can merge without executing the owner-mismatch path. Make this case mandatory in a supported test environment instead of treating inability to construct the fixture as success.
  • 🚨 tests/fm-extension-binding.test.sh:621 - Required criterion: conformance coverage must exercise “independent local and remote-home paths.” Both homes here are ordinary local temporary directories and invoke the scripts directly; no supported remote-home execution or transfer boundary is exercised. Add an executable remote-home-path case, or explicitly approve same-host simulation as containment.

🔧 Fix: Enforce owner and remote-home conformance
1 error still open:

  • 🚨 tests/fm-extension-binding.test.sh:693 - Required criterion: remote-home coverage must use an “independently addressed remote home” and preserve its “serialization and path boundary.” The bind passes controller-local $P_REMOTE through fm-on, while the fake SSH process shares the same filesystem, so no package bytes cross a remote transfer boundary and this would not work against a genuinely remote host. Stage the package through an existing supported remote transfer mechanism into a remote-only path, or re-escalate if none exists.

🔧 Fix: Enforce serialized remote extension package lifecycle
2 errors still open:

  • 🚨 docs/configuration.md:616 - Required criteria say an external adapter must be “safely retired” and require repository-native retirement commands. The only extension retirement command is retire-transfer; the documentation explicitly says it leaves the enabled binding intact, so the adapter remains discoverable and invokable unless an operator manually deletes registry state. Add identity-conditional binding retirement with local and remote lifecycle coverage.
  • 🚨 bin/fm-extension.mjs:1497 - Transfer retirement validates the staged package structurally but never compares the returned manifest identity or tree digest with the receipt. A modified staged tree can therefore be moved as the purported exact transfer. Compare the validated package id, version, and digest—and its version directory—with the receipt before renaming it.

🔧 Fix: Enforce identity-conditional extension retirement
2 errors still open:

  • 🚨 bin/fm-extension.mjs:1553 - Required criterion: bindings must be “safely retired,” and retirement must refuse while a registration depends on the binding. register-extension resolves the binding before acquiring its source lock, while retirement separately runs this preflight and then removes the binding. A registration can resolve, retirement can observe no registration and remove the binding, and registration can then publish a dangling owner record. Serialize resolve-and-publication with preflight-and-removal at one home-local lifecycle boundary.
  • 🚨 bin/fm-extension.mjs:1524 - Required criterion: transferred adapters must be safely and reversibly retired through repository-native commands. A crash after moving the binding into staging/.../binding.json but before moving the staging directory leaves a partial retirement. Retrying fails earlier with binding-missing, so the later retirement-partial check cannot recover or complete it. Make retire-transfer recognize and resume or restore this exact digest-bound partial state.

🔧 Fix: Serialize extension retirement and recover crash cuts
2 errors still open:

  • 🚨 bin/fm-extension.mjs:1778 - Required criterion: an external adapter must be “safely retired.” The executable dispatcher exposes retire-binding-locked and retire-transfer-locked directly, bypassing the lifecycle lock. A registration can therefore resolve and pause before publication, a direct locked retirement can observe no registration and remove the binding, and registration can then publish a dangling owner record. Keep the locked implementation unreachable from the public dispatcher, or enforce serialization at the shared Node retirement boundary.
  • 🚨 bin/fm-procevent.sh:1243 - Required criterion: retirement must remain safely serialized. The shell owns the lifecycle lock while a separate Node child performs retirement. If that shell process dies without also terminating the child, lock recovery can admit registration while the original child continues preflight and removal, recreating the registration/retirement race. Make the process performing retirement own the lock for its full lifetime, or ensure owner death cannot release serialization while its child remains active.

🔧 Fix: Unify retirement worker and lifecycle lock ownership
3 errors still open:

  • 🚨 bin/fm-procevent.sh:408 - Required criterion: an external adapter must be “safely retired.” register-extension can replace source X while X’s previous extension runner is still polling. Retirement of the old binding then sees only the replacement registration, removes the old binding, and the old runner can subsequently capture an unclassifiable result pinned to that retired binding. Track the binding dependency through the active claim lifecycle or prevent replacement until the prior runner stops.
  • 🚨 bin/fm-extension.mjs:964 - The SIGTERM/SIGINT handler releases the lifecycle lock while an asynchronous retirement rename may still be in flight. Registration can acquire the released lock, resolve the binding, and publish before that rename commits, recreating a dangling registration. Keep the lock until process exit and let dead-owner recovery reclaim it, or join all mutations before releasing.
  • 🚨 bin/fm-extension.mjs:1707 - Retirement propagates FM_STATE_OVERRIDE to the lock-owning worker, but the worker drops it when spawning binding-retirement-preflight. With registrations under the overridden state root, preflight scans $FM_HOME/state, finds no dependency, and can remove an in-use binding. Propagate the same override into the preflight environment.

🔧 Fix: Harden extension lifecycle retirement serialization
2 errors still open:

  • 🚨 bin/fm-procevent.sh:416 - Required criterion: external adapters must be “safely retired.” The new active-runner refusal only guards register-extension; ordinary register can still overwrite the same source with a built-in record while its extension runner is polling. Retirement then sees neither an extension registration nor a captured result, removes the binding, and the old runner subsequently captures evidence pinned to the retired binding. Enforce the extension-claim dependency at the shared registration-publication boundary for every registration owner transition.
  • 🚨 bin/fm-extension.mjs:1052 - An extension registered with FM_STATE_OVERRIDE captures results below the overridden state root, but the host only accepts result files below $FM_HOME/state/procevent-inbox. Consequently terminal/silent evaluation and classify reject valid captures as path-unsafe. Derive the effective state root consistently for captured-result confinement and extension working state.

🔧 Fix: Unify extension registration and overridden-state lifecycle boundaries
✅ Re-checked - no issues remain.

⚠️ **Test** - 1 warning
  • ⚠️ tests/fm-extension-binding.test.sh:289 - The authoritative intent requires conformance coverage for same-user ownership checks, but the foreign-owner rejection fixture was skipped because this environment lacks chown privilege. Captain, either rerun this focused test in an isolated environment able to create foreign-owned fixtures or accept that this required behavior was not demonstrated locally.
  • git diff --stat and git diff --name-status 7ee0c192e9d664b022361bd4609303bebfc7de14..b76e5e6832039a4a5bd43a307addc6db098eaf6e
  • bin/fm-extension.sh --help and bin/fm-procevent.sh --help
  • bash tests/fm-extension-binding.test.sh
  • Fresh-home operator flow: list → bind → list/inspect/verify → register-extension → supervised start → captured-result inspection → classify/list → handled → owner-matched retire → digest-matched retire-binding
  • Initial manual bind through macOS’s /var alias, which correctly rejected symlink traversal; retried successfully through canonical /private/var
  • git status --short after testing to confirm no worktree artifacts remained
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ linter found issues (exit code 1)

🔧 Fix: Captain: fix extension binding ShellCheck findings
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Confidence Score: 4/5

The PR is not yet safe to merge because an unrelated same-user daemon can persistently block extension invocation through the orphan quarantine path.

The new orphan mitigation avoids directly killing ambiguous processes, but it still treats timing and reparenting as sufficient attribution and stores unrelated live identities in a quarantine that rejects all later invocations.

Files Needing Attention: bin/fm-extension.mjs

Reviews (8): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile

Comment thread bin/fm-extension.mjs Resolved
Comment thread bin/fm-extension.mjs Resolved
Comment thread bin/fm-extension.mjs Resolved
Comment thread bin/fm-extension.mjs Resolved
Comment thread bin/fm-extension.mjs Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Reviewed HEAD ac8d7bcf5089d3d86492af32c9145aa8c8355eef vs main. Full thread re-read. Diff reviewed across extension binding surface (bin/fm-extension.mjs +2051, bin/fm-extension.sh, bin/fm-procevent.sh / lib, docs/examples/tests) and .github/workflows/ci.yml (+11). M00NLIG7 is not on a blocked-authors list; this is still a security flag.

Class: opt-in (home-local registry, explicit consents, absent registry inert) with security.

Security (immediate): .github/workflows/ci.yml adds job extension-owner-conformance that runs contributor/PR test code under sudo:

sudo env "PATH=$PATH" FM_TEST_OWNER_ONLY=1 FM_TEST_REQUIRE_FOREIGN_OWNER=1 \
  bin/fm-test-run.sh tests/fm-extension-binding.test.sh

That widens privilege on the CI runner for fork PR code (root execution of the PR's test harness). First-time fork CI is withheld for this HEAD under the security-risk exception. Pending runs left unapproved: 33120599867 (CI), 33120599865 (Require no-mistakes).

VISION (per rule, inspected evidence):

  • One captain, one interface — aligns in design. Operator bind/inspect/verify/retire commands; absent registry stays silent.
  • Authority is explicit — aligns in design. Explicit --trust-same-user-code / consent facts; extension bytes described as untrusted evidence; no merge/force/credential grants. Does not align on the CI sudo path, which assumes elevated runner consent for untrusted fork code.
  • Scripts own the mechanics — aligns. Deterministic validation/handshake/spawn without shell eval of extension code (spawn of pinned entrypoint).
  • A restart is a non-event — aligns. Bindings/digests/retired-bindings are durable home-local state.
  • Delegation with a spine — aligns. Owner-matched retirement; registration/retirement serialization work in the review loop.
  • The fleet outlives any vendor — aligns. Narrow process-event-adapter/1 only; vendor-independent contract.
  • Scope — partially aligns. Extension binding is command-layer; the new privileged CI job grows forge privilege for one conformance case.

What is not cleared:

  1. Attestation head_sha is 609868bd2519... but HEAD is ac8d7bcf5089... (post-attestation no-mistakes: apply CI fixes commits). Mismatch — blocking.
  2. Greptile: detached adapter descendant can evade tracking / survive invocation cleanup.
  3. Large new trusted-same-user execution surface (remote transfer, concurrent retirement) — residual medium risk even if CI sudo is removed/replaced.
  4. Foreign-owner fixture historically skipped without chown — the sudo job is how this PR tries to force it; that approach is the security problem.

Captain / Firstmate flag: YES — security (workflow privilege widening via sudo on fork PR CI). Do not approve workflows and do not merge until the ci.yml job is redesigned without running PR code as root (or an equivalent non-widening conformance path lands) and attestation matches HEAD.

Merge-eligible: NO.

Comment thread bin/fm-extension.mjs Resolved
Comment thread bin/fm-extension.mjs
Comment on lines +968 to +974
if (pid === tracker.rootPid || entry.ppid !== 1 || entry.uid !== tracker.uid || entry.state.startsWith("Z")) continue;
if (entry.startedAt < tracker.startedAt - 1000 || tracker.baseline.get(pid) === entry.identity) continue;
if (tracker.descendants.get(pid) === entry.identity) continue;
if (tracker.unrelated.get(pid) === entry.identity) continue;
candidates.push({ pid, identity: entry.identity });
}
return candidates;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Unrelated processes block invocation

When an unrelated long-lived same-user process starts and reparents to PID 1 during an extension invocation, ambiguousInvocationOrphans attributes it from timing and reparenting alone and persists it in the extension quarantine. The current invocation fails with process-attribution-ambiguous, and later invocations remain blocked with process-quarantined until the unrelated process exits.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: closing this for the sudo-root CI job (extension-owner-conformance runs this PR's tests as root). That is a security risk, not waiting on you.

You can reopen without that job.

@karawyi

karawyi commented Nov 2, 2026

Copy link
Copy Markdown

@coderabbitai review

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.

3 participants