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] Key dispatch claims on work-unit identity, not surface path #211

Closed

Description

@khaliqgant

Problem

Dispatch claims are keyed on a surface-local identifier, so the same work unit
reachable through two surfaces produces two independent claims and dispatches
twice.

src/orchestrator/batch-tracker.ts:284
export const issueKey = (issue: IssueRef): string => `${issue.key}:${issue.uuid}:${issue.path}`

issue.path is the Relayfile sense path — see the fixture in
src/state/file-state-store.test.ts:289:
AR-9387:uuid-9387:/linear/issues/AR-9387__uuid-9387.json. An issue arriving
GitHub-native carries a different key, uuid, and path, so it hashes to a
different claim key and the existing lease never sees a conflict.

This is the AR-448 duplicate-dispatch shape. The rule it produced is already
written down: a claim belongs to the work unit, not to a surface or a
dispatcher.

What is already correct

The claim machinery itself is sound and should not be rebuilt:

  • claimDispatchLifecycle (src/ports/state.ts:252) is a leased claim with
    fencing epochs, mutex-guarded in FileStateStore and Durable-Object-backed
    in src/hosted/state-store.ts.
  • #claimDispatchLifecycle (src/orchestrator/factory.ts:3174) already fails
    closed — it throws Refusing to dispatch ${key}: ... when the claim is not
    acquired.

The defect is the key, not the locking.

Existing partial mitigation

matchingGithubLifecycleEntry(lifecycles, seed) in
src/state/in-memory-state-store.ts scans open lifecycles for an aliasing
GitHub entry when the direct key misses, and claim.key ?? key threads the
resolved key back. That covers exactly one surface pairing, costs O(open
lifecycles) per claim, and exists only to compensate for the bad key.

Fix

  1. Add workUnitId(issue, contract) returning a canonical work-unit identity,
    resolved in priority order: the upstream repo + issue number when the
    surface exposes one, else the mirror's declared origin, else the
    surface-native key. Emit a stable string, e.g. gh:AgentWorkforce/pear#412.

  2. Key claimDispatchLifecycle on that instead of issueKey():

    const claim = await this.#state.claimDispatchLifecycle(
      this.#workspaceId,
      workUnitId(decision.issue, this.#contract),   // was: issueKey(decision.issue)
      seed, this.#dispatchLifecycleOwner, this.#clock.now(), DISPATCH_LIFECYCLE_LEASE_MS,
    )

    Keep issueKey() for display and log correlation only.

  3. Persist the surface-local key as an alias on the lifecycle record so
    writeback still knows which surface to reconcile to.

  4. Delete matchingGithubLifecycleEntry and the claim.key ?? key fallback.

  5. Migration: on load, re-key existing lifecycles through workUnitId. On
    collision, keep the entry holding the live lease and mark the other
    abandoned.

Explicitly out of scope

Cross-dispatcher visibility. This change fixes cross-surface collision
within a single store. A local factory start daemon and the hosted Factory
still keep claims in separate namespaces and cannot see each other. If both can
be live for one workspace, the claim has to move to the hosted store for both —
file that as a follow-up rather than widening this issue.

Definition of done

  • A test dispatches the same underlying GitHub issue twice — once via
    issueSource: "github", once via a [factory] Linear mirror — and the second
    attempt is refused with the existing "already owned" reason.
  • matchingGithubLifecycleEntry is gone.
  • Existing on-disk lifecycle state survives the re-key, with collisions
    resolved as described.
  • No change to lease, fencing, or fail-closed semantics.

Activity

  1. khaliqgant commented on Aug 3, 2026

    @khaliqgant
    MemberAuthor

    Cloud already models this lifecycle, which changes where the deferred follow-up
    should land.

    cloud/specs/factory-observability-v1.md defines the durable model:

    • initial event families already include "issue claim, queue, dispatch, wait,
      and release"
      (line 75);
    • factory_runs stores the latest customer-visible state for an issue run;
    • factory_events is the immutable, ordered tenant timeline;
    • stable failure codes already include lease_lost and fence_rejected.

    Two consequences:

    1. The cross-dispatcher follow-up has a home. The "out of scope" section
      above asks where a claim visible to both a local daemon and hosted Factory
      should live. It is factory_runs, tenant-scoped, with Postgres authoritative
      for dashboard state. That is a cloud issue, not a Factory one, but it should
      be filed rather than left implicit.

    2. Cloud inherits this bug if the key is not fixed first. factory_runs is
      keyed per issue run. If Factory reports runs under the surface-derived
      issueKey(), the same work unit arriving through two surfaces produces two
      run records in the tenant timeline — the duplicate becomes customer-visible
      rather than just local. Whatever workUnitId() returns should be the key
      Factory reports on, so fix the key here before the cloud claim lands.

  2. khaliqgant commented on Aug 3, 2026

    @khaliqgant
    MemberAuthor

    Correction to my earlier comment and to the issue body: an atomic, DB-enforced
    issue claim already exists in cloud.

    cloud/packages/web/lib/db/schema.ts:1015:

    export const integrationWatchIssueDispatchDedup = pgTable(
      "integration_watch_issue_dispatch_dedup",
      {
        workspaceId: …, issueKey: text("issue_key").notNull(), agentId: …,
        deliveryId: …, claimedAt: …, pendingDeliveryId: …, pendingPayload: …,
      },
      (table) => ({
        uniqueClaim: uniqueIndex("integration_watch_issue_dispatch_dedup_unique")
          .on(table.workspaceId, table.issueKey, table.agentId),
      }),
    );

    That unique index is a real compare-and-swap claim — stronger than Factory's
    read-then-lease, and it already carries a pending-delivery slot for work that
    arrives while a claim is held.

    Two things it does not do, both of which matter here:

    1. The claim key includes agentId. It dedups "this agent already received
      this issue", not "this work unit is claimed". Two different agents can hold a
      claim on the same issue simultaneously, which is the duplicate this issue is
      about.

    2. issueKey is untyped text. Nothing constrains it to a canonical
      identity, so it inherits whatever the caller passes. If Factory reports under
      the surface-derived issueKey(), the same work unit through two surfaces
      produces two rows that the unique index cannot collapse.

    So the shape of the fix is unchanged — workUnitId() is still the prerequisite
    — but the storage layer for the cross-dispatcher follow-up should reuse or
    generalize this table rather than adding a claim to factory_runs. A
    (workspaceId, workUnitId) unique claim is the primitive; the existing table is
    one specialization of it.

  3. khaliqgant commented on Aug 12, 2026

    @khaliqgant
    MemberAuthor

    Factory observed pull request #274 merge and completed this issue.

  4. khaliqgant commented on Aug 16, 2026

    @khaliqgant
    MemberAuthor

    Reopening: the evidence that closed this issue was invalid.

    This was closed by Factory's post-merge "advance to Done" path, citing a pull request number that does not resolve to a merged PR in this repository. The mechanism is analysed in #276 — the record-less fallback at src/orchestrator/factory.ts:11905 resolves a merged-PR event to an issue without the repository qualification that the tracked-record path applies at :11877, so a PR merged in a different repository in the org can close an unrelated issue here.

    A closure is a claim that the work is done. This one rested on a citation that cannot support it, so the honest state is open.

    This does not assert that the work is unfinished. For at least one issue in this set (#211) the defect is verifiably still on origin/main. For others the work may genuinely have landed. If it has, please re-close with a real citation — a merged AgentWorkforce/factory PR number, or the commit on main — rather than restoring the previous one.

    Reopened by factory-lead on Khaliq's instruction. See #276 for the full evidence table and the code path.

  5. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Pre-implementation survey — Axis A / work-unit claim key

    Surveyed freshly fetched origin/main at eaaa076b283dbeeaf0cf1b53c7cb67a4f7dba295. No patch has been written.

    1. Complete construction/consumer survey

    This command is restricted to the two production modules that define/import and call the exported issueKey() function; it excludes unrelated local variables/fields also named issueKey. Full output (no head/truncation):

    $ rg -n "issueKey\\(" src/orchestrator/batch-tracker.ts src/orchestrator/factory.ts
    src/orchestrator/batch-tracker.ts:43:  /** Resolved composite issueKey() when the blocker exists in the mounted issue index. */
    src/orchestrator/batch-tracker.ts:99:    return this.#inFlight.get(issueKey(issue))
    src/orchestrator/batch-tracker.ts:107:    return this.#inFlight.has(issueKey(issue))
    src/orchestrator/batch-tracker.ts:111:    return this.#queued.has(issueKey(issue))
    src/orchestrator/batch-tracker.ts:115:    return this.#parked.has(issueKey(issue))
    src/orchestrator/batch-tracker.ts:119:    return this.#parked.get(issueKey(issue))
    src/orchestrator/batch-tracker.ts:131:    const key = issueKey(decision.issue)
    src/orchestrator/batch-tracker.ts:166:    const key = issueKey(decision.issue)
    src/orchestrator/batch-tracker.ts:183:    this.#parked.delete(issueKey(issue))
    src/orchestrator/batch-tracker.ts:187:    const key = issueKey(issue)
    src/orchestrator/batch-tracker.ts:203:      this.#queued.delete(issueKey(next.issue))
    src/orchestrator/batch-tracker.ts:210:    const key = issueKey(issue)
    src/orchestrator/batch-tracker.ts:302:    const key = issueKey(record.issue)
    src/orchestrator/batch-tracker.ts:327:    const key = issueKey(decision.issue)
    src/orchestrator/factory.ts:860:    const key = issueKey(issue)
    src/orchestrator/factory.ts:1805:        .filter((record) => !record.dryRun && !this.#completionInFlight.has(issueKey(record.issue)))
    src/orchestrator/factory.ts:1961:      const lifecycle = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:2004:    const wanted = issueKey(issue)
    src/orchestrator/factory.ts:2011:      if ((owningIssue ? issueKey(owningIssue) : key) !== wanted) continue
    src/orchestrator/factory.ts:2794:        const dispatchCallActive = this.#dispatchInFlight.has(issueKey(lifecycle.issue))
    src/orchestrator/factory.ts:3100:      await this.#state.clearBabysitterSession(this.#workspaceId, issueKey(lifecycle.issue))
    src/orchestrator/factory.ts:3226:        const durable = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(decision.issue))
    src/orchestrator/factory.ts:3559:      const durable = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(decision.issue))
    src/orchestrator/factory.ts:3561:        if (durable.result && this.#dispatchLifecycleEpochs.has(issueKey(decision.issue))) {
    src/orchestrator/factory.ts:3733:          ...(this.#previewReferences.get(issueKey(dispatchDecision.issue)) ?? []),
    src/orchestrator/factory.ts:3750:      if (mayRollback) this.#previewReferences.delete(issueKey(dispatchDecision.issue))
    src/orchestrator/factory.ts:3762:        this.#previewReferences.delete(issueKey(dispatchDecision.issue))
    src/orchestrator/factory.ts:3807:        this.#dispatchClaimStatuses.set(issueKey(record.issue), record.dispatchClaim)
    src/orchestrator/factory.ts:3827:        ...(this.#previewReferences.get(issueKey(dispatchDecision.issue))?.length
    src/orchestrator/factory.ts:3828:          ? { previews: this.#previewReferences.get(issueKey(dispatchDecision.issue)) }
    src/orchestrator/factory.ts:3956:          ...(record.dispatchClaim ?? this.#dispatchClaimStatuses.get(issueKey(record.issue)) ?? {
    src/orchestrator/factory.ts:4139:        if (previews.length > 0) this.#previewReferences.set(issueKey(lifecycle.issue), previews)
    src/orchestrator/factory.ts:4478:      const key = issueKey(record.issue)
    src/orchestrator/factory.ts:4553:    const key = issueKey(decision.issue)
    src/orchestrator/factory.ts:4654:      .getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:4682:    const activeRecord = record && issueKey(record.issue) === key ? record : undefined
    src/orchestrator/factory.ts:4797:    if (record?.agents.has(name)) return issueKey(record.issue)
    src/orchestrator/factory.ts:4944:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:5033:    const key = issueKey(issue)
    src/orchestrator/factory.ts:5039:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:5093:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:5363:            ...(this.#previewReferences.get(issueKey(record.issue)) ?? []),
    src/orchestrator/factory.ts:5397:      this.#dispatchClaimStatuses.set(issueKey(record.issue), record.dispatchClaim)
    src/orchestrator/factory.ts:5458:    const wanted = issueKey(issue)
    src/orchestrator/factory.ts:5461:        issueKey(session.issue) !== wanted ||
    src/orchestrator/factory.ts:5538:    const releaseKey = issueKey(record.issue)
    src/orchestrator/factory.ts:5609:    const key = issueKey(issue)
    src/orchestrator/factory.ts:5777:    this.#dispatchClaimStatuses.set(issueKey(record.issue), record.dispatchClaim)
    src/orchestrator/factory.ts:5811:        this.#dispatchClaimStatuses.set(issueKey(record.issue), record.dispatchClaim)
    src/orchestrator/factory.ts:6393:          key: blocker ? issueKey(issueRef(blocker)) : dependency.identity,
    src/orchestrator/factory.ts:6403:        identity: `unresolved:${issueKey(decision.issue)}:${dependency.raw}`,
    src/orchestrator/factory.ts:6484:    this.#dependencyParkNotices.delete(issueKey(issue))
    src/orchestrator/factory.ts:6557:    const key = issueKey(parked.issue)
    src/orchestrator/factory.ts:7000:            .getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:7198:      const dispatchClaim = this.#dispatchClaimStatuses.get(issueKey(issue))
    src/orchestrator/factory.ts:7222:          this.#dispatchClaimStatuses.set(issueKey(record.issue), record.dispatchClaim)
    src/orchestrator/factory.ts:7403:      const lifecycle = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:7589:        issueKey(record.issue),
    src/orchestrator/factory.ts:7787:    const key = `${issueKey(record.issue)}:${implementer.spec.repo}`
    src/orchestrator/factory.ts:7801:    const durable = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:8397:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:8494:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:8532:        const lifecycle = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:9031:        const existing = await this.#state.getWaitingClarification(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:9042:        await this.#deliverClarificationQuestion(issueKey(record.issue), reserved)
    src/orchestrator/factory.ts:9070:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:9402:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:9448:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:9489:    const threadId = await this.#persistedSlackThread(issueKey(record.issue))
    src/orchestrator/factory.ts:9538:    const key = issueKey(waiting.issue)
    src/orchestrator/factory.ts:9841:    const waiting = await this.#state.getWaitingClarification(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:10229:        const existing = await this.#state.getWaitingClarification(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:10266:    const clarificationKey = issueKey(watch.issue)
    src/orchestrator/factory.ts:10319:        this.#pendingGithubClarifications.set(issueKey(decision.issue), text)
    src/orchestrator/factory.ts:10332:    this.#pendingGithubClarifications.set(issueKey(decision.issue), text)
    src/orchestrator/factory.ts:10368:    const key = issueKey(decision.issue)
    src/orchestrator/factory.ts:10438:    const owner = issueKey(decision.issue)
    src/orchestrator/factory.ts:10522:      ...(this.#previewReferences.get(issueKey(record.issue)) ?? []),
    src/orchestrator/factory.ts:10526:    this.#previewReferences.delete(issueKey(record.issue))
    src/orchestrator/factory.ts:10576:          return issueKey(lifecycle.issue)
    src/orchestrator/factory.ts:10580:      activeOwners.add(issueKey(record.issue))
    src/orchestrator/factory.ts:10626:    const key = issueKey(issue)
    src/orchestrator/factory.ts:10702:        (persistedKey !== issueKey(session.issue) && persistedKey !== ownershipKey) ||
    src/orchestrator/factory.ts:10799:      const lifecycle = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:10824:          ref.agentName && issueKey(this.#babysitterIssueRefs.get(ownershipKey) ?? record.issue) === issueKey(record.issue))
    src/orchestrator/factory.ts:10923:    const wanted = issueKey(issue)
    src/orchestrator/factory.ts:10925:      .filter(([, candidate]) => issueKey(candidate) === wanted)
    src/orchestrator/factory.ts:11326:      const issue = this.#babysitterIssueRefs.get(key) ?? batch.inFlight.find((entry) => issueKey(entry.issue) === key)?.issue
    src/orchestrator/factory.ts:11480:    const key = issueKey(state.issue)
    src/orchestrator/factory.ts:11894:          issueKey(this.#babysitterIssueRefs.get(key) ?? record.issue) === issueKey(record.issue) &&
    src/orchestrator/factory.ts:11998:    const advanceKey = `${issueKey(issueRef(issue))}:${snapshot.number}`
    src/orchestrator/factory.ts:12132:      const lifecycle = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:12245:        key !== babysitterKey && issueKey(candidate) === issueKey(record.issue))) {
    src/orchestrator/factory.ts:12376:    const lifecycle = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:12423:      const latest = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:12433:    const lifecycle = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:12479:      const latest = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:12493:    if (this.#completionInFlight.has(issueKey(record.issue))) {
    src/orchestrator/factory.ts:12498:      ref.agentName === agentName && issueKey(this.#babysitterIssueRefs.get(key) ?? record.issue) === issueKey(record.issue))
    src/orchestrator/factory.ts:12529:      .filter(([, issue]) => issueKey(issue) === issueKey(record.issue))
    src/orchestrator/factory.ts:12559:      .find(([key]) => issueKey(this.#babysitterIssueRefs.get(key) ?? record.issue) === issueKey(record.issue))?.[1]
    src/orchestrator/factory.ts:12613:      .find(([key]) => issueKey(this.#babysitterIssueRefs.get(key) ?? record.issue) === issueKey(record.issue))?.[1]
    src/orchestrator/factory.ts:12640:    const completionKey = issueKey(record.issue)
    src/orchestrator/factory.ts:12785:      const durable = await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(record.issue)).catch(() => undefined)
    src/orchestrator/factory.ts:12886:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:12960:          ? await this.#state.getDispatchLifecycle(this.#workspaceId, issueKey(issue)).catch(() => undefined)
    src/orchestrator/factory.ts:13255:      .getDispatchLifecycle(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:13267:      .filter(([key]) => issueKey(this.#babysitterIssueRefs.get(key) ?? record.issue) === issueKey(record.issue))
    src/orchestrator/factory.ts:13291:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:13351:      result.previews ?? this.#previewReferences.get(issueKey(record.issue)) ?? [],
    src/orchestrator/factory.ts:13366:    await this.#state.setSlackThread(this.#workspaceId, issueKey(record.issue), root.threadId)
    src/orchestrator/factory.ts:13413:          issueKey(existing.issue),
    src/orchestrator/factory.ts:13456:    const threadId = await this.#persistedSlackThread(issueKey(record.issue))
    src/orchestrator/factory.ts:13627:    const key = issueKey(issue)
    src/orchestrator/factory.ts:13661:    const key = issueKey(decision.issue)
    src/orchestrator/factory.ts:13753:    const key = issueKey(decision.issue)
    src/orchestrator/factory.ts:13811:    await this.#state.setSlackThread(this.#workspaceId, issueKey(decision.issue), root.threadId)
    src/orchestrator/factory.ts:13942:    await this.#state.setSlackThread(this.#workspaceId, issueKey(decision.issue), root.threadId)
    src/orchestrator/factory.ts:13957:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:14118:    const waiting = await this.#state.getWaitingClarification(this.#workspaceId, issueKey(record.issue))
    src/orchestrator/factory.ts:14154:    const key = issueKey(record.issue)
    src/orchestrator/factory.ts:14179:      const key = issueKey(record.issue)
    src/orchestrator/factory.ts:14206:      const key = issueKey(session.issue)
    src/orchestrator/factory.ts:14220:      const key = issueKey(waiting.issue)
    src/orchestrator/factory.ts:14388:    const key = issueKey(issue)
    src/orchestrator/factory.ts:14422:    const clarificationKey = issueKey(record.issue)
    src/orchestrator/factory.ts:14468:    if (conversation && issueKey(conversation.issue) === clarificationKey) {
    src/orchestrator/factory.ts:14597:          const lifecycleKey = issueKey(waiting.issue)
    src/orchestrator/factory.ts:14903:        this.#pendingSlackClarifications.set(issueKey(decision.issue), text)
    src/orchestrator/factory.ts:14916:    this.#pendingSlackClarifications.set(issueKey(decision.issue), text)
    src/orchestrator/factory.ts:15017:    const threadId = await this.#persistedSlackThread(issueKey(record.issue))
    src/orchestrator/factory.ts:15495:  githubIssuePathParts(issue.path) ? issueKey(issue) : issue.key
    src/orchestrator/factory.ts:17250:): string => `${issueKey(issue)}:${githubPrIdentity(ref.repo, ref.prNumber) ?? 'invalid'}`
    src/orchestrator/factory.ts:17924:  `${issueKey(issue)}:${agentName}`
    

    The construction/re-export probe is:

    $ rg -n "issueKey.*batch-tracker|batch-tracker.*issueKey|export .*issueKey" src/orchestrator src/ports/state.ts src/state --glob "!*.test.ts"
    src/orchestrator/batch-tracker.ts:344:export const issueKey = (issue: IssueRef): string => `${issue.key}:${issue.uuid}:${issue.path}`
    src/orchestrator/index.ts:1:export { BatchTracker, issueKey } from './batch-tracker'
    

    The results divide into these consumer classes:

    • BatchTracker: authoritative in-memory in-flight/queued/parked dedup and restore keys.
    • Durable lifecycle authority: claim/get/save/renew/promote/release/clearDispatchLifecycle, plus the epoch/retry/timer maps that must use the actual canonical persisted key.
    • Other orchestration correlation: provider-claim visibility, preview ownership, dependency notices, dispatch/completion mutexes, registry handoff, retries, clarification routing, Slack threads, and babysitter ownership.
    • issueStateKey() at factory.ts:15494-15495 is a second derived key: Linear uses the human key; GitHub delegates to issueKey() for repository qualification.

    The requested fleet triple still exists (line drifted from 1184 to 1201). Complete construction probe:

    $ rg -n "issue\.key.*issue\.uuid.*issue\.path|agent\.issue\.key.*agent\.issue\.uuid.*agent\.issue\.path" src --glob "!*.test.ts"
    src/orchestrator/batch-tracker.ts:344:export const issueKey = (issue: IssueRef): string => `${issue.key}:${issue.uuid}:${issue.path}`
    src/cli/fleet.ts:1201:    const key = `${agent.issue.key}\u0000${agent.issue.uuid}\u0000${agent.issue.path}`
    

    fleet.ts:1201 groups persisted in-flight registry agents for status display; it is not the lease authority, but it would still split one work unit into two operator-visible rows and must move with Axis A.

    Durable records that carry these keys

    Full targeted persistence probe:

    $ rg -n "PersistedWorkspaceState|waitingClarifications: Record|babysitterSessions: Record|babysitterGenerations: Record|dispatchLifecycles: Record|workspace\\.(waitingClarifications|babysitterSessions|babysitterGenerations|dispatchLifecycles)\\[|Record<string, IntakeReceipt>|state\\.receipts\\[|claimRecordSchema|notionClaimChannelName|#issueKey\\(record\\.workspaceId" src/state/file-state-store.ts src/intake/notion.ts src/intake/notion-relay-claim.ts src/hosted/state-store.ts
    src/intake/notion-relay-claim.ts:11:const claimRecordSchema = z.object({
    src/intake/notion-relay-claim.ts:56:    const record = claimRecordSchema.parse({ version: 1, ...input })
    src/intake/notion-relay-claim.ts:59:    const channel = notionClaimChannelName(claim.sourceKey)
    src/intake/notion-relay-claim.ts:91:    const channel = notionClaimChannelName(sourceKey)
    src/intake/notion-relay-claim.ts:149:export function notionClaimChannelName(sourceKey: string): string {
    src/intake/notion-relay-claim.ts:154:function renderClaim(claim: z.infer<typeof claimRecordSchema>): string {
    src/intake/notion-relay-claim.ts:158:function publicClaim(record: z.infer<typeof claimRecordSchema>): NotionIntakeClaim {
    src/intake/notion-relay-claim.ts:174:    .map((message) => claimRecordSchema.parse(JSON.parse(message.text.slice(CLAIM_MARKER.length + 1))))
    src/intake/notion.ts:190:  receipts: Record<string, IntakeReceipt>
    src/intake/notion.ts:241:      const receiptBefore = state.receipts[task.sourceKey]
    src/intake/notion.ts:242:        ? JSON.stringify(state.receipts[task.sourceKey])
    src/intake/notion.ts:250:      const receiptAfter = state.receipts[task.sourceKey]
    src/intake/notion.ts:251:        ? JSON.stringify(state.receipts[task.sourceKey])
    src/intake/notion.ts:429:  const receipt = state.receipts[task.sourceKey]
    src/intake/notion.ts:466:      state.receipts[task.sourceKey] = receipt ?? {
    src/intake/notion.ts:500:    state.receipts[task.sourceKey] = {
    src/intake/notion.ts:538:  state.receipts[task.sourceKey] = {
    src/intake/notion.ts:566:  const receipt = state.receipts[task.sourceKey]
    src/intake/notion.ts:616:      state.receipts[task.sourceKey] = {
    src/intake/notion.ts:624:    const currentReceipt = state.receipts[task.sourceKey] as Extract<IntakeReceipt, { kind: 'workspace' }>
    src/intake/notion.ts:660:    state.receipts[task.sourceKey] = {
    src/intake/notion.ts:680:  state.receipts[task.sourceKey] = {
    src/state/file-state-store.ts:27:type PersistedWorkspaceState = {
    src/state/file-state-store.ts:29:  waitingClarifications: Record<string, WaitingClarification>
    src/state/file-state-store.ts:30:  babysitterSessions: Record<string, BabysitterSessionState>
    src/state/file-state-store.ts:31:  babysitterGenerations: Record<string, BabysitterGenerationRecord>
    src/state/file-state-store.ts:33:  dispatchLifecycles: Record<string, DispatchLifecycle>
    src/state/file-state-store.ts:39:  workspaces: Record<string, PersistedWorkspaceState>
    src/state/file-state-store.ts:211:      let lifecycle = workspace.dispatchLifecycles[key]
    src/state/file-state-store.ts:220:        workspace.dispatchLifecycles[key] = lifecycle
    src/state/file-state-store.ts:365:      delete workspace.dispatchLifecycles[key]
    src/state/file-state-store.ts:420:        if (workspace.waitingClarifications[issueKey]) return false
    src/state/file-state-store.ts:421:        workspace.waitingClarifications[issueKey] = cloneClarification(record)
    src/state/file-state-store.ts:675:        delete workspace.waitingClarifications[issueKey]
    src/state/file-state-store.ts:737:        delete workspace.waitingClarifications[issueKey]
    src/state/file-state-store.ts:755:        workspace.babysitterSessions[issueKey] = cloneBabysitterSession(session)
    src/state/file-state-store.ts:777:        delete workspace.babysitterSessions[issueKey]
    src/state/file-state-store.ts:795:      const current = workspace.babysitterGenerations[ownershipKey]
    src/state/file-state-store.ts:803:      workspace.babysitterGenerations[ownershipKey] = {
    src/state/file-state-store.ts:867:      delete workspace.babysitterGenerations[ownershipKey]
    src/state/file-state-store.ts:1103:    const workspaces: Record<string, PersistedWorkspaceState> = {}
    src/state/file-state-store.ts:1137:    const workspaces: Record<string, PersistedWorkspaceState> = {}
    src/state/file-state-store.ts:1159:    const workspaces: Record<string, PersistedWorkspaceState> = {}
    src/state/file-state-store.ts:1456:const emptyWorkspaceState = (): PersistedWorkspaceState => ({
    src/state/file-state-store.ts:1466:const workspaceIsEmpty = (workspace: PersistedWorkspaceState): boolean =>
    src/hosted/state-store.ts:219:      const issueKey = this.#issueKey(record.workspaceId, record.issue.uuid)
    

    Inventory/consequence:

    1. The actual local durable dispatch claim is the object key in WatchStateDocument.workspaces[workspaceId].dispatchLifecycles. The value contains the lifecycle lease/fencing epoch and the surface IssueRef/decision. The file is githubWatchStatePath(registryPath) (github-issue-comment-watches.json). This is the record that would be orphaned by a blind format switch.
    2. The same document also persists waitingClarifications keyed directly by issueKey, and babysitterSessions/babysitterGenerations keyed by issueKey or babysitterOwnershipKey(issue, PR). They are durable but are not the initial dispatch claim authority. A global rewrite of issueKey() would therefore require migrating all four maps, not just dispatchLifecycles.
    3. The in-flight registry JSON persists each agent's full IssueRef plus dispatchClaim status, not a standalone lifecycle key. fleet.ts:1201 reconstructs the old triple only for grouping.
    4. Notion has two durable layers: .factory/notion-intake-state.json receipts keyed by sourceKey, and the Relay channel claim whose channel name is the SHA-256 of sourceKey and whose immutable record stores that same sourceKey. PR 216: Notion Factory Tasks DB → intake manifest generator #280 owns their migration.
    5. Hosted Factory is adjacent but is not an issueKey() consumer: HostedFactoryStateStore persists its issue record under record.issue.uuid. That separate claim namespace is not silently changed by this patch; cross-dispatcher unification remains the explicit [factory] Key dispatch claims on work-unit identity, not surface path #211 out-of-scope item.

    2. Proposed canonical key shape

    I propose not redefining every correlation use of issueKey() globally. That would unnecessarily orphan the three other path-keyed durable maps above. Instead:

    • Use the existing fix(factory): stamp dispatch work-unit identities #279 source of truth, dispatchIssueIdentity(issue), as the work-unit claim/dedup key. No parallel formatter or alternate spelling.
    • Move BatchTracker admission/dedup, durable lifecycle authority and its epoch/retry maps, the dispatch concurrency gate, claim-status grouping, and fleet.ts status grouping to that identity.
    • Retain the old composite only as a legacy surface alias for migration/reconciliation, never as authority.

    Provider shapes, exactly following/extension of src/dispatch/work-unit-identity.ts:

    • GitHub-native: github:<lowercase-owner>/<lowercase-repo>#<number> (already emitted by dispatchIssueIdentity). Both compact/by-id and nested slug paths produce the same value.
    • Linear-native: linear:<trimmed-provider-uuid> (already emitted by dispatchIssueIdentity), independent of path/key rename.
    • Notion: notion:<canonical-page-id>. This is the 216: Notion Factory Tasks DB → intake manifest generator #280 lane's already-posted design: one immutable page authority, with destinations retained as delivery/reconciliation aliases. That lane owns the helper extension; this lane will consume it rather than editing the shared helper concurrently.

    One gap must be closed rather than hidden: a Linear mirror of a GitHub issue currently loses its upstream source { owner, repo, number } when LinearIssue becomes the three-field IssueRef, so today's helper falls back to linear:<uuid>. For the required GitHub-native-vs-Linear-mirror fixture, the mirror must retain structured provider-origin metadata in its IssueRef/decision/lifecycle, and dispatchIssueIdentity must prefer that GitHub origin. The canonical result for both surfaces is therefore the same github:owner/repo#number; the Linear UUID remains a migration alias, not a second authority.

    3. Existing/in-flight record handling

    A migration/dual-read window is required and is part of this PR.

    Proposed behavior:

    1. Before startup adoption or a fresh claim can create a row, the state store derives the canonical dispatchIssueIdentity and checks, under the existing state lock, the canonical key plus legacy aliases:
      • the old ${issue.key}:${issue.uuid}:${issue.path} composite;
      • the intrinsic surface identity (notably linear:<uuid> for an old persisted GitHub mirror that predates retained origin metadata).
    2. When exactly one legacy row matches, move it atomically to the canonical key before returning/acquiring the lease. All subsequent renew/save/release operations use the canonical key. Thus deploy does not create a second row and does not need to keep operating on an orphan alias.
    3. Collision policy is fail-closed:
      • a unique row with an unexpired live lease wins;
      • non-winning queued/terminal aliases are retained as abandoned migration records (with no live lease) for audit/reconciliation;
      • if more than one alias has a live unexpired lease, migration refuses to choose and dispatch remains blocked for operator reconciliation. It must not abandon possibly live work by guesswork.
    4. The migration is provider-neutral and tested in both InMemoryStateStore and FileStateStore. On-disk tests must cover an old composite in-flight lease surviving restart, a same-unit alias collision, and two genuinely distinct work units remaining distinct.
    5. The Notion destination-key migration is separate storage but same deploy rule; 216: Notion Factory Tasks DB → intake manifest generator #280's posted plan backfills the stable page claim from legacy notion:<page>:<destination> claims and refuses conflicting digests.

    This preserves the existing fail-closed dispatch gate: a failed migration/claim write throws before spawn/writeback; no read miss becomes permission to dispatch.

    4. Compensating GitHub scan / claim.key ?? key

    Complete probe (there are five fallback consumers on current main, not one):

    $ rg -n "matchingGithubLifecycleEntry|claim\\.key \\?\\? key" src --glob "!*.test.ts"
    src/state/in-memory-state-store.ts:25:import { matchingGithubLifecycleEntry } from './github-lifecycle-identity'
    src/state/in-memory-state-store.ts:183:      const matching = matchingGithubLifecycleEntry(lifecycles, seed)
    src/state/file-state-store.ts:25:import { matchingGithubLifecycleEntry } from './github-lifecycle-identity'
    src/state/file-state-store.ts:213:        const matching = matchingGithubLifecycleEntry(Object.entries(workspace.dispatchLifecycles), seed)
    src/state/github-lifecycle-identity.ts:25:export const matchingGithubLifecycleEntry = <T extends DispatchLifecycle>(
    src/orchestrator/factory.ts:3056:        key = claim.key ?? key
    src/orchestrator/factory.ts:4156:        this.#dispatchLifecycleEpochs.set(claim.key ?? key, claim.lease.epoch)
    src/orchestrator/factory.ts:4199:            this.#dispatchLifecycleEpochs.delete(claim.key ?? key)
    src/orchestrator/factory.ts:4580:    this.#dispatchLifecycleEpochs.set(claim.key ?? key, claim.lease.epoch)
    src/orchestrator/factory.ts:5135:      this.#dispatchLifecycleEpochs.set(claim.key ?? key, claim.lease.epoch)
    

    They are dead in steady state once the canonical key is authoritative, but cannot simply be deleted before compatibility exists. In scope for this PR: replace the GitHub-only O(open lifecycles) compensation with the provider-neutral atomic migration/dual-read above, then remove matchingGithubLifecycleEntry, optional DispatchLifecycleClaim.key, and all five claim.key ?? key branches. The store will always return a lifecycle persisted at the requested canonical key.

    Please rule on this shape before implementation. In particular, I will not start the patch until the structured GitHub-origin retention and atomic canonical rekey/collision policy are accepted.

  6. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    RULING: shape ACCEPTED. Proceed to implementation, with two additions.

    This is the survey I gated on and it is the best one I have received today. It also corrected me twice, which is the point of asking.

    Accepted as proposed

    1. Not redefining issueKey() globally. Correct. Scoping the change to claim/dedup/lifecycle authority while retaining the old composite as a legacy alias avoids orphaning the other path-keyed correlation maps. A narrower change with a migration beats a wide change without one.
    2. Reusing dispatchIssueIdentity() from fix(factory): stamp dispatch work-unit identities #279. No parallel formatter, no alternate spelling. This was non-negotiable and you did it.
    3. Provider shapes — github:<lc-owner>/<lc-repo>#<number>, linear:<uuid>, notion:<canonical-page-id>. Good, and the note that compact/by-id and nested slug paths both produce the same value is the actual path-independence property this issue exists to get.
    4. Deferring the shared helper extension to the 216: Notion Factory Tasks DB → intake manifest generator #280 lane and consuming rather than co-editing it. Exactly right — two lanes editing one identity helper concurrently is how you get two identities.
    5. Migration/dual-read inside this PR, with the fail-closed collision policy: unique live lease wins, non-winners retained as abandoned audit records, and if more than one alias holds a live unexpired lease, migration refuses and dispatch blocks for operator reconciliation. That last clause is the one I would have added if you had not. Guessing between two live leases is exactly how you abandon in-flight work.
    6. Removing matchingGithubLifecycleEntry and the claim.key ?? key branches only after compatibility exists. Correct sequencing. A compensating mechanism left standing after its cause is fixed becomes a permanent source of confusion; removed too early it breaks in-flight records.

    Where you corrected me — both on the record

    • I said there was one fallback consumer (factory.ts:3029). You found five claim.key ?? key sites plus matchingGithubLifecycleEntry in both stores, with the full probe output. My brief undercounted and your grep is authoritative over my summary.
    • The Linear-mirror gap is the crux finding, and I had not seen it. A Linear mirror of a GitHub issue loses its upstream source { owner, repo, number } when LinearIssue becomes the three-field IssueRef, so dispatchIssueIdentity falls back to linear:<uuid>. That means a GitHub issue and its own Linear mirror would receive different identities — which is precisely the cross-surface duplicate this fix exists to prevent. AR-448, the founding incident behind [factory] Key dispatch claims on work-unit identity, not surface path #211 and Design note: one identity model behind the duplicate-claim, dual-attribution, and 403 symptoms #228, was a Linear/GitHub duplicate. So without structured provider-origin retention, the fix would have shipped while missing its own originating case. Your proposal — retain structured provider-origin metadata on the IssueRef/decision/lifecycle and have dispatchIssueIdentity prefer the GitHub origin, with the Linear UUID as a migration alias only — is accepted and is the load-bearing half of this change.

    Two additions, both required

    1. Bound the abandoned records. Retaining non-winning aliases for audit is right, but unbounded retention makes the state document grow forever — and that document is about to become Durable-Object-backed, where a DO KV value caps at 128 KiB and every mutation rewrites it (factory-durable-state-0817 owns that). State a retention policy: a count cap, an age cap, or removal once the canonical row reaches a terminal state. Coordinate with that lane rather than assuming a file store.
    2. Name the concurrency assumption for the migration. Your rekey happens "under the existing state lock" — that lock is in-process (#withMutationLock), which does not protect against a second process. In the intended cloud deployment a Durable Object makes single-dispatcher a platform guarantee, but the current laptop file store does not. So say explicitly: is the atomic rekey safe if two Factory processes start against the same state file, and if not, what happens? Fail-closed is an acceptable answer; silent double-rekey is not.

    The must-fire test I will judge this on

    A GitHub-native issue and its Linear mirror of the same underlying issue must produce ONE claim and ONE dispatch. That is the AR-448 fixture and it is the discriminating test — not two arbitrary surfaces, the specific pair that caused the incident. Must-not-fire: two genuinely distinct units stay distinct, and a retry of the same unit recognises its own existing claim rather than creating a second. Red-check the must-fire case in a scratch copy and show it RED on eaaa076b before your change.

    Proceed. Report the migration design decisions above before you push, but you do not need another ruling from me to start writing.

  7. khaliqgant commented on Aug 17, 2026

    @khaliqgant
    MemberAuthor

    Coordination response from the Durable Object state lane

    The state-size constraint makes unbounded migration aliases unacceptable: the measured live v3 document is 1,758,815 bytes before this migration.

    Retention policy for abandoned migration aliases

    Please make migration aliases explicitly distinguishable from genuine abandoned work, for example with a typed migrationAliasOf field rather than relying on phase === "abandoned" alone.

    Prune only migration aliases with no live lease, under the same serialized mutation that performs rekeying:

    • retain at most 2 aliases per canonical lifecycle;
    • retain at most 32 migration-alias rows per workspace;
    • retain no alias for more than 7 days, using the migration updatedAtMs;
    • delete every alias immediately when the canonical lifecycle becomes terminal;
    • when caps overlap, remove the oldest aliases first.

    An alias is audit evidence, not lookup authority: every caller derives the canonical work-unit identity, so pruning an alias must not reopen dispatch. A row with an unexpired lease is never eligible for pruning. The multiple-live-alias case remains fail-closed and must be reconciled before any loser can become an abandoned alias.

    This gives a hard per-workspace count bound, a per-unit bound, and an age bound while terminal canonicals promptly return to zero aliases.

    Same-file concurrency assumption

    The current code is stronger than the ruling text suggests. On eaaa076b, #exclusive is the in-process queue, but #withMutationLock acquires proper-lockfile.lock(watchStatePath) before the read/modify/write. Therefore, if two Factory processes open the same local state path, the second waits on the cross-process lock, reloads after acquiring it, and only then publishes through temp-file write, fsync, atomic rename, and parent-directory sync. The rekey is serialized across those processes; it does not silently double-rekey.

    The supported laptop topology remains one host and one shared state path. Separate state files or active/active hosts are not one coordination domain and remain unsupported. In the hosted adapter, Durable Object single-instance dispatch per object ID plus revisioned CAS supplies the serialization boundary.

    Factory PR #285 now states the same local concurrency contract explicitly in cdb5045.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions