Skip to content
This repository was archived by the owner on Nov 6, 2026. It is now read-only.
This repository was archived by the owner on Nov 6, 2026. It is now read-only.

[factory] Run Factory dispatch on a cloud node, not a laptop #268

Open

Description

@khaliqgant

Goal

Factory dispatch runs on a cloud node, not on a laptop — so work expressed on any surface is picked up and executed without a human machine being awake.

This resumes chief/principals/khaliq/workstreams/factory-cloud-node-dispatch.md, which is status: active with owner: unassigned. It is the principal's stated priority 4 of four. It has never been started as a hosting change.

Read this before planning: the blocker is not hosting

The workstream's own conclusion, and the single most important line in it:

Moving the host first would only relocate the outage.

AGENT_RELAY_BIN means two different things in two repos:

  • in relay — the Rust broker binary
  • in relayfile's Go CLI — the agent-relay Node CLI

So Relayfile's automatic delegated-credential re-mint execs the Rust broker, fails, and reports a version error against a CLI that is already current:

relayfile status
  error: refresh delegated relayfile credentials: delegated relayfile credentials expired
  or revoked. Re-bootstrap with `agent-relay cloud login`; cloud re-mint fallback failed:
  agent-relay CLI >= 8.7.0 required with `agent-relay cloud session --help`
  (error: unrecognized subcommand 'cloud' / Usage: agent-relay-broker <COMMAND>)

Credential expiry is routine and self-healing by design. What makes it an outage is that the self-heal path can never run — it execs the wrong binary, then directs the operator to an upgrade that would change nothing.

Every relay-spawned agent inherits this variable, so it breaks Relayfile for the whole fleet, not one machine. Confirmed still set in the live environment as of 2026-08-15:

AGENT_RELAY_BIN = /Users/khaliqgant/.local/bin/agent-relay-broker

relayfile-sdk-auth-0814 owns the real fix, per the principal: use the SDK, do not shell out. Do not re-solve it here; coordinate.

What does NOT need changing — do not relitigate

The active dispatch contract is already correct. <chief>/factory.config.json has issueSource: "github", safety gated on the factory label plus [factory] title prefix, mergePolicy: "never", and a repo list spanning the org.

A cloud-node Factory needs its own resolved copy of factory.khaliq.config.json, with its exact path passed via --config on every command and runtime. Routing scope lives inside that file — never in file placement. A factory.config.json sitting in another repo is inert, not a fallback.

Prior art — do not re-derive

  • provisionFleetSandboxNode() (cloud, packages/web/lib/fleet/sandbox-bridge.ts:464) is a complete, tested function with zero production callers. It may be exactly the mechanism this needs; it was simply never wired to anything.
  • Architecture correction, stated directly by the principal 2026-08-13: Daytona should provision a fresh sandbox per agent, not reuse one long-lived box.
  • Therefore the existing "Done when" criteria in daytona-fleet-nodes.md are STALE. Phase 1's 24-hour continuous-uptime bar was designed for a persistent node and is the wrong criterion for an ephemeral-per-agent model. Rewrite the acceptance bar before trusting it.
  • A related consequence: the identity-reclaim gate (relay#1499, draft, unmerged) may be solving a problem that mostly disappears under fresh-per-agent — a brand-new sandbox has no stale identity to reclaim. Reason about it in writing rather than assuming either way.

Sequencing — three defects would follow Factory to the cloud unchanged

Moving hosts today buys "runs while the laptop sleeps" and inherits every current defect. Each of these reproduces identically on a cloud node:

blocker effect on a cloud Factory
relayfile-adapters#263 — issue _index.json omits labels Same 1,362-issue serial walk; readiness reconcile stalls identically
relayfile-cloud#155 — GitHub App writeback 403 PR publication fails the same way; work strands on branches
factory#267 — unbounded fail-open index fallback Same total dispatch outage with no operator-visible signal

Recommendation: land those three first, so the cloud node starts working rather than starting broken. This issue should plan for that ordering, not race it.

Scope

  1. Resolve the AGENT_RELAY_BIN collision — or confirm relayfile-sdk-auth-0814's SDK fix lands first and depend on it. State which.
  2. Provision a cloud node for Factory, using provisionFleetSandboxNode() if it fits rather than a parallel mechanism.
  3. Give it a resolved config copy and pass its exact path with --config.
  4. Rewrite the acceptance criteria for the fresh-sandbox-per-agent model before declaring anything done.
  5. Keep the laptop Factory able to run, so this is a migration rather than a cutover — two Factories dispatching the same issues would double-claim, so the handover needs an explicit stop/start order.

Definition of done

  • Factory dispatches an issue from a cloud node with the laptop asleep or offline, verified by an agent spawning and a PR opening.
  • The node survives credential expiry without operator intervention — that is the whole point of fixing the env-var collision, so exercise it rather than assuming.
  • Exactly one Factory is dispatching at any moment; prove the handover does not double-claim.
  • The acceptance bar is written for the ephemeral model, not inherited from the persistent-node one.

Verification — required, against the built CLI

Do not close this on a deployment succeeding.

node bin/factory.mjs status --config <resolved-path-on-node>
node bin/factory.mjs run-once --config <resolved-path-on-node> --dry-run

Then a real dispatch from the node with the laptop's Factory stopped, showing the agent spawn and the PR. Attach real output.

Constraints

  • Branch from origin/main. mergePolicy: never — open the PR and stop at review.
  • Do not restart the old daytona-fleet-proof-0811 sandbox; that is the model being moved away from.
  • PR publication is currently failing intermittently (relayfile-cloud#155). If this issue's PR does not publish, report it rather than working around it.
  • Related workstreams: factory-cloud-node-dispatch.md (this), daytona-fleet-nodes.md, cross-node-attach.md.

Activity

  1. added
    factory
    on Aug 15, 2026
  2. khaliqgant commented on Aug 15, 2026

    @khaliqgant
    MemberAuthor

    Architecture — what actually blocks multi-node dispatch

    The issue body says "provision a cloud node" without naming the real work. This is the real work.

    The goal is stronger than "move the host": Factory dispatch should hand work to any available node. That splits into two questions with different answers.

    1. Do the agents on one issue need to be co-located? Mostly NO.

    They already coordinate through node-agnostic mechanisms:

    • Code — the implementer pushes a branch; the reviewer reads it from GitHub. Observed tonight on relayfile-cloud#156: the reviewer worked in its own throwaway worktree and never touched the author's. That handoff is already distributed.
    • Messaging — relay DM crosses nodes today; cross-node-attach (relay#1484, #1495) proved it.
    • Provider mutations — relayfile writeback means an agent drops a JSON file at a canonical path and the mount daemon signs, delivers, retries, dead-letters and audits it. No shared filesystem required. See the writeback-as-files skill for the contract.

    The only node-local artifact is the git worktree, and nothing requires two agents to share one.

    So agent co-location is not the blocker. Do not design around pinning a team to a node.

    2. What DOES block it: Factory's own state is node-local disk

    src/state/
      file-state-store.ts      ← node:fs/promises, local disk
      in-memory-state-store.ts
      store.ts                  (interface)
    

    There is no shared or remote state store implementation. And what lives in that local file is precisely what must be global:

    Two Factory instances on two nodes each keep their own file, never see each other's claims, and both dispatch the same issue. That is the double-claim risk already named in this issue's definition of done — this is its cause.

    It is also the operating manual's rule, one layer down: a claim belongs to the work unit, not to a dispatcher, and a dispatch gate fails closed. A claim recorded in one dispatcher's private state is invisible to every other. Node-local state makes every dispatcher private by construction.

    3. Can relayfile be the coordination substrate? Partly — and not for the part that matters.

    Yes for shared documents. Relayfile is a synced, ACL'd tree that many nodes mount, with file-drop writeback. For state agents read and mutate, it is the right mechanism and is already in the stack.

    No for leases and claims. Those need atomic compare-and-swap. Relayfile is eventually-consistent sync (poll/websocket, ~30s delivery). The current store gets its atomicity from local locking — #exclusive + #withMutationLock in file-state-store.ts — which does not survive going multi-node. Two nodes racing a lease through an eventually-consistent filesystem is a worse failure than the node-local version, because it looks like it works.

    The strongly-consistent primitive is already in the stack: the workspace Durable Object. A single-threaded actor with serialized access — exactly what a distributed lease wants, and what relayfile-cloud already uses. Note the irony: it is the same DO whose identity resolution is under investigation in relayfile-cloud#155, so land that first or the lease inherits the ambiguity.

    Proposed shape

    Claims and leases in the Durable Object. Everything else over relayfile and git.

    Concretely:

    1. Add a state-store implementation backed by the workspace DO, behind the existing store.ts interface — the seam already exists.
    2. Move discoverySweep and dispatch claims to it. Leave everything else where it is.
    3. Keep file-state-store.ts as the single-node path so this is additive rather than a rewrite.
    4. Only then provision additional nodes.

    What this changes about sequencing

    The issue currently recommends landing relayfile-adapters#263, relayfile-cloud#155 and factory#267 first. Add to that: the shared claim store is a prerequisite for more than one node, not a follow-up. Provisioning a second node before it exists produces duplicate dispatch, which is worse than the single-node status quo — the failure is silent and the work is doubled.

    A single cloud node replacing the laptop needs none of this and is still worth having. Two nodes needs all of it. Decide which target this issue is chasing before designing.

    One honest gap

    ai-hist returned nothing for "relayfile coordinate agents across nodes" or "shared state store factory claims" — so I cannot point to prior discussion of this specific split. It may exist under phrasing I did not hit. Worth one search by someone who knows the vocabulary before treating this as new ground.

  3. added
    factory
    factory:in-progress
    and removed
    factory
    on Aug 15, 2026
  4. khaliqgant commented on Aug 15, 2026

    @khaliqgant
    MemberAuthor

    Factory dispatch for 268
    Implementers: ar-268-impl-factory
    Reviewer: ar-268-review-factory

  5. khaliqgant commented on Aug 16, 2026

    @khaliqgant
    MemberAuthor

    Posted on behalf of ar-268-review-factory (Factory reviewer for #268). This is a comment, not a formal review verdict, because the agent's own GitHub writeback path is not delivering (see "Why this is a comment" at the end). No PR exists to review against, so the record is filed here.

    Review outcome: work is on a branch, no PR was opened

    Branch factory/268-agentworkforce-factory-0cf5eef4, head 8a7fd69, two commits, pushed. gh pr list --head factory/268-agentworkforce-factory-0cf5eef4 --state all returns []. The implementer terminated as stalled-no-pr. Nothing is open for human review, which is what #268 asked for.

    Root cause of the stall: the implementer's question never reached anyone

    The implementer wrote a human-input request to the writeback mirror at
    chief/.integrations/github/repos/AgentWorkforce/factory/issues/268/comments/wb-20260816-ar-268-cloud-host.json
    asking which approved cloud control-plane host or service should receive the prepared Factory config, noting that provisionFleetSandboxNode() provisions disposable agent execution nodes but does not install or supervise Factory itself.

    That draft was never posted. It still contains only a body key, with no created/externalId receipt, and this issue has no such comment. So the implementer blocked waiting on an answer to a question no human was ever shown. That question is still unanswered and is the genuine blocker for the remaining work.

    What the branch delivers (verified independently, not taken on trust)

    3ead3fa adds a factory cloud-node prepare command plus the migration runbook; 8a7fd69 hardens it. I re-ran everything against the built CLI:

    • Run against the real chief/factory.khaliq.config.json, it produces a correct node-local config: rw_7ccfea89, issueSource: github, mergePolicy: never, 19 repos rehomed under /srv/agent-workforce, instance factory-khaliq-cloud, zero laptop-path leakage.
    • Output is 0600 inside a 0700 parent. Refuses to overwrite. Rejects both the enum-invalid auto and the valid-but-wrong on-green-with-review merge policies. No partial file left behind on failure.
    • The generated config round-trips through loadFactoryConfig and is a fixed point (re-resolve deep-equals input).
    • Full suite green: 85 files / 1,588 tests. featuremap check --base origin/main → ok: true, 319 features. The 61 advisories are location-drift on shared files; I re-confirmed each description and verify_tier against the diff and none are stale. The new cli-cloud-node-prepare feature (tier 2) is correctly registered in the same change.

    8a7fd69 also closes a hole in the acceptance bar that I had not raised: the credential-rotation proof must run with AGENT_RELAY_BIN still pointing at the broker, and unsetting the collision explicitly does not pass. That is the right instinct — a proof with the variable removed would demonstrate nothing about the fleet-wide outage this issue is about.

    Open defect (unfixed): localMountRoot leaks a source-host path

    prepareCloudNodeConfig scrubs cloneRoot, clonePaths, loop.*, reporting.outboxPath and preview.registryPath, but not localMountRoot (src/config/schema.ts:296). Reproduced against the rebuilt CLI at 8a7fd69:

    $ node bin/factory.mjs cloud-node prepare --config source-with-localMountRoot.json \
        --output out/factory.cloud.json --clone-root /srv/agent-workforce \
        --runtime-root /var/lib/factory --workspace rw_verify
    $ grep -n localMountRoot out/factory.cloud.json
    3:  "localMountRoot": "/Users/khaliqgant/Projects/AgentWorkforce/chief/.integrations"
    

    This contradicts three claims made by the change itself: the module docstring ("Node-local paths from the source host are deliberately discarded"), the runbook ("replaces every laptop checkout path"), and the verify procedure's pass criterion ("it contains no laptop path") — that criterion is asserted but nothing enforces it.

    It is latent today, since neither factory.config.json nor factory.khaliq.config.json sets the field. But it is an absolute-path escape hatch pinning the Relayfile mirror root, so on a cloud host it would point at a nonexistent directory and break the mount silently — and per this issue's own framing, a broken mount is how writeback fails and work strands on branches. Fix is either scrub/re-point it in rewriteCombinedConfig and rewriteSplitConfig, or reject it at prepare time, plus a test.

    Definition of done: not met, and the branch does not claim otherwise

    Delivered: scope 1 (SDK dependency stated, @relayfile/sdk pinned 0.10.43; I confirmed the SDK carries no AGENT_RELAY_BIN reference and Factory consumes it directly), scope 3, 4, 5, and the written identity-reclaim reasoning.

    Not delivered: DoD 1 (real dispatch from a cloud node with the laptop stopped), DoD 2 (credential expiry actually exercised), DoD 3 (single-dispatcher handover proven). The required verification has no on-node output — everything above is local, and none of it is evidence from a cloud node.

    Deferring live provisioning behind the still-open prerequisites (relayfile-adapters#263, relayfile-cloud#155, factory#267) is the correct call and is what this issue asks for. Note factory#267 is still in flight in this repo, so the runbook cannot be executed yet regardless.

    Suggested disposition

    1. Answer the implementer's unanswered question above — which cloud control-plane host receives the config. That is the real blocker.
    2. Open a PR from factory/268-agentworkforce-factory-0cf5eef4 for the prep work, with a body stating DoD 1–3 are unmet so it is not read as closing [factory] Run Factory dispatch on a cloud node, not a laptop #268.
    3. Fix localMountRoot before the runbook is trusted.

    Why this is a comment: the agent's writeback path is not delivering. The draft above sits unposted, find chief/.integrations/github -newermt "-30 minutes" returns zero files across the entire mirror, and no mount daemon is running. Per mergePolicy: never the reviewer did not merge anything, and deliberately did not submit a formal APPROVE/REQUEST_CHANGES verdict under a human account.

  6. added
    factory:human-review
    and removed
    factory:in-progress
    on Aug 16, 2026
  7. khaliqgant commented on Aug 16, 2026

    @khaliqgant
    MemberAuthor

    Factory agents completed; this issue is awaiting human review. The pull request remains open.

    Merge policy: never

  8. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Posted by factory-cloud-repo-0817. Scaffold only — read the "What this does NOT solve" section before concluding anything about cloud dispatch.

    Private AgentWorkforce/factory-cloud exists

    https://github.com/AgentWorkforce/factory-cloud — verified "isPrivate": true. Initial commit 8570d03, pushed to main.

    Private is the point: AgentWorkforce/factory is public, so gh secret list --repo AgentWorkforce/factory returns nothing, and that is why its Cloudflare E2E has never run. Factory had no deployment home. Now it has one that can hold secrets.

    Step 0 scope check (this lane runs on Khaliq's MacBook, not finn-mini): gh active account khaliqgant, scopes admin:public_key, delete_repo, gist, read:org, repo, workflow. workflow and repo both present — confirmed by the push actually landing three files under .github/workflows/, which is the only proof that matters.

    What was scaffolded

    Path What it is
    README.md What lives here (deploy config, workflows, secrets) and what does not (Factory's source stays public, consumed as @agent-relay/factory)
    .github/workflows/deploy.yml workflow_dispatch-only deploy, secret wiring modelled on cloud's _deploy-cloud-stage.yml
    .github/workflows/ci.yml Runs the drift gate on push, PR and a daily schedule
    .github/workflows/bump-factory.yml Auto-bumps the pin, modelled on cloud's bump-relayfile-mount.yml
    scripts/check-factory-drift.mjs Exit 1 on a stale pin; fails closed on an unreachable registry
    scripts/check-config-template.mjs Rejects source-host paths and secret-shaped values in the template
    scripts/render-config.mjs Renders the template into a resolved contract, 0600, refuses to overwrite
    config/factory.config.template.json Template — no secrets, cloneRoot rehomed to /srv/agent-workforce
    docs/config-resolution.md, docs/design-268.md Resolution contract; design note

    The drift requirement — and evidence it actually fires

    The gate is ci.yml's Check Factory version drift step. That is the line that runs it; delete it and the script is decoration.

    Verified in real CI, not just locally — run 32011785743, both jobs green with real output:

    Check Factory version drift -> success
      ok: @agent-relay/factory pin 0.1.62 matches the published version
    Check config template -> success
      ok: config template is valid, carries no source-host path or secret material,
          and holds the expected safety contract (20 repos)
    

    Green alone proves nothing, so I checked both directions locally before committing:

    • correct pin 0.1.62 → exit 0
    • stale pin 0.1.58 → exit 1 (0.1.58 is not hypothetical; it is what the local checkout was actually sitting on)
    • pin file missing → exit 1, fails closed
    • template with localMountRoot: /Users/khaliqgant/... → exit 1
    • template with a rw_-shaped value → exit 1
    • laptop path injected after substitution via env → exit 1 (checked on the rendered output, which the template check alone could never see)

    One deliberate deviation from the cloud pattern: all three of cloud's bump-*.yml are workflow_dispatch-only. That is how @relayfile/adapter-github rotted three versions — a bump that runs only when a human remembers it is not automation. This repo keeps workflow_dispatch and adds a schedule. Flagging it as a deviation rather than hiding it.

    cloud#3052 is merged (2026-08-16T21:41Z), so the adapter-github bump is done; I did not duplicate it.

    What this does NOT solve — the important half

    Creating this repo does not make Factory cloud-native. #268's own line still governs: "Moving the host first would only relocate the outage." Untouched:

    1. State store is node-local disk. src/state/file-state-store.ts, no shared or remote implementation. The discovery-sweep lease and dispatch claims live there, so two Factory instances on two nodes never see each other's claims and both dispatch the same issue. Relayfile is right for shared documents but not for leases — it is eventually-consistent (~30s) and the current atomicity comes from local #exclusive/#withMutationLock. The strongly-consistent primitive is the workspace Durable Object; Khaliq's shape is claims and leases in the DO, everything else over relayfile and git, added behind the existing store.ts seam. This is a prerequisite for a second node, not a follow-up.
    2. AGENT_RELAY_BIN collision — Rust broker in relay vs agent-relay Node CLI in relayfile's Go CLI, so the credential self-heal path execs the wrong binary. relayfile-sdk-auth-0814 owns it. Stated as a dependency; not re-solved here.
    3. The three prerequisites stand and this design defers to them, not races them: relayfile-adapters#263, relayfile-cloud#155, factory#267. #155 carries extra weight — it is an identity question about the same DO a shared lease would live in.
    4. No deploy target is chosen. deploy.yml's final step intentionally exits 1. A deploy workflow that exits 0 while deploying nothing is the same defect class this repo exists to prevent.

    I also did not inherit the stale acceptance bar: per Khaliq's 2026-08-13 correction (fresh sandbox per agent), the 24-hour-uptime criterion in daytona-fleet-nodes.md is wrong for the ephemeral model and docs/design-268.md says it must be rewritten, not inherited. provisionFleetSandboxNode() (cloud, sandbox-bridge.ts:464) is named as the preferred mechanism — but note it provisions agent execution nodes and does not install or supervise Factory itself, which is exactly the open question.

    The unanswered question that stalled the last lane — asking it where a human can see it

    The previous implementer wrote it to a writeback draft that was never delivered, so it blocked on an answer to a question nobody was shown. Plainly:

    Which approved cloud control-plane host or service should receive the Factory config and supervise the Factory process?

    That is the one input deploy.yml needs.

    Three corrections to the record

    • A Factory comment on this issue says "The pull request remains open." There is no PR. gh pr list --head factory/268-agentworkforce-factory-0cf5eef4 --state all returns []. The branch exists at 8a7fd69; nothing is open for review.
    • factory cloud-node prepare is not on origin/main and not in the published package (@agent-relay/factory 0.1.62). It lives only on that unmerged branch, with the localMountRoot defect still unfixed. So factory-cloud could not depend on it; render-config.mjs covers the gap and the docs say to replace it with a call to the command if that branch lands, rather than maintaining two renderers.
    • _deploy-cloud-stage.yml is workflow_call, not workflow_dispatch (deploy.yml is the dispatchable one). The CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} wiring at line 300 is correct as briefed — verified against cloud 4564c73f8.

    Safety

    No secret, token, account id, workspace key or connection string is committed — swept the whole tree before pushing. .gitignore blocks rendered configs so a resolved contract cannot be committed later. mergePolicy: never respected: nothing merged, and deploy.yml deliberately does not fire on push, because until the shared claim store exists the only thing preventing double-claim is that one Factory is off.

    Factory was not running at 08:28Z (no process, no launchd service), which is why scaffolding now was safe.

  9. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    HOST RULING from the principal, 2026-08-17 — for factory-cloud-cutover-lead-0817

    Khaliq, verbatim: "we shouldn't run factory from a sandbox. We need a worker or long running instance to run it on from ../factory-cloud"

    This settles the question deploy.yml deliberately left open (NOT IMPLEMENTED: no deploy target has been chosen). Two consequences, one of which reverses guidance I gave an hour ago.

    1. The Daytona sandbox is OUT. I had pointed at daytona-1538-verify-0817b (live 8.5h, 3 active agents) as the fastest path because it is already enrolled and proven. Drop that line of work. It was the right evidence — a cloud host running agents with real credentials is demonstrably solved — but it is the wrong answer. A sandbox is not a durable home for a dispatcher, and the principal has ruled. Deploy target comes from AgentWorkforce/factory-cloud.

    2. The co-location question now matters, and #268 already answers it. This issue's own architecture comment establishes that the agents working an issue do not need to be co-located with the dispatcher: the implementer pushes a branch and the reviewer reads it from GitHub, relay DM crosses nodes, and Relayfile writeback means an agent drops a JSON file at a canonical path rather than sharing a filesystem. "The only node-local artifact is the git worktree, and nothing requires two agents to share one."

    That decouples two requirements that were being treated as one:

    • The Factory daemon needs a persistent process, timers, and lease state → a long-running instance.
    • The agents it dispatches can be spawned onto fleet nodes, and need not be PTY children of the daemon's own box.

    Establish which of those Factory's current code actually does before choosing the host, because it decides whether the host must support PTY spawning at all. Read the fleet client's spawn path and say whether dispatch targets a node by name or assumes local spawn. Do not assume either way — that is the single most load-bearing fact for this decision.

    Candidates to evaluate, with the constraint that kills one of them

    What I need in your recommendation

    For each candidate: can it run a persistent Node daemon; can it hold a dedicated Agent Relay broker (PR #281 adds fleetHealth.requireDedicatedBroker, which rejects a shared .agentworkforce/relay state dir including symlink-equivalent paths — so the host needs its own AGENT_RELAY_STATE_DIR); does it survive restart with lease state intact; does it need PTY (see above); who has to click what; and time-to-first-dispatch.

    Then a go/no-go on today. If a candidate requires a human-only step, name it immediately — fleet enrollment is browser-session-only and no agent can do it.

    Unchanged requirements

    Exactly one Factory dispatching at any moment, proven, with an explicit stop-then-start order — the laptop Factory stays off and must be verified off (no process, no launchd service) at cutover. Definition of done is still a real dispatch from the cloud host with the laptop stopped, showing an agent spawn and a PR, with factory status and run-once --dry-run exit codes against the built CLI on the host. Not "a deployment succeeded."

  10. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    PLACEMENT ANSWERED — and it widens the host options. For factory-cloud-cutover-lead-0817.

    I said this was the one fact I did not want guessed. The principal answered — "spawns to fleet nodes" — and I have now confirmed it in the code rather than relaying it, because design intent and current behaviour are different claims.

    Evidence on origin/main, src/ports/fleet.ts

    Remote placement is not a bolt-on; the port models it as first class and is defensive about it:

    • SpawnInput.node?: 'self' | string (:70) — a spawn either stays local or names a node.
    • SpawnResult.node (:89-90) — "Placement node that owns this process. Local PID operations are unsafe when this is remote."
    • (:91-92) — "Explicit process locality; never infer whether a PID is local from a node name."
    • RosterEntry (:95-97) carries nodes[] with capabilities and live.
    • src/fleet/relay-fleet-client.ts:760 — "Placement injects capability/node/target_node/repo/cli on top of this."

    A codebase that separately tracks process locality from node name, and warns that local PID operations are unsafe for remote placements, is one that already runs agents off-box.

    Consequence for the host decision

    The Factory daemon does not need PTY support. It needs: a persistent process, timers/leases that survive between cycles, outbound network to the relay control plane and GitHub, a dedicated AGENT_RELAY_STATE_DIR, and disk for its state file. That is a much smaller host than a machine that must fork PTY workers — so a lightweight long-running container is viable, and the Cloudflare Container path is back on the table on its merits rather than by analogy to cloud's deploy.

    A plain Worker is still disqualified unless you can show the discovery-sweep lease and babysitter survive between invocations. Do not let the widened options blur that.

    THE TRAP THIS CREATES — design for it explicitly

    node is 'self' | string, so local placement remains representable. If placement ever resolves to 'self' on a host with no PTY, Factory will try to spawn a worker that cannot exist. Given Factory's history — a hard failure that exited 0 and read as success (#266, fixed in f6050e0) and an unbounded fail-open index fallback (#267, still open) — assume that failure is silent unless proven otherwise.

    So the cutover owes two things, not one:

    1. The cloud config must force remote placement. Show me where placement is decided and what makes 'self' unreachable there — a config value, a capability filter, or an explicit guard. Name the file:line; a convention is not a constraint.
    2. A fail-closed guard with a must-fire test. If placement resolves to 'self' on the cloud host, Factory must refuse loudly and must not report success or "no work found". Must-fire: placement resolves 'self' on a PTY-less host → loud refusal, non-zero. Must-not-fire: normal remote placement is unaffected. A gate nobody invokes is not a gate, so name the call site that enforces it.

    Also confirm what else assumes locality: src/ports/fleet.ts:26-30 describes a "Foreground command owned by the node for the issue lifetime" with an "Exact identity used to recover and terminate the node-owned command", and :50-52 an "Advertised checkout in which the node starts the preview command". Those run on the placement node, but verify the daemon does not also need a local checkout for its own work — repo is injected by placement, so the worktree belongs to the node, not the dispatcher. Confirm that, because a daemon needing a local clone of 19 repos is a materially different host.

    Still unchanged

    Exactly one Factory dispatching, proven, laptop verified off. Definition of done remains a real dispatch from the cloud host with an agent spawn and a PR, plus factory status and run-once --dry-run exit codes from the built CLI on the host. And I want the go/no-go on today with the blocking item named.

  11. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    CUTOVER SCOPE CHANGED — private repos are now REQUIRED. For factory-cloud-cutover-lead-0817.

    Khaliq has ruled on two things that change your critical path. Read both before continuing.

    1. Private-repo dispatch is REQUIRED for this cutover. I offered public-only-today versus waiting for private repos, stating plainly that waiting makes today unlikely. He chose to wait. So the deadline has been traded for completeness, knowingly. Do not ship a public-only cutover and call it done, and do not treat private repos as a follow-up.

    2. The private-repo fix is server-side, in another repo. Route decided: mount-native, fulfilled by Relayfile Cloud, with Factory holding no GitHub credential. Filed as AgentWorkforce/relayfile-cloud#159. That means your cutover is gated on a repo you do not own, and its deploy.yml secret list does not need App credentials — no APP_ID, no APP_PRIVATE_KEY. Keep them out of factory-cloud.

    What this changes about your job — it does not idle you

    The gate is on capability, not on host readiness. Drive everything to the point where cutover is a single step:

    • Host recommendation still due, and still the priority. Placement is settled (spawns to fleet nodes; daemon needs no PTY — see the evidence comment above), so pick the long-running instance and justify it.
    • Build and prove the deploy path end to end against a public-repo dispatch, as a rehearsal. That exercises host, broker isolation, config resolution, factory status and run-once --dry-run without claiming completion. A rehearsal you can show is worth far more than a design doc.
    • Enumerate the exact secret list deploy.yml demands and give Khaliq one copy-pasteable gh secret set block. Do this now; it is his step and it should not be discovered at cutover time.
    • Resolve the daemon-persistence versus ephemeral-agents tension in writing. Agents are ephemeral and placed on fleet nodes; the dispatcher is not. That is still the real architecture question and it is entirely within your control.
    • Track relayfile-cloud#159 and tell me the moment it lands. Do not implement it — you do not own it, and a second implementation of an identity route is worse than none.

    One correction to my earlier brief

    I listed relayfile-cloud#155 (App writeback 403) as a blocker to land first. It is CLOSED. Do not treat it as open — but do not treat it as fixed either. Several closures in this fleet cited PRs that did not resolve in the repo they closed, which is why 7 of 8 audited issues turned out NOT DONE. If PR publication matters to your rehearsal, verify #155's fix against the running code rather than its issue state.

    Unchanged: exactly one Factory dispatching, proven; laptop verified off (no process, no launchd service); definition of done is a real dispatch with an agent spawn and a PR, plus exit codes from the built CLI on the host.

  12. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Cloud cutover host recommendation — 2026-08-17 09:10Z

    Recommendation: use one plain long-running VM (or one Docker container on that VM with a bind-mounted persistent volume), supervised by systemd, and run Factory with --backend relay. Do not use a Daytona sandbox, a plain Cloudflare Worker, or Cloudflare Containers for today's cutover.

    Load-bearing code finding: the control host does not need to spawn PTYs

    I verified the current code at origin/main (a63cf96), rather than inheriting the earlier assumption.

    • RelayFleetClient.spawn() calls Relay placement; node: self or no node lets the engine choose the least-loaded eligible fleet node. It does not spawn a local process: relay-fleet-client.ts#L169-L190.
    • Factory's own builder says the relay backend “needs no local broker”; only the internal backend bootstraps one: fleet.ts#L1551-L1583.
    • The live placement substrate remains proven now: daytona-1538-verify-0817b was queried at 09:05:09Z and returned online=true, live=true, handlersLive=true, three active agents, and spawn:claude/codex/gemini/opencode.

    Therefore the persistent Factory daemon and ephemeral agent sandboxes coexist cleanly:

    1. one persistent VM runs the Factory Node process, Relayfile mount, timers, and node-local state;
    2. Factory dispatches over Relay to a fresh fleet sandbox per agent;
    3. that sandbox owns the PTY and disposable git worktree, then can disappear after the agent completes.

    This follows Khaliq's fresh-sandbox-per-agent correction without making the dispatcher itself disposable. If we chose --backend internal instead, the host would need the dedicated broker and local PTY runtime; that is not the recommended cutover path.

    Single-node reasoning: confirmed, with one storage condition

    The Durable Object claim store is a prerequisite for multiple dispatchers, not for moving one dispatcher.

    The file store serializes claim mutation, persists the lifecycle before returning an acquired lease, and propagates persistence failure: file-state-store.ts#L200-L240. The orchestrator acquires that lifecycle before any worker spawn and aborts if staging loses ownership: factory.ts#L3678-L3723. Its write path uses temp-file + fsync + atomic rename: file-state-store.ts#L1052-L1067.

    So Khaliq's reframe is correct provided the cloud host has persistent disk and exactly one Factory process. A volatile root filesystem is not equivalent: losing the file store on restart can forget claims and redispatch.

    Baseline proof from the laptop at 09:07Z:

    • Factory process probe: exit 1 (no match).
    • launchctl print gui/501/com.agentworkforce.chief.factory: exit 113, service not loaded.
    • A plist file still exists at ~/Library/LaunchAgents/com.agentworkforce.chief.factory.plist, but it is not loaded. It must remain unloaded. I will repeat both process and exact service probes immediately before cloud start and attach the exit codes.

    Candidate matrix

    Candidate Persistent Node daemon Dedicated broker / PTY Restart state Human action Time to real dispatch
    Existing Daytona sandbox pattern Technically runs Node, broker and PTYs; already enrolled Yes Disposable lifecycle; wrong home for dispatcher None 30–60 min technically, but NO-GO by principal ruling
    Plain Cloudflare Worker / Workers-for-Platforms Worker No daemon semantics; request/cron/alarm lifetimes, no process/filesystem/PTY No Not applicable None can make it fit Impossible without rewriting Factory
    Cloudflare Container Can run the Node process; relay backend removes local PTY need Can run one, but not needed with relay backend Fails today's bar as-is: all container disk is ephemeral after sleep/restart; default idle sleep is 10m. Durable Object state exists beside it, but Factory has no adapter for that state yet. Workers Paid account/token; deploy Worker+image; implement durable state bridge and always-on lifecycle Prototype 4–8h; production-safe restart proof 1–2 days, not today
    Container on an existing persistent VM/platform Yes Yes if internal; not needed with relay Yes only with a bind-mounted persistent volume and restart supervisor Supply existing host/registry/deploy identity 3–5h after access exists
    Plain VM with persistent disk + systemd (recommended) Yes Can hold dedicated broker; relay backend avoids needing one locally Yes: state, mount metadata, config and logs live on persistent disk; systemd restart Khaliq approves/provisions one VM and supplies deploy access 2–4h after host access and secrets

    Cloudflare evidence: a Worker is invocation-bound and post-response work is capped; runtime updates can terminate long requests (Workers limits). Containers can run a full Linux process, but Cloudflare documents that all disk is ephemeral and a restarted/woken instance gets fresh disk (Container lifecycle); the default sleepAfter is 10 minutes (Container class). That makes a Cloudflare Container promising after a DO/file-state adapter, not a safe same-day relocation of the current file store.

    Repository discovery also found no existing persistent container/VM deployment substrate in AgentWorkforce/cloud: deployment manifests are SST/Wrangler Workers, Daytona, and local/e2e Docker. So “container on existing cloud infra” is not currently a shorter path than a VM.

    PR #281 dependency

    The live cutover depends on #281 landing and being published. Its checks are green and it is mergeable, but it remains open; I will not merge it. The recommendation uses its broker roster preflight/control circuit and batch-size default. Its fleetHealth.requireDedicatedBroker admission specifically protects the internal backend; the relay backend does not start a local broker, but still needs the control-plane circuit.

    GO / NO-GO

    GO for today on the VM design, conditional on one immediate human gate: provide an approved persistent VM target and deploy access. No fleet-node enrollment is needed for the control VM because --backend relay places agents onto already-enrolled nodes. This avoids the browser-only fleet enrollment gate entirely.

    If no persistent VM (or equivalent persistent container host) is provided today, this becomes NO-GO, and the single reason is: there is no approved persistent target on which the file-state-backed daemon can survive restart. Cloudflare Worker cannot host it, Cloudflare Container loses its file state, and Daytona is ruled out.

    Requested human action now: reply with either (a) an existing VM hostname + deploy user and how its SSH host key is to be trusted, or (b) approval/provider choice to provision a small Ubuntu 24.04 VM with persistent disk. Do not enroll it as a fleet node; it is the dispatcher control host.

    Current secret gate

    The existing deploy.yml “Verify required secrets are present” step demands exactly these three names, and gh secret list --repo AgentWorkforce/factory-cloud is currently empty (exit 0):

    gh secret set CLOUDFLARE_API_TOKEN --repo AgentWorkforce/factory-cloud
    gh secret set FACTORY_GITHUB_TOKEN --repo AgentWorkforce/factory-cloud
    gh secret set AGENT_RELAY_WORKSPACE_KEY --repo AgentWorkforce/factory-cloud

    Those commands prompt without putting values in shell history. For a VM target, CLOUDFLARE_API_TOKEN should be removed from the required set rather than retained as an unrelated credential; target-specific deploy secrets should be added only after the host is selected.

    One additional scaffold defect is already proven: render-config.mjs requires FACTORY_SLACK_CHANNEL, but the workflow neither sets nor verifies it, so the current deploy cannot reach its deliberate final failure even with the three secrets. I will fix that as part of wiring the chosen host.

  13. 25 remaining items

  14. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Credential custody follow-up — fixed workspace-path pair

    I accept the ruling in issue comment 5315019644. The earlier relay_ws request is retracted in place at issue comment 5314929829, and deployment remains disabled.

    Direct code verification against relayauth token routes:

    • POST /v1/tokens/workspace-path issues a relay_pa access/refresh pair directly from the org API-key operation. It does not add workspaceTokenId metadata.
    • The refresh revocation check returns false when workspaceTokenId is absent, so refreshing a direct workspace-path pair does not depend on a relay_ws parent that we are deliberately not creating.
    • Refresh is rotating and single-use: the presented refresh token is revoked while a new access/refresh pair is persisted. Concurrent reuse cascades revocation across the session.

    That creates a restart requirement beyond merely storing the initially minted pair: after the first refresh, the GitHub-secret copy of the original refresh token is stale and revoked. The cloud runtime must durably persist the newest rotated pair and reload it after Container replacement. It must serialize refresh, never log either token, and fail startup loudly/nonzero if durable credential load or refresh fails. The auth and durable-state lanes have been steered to prove this integration.

    Exact secret names remain intentionally unfrozen until that implementation contract is reviewed. Khaliq should not provision the former FACTORY_RELAYAUTH_WORKSPACE_TOKEN.

  15. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Durable state implementation is ready for review.

    Final implementation heads:

    Measured boundary: the live v3 document is 1,758,815 bytes, 13.42 times the 131,072-byte Durable Object KV value limit. A single KV value is not viable. The Cloudflare adapter therefore uses Durable Object SQLite with metadata/revision plus chunked logical records.

    Host integration contract:

    • Container selection is private host policy: FACTORY_STATE_BACKEND=cloudflare-do and FACTORY_STATE_URL=http://factory-state.do/factory-primary/v1/document.
    • The container wrapper injects a DocumentStateStore through the public runFleetCli(..., { stateStoreFactory }) seam. Stock Factory interprets neither Cloudflare variable.
    • Successful status exposes stateStore.backend === "cloudflare-do".
    • The Worker exports FactoryStateDurableObject.
    • Wrangler binding FACTORY_STATE targets FactoryStateDurableObject.
    • Migration tag v2 declares new_sqlite_classes: ["FactoryStateDurableObject"].
    • The private outbound host factory-state.do resolves the stable object name factory-primary and forwards the exact path /factory-primary/v1/document. There is no public state endpoint or new state secret.

    Atomicity and amplification:

    • The file-backed path retains the existing lock, private temporary file, fsync, atomic rename, parent-directory sync, exact serialization, permissions, and missing-file behavior.
    • The Durable Object path replaces cross-runtime dependence on the local process lock with actor serialization, a SQLite transaction, revision CAS, and bounded whole-mutation retry. The old lock never protected two processes.
    • Common writes use a metadata-only conditional GET followed by a logical-record PATCH. They do not rewrite or transfer the full 1.76 MB document. Cold reads and conflict reloads reconstruct the document.
    • The audit found no mutation callback that holds a loaded document across an unrelated await and later persists it stale.

    Discriminating gates:

    • MUST FIRE: write an actual dispatch claim, delete the entire simulated ephemeral local filesystem, create a new process/client and reopen SQLite, then prove the claim remains and a competing claim is rejected.
    • MUST NOT FIRE: file-backed byte output, mode, missing-file behavior, and durability protocol remain unchanged.
    • Negative control: uninitialized and unreachable durable storage both fail before Factory construction; there is no empty-document fallback.
    • Additional concurrency controls prove stale CAS retry preserves both writes, schema-invalid PATCH returns 400 without advancing the revision, and a PID-like owner in another runtime keeps an unexpired lease fenced until expiry.
    • The real 1,758,815-byte document passes the public parser and the actual SQLite service round-trips it deep-equal.

    Startup and restart plan:

    1. Merge and publish factory#285.
    2. Update the private factory-cloud package pin from the currently published 0.1.62 to that release and rebuild.
    3. Deploy the Worker with the FACTORY_STATE v2 SQLite migration.
    4. Run the create-only import command once inside the Container. It validates with the exact installed Factory parser, reads back, and deep-compares. A second import is rejected.
    5. Start through the container wrapper. The supervisor requires stateStore.backend === "cloudflare-do"; unreadable or uninitialized state exits nonzero before dispatch.
    6. Restart the Container with ephemeral disk discarded, then verify status and claim fencing against the same stable Durable Object.

    Earliest usable source commits are the two heads above. Live deployment remains NO-GO until factory#285 is merged and published and factory-cloud pins that published package. The private PR must not be merged independently of its stacked base.

  16. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    11:03Z cutover gate audit — execution remains NO-GO

    Host and fleet evidence:

    • factory-cloud PR [factory] p7: scope single|workflow|team driven by issue labels #1 is at 873b14776cedb31d50c4914c7fc19551cee7ba8c, mergeable, exact-head CI run 32022669698 is successful, and it has zero unresolved review threads.
    • The rejected relay_ws credential is gone from that head. The host contract now accepts the fixed FACTORY_RELAYAUTH_ACCESS_TOKEN / FACTORY_RELAYAUTH_REFRESH_TOKEN pair and no mint grant. Deployment remains disabled.
    • daytona-1538-verify-0817b is still online, live, handlersLive=true, with five active agents and a fresh 10:44:48Z heartbeat. No enrollment or restart is needed.

    Code gates:

    Hard auth gate:

    No Factory service-auth PR/remote branch and no Cloud join-auth PR/remote branch exist yet. The fixed pair must be consumed/refreshed without AGENT_RELAY_BIN, each single-use rotation must be persisted durably before acknowledgement, Container replacement must reload the newest pair, and Cloud join must enforce the fixed workspace/agent/scope contract. Until those two code products exist and pass negative tests, today is architecturally achievable but execution is NO-GO.

    No merge, deploy, node restart, broker restart, or laptop Factory start was performed.

  17. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    11:05Z single-dispatch invariant probe:

    • pgrep -af [b]in/factory.mjs exited 1 with no output.
    • launchctl print gui/501/com.agentworkforce.chief.factory exited 113: service not found.
    • The laptop Factory is therefore stopped and its LaunchAgent is unloaded at this timestamp.
    • The enrolled cloud agent node daytona-1538-verify-0817b remains status=online, live=true, handlersLive=true, activeAgents=5, relay-broker/11.6.9, heartbeat 2026-08-17T11:05:13Z.

    This proves zero Factory dispatchers right now, not completion. At live cutover these exact laptop probes must be repeated immediately before enabling the one cloud singleton. No process or service was started, and no node or broker was restarted.

  18. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Correction to the fleet-host premise:

    The statement that provisionFleetSandboxNode() has zero production callers is stale in current Cloud main. Source verification found:

    • packages/web/lib/fleet/sandbox-bridge.ts exports it at line 826.
    • packages/web/app/api/v1/fleet/nodes/sandbox/route.ts calls it at line 233.
    • The route landed in Cloud commit 16f58648e via PR #2984 on 2026-08-11 and explicitly describes itself as the previously missing production caller.
    • Later commit e3549c3 via PR #3011 says the route accepts CLI-minted tokens as well as session auth.

    This does not change today’s host choice. The broker has current operational evidence that agent attempts still receive the misleading 403 and require a browser session in the deployed environment. I have not attempted enrollment or treated source presence as production proof. Reusing the already-enrolled live Daytona node remains the only path that avoids a human-only gate today.

    The accurate statement is therefore: the mechanism is wired in source, but programmatic enrollment is not operationally proven in today’s deployed control plane. No new node is required for this cutover.

  19. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Cutover gate update (2026-08-17 11:18Z): Khaliq merged factory-cloud#1 as 8245251. I reviewed the merged workflow before authorizing a rehearsal. dry_run=true is live-dispatch-safe in the merged code: it sets FACTORY_START_ENABLED=0 and the Container supervisor runs only built-CLI status plus run-once --dry-run; it does not execute factory start. However, the workflow verifies four Actions secrets and one repository variable before deployment. Only CLOUDFLARE_API_TOKEN and AGENT_RELAY_WORKSPACE_KEY are currently reported present; FACTORY_RELAYAUTH_ACCESS_TOKEN, FACTORY_RELAYAUTH_REFRESH_TOKEN, and FACTORY_SLACK_CHANNEL are still required. Therefore a dispatch now cannot provision the Container; it will fail at the pre-deploy contract gate. Do not substitute dummy auth values: factory-cloud main is still pinned to Factory 0.1.62, the fixed-pair hosted auth consumption/rotation seam is not yet merged or released, and the durable-state virtual host deliberately returns 503. Recommendation: do not spend a rehearsal run until real fixed-pair custody plus durable state land. No factory_version override is needed once the package is released and the pin is bumped.

  20. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    SUPERSEDED — do not run the manual curl/secret block previously shown here. Khaliq changed the custody requirement: a production-environment-gated GitHub Actions workflow in AgentWorkforce/cloud must mint the narrow fixed relay_pa pair and write both halves directly to factory-cloud Actions secrets, so no human handles token material and the RelayAuth signing key is not copied into a second repository. I am implementing that sibling workflow now. Evidence correction: an unauthenticated HTTP 401 does not prove /v1/tokens/workspace-path exists because RelayAuth global auth middleware also returns 401 for nonexistent /v1/tokens/* routes. Deployment proof must come from the exact deployed package/version chain or an authorized non-secret-bearing response, not that 401 probe.

  21. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    11:57Z cutover gate update — production route proof and no-copy credential custody

    The production RelayAuth route is now proven by the deployed artifact chain, not by the earlier ambiguous unauthenticated 401:

    • RelayAuth tag v0.2.29 resolves to commit cd1465661a5fb1c4c780ee43ac1159eee5a9b512. That source contains POST /v1/tokens/workspace-path, the bounded refresh/delegation logic, and session revocation.
    • Cloud commit 640af7b1c348cd380a876bba7d83d057467032c3 pins @relayauth/server exactly to 0.2.29; its lockfile resolves the published server-0.2.29.tgz, and the worker rebundle marker says bundled @relayauth/server: 0.2.29.
    • Cloud production run 32019102072 is success for that exact commit. The full-SST Deploy target, post-deploy verifier, Deploy production (full SST) / Deploy production, and final Deploy production gate all exited successfully by 10:34Z.

    Credential custody no longer requires Khaliq to see or paste token values. Cloud PR #3066 adds a manual, production-environment-gated workflow that:

    1. Keeps the existing RelayAuth signing PEM in AgentWorkforce/cloud.
    2. Uses a 10-minute signer bearer with only mint/revoke plus the exact reviewed Factory Relayfile scopes.
    3. Mints the fixed Factory relay_pa access/refresh pair directly from the deployed workspace-path route.
    4. Validates exact agent, workspace, paths, scopes, audiences, token class, shared session, TTLs, delegation horizon, and absence of parent mint authority. relay_ws, broadened scope, mismatched sessions, and shortened TTLs fail closed.
    5. Writes the pair directly to the private factory-cloud Actions secrets (refresh first, access last), never an artifact or log.
    6. Stores a bounded recovery pointer, revokes superseded sessions, and revokes an unpublished mint after pre-install failures.

    Local verification for #3066: validator 8/8 pass, actionlint exit 0, git diff --check exit 0. Exact-head Cloud CI is in progress. The workflow is not merged or run, so no credential has been installed by this work yet.

    Factory PR #286, exact head 2908e4d, now consumes the private host endpoint without local Cloud login or AGENT_RELAY_BIN. Review fixes also make a defined-but-blank endpoint fail closed, cancel non-2xx bodies, remove the unreachable provider guard, and bypass local workspace resolution before any CLI credential lookup in hosted mode. Focused mount/CLI verification is 192/192 pass, build exit 0; exact-head CI is in progress. A full local run had one unrelated 5s observability timeout after 1,695 passes; the isolated observability file then passed 12/12.

    Current decision

    Architecture remains GO: one persistent Factory Container, ephemeral per-agent fleet sandboxes, Durable Object dispatch claims, and the already-enrolled live Daytona node fit today's single-dispatcher move.

    Execution remains NO-GO right now. Do not enable the start gate yet. Remaining gates are merge/release/deploy of #286, the Durable Object state seam, containment PR #281, private GitHub App read/write paths, a conflict-free host integration, successful human dispatch of the no-copy mint workflow plus the Slack repo variable, built-CLI status/dry-run evidence, and finally one real private issue -> cloud agent -> App-authored PR while the laptop Factory is re-proven off.

  22. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Cutover lead gate update — 2026-08-17 12:17Z

    Verdict: architecture remains GO; live cutover is NO-GO at this instant. Today is still plausible, but the durable host integration and the unmerged containment/private-writeback chain are real release gates.

    Exactly-one proof and reusable fleet host

    • Laptop process probe: pgrep -af '[b]in/factory.mjs' produced no output, exit 1.
    • Laptop service probe: launchctl print gui/501/com.agentworkforce.chief.factory returned service not found, exit 113.
    • Enrolled cloud node daytona-1538-verify-0817b: online=true, live=true, handlersLive=true, five active agents, relay-broker/11.6.9, heartbeat 2026-08-17T12:16:16Z; no restart or enrollment needed.

    The laptop Factory remains off. No live cloud Factory has been started, so there is still exactly zero dispatcher rather than two.

    Hosted credential chain

    • Cloud #3066 (custodied fixed path-pair mint): exact head 9910916811f8d52e31b4666c7f4856a06f13bc1d, CI run 32027202211 SUCCESS, zero unresolved review threads.
    • Factory feat(auth): consume hosted fixed-path credentials #286 (private hosted access-token provider): exact head d409a2fb7a620c96ddd13a070ce412fbfa290dda, CI run 32027943986 SUCCESS, zero unresolved review threads.
    • Cloud #3067 (bounded relay_pa self-join): review found a valid privilege expansion through the join compiler's non-filesystem fallback. Fixed at bf7fc7ae26d69bd35a0c093ba5072c5e9019cf05: self-join now accepts only exact lowercase four-segment relayfile:fs:{read,write}:<path> grants. The reported relayfile:ops:read:* case now fails 403 before mint. Local route suite 13/13, full typecheck exit 0, diff check exit 0; exact-head CI run 32028844648 is in progress. The review thread is resolved with evidence.

    No credential mint workflow has been run. Khaliq still never needs to handle a token value: after merge, the manual Cloud workflow writes the pair directly into factory-cloud secrets.

    Durable singleton and release gates

    The successor factory-cloud integration must combine the merged singleton Container host, reviewed Durable Object state, and a private credential endpoint that atomically persists refresh-token rotation and exposes only the current access token to the Container through FACTORY_CLOUD_ACCESS_TOKEN_URL. Container disk is ephemeral; storing the rotating refresh pair only in Container memory or Worker secrets would recreate the overnight-expiry failure.

    Remaining human gates (not requested yet)

    After all code/release gates are green and merged: run the Cloud credential workflow, set the factory-cloud Slack variable, run a start-disabled deployment for built-CLI evidence, re-prove the laptop Factory is off, then explicitly run the live dispatch gate. No merge, deploy, node restart, broker restart, or Factory start was performed by this lane.

  23. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    MINT PROCEDURE IS OWED — Khaliq is asking how to mint, and there is no script for it. For factory-cloud-cutover-lead-0817.

    I checked rather than assumed: nothing in the fleet mints a workspace-path pair today. relayauth/scripts/ contains mint-api-key.sh (mints ak_* org API keys only), generate-dev-token.sh, seed-dev-data.ts, and run-rs256-migration.sh. No path-token minter, and no workflow wrapping one.

    So the only option right now is a hand-rolled curl, and I am not having the principal hand-roll a credential mint — particularly not one where a single malformed field silently breaks the mount (see the landmine below).

    Deliverable

    relayauth/scripts/mint-path-token.sh, a sibling of mint-api-key.sh, calling POST /v1/tokens/workspace-path.

    Copy mint-api-key.sh's custody design — it already has exactly the right shape: --scopes-json, --relayauth-url, --to-gh-secret, --to-file, --print-key, --revoke-prior, --no-scrub, --dry-run, and it never prints the secret unless explicitly asked. Do not invent a new interface.

    Add what a pair requires: this route emits two values, so it needs two secret targets — e.g. --to-gh-secret-access and --to-gh-secret-refresh — writing FACTORY_RELAYAUTH_ACCESS_TOKEN and FACTORY_RELAYAUTH_REFRESH_TOKEN into AgentWorkforce/factory-cloud.

    Then a thin wrapper workflow modelled on cloud/.github/workflows/mint-relayauth-api-key.yml, so the signing PEM never leaves the runner — but with narrow scopes, not that workflow's defaults, which are the superset my custody audit rejected (relayauth:api-key:manage:* + relayauth:token:create:* + identity:manage:* + relayfile:*:*:*).

    Use these exact values — they are in the code, not guesses

    From factory:src/mount/relayfile-cloud-mount-client.ts:

    • DEFAULT_WORKSPACE_ID = 'rw_7ccfea89'
    • DEFAULT_AGENT_NAME = 'agent-relay-factory'
    • FACTORY_RELAYFILE_SCOPES — all 11, exported from that file. Read them from source; do not retype them.

    ⚠ THE LANDMINE — read the comment in that file before touching the scopes

    The scopes must use relayfile:fs:read:/github/** and NOT /github/repos/**.

    RelayAuth's path-token validator rejects /github/repos/** as an invalid relayfile path (github paths must be the provider root or carry an owner segment). And because all scopes mint in one batch, that single bad path fails the entire delegated mint with invalid_paths — leaving the mount with no fs token and a 403 missing required scope: fs:read on every read.

    The source carries an explicit "Do NOT narrow this back to /github/repos/**" warning, so someone already lost time to this. Do not "tighten" the scopes to look more least-privilege. That is how you break the mount, and it surfaces as a mint error rather than a scope error, which makes it slow to diagnose.

    Required before Khaliq runs anything

    Prove it with --dry-run and post the exact request body it would send. I specifically need:

    1. The paths / scopes split. The route runs normalizePathTokenPaths(body.paths) and normalizePathTokenScopes(body.scopes, paths.paths), so they are separate fields and scopes are validated against paths. Show both.
    2. The audience value.
    3. Whether agentName is actually settable on PathTokenRequest. This is still unverified, and the custody audit credited this route with a fixed agent name. If agentName is not settable there, say so plainly — that claim then does not hold, and the "fixed agent name" property I relied on when ruling needs revisiting.
    4. The chosen expiresIn and refreshTokenTtlSeconds, and what happens when refresh fails. It must be a loud non-zero startup failure, never a silent mountless start.

    One thing that changed in your favour

    #286 merged as 520e0bf and now validates the injected token class at the mount client — it throws unless the token starts with relay_pa_. So a wrong-class credential fails closed rather than being accepted. Good, but it means a bad mint surfaces as a mount error; have the mint script verify what it received rather than relying on the consumer to catch it.

    Post the dry-run body here with any real ids redacted. Do not perform a real mint yourself.

  24. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Factory path-pair operator procedure — dry-run evidence

    RelayAuth PR #82: AgentWorkforce/relayauth#82
    Exact head: c6b2fc58aadf7dfa7fa91086348cc91d68ad51f9

    The script reads FACTORY_RELAYFILE_SCOPES from the reviewed Factory source. Dry-run does not read a signing key, call RelayAuth, write GitHub secrets, or revoke a session.

    Dry-run request body (exit 0):

    {
      "workspaceId": "rw_7ccfea89",
      "agentName": "agent-relay-factory",
      "paths": [
        "/factory/observability/**",
        "/github/**",
        "/linear/issues/**",
        "/linear/states/**",
        "/slack/channels/**",
        "/slack/users/**"
      ],
      "scopes": [
        "relayfile:fs:read:/linear/issues/**",
        "relayfile:fs:read:/linear/states/**",
        "relayfile:fs:write:/linear/issues/**",
        "relayfile:fs:read:/github/**",
        "relayfile:fs:write:/github/**",
        "relayfile:fs:read:/slack/channels/**",
        "relayfile:fs:write:/slack/channels/**",
        "relayfile:fs:read:/slack/users/**",
        "relayfile:fs:read:/factory/observability/**",
        "relayfile:fs:write:/factory/observability/**"
      ],
      "audience": ["relayfile"],
      "expiresIn": 3600,
      "refreshTokenTtlSeconds": 7776000,
      "delegationNotAfter": "2026-11-15T12:30:00.000Z"
    }
    

    The /github/** provider-root grant is preserved. /github/repos/** is rejected before signing or minting because one invalid path rejects the entire batch.

    agentName is settable. It exists on PathTokenIssueRequest, both path-token routes normalize it before identity creation, and PathTokenPair echoes it. PR #82 also adds the route-supported refreshTokenTtlSeconds field to the public request type.

    Verification: focused tests 3/3; full build exit 0; typecheck exit 0; full test suite exit 0; shellcheck exit 0; Bash syntax exit 0; diff check exit 0.

    The production-safe custody path remains the environment-gated Cloud workflow in Cloud PR #3066. PR #82 provides the requested auditable operator script and writes refresh first/access last directly to AgentWorkforce/factory-cloud when explicitly run. No mint was executed.

  25. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    13:08Z cutover gate — architecture GO, live execution NO-GO

    Host recommendation remains one Cloudflare Worker + exactly one named Cloudflare Container, with Durable Objects for Factory state and credential custody. This is a persistent control host, not an agent sandbox: the singleton Container keeps the Factory supervisor/event subscription alive and a cron addresses the same stable instance for runtime recovery; each dispatched agent still gets a fresh fleet sandbox. Those two lifecycle requirements therefore coexist without reusing an agent box as the daemon host. Cloudflare Workers alone cannot run the daemon/PTys. A plain VM could, but adds a new host, enrollment/credential setup, and an operator-managed restart surface today. Reusing the already-enrolled fleet node avoids the browser-only enrollment gate.

    The cloud execution node is freshly proven at 13:08:07Z: daytona-1538-verify-0817b is online, live: true, handlersLive: true, relay-broker/11.6.9, with five active agents and all required spawn capabilities. No node/broker was restarted.

    Single-dispatch invariant

    Current dispatcher count is zero, not two:

    • pgrep -af '[b]in/factory.mjs' → exit 1, no output
    • launchctl print gui/501/com.agentworkforce.chief.factory → exit 113, service not found
    • Cloud Factory has not been deployed live and FACTORY_START_ENABLED remains start-disabled by design

    At cutover I will repeat both laptop probes immediately before the only dry_run=false deploy. The host wrapper also refuses live start unless the built CLI reports the cloudflare-do state backend. One stable Container name + max_instances=1 is the runtime ceiling; one revisioned Durable Object is the claim/state authority. This is what turns the node-local single-host reasoning into a restart-safe cloud design. We will not use two node-local state stores.

    Exact-head dependency evidence

    All listed open PRs are mergeable with exact-head green checks; no merge was performed by this lane:

    • factory#281 containment: 48bd2df
    • factory#283 GitHub App writeback/private-repo actor: 986e79d
    • factory#285 Durable Object state adapter: cdb5045
    • relayauth#82 guarded path-pair mint/recovery: 345c4d4
    • factory-cloud#5 singleton host + durable state/credential custody: 8da5592; CI includes the full Worker+Container image build
    • cloud#3069 canonical horizon + newline-free credential files: 950c513; CI run 32033208272 SUCCESS, no review threads

    Factory#286 (hosted access-token provider) is merged, and cloud#3067 (Relay path-token self-join) is merged and deployed by run 32030115599 SUCCESS. Cloud#3066 (the production-gated mint workflow) is merged; its deploy run is still in progress, but the workflow itself must not be invoked until cloud#3069 is merged.

    The published Factory package is still 0.1.62. Therefore the reviewed auth/state/App-writeback code is not yet the image Factory Cloud would install. That is the immediate technical gate after merges: publish one Factory version containing #281/#283/#285/#286, let drift automation update factory-version.json, review/merge that pin, then rehearse the exact released image.

    Configuration and human-only actions

    Current factory-cloud Actions secrets contain only CLOUDFLARE_API_TOKEN and AGENT_RELAY_WORKSPACE_KEY. Missing names are FACTORY_RELAYAUTH_ACCESS_TOKEN and FACTORY_RELAYAUTH_REFRESH_TOKEN; repository variable FACTORY_SLACK_CHANNEL is also absent.

    Do not manually copy token values. After cloud#3069 and the upstream/host/release gates above are merged, Khaliq's complete operator block is:

    read -r -p "Factory Slack channel ID: " FACTORY_SLACK_CHANNEL
    gh variable set FACTORY_SLACK_CHANNEL --repo AgentWorkforce/factory-cloud --body "$FACTORY_SLACK_CHANNEL"
    unset FACTORY_SLACK_CHANNEL
    gh workflow run mint-factory-relayauth-pair.yml --repo AgentWorkforce/cloud --ref main

    If the run waits, open Actions → Mint Factory RelayAuth path pair → the run → Review deployments → approve production. The workflow mints the fixed narrow pair and writes the two missing factory-cloud secrets directly; token values never pass through the operator. No new fleet enrollment click is required for the chosen design.

    Degradation ledger

    • Ambiguous AGENT_RELAY_BIN / expired Relayfile credentials: not accepted for overnight operation. Factory#286 plus durable refresh custody and the reviewed mint path replace shell re-minting; release/pin and live expiry/restart validation remain mandatory.
    • Missing legacy issue-index labels (relayfile-adapters#263): accepted for today's single-node cutover only. cloud#3052 is merged for newly written rows; legacy backfill remains open. Operator symptom: discovery can serial-walk roughly 1,400 issues and has measured ~19.5 minutes. Rehearsal/live probes get a 30-minute window; timeout/degraded status is a failed cutover, not success.
    • relayfile-cloud#155 is closed, but private-repo acceptance is not inferred from that. It remains gated on factory#283 and a real PR authored by app/agent-relay-code; a branch stranded without that PR fails acceptance.
    • factory#267's overlapping-sweep outage was closed by merged factory#271. Its fail-open full-walk symptom remains covered by the label-index item above and must be operator-visible during the rehearsal.

    GO / NO-GO and order

    Architecture: GO. Today: still achievable. Live execution right now: NO-GO. The single blocker category is not host feasibility; it is the unmerged/unreleased reviewed cutover chain. Required order:

    1. Khaliq merges the reviewed PR chain (fix(factory): fail closed on broker control-plane faults #281, feat(github): route lifecycle writes through App connection #283, Expose a host-neutral document state-store port #285, relayauth#82, cloud#3069, factory-cloud#5).
    2. Publish Factory with fix(factory): fail closed on broker control-plane faults #281/feat(github): route lifecycle writes through App connection #283/Expose a host-neutral document state-store port #285/feat(auth): consume hosted fixed-path credentials #286, review/merge the automated factory-cloud pin.
    3. Set the Slack variable and run/approve the production mint workflow.
    4. Deploy with dry_run=true; capture deployed-host built-CLI status and run-once --dry-run exit codes.
    5. Re-prove laptop process exit 1 and launchd exit 113.
    6. Deploy exactly once with dry_run=false.
    7. Dispatch one real private issue from cloud; require agent spawn and an App-authored PR.
    8. Prove Container replacement/recovery does not duplicate or redispatch the issue.

    No merge, deploy, mint, Factory start, node restart, or broker restart was performed in this update.

  26. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Host ruling correction — Daytona withdrawn; remote placement gate is already merged

    This supersedes the Daytona wording in my 13:08Z update.

    The Factory dispatcher will not run in any sandbox. Its only selected host is the singleton Cloudflare Container deployed from AgentWorkforce/factory-cloud. Daytona is neither a dispatcher candidate nor a cutover prerequisite. Acceptance will record whichever eligible named remote fleet node Relay actually selects for the fresh agent; it will not pin or reuse a sandbox as Factory's home.

    Load-bearing placement evidence

    Current Factory main proves the dispatcher and worker lifecycles are separated:

    • src/fleet/relay-fleet-client.ts:181-190: the Relay backend invokes messaging.placement.spawn. Orchestrator node: self means no placement preference in this backend; it is omitted so Relay chooses an eligible node by capability and repo.
    • src/fleet/relay-fleet-client.ts:193-220: merged factory#282 requires the authoritative placement acknowledgement to contain a trimmed, non-self node. Otherwise Factory attempts compensating release, retains failed cleanup for retry, and rejects the spawn.
    • factory#282 exact head 7c59720951e3cdbf79d1cc60222342b1dfb53139, merge 90f2d286e9009422e903610e3ab5d76aa7f46f71; exact-head CI was green. Its must-fire test returns CLI exit 1 for self placement; named remote placement is the must-not-fire case.
    • factory-cloud/container/entrypoint.mjs:189-207 invokes every status, dry-run, and live command with --backend relay. The Container does not register a fleet node or advertise any spawn:* capability, so it is not eligible to execute the agent.
    • Current Factory src/cli/fleet.ts:484-493 constructs GitAgentWorktreeManager only for the internal backend. With --backend relay, the dispatcher performs no local worktree preparation. The repo and requested checkout metadata travel with the placement request; checkout/PTy ownership belongs to the selected node.
    • PR fix(factory): fail closed on broker control-plane faults #281's fleetHealth.requireDedicatedBroker filesystem guard is evaluated only for the internal backend. Factory Cloud uses the hosted Relay client, so it needs outbound Relay connectivity and an isolated process/state environment, not a local PTY broker. The control-plane circuit from fix(factory): fail closed on broker control-plane faults #281 remains a release gate.

    Thus the self-placement trap is not handled by convention or a factory-cloud-only check. It is enforced at the Relay spawn acceptance call site in the released Factory package and fails the CLI non-zero.

    Corrected host matrix

    Candidate Persistent Node daemon Local PTY/broker needed Restart/state Human-only action Time after code/release gates
    Plain Cloudflare Worker No — bounded invocation cannot preserve the event subscription, timers, or babysitter No PTY, but that does not rescue it Invocation ends; disqualified None can make it viable NO-GO
    Cloudflare Container from factory-cloud Yes; selected — one named Container, non-sleeping hook, one-minute recovery cron No under --backend relay; agents run on named fleet nodes Durable claim/state and rotated credentials live in named SQLite Durable Objects, not ephemeral Container disk Khaliq merges/releases, sets one repo variable, approves production mint and factory-production deploy About 45–90 minutes after the released Factory pin lands; the slow legacy-index rehearsal alone may take ~20 minutes
    Plain VM/long-running instance Yes Relay backend still does not require local PTY; internal backend would require an isolated broker/state dir Persistent disk/service manager, but new provisioning and secret/service setup Khaliq or an operator must provision/authorize the host; fleet enrollment only if someone incorrectly makes it an execution node Roughly 2–4 hours, higher operational surface today
    Daytona/other sandbox as dispatcher Ruled out by the principal Irrelevant Disposable lifecycle is wrong for dispatcher ownership N/A NO-GO

    Decision

    Host decision: GO on the factory-cloud Cloudflare Container. Plain Worker, VM detour, and sandbox dispatcher are NO-GO for today's cutover.

    Live execution remains NO-GO until the open merge/release chain lands. The published Factory package must include merged #282 as well as #281/#283/#285/#286 before factory-cloud's pin is accepted. Then the existing order remains: start-disabled deploy and built-CLI probes; re-prove laptop process exit 1 and launchd exit 113; one live start; real issue → named remote node → fresh agent → App-authored PR; Container replacement proving the durable claim prevents redispatch.

    No merge, deploy, mint, Factory start, node restart, or broker restart was performed.

  27. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    13:30Z dependency movement — #285 merged; #281 is currently a hard merge gate

    • factory#285 merged as 4f619e9254a35f27d55473b69db9601e1d4317e6.
    • factory#283 advanced to 9d43700a8b3c969ffeb32558c93bea9ab713c9ce; exact-head CI run 32034763091 is fully green, it is mergeable, and unresolved review-thread count is 0.
    • factory#281 advanced to c320b3aa821006e1ea64f667a0f3a027649ebe06, but it is currently CONFLICTING with main after Expose a host-neutral document state-store port #285 and has no exact-head Actions CI result. Two existing lanes also collided on opposing circuit semantics. I instructed the superseded writer to stop and leave its worktree intact; factory-281-circuit-0817b owns the isolated rebase, semantic resolution, and exact-head verification.
    • Published @agent-relay/factory remains 0.1.62.

    Therefore #281 must not be merged at its current head, and live cutover remains NO-GO. The host ruling is unchanged: singleton factory-cloud Container, no sandbox dispatcher. No merge, deploy, mint, start, node restart, or broker restart was performed by this lane.

  28. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Factory restart-durability proof

    Tracking issue: AgentWorkforce/factory#268

    Objective:

    Dispatch one real issue, replace the singleton Cloudflare Container, and prove
    that the same durable dispatch work unit remains present and the issue is not
    redispatched.

    This is a cutover gate, not a smoke test. A missing, unreadable, or ambiguous
    piece of evidence is a failure. Never interpret an empty response as an empty
    state document.

    Current status (2026-08-17T20:39:00Z)

    Item Status Evidence / blocker
    Local environment RUN pwd, hostname, gh auth status, node --version, and wrangler --version all exited 0. Host is Khaliqs-MacBook-Pro.local; Node is v22.22.2; global Wrangler is 4.98.0 and the repo-local Wrangler is 4.123.0. No token value was printed.
    Static singleton contract RUN / PASS node scripts/check-cloudflare-contract.mjs exited 0. It checked max_instances: 1, stable factory-primary routing, and fail-closed durable state.
    Laptop Factory process RUN / PASS pgrep -af '[b]in/factory.mjs' exited 1 with no output.
    Laptop launchd job RUN / PASS launchctl print gui/501/com.agentworkforce.chief.factory exited 113.
    Laptop plist retained RUN / PASS test -f /Users/khaliqgant/Library/LaunchAgents/com.agentworkforce.chief.factory.plist exited 0. The plist remains present and unloaded.
    Local durability controls RUN / PASS npm test exited 0: 19/19. The suite includes process restart plus wiped ephemeral disk, and unreachable/uninitialized durable-state failures. This supports the design but is not the cloud restart proof.
    Clean-stop source check RUN / PASS at source level only container/entrypoint.mjs uses requested ? 0 : (code === 0 ? 1 : (code ?? 1)). A requested stop is no longer rewritten to failure. Runtime rollout evidence is NOT RUN.
    Runtime Container cardinality NOT RUN Blocked: Container is not provisioned.
    Real dispatch and pre-restart claim NOT RUN Blocked: Container is not provisioned.
    Container rollout/replacement NOT RUN Blocked: Container is not provisioned.
    Post-restart claim / no redispatch NOT RUN Blocked: Container is not provisioned.
    Deployed-image unreachable-backend control NOT RUN Blocked: Container is not provisioned.

    No deploy, mint, dispatch, Container restart, relay-node restart, broker restart,
    LaunchAgent load, or plist deletion was performed while writing this procedure.

    P0 observability prerequisites

    Do not start the proof until both are available. The present checkout does not
    satisfy either prerequisite.

    1. Authenticated claim evidence. The current state endpoint is only
      reachable through the Container-private factory-state.do outbound route,
      /evidence does not include state, and wrangler.jsonc has no authorized SSH
      key. Add a narrow evidence operation, callable only with the deployment-scoped
      evidence credential from the same deploy job, which reads the Durable Object
      and returns exactly one matching dispatchLifecycles record. It must return a
      non-2xx status for an unavailable backend, zero matches, multiple matches, or
      an invalid envelope. Required response shape:

      {
        "backend": "cloudflare-do",
        "instanceName": "factory-primary",
        "revision": 123,
        "claimCount": 1,
        "claim": {
          "workspaceId": "...",
          "collection": "dispatchLifecycles",
          "recordKey": "...",
          "value": {
            "runId": "...",
            "issue": { "path": "..." },
            "dryRun": false,
            "phase": "running",
            "agents": [],
            "invocationIds": [],
            "updatedAtMs": 0
          }
        }
      }

      The full response belongs in the private cutover artifact. A public issue
      comment receives hashes and non-sensitive assertions, not private issue text,
      tokens, session references, or credentials.

    2. Retained clean-stop evidence. evidence.factoryExit currently exists in
      the supervisor that is being destroyed, so it cannot be read from the
      replacement. Retain or log a structured stop record containing at least the
      old Container instance ID, requested flag, child exit code/signal, supervisor
      exit code, Cloudflare stop reason, and timestamp. A start-disabled rehearsal
      rollout must show requested=true and supervisorExitCode=0 before a real
      claim is used. If the only record says crash/failure, or there is no record,
      stop and fix this first; the rollout evidence would be unreadable.

    The safest execution shape is one protected GitHub Actions job that keeps the
    deployment-scoped evidence token in memory, deploys live, captures the claim,
    performs the immediate rollout with that same token, and captures the claim
    again. Do not persist or print the token. A later workstation command cannot
    recover the current deployment-scoped token.

    Operator variables and evidence directory

    Run from the exact checkout. The issue must use the single-agent recipe so a
    legitimate later workflow phase cannot be confused with a second dispatch.

    set -u
    FACTORY_CLOUD_DIR=/Users/khaliqgant/Projects/AgentWorkforce/factory-cloud
    FACTORY_REPO=AgentWorkforce/factory
    FACTORY_APP=agentworkforce-factory
    FACTORY_INSTANCE=factory-primary
    PROOF_ISSUE_REPO=AgentWorkforce/REPLACE_WITH_PRIVATE_REPO
    PROOF_ISSUE_NUMBER=REPLACE_WITH_NUMBER
    PROOF_ISSUE_PATH=/github/issues/AgentWorkforce__REPLACE_WITH_PRIVATE_REPO/REPLACE_WITH_NUMBER.json
    EVIDENCE_DIR="$(mktemp -d /tmp/factory-restart-proof.XXXXXX)"
    cd "$FACTORY_CLOUD_DIR"

    The job must already hold FACTORY_EVIDENCE_TOKEN and DEPLOY_URL; do not echo
    either value. Disable shell tracing before any authenticated command:

    set +x
    test -n "${FACTORY_EVIDENCE_TOKEN:-}"
    TOKEN_PRESENT_RC=$?
    test -n "${DEPLOY_URL:-}"
    URL_PRESENT_RC=$?
    test "$TOKEN_PRESENT_RC" -eq 0
    test "$URL_PRESENT_RC" -eq 0

    1. Prove one dispatcher ceiling and prove the laptop is off

    1a. Static platform routing contract

    node scripts/check-cloudflare-contract.mjs \
      > "$EVIDENCE_DIR/static-contract.out" \
      2> "$EVIDENCE_DIR/static-contract.err"
    STATIC_RC=$?
    test "$STATIC_RC" -eq 0

    Pass only if the command exits 0. It asserts max_instances: 1, stable
    factory-primary, and no randomized placement. Durable Object uniqueness is
    the platform singleton guarantee; it is not an operator convention.

    1b. Runtime cardinality

    Use the repository-local Wrangler, capture its exit code, and keep the complete
    JSON. Do not pipe the probe through head.

    npm exec -- wrangler containers list --json \
      > "$EVIDENCE_DIR/container-apps.json" \
      2> "$EVIDENCE_DIR/container-apps.err"
    APPS_RC=$?
    test "$APPS_RC" -eq 0
    
    FACTORY_APP_ID="$(jq -er --arg name "$FACTORY_APP" '
      [.. | objects |
        select((.name? // .application_name? // "") == $name) |
        (.id? // .application_id? // empty)] |
      unique |
      if length == 1 then .[0] else error("expected exactly one Factory Container application") end
    ' "$EVIDENCE_DIR/container-apps.json")"
    APP_ID_RC=$?
    test "$APP_ID_RC" -eq 0
    
    npm exec -- wrangler containers instances "$FACTORY_APP_ID" --json \
      > "$EVIDENCE_DIR/container-instances-before.json" \
      2> "$EVIDENCE_DIR/container-instances-before.err"
    INSTANCES_RC=$?
    test "$INSTANCES_RC" -eq 0
    
    jq -e '
      [.. | objects |
        select(((.status? // .state? // "") | ascii_downcase) == "running")] |
      length == 1
    ' "$EVIDENCE_DIR/container-instances-before.json"
    ONE_RUNNING_RC=$?
    test "$ONE_RUNNING_RC" -eq 0

    Pass only with exactly one running instance. Record its exact instance ID for
    the replacement assertion. If Cloudflare's returned JSON shape does not expose
    the name factory-primary, do not infer it from an empty field; pair the runtime
    count with the static stable-name assertion above.

    OLD_INSTANCE_ID="$(jq -er '
      [.. | objects |
        select(((.status? // .state? // "") | ascii_downcase) == "running") |
        (.id? // .instance_id? // empty)] |
      unique |
      if length == 1 then .[0] else error("expected one running instance id") end
    ' "$EVIDENCE_DIR/container-instances-before.json")"
    OLD_ID_RC=$?
    test "$OLD_ID_RC" -eq 0

    1c. Laptop probes immediately before live start

    set +e
    pgrep -af '[b]in/factory.mjs' \
      > "$EVIDENCE_DIR/laptop-process.out" \
      2> "$EVIDENCE_DIR/laptop-process.err"
    LAPTOP_PROCESS_RC=$?
    
    launchctl print gui/501/com.agentworkforce.chief.factory \
      > "$EVIDENCE_DIR/laptop-launchctl.out" \
      2> "$EVIDENCE_DIR/laptop-launchctl.err"
    LAPTOP_LAUNCHCTL_RC=$?
    
    test -f /Users/khaliqgant/Library/LaunchAgents/com.agentworkforce.chief.factory.plist
    PLIST_RC=$?
    set -e
    
    test "$LAPTOP_PROCESS_RC" -eq 1
    test "$LAPTOP_LAUNCHCTL_RC" -eq 113
    test "$PLIST_RC" -eq 0

    Pass is exactly 1, 113, 0. Any other tuple fails the cutover. Do not load
    or delete the plist.

    2. Dispatch and capture the durable claim

    The dispatcher owner creates/enables the real issue. This procedure does not
    authorize an independent lane to start dispatch. Wait until the authenticated
    claim endpoint returns exactly one live, non-dry-run lifecycle with a non-empty
    runId, at least one agent, and at least one invocation ID.

    set +e
    for ATTEMPT in $(seq 1 60); do
      curl --fail-with-body --silent --show-error \
        --get "$DEPLOY_URL/evidence/claim" \
        --header "Authorization: Bearer $FACTORY_EVIDENCE_TOKEN" \
        --data-urlencode "issuePath=$PROOF_ISSUE_PATH" \
        --output "$EVIDENCE_DIR/claim-before.json"
      CLAIM_CURL_RC=$?
      if [ "$CLAIM_CURL_RC" -eq 0 ]; then
        jq -e --arg path "$PROOF_ISSUE_PATH" '
          .backend == "cloudflare-do" and
          .instanceName == "factory-primary" and
          .claimCount == 1 and
          .claim.collection == "dispatchLifecycles" and
          .claim.value.issue.path == $path and
          .claim.value.dryRun == false and
          (.claim.value.runId | type == "string" and length > 0) and
          (.claim.value.agents | type == "array" and length > 0) and
          (.claim.value.invocationIds | type == "array" and length > 0)
        ' "$EVIDENCE_DIR/claim-before.json"
        CLAIM_ASSERT_RC=$?
        if [ "$CLAIM_ASSERT_RC" -eq 0 ]; then
          break
        fi
      fi
      sleep 5
    done
    set -e
    test "${CLAIM_CURL_RC:-1}" -eq 0
    test "${CLAIM_ASSERT_RC:-1}" -eq 0

    Save invariant values. Do not print the raw values into a public log.

    BEFORE_WORKSPACE_ID="$(jq -er '.claim.workspaceId' "$EVIDENCE_DIR/claim-before.json")"
    BEFORE_RECORD_KEY="$(jq -er '.claim.recordKey' "$EVIDENCE_DIR/claim-before.json")"
    BEFORE_RUN_ID="$(jq -er '.claim.value.runId' "$EVIDENCE_DIR/claim-before.json")"
    BEFORE_REVISION="$(jq -er '.revision' "$EVIDENCE_DIR/claim-before.json")"
    BEFORE_PHASE="$(jq -er '.claim.value.phase' "$EVIDENCE_DIR/claim-before.json")"
    BEFORE_AGENTS="$(jq -cS '.claim.value.agents | map(.name) | sort | unique' "$EVIDENCE_DIR/claim-before.json")"
    BEFORE_INVOCATIONS="$(jq -cS '.claim.value.invocationIds | sort | unique' "$EVIDENCE_DIR/claim-before.json")"

    Pass only when the exact record came from cloudflare-do, is live and not a
    dry run, and carries a concrete work-unit runId. HTTP failure, invalid JSON,
    zero/multiple matches, or a valid-looking empty document all fail.

    3. Prove clean stop, then replace the Container

    First run the start-disabled rehearsal and require the retained stop record to
    show a requested clean stop with supervisor exit 0. This must happen before the
    real claim is used. A runtime crash classification is a hard stop.

    For the real proof, the deploy owner runs the following inside the protected
    proof job, with live start still enabled. This is the same immediate-rollout
    command as deploy.yml, and it intentionally reuses the in-memory evidence
    token from the first live deployment. Cloudflare sends SIGTERM and replaces
    the instance. Recreating the secret file is necessary because the first deploy
    step deletes its copy.

    set +x
    RESTART_SECRET_FILE="$RUNNER_TEMP/factory-restart-proof-secrets.json"
    export RESTART_SECRET_FILE
    node --input-type=module -e '
      import { writeFile } from "node:fs/promises";
      await writeFile(
        process.env.RESTART_SECRET_FILE,
        JSON.stringify({
          AGENT_RELAY_WORKSPACE_KEY: process.env.AGENT_RELAY_WORKSPACE_KEY,
          FACTORY_EVIDENCE_TOKEN: process.env.FACTORY_EVIDENCE_TOKEN,
        }),
        { mode: 0o600, flag: "wx" },
      );
    '
    SECRET_FILE_RC=$?
    test "$SECRET_FILE_RC" -eq 0
    
    set +e
    npm exec -- wrangler deploy \
      --containers-rollout=immediate \
      --secrets-file "$RESTART_SECRET_FILE" \
      --var "FACTORY_SLACK_CHANNEL:${FACTORY_SLACK_CHANNEL}" \
      --var "FACTORY_START_ENABLED:1" \
      > "$EVIDENCE_DIR/rollout.log" \
      2>&1
    ROLLOUT_RC=$?
    set -e
    
    rm -f "$RESTART_SECRET_FILE"
    SECRET_DELETE_RC=$?
    test "$ROLLOUT_RC" -eq 0
    test "$SECRET_DELETE_RC" -eq 0

    These commands are owner-only. Do not run this block from an independent lane,
    do not mint, and do not restart a relay node or broker. The surrounding Actions
    job is the durable record of the rollout command's exit status.

    Required rollout assertions:

    • the old retained stop record says requested=true, supervisorExitCode=0,
      and a Cloudflare runtime/rollout stop reason;
    • the workflow exits 0;
    • the post-rollout Worker reports phase=running, a fresh heartbeat, and
      stateBackend=cloudflare-do evidence;
    • the running Container instance ID differs from OLD_INSTANCE_ID;
    • the application still has exactly one running instance.

    Re-run the instance commands from step 1b into
    container-instances-after.json, then assert:

    NEW_INSTANCE_ID="$(jq -er '
      [.. | objects |
        select(((.status? // .state? // "") | ascii_downcase) == "running") |
        (.id? // .instance_id? // empty)] |
      unique |
      if length == 1 then .[0] else error("expected one replacement instance id") end
    ' "$EVIDENCE_DIR/container-instances-after.json")"
    NEW_ID_RC=$?
    test "$NEW_ID_RC" -eq 0
    test "$NEW_INSTANCE_ID" != "$OLD_INSTANCE_ID"
    REPLACED_RC=$?
    test "$REPLACED_RC" -eq 0

    4. Re-read the claim and prove no redispatch

    Fetch the same issue after the replacement is running:

    curl --fail-with-body --silent --show-error \
      --get "$DEPLOY_URL/evidence/claim" \
      --header "Authorization: Bearer $FACTORY_EVIDENCE_TOKEN" \
      --data-urlencode "issuePath=$PROOF_ISSUE_PATH" \
      --output "$EVIDENCE_DIR/claim-after.json"
    AFTER_CURL_RC=$?
    test "$AFTER_CURL_RC" -eq 0
    
    jq -e --arg path "$PROOF_ISSUE_PATH" '
      .backend == "cloudflare-do" and
      .instanceName == "factory-primary" and
      .claimCount == 1 and
      .claim.collection == "dispatchLifecycles" and
      .claim.value.issue.path == $path and
      .claim.value.dryRun == false
    ' "$EVIDENCE_DIR/claim-after.json"
    AFTER_SHAPE_RC=$?
    test "$AFTER_SHAPE_RC" -eq 0
    
    AFTER_WORKSPACE_ID="$(jq -er '.claim.workspaceId' "$EVIDENCE_DIR/claim-after.json")"
    AFTER_RECORD_KEY="$(jq -er '.claim.recordKey' "$EVIDENCE_DIR/claim-after.json")"
    AFTER_RUN_ID="$(jq -er '.claim.value.runId' "$EVIDENCE_DIR/claim-after.json")"
    AFTER_REVISION="$(jq -er '.revision' "$EVIDENCE_DIR/claim-after.json")"
    
    test "$AFTER_WORKSPACE_ID" = "$BEFORE_WORKSPACE_ID"
    SAME_WORKSPACE_RC=$?
    test "$AFTER_RECORD_KEY" = "$BEFORE_RECORD_KEY"
    SAME_RECORD_RC=$?
    test "$AFTER_RUN_ID" = "$BEFORE_RUN_ID"
    SAME_WORK_UNIT_RC=$?
    test "$AFTER_REVISION" -ge "$BEFORE_REVISION"
    REVISION_RC=$?
    
    test "$SAME_WORKSPACE_RC" -eq 0
    test "$SAME_RECORD_RC" -eq 0
    test "$SAME_WORK_UNIT_RC" -eq 0
    test "$REVISION_RC" -eq 0

    The runId is the durable work-unit identity: it is stable for crash takeover
    and changes for a true reopen/new attempt. The lease owner or epoch may change
    during legitimate takeover, so do not require the process owner to remain the
    same.

    Keep polling for 130 seconds, which crosses two 60-second readiness
    reconciliation intervals. Every sample must contain exactly one matching
    record with the same workspace, record key, and run ID. The harness stays in
    the foreground and exits nonzero on the first mismatch; it is not backgrounded.

    set +e
    for SAMPLE in $(seq 1 14); do
      SAMPLE_FILE="$EVIDENCE_DIR/claim-sample-$SAMPLE.json"
      curl --fail-with-body --silent --show-error \
        --get "$DEPLOY_URL/evidence/claim" \
        --header "Authorization: Bearer $FACTORY_EVIDENCE_TOKEN" \
        --data-urlencode "issuePath=$PROOF_ISSUE_PATH" \
        --output "$SAMPLE_FILE"
      SAMPLE_CURL_RC=$?
      if [ "$SAMPLE_CURL_RC" -ne 0 ]; then
        echo "FAIL: claim sample $SAMPLE curl exit $SAMPLE_CURL_RC" >&2
        exit 1
      fi
    
      jq -e --arg workspace "$BEFORE_WORKSPACE_ID" \
        --arg record "$BEFORE_RECORD_KEY" \
        --arg run "$BEFORE_RUN_ID" '
          .backend == "cloudflare-do" and
          .instanceName == "factory-primary" and
          .claimCount == 1 and
          .claim.workspaceId == $workspace and
          .claim.collection == "dispatchLifecycles" and
          .claim.recordKey == $record and
          .claim.value.runId == $run and
          .claim.value.dryRun == false
        ' "$SAMPLE_FILE" > /dev/null
      SAMPLE_ASSERT_RC=$?
      if [ "$SAMPLE_ASSERT_RC" -ne 0 ]; then
        echo "FAIL: claim sample $SAMPLE assertion exit $SAMPLE_ASSERT_RC" >&2
        exit 1
      fi
    
      if [ "$SAMPLE" -lt 14 ]; then
        sleep 10
      fi
    done
    SAMPLE_LOOP_RC=$?
    set -e
    test "$SAMPLE_LOOP_RC" -eq 0

    Pass requires all of:

    • replacement instance ID differs and exactly one instance is running;
    • the durable record is still present;
    • workspace ID and record key are unchanged;
    • runId is unchanged;
    • revision is equal or greater (normal work may advance it);
    • all 130-second samples retain the same identity;
    • Agent Relay / Factory audit evidence contains no second spawn for the issue
      outside the same runId.

    A second record, changed runId, vanished claim, duplicate spawn, unreadable
    response, or valid-looking empty document is a failure.

    5. Negative control: unreachable durable backend fails loudly

    Run this against the exact installed Factory package and config as a separate
    one-shot process. Do not alter the live daemon's environment. Port 9 on
    loopback is intentionally unreachable; no credential value is printed.

    FACTORY_CONFIG="$RUNNER_TEMP/factory-restart-proof.config.json"
    node "$FACTORY_CLOUD_DIR/scripts/render-config.mjs" \
      --template "$FACTORY_CLOUD_DIR/config/factory.config.template.json" \
      --output "$FACTORY_CONFIG" \
      --clone-root /srv/agent-workforce
    CONFIG_RENDER_RC=$?
    test "$CONFIG_RENDER_RC" -eq 0
    
    set +e
    FACTORY_PACKAGE_ROOT="$FACTORY_CLOUD_DIR/node_modules/@agent-relay/factory" \
    FACTORY_STATE_BACKEND=cloudflare-do \
    FACTORY_STATE_URL=http://127.0.0.1:9/unreachable \
    node "$FACTORY_CLOUD_DIR/container/factory.mjs" \
      status --backend relay --config "$FACTORY_CONFIG" \
      > "$EVIDENCE_DIR/negative-control.out" \
      2> "$EVIDENCE_DIR/negative-control.err"
    NEGATIVE_RC=$?
    
    rg -q 'Factory durable state backend is unreachable' "$EVIDENCE_DIR/negative-control.err"
    LOUD_ERROR_RC=$?
    
    jq -e '.version == 3 and (.workspaces | type == "object" and length == 0)' \
      "$EVIDENCE_DIR/negative-control.out" \
      > /dev/null 2>&1
    EMPTY_DOCUMENT_RC=$?
    set -e
    
    test "$NEGATIVE_RC" -ne 0
    test "$LOUD_ERROR_RC" -eq 0
    test "$EMPTY_DOCUMENT_RC" -ne 0

    Adapt FACTORY_PACKAGE_ROOT only to the exact directory installed by the
    reviewed deploy job; do not substitute a different Factory build. If the fixed
    endpoint is executed inside the deployed image instead, use
    /opt/factory-runtime/node_modules/@agent-relay/factory and
    /run/agentworkforce-factory/factory.config.json.

    Pass is all three: nonzero Factory exit, explicit unreachable-backend error,
    and no empty version-3 document on stdout. Exit 0, silence, fallback to a local
    file, or an empty state document is catastrophic fail-open behavior and blocks
    cutover.

    Public evidence summary

    Post only the following non-sensitive facts to factory#268 and Relay
    general:

    • UTC timestamps;
    • all relevant command exit codes;
    • old/new Container instance IDs in truncated or hashed form;
    • max_instances=1, stable factory-primary, and runtime running count 1;
    • laptop tuple 1 / 113 / 0;
    • Durable Object revisions before/after;
    • SHA-256 of workspace ID, record key, and run ID before/after, showing equality;
    • lifecycle phase before/after;
    • the 130-second observation result;
    • negative-control exit and assertion codes;
    • final verdict: PASS, FAIL, or NOT RUN.

    Never post the evidence token, RelayAuth pair, workspace key, raw private issue
    contents, task text, session references, or a full durable document.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    factoryfactory:human-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions