mirror of
https://github.com/multica-ai/multica.git
synced 2026-08-01 01:16:17 +02:00
* feat(attribution): Phase 1 foundation — provenance schema + resolver (MUL-4302)
Human Attribution, Phase 1 (地基) first increment. Every agent run must be
traceable to exactly one accountable human AND record at which waterfall level
that human was resolved, so a NULL originator can be told apart from a genuine
'no human in the chain'.
- migration 149: add originator_source (waterfall label) + delegation/retry/
rerun/rule-version lineage + kind-tagged trigger evidence to agent_task_queue.
No FK, no cascade, no CHECK on the source enum (MUL-4302 §7); nullable ADD
COLUMNs = fast metadata-only change on the hot queue table.
- internal/attribution: the accountable-human vocabulary (Source, EvidenceKind,
TriggerKind) + pure, unit-tested classification rules (ClassifyComment/
ClassifyDirect). No DB, no authorization — provenance labeling only.
- service: attributionFor{IssueTask,TriggerComment} gather facts and delegate to
the pure classifier; the legacy originator resolvers now delegate here so
there is one source of truth. originator_user_id's VALUE is unchanged, so the
Composio-overlay and canInvokeAgent A2A authorization boundaries are
byte-for-byte preserved (MUL-4302 §1.3).
- enqueueIssueTask / enqueueMentionTask stamp originator_source + evidence;
CreateRetryTask carries the parent attribution forward and records
retry_of_task_id so retry and manual rerun stay separable (MUL-4302 §5).
Verified: go build ./..., go vet, gofmt clean; new attribution unit tests +
enqueue stamping integration test green; existing resolve_originator tests
unchanged.
Co-authored-by: multica-agent <github@multica.ai>
* feat(attribution): split accountable_user_id from originator, close enqueue bypasses (MUL-4302)
Phase 1, per Bohan's decision on the MUL-4302 thread: audit and authorization
answer different questions and get different columns.
- Migration 151 adds agent_task_queue.accountable_user_id (no FK, no cascade).
Authorization keeps reading ONLY originator_user_id (canInvokeAgent A2A gate,
Composio overlay); audit/UI/usage read accountable_user_id + source + evidence.
- Invariant (finalizeAttribution, single chokepoint + §11 tests): originator
non-null ⟹ accountable equals it. The two diverge only when originator is null
(autopilot / degraded fallback), which is the deferred rule_owner/owner_fallback
increment; this lands the column + mirror-write so that split has a home.
- Close the NULL-source enqueue bypasses Elon flagged: chat, quick-create,
deferred-fallback and run_only-autopilot now stamp originator_source + evidence
(+ accountable where a human exists). Autopilot stays unattributed until the
rule-version snapshot table lands, but is no longer a silent NULL-source row.
Retry inherits accountable_user_id like the rest of the attribution lineage.
- Fix assign/promote attribution (§4): a member who assigns/promotes an existing
issue is now the accountable human (and, by the invariant, originator) ahead of
the issue creator. Threaded as an OPTIONAL actor override, so comment/rerun/
autopilot paths keep today's resolution and create-with-assignee (creator ==
actor) is unchanged. The squad leader gate already judged the same member.
Also merges origin/main: renumbers the attribution migration 149→150 (main took
149 for issue_origin_agent_create) and folds agent_create into ClassifyDirect's
origin inheritance.
go build/vet/gofmt clean; attribution unit tests + service stamp/actor tests +
handler suite pass on a fresh DB migrated through 151.
Co-authored-by: multica-agent <github@multica.ai>
* docs(attribution): fix accountable NULL semantics + close chat/quick-create evidence boundary (MUL-4302)
Addresses Elon's 2nd-round review on PR #5150 (pre-merge doc/evidence items):
- Migration 151 no longer overclaims NULL. accountable_user_id is NULL not only
on pre-migration rows but on NEW rows whose audit source resolved no human yet
(run_only autopilot writes originator_source='unattributed' with NULL
accountable until rule_owner lands). Header + COMMENT ON COLUMN reworded so a
schema reader does not misjudge the invariant.
- Chat now uses the UNIFORM evidence pair (kind=chat, ref=chat_session_id), like
autopilot_run/issue_assignment, instead of relying only on the dedicated
chat_session_id column — new EvidenceChat kind. Added a service test asserting
chat stamps direct_human + chat evidence.
- Quick-create is documented as the ONE intentional no-antecedent-row path: no
comment/issue/session/run exists at enqueue time (the run creates the issue), so
trigger_evidence_kind/ref stay NULL while the human rides originator/accountable
and source is direct_human — not a NULL-source bypass.
No authorization behavior change. attribution + service + handler suites pass on a
DB migrated through 151.
Co-authored-by: multica-agent <github@multica.ai>
* chore(attribution): renumber migrations 150/151 → 157/158 after merging main (MUL-4302)
main's #5162 ("unblock release migrations") renumbered the chat migrations and
took 150 (agent_task_coalesced_comments) and 151 (chat_read_cursor), colliding
with this branch's attribution migrations. Renumber them above main's new highest
(156) so TestMigrationNumericPrefixesStayUniqueAfterLegacySet passes:
- 150_agent_task_attribution → 157_agent_task_attribution
- 151_agent_task_accountable_user → 158_agent_task_accountable_user
Fixed the internal "migration 150" references in 158's header to 157. Migrations
apply cleanly through 158 on a fresh DB; migration lint green.
Co-authored-by: multica-agent <github@multica.ai>
* feat(attribution): autopilot rule_owner — accountable = rule version publisher (MUL-4302)
Implements rule_owner (MUL-4302 §3.4), the first attribution source where the
accountable human diverges from the (NULL) authorization originator.
- Migration 159 adds the append-only autopilot_rule_version snapshot table (no FK,
no cascade); migration 160 adds its CONCURRENTLY lookup index.
- Write-on-publish: CreateAutopilot appends v1 (publisher = creator); UpdateAutopilot
appends a new version when a SUBSTANTIVE autopilot-row field changes (assignee /
status / execution_mode) — cosmetic edits (title/description/template) write none.
Both run inside the existing handler tx (atomic with the autopilot write).
- Dispatch resolution: both autopilot execution modes now resolve the active rule
version and stamp originator_source='rule_owner', accountable_user_id=publisher,
rule_version_id=<snapshot>, with originator_user_id left NULL (authorization
unchanged). run_only stamps CreateAutopilotTask directly; create_issue resolves in
attributionForIssueTask so both modes attribute identically. A missing version /
non-member publisher degrades to unattributed — never fabricates a human.
- finalizeAttribution now enforces the invariant ONE-WAY: it mirrors originator onto
accountable only when originator is valid, leaving an explicitly-set accountable
(rule_owner / future owner_fallback) intact when originator is NULL. Added
rule_version_id to CreateAgentTask so the create_issue path persists it too.
Also merges origin/main and renumbers this branch's attribution migrations
150/151 → 157/158 (main's #5162 took 150/151); rule_version table is 159/160.
Tests: attribution unit RuleOwner + one-way invariant table; service integration
tests proving an autopilot-origin issue stamps rule_owner + rule_version_id (and
degrades to unattributed with no version). Full service/attribution/handler/
migration suites pass on a DB migrated through 160; build/vet/gofmt clean.
Deferred (same PR): trigger-table republish (cron/webhook/event_filters) and
system-pause/archive versioning; owner_fallback + fail-closed; manual rerun.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): manual autopilot trigger → direct_human to the triggering member (MUL-4302)
Elon's blocking finding: a member manually triggering an autopilot was attributed
rule_owner (accountable = rule publisher, originator NULL) like a schedule/webhook
run, so member B triggering member A's autopilot landed accountable=A and carried
no originator authorization context for the run. Per MUL-4302 §4 a manual "run now"
is a direct human action and must attribute direct_human to the triggering member.
- Thread the triggering member from TriggerAutopilot into dispatch: new
DispatchAutopilotManual carries actorUserID (resolved via resolveActor +
memberActorUserID, so only a member actor is a human; an A2A agent actor falls
back to rule_owner). DispatchAutopilot / DispatchAutopilotForPlan keep their
public signatures (pass an invalid actor); only the internal dispatchAutopilot /
dispatchCreateIssue / dispatchRunOnly gained the param, so the many existing
callers are untouched.
- run_only: dispatchRunOnly stamps direct_human (originator == accountable ==
actor, no rule_version) for a manual actor, else rule_owner. CreateAutopilotTask
gains an originator_user_id param for the manual case.
- create_issue: dispatchCreateIssue enqueues a manual trigger via the actor-carrying
*WithHandoff entry points; attributionForIssueTask's autopilot-origin rule_owner
branch is now guarded on !actorUserID.Valid, so a valid actor falls through to the
direct_human override. Both execution modes attribute identically.
- schedule / webhook keep rule_owner (no actor). Trigger-table + system-pause/archive
versioning remain the pre-merge follow-ups.
Tests: the run_only row assertion Elon asked for (schedule → rule_owner row on
CreateAutopilotTask), plus manual direct_human on BOTH modes (run_only and
create_issue), including a manual actor distinct from the rule publisher. Full
service/attribution/handler/migration/scheduler/cmd suites pass on a DB migrated
through 160; build/vet/gofmt clean.
Co-authored-by: multica-agent <github@multica.ai>
* feat(attribution): owner_fallback + fail-closed policy, and manual-rerun direct_human (MUL-4302)
Two of the three remaining Phase 1 items (trigger-table / system-pause versioning
is deferred — see PR description).
owner_fallback + fail-closed (§1/§3.5) — the never-null accountable guarantee:
- attribution.OwnerFallback degrades an UNATTRIBUTED result to owner_fallback:
accountable = agent owner, originator stays NULL (audit-only, authz untouched),
Source.Precise()==false. finalizeAttribution's one-way invariant already allows
accountable-set / originator-NULL divergence, so nothing else changes.
- Migration 161 adds workspace.attribution_fail_closed (default FALSE) + a lean
GetWorkspaceAttributionFailClosed read. (Also added the column to ListWorkspaces'
explicit column list so its row type stays db.Workspace.)
- applyAttributionFallback is applied at every enqueue boundary (issue, mention,
chat, quick-create, deferred-fallback, autopilot run_only): unattributed →
owner_fallback (agent owner) by default, or ErrAttributionFailClosed when the
workspace is fail-closed, which the caller surfaces to refuse the enqueue (the
run does not start). So no run is left without an accountable human, and a
compliance workspace can block unattributable runs instead.
manual rerun (§5) — a rerun is a NEW direct_human trigger to the rerunning member:
- RerunIssue threads the acting member (resolved in the handler via resolveActor)
down to enqueueRerunTask, and attributionForIssueTask is now actor-first so the
actor wins over an INHERITED trigger comment (a rerun keeps the comment for the
daemon's prompt context but must attribute to whoever clicked rerun, not the
original comment's human).
- rerun_of_task_id lineage is recorded via a targeted SetAgentTaskRerunOf update on
the rerun path only (keeping the shared CreateAgentTask insert untouched), so
system retry (retry_of_task_id) and human rerun stay separable in reporting.
Tests: OwnerFallback unit test; owner_fallback + fail-closed-refusal + manual-rerun
(direct_human + rerun_of_task_id) service tests; the prior "degrades to unattributed"
test updated to owner_fallback. Full service/attribution/handler/migration/scheduler/
cmd suites pass on a DB migrated through 161; build/vet/gofmt clean.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): close fail-open holes + move rerun_of_task_id into creation snapshot (MUL-4302)
Addresses Elon's two must-fixes on PR #5150.
1. accountable-never-null / fail-closed had fail-open holes. applyAttributionFallback
now, for an UNATTRIBUTED run, refuses the enqueue (ErrAttributionFailClosed) in
THREE cases instead of silently degrading to a runnable NULL-accountable task:
- workspace policy read fails (or no workspace) → fail closed; we cannot confirm
fallback is permitted, so we don't run an unattributable task on a DB hiccup.
(Only the rare unattributed path pays this; precise runs never read the policy.)
- workspace is fail-closed → refuse (unchanged).
- owner_fallback has no valid agent owner → refuse rather than enqueue a task with
a NULL accountable_user_id.
ErrAttributionFailClosed's doc now covers all three "cannot guarantee an
accountable human" refusals. Added missing-owner / policy-read-failure /
precise-passthrough tests.
2. manual rerun rerun_of_task_id was a post-notify UPDATE (race: the queued event /
daemon claim could see rerun_of_task_id = NULL, and a failed update degraded the
run to a plain direct_human). It now rides the CreateAgentTask insert — threaded
through enqueueIssueTask / enqueueMentionTask as a creation param (like
retry_of_task_id) so it is written in the same statement before the daemon is
notified. Removed the SetAgentTaskRerunOf follow-up query.
Also merges origin/main (unrelated CLI fix #5167, no conflict). Full service /
attribution / handler / migration / scheduler / cmd suites pass on a DB migrated
through 161; build / vet / gofmt clean.
Co-authored-by: multica-agent <github@multica.ai>
* feat(attribution): rule_owner versioning on trigger edits + system-pause/archive (MUL-4302)
The final remaining Phase 1 item: substantive publishes beyond the autopilot row now
republish the rule version, so a run's rule_owner accountable follows whoever last
changed what the rule does.
- Extracted the config-summary + insert into service.RecordAutopilotRuleVersion so
the handler and the (different-package) failure monitor share one writer; the
handler's recordAutopilotRuleVersion is now a thin wrapper.
- Trigger edits: UpdateAutopilotTrigger and DeleteAutopilotTrigger republish the rule
version with the acting member as publisher, ATOMICALLY (tx-wrapped mutation +
version write, mirroring CreateAutopilot/UpdateAutopilot). CreateAutopilotTrigger
republishes best-effort — the webhook path mints its token with a retry loop that
cannot share one tx, and a create is usually initial setup already covered by v1;
a failed write there is benign (active version stays the current publisher, the new
trigger fires under it, no immediate daemon claim rides it).
- Archive (DeleteAutopilot) republishes (member, status=archived), tx-wrapped.
- System auto-pause (failure monitor) republishes with a 'system' publisher,
best-effort — a background sweep to a non-dispatching state (a paused autopilot
never dispatches; a later member resume supersedes).
- RotateWebhookToken / SetSigningSecret deliberately do NOT version: they rotate
credentials, not the rule's behavior (not §3.4 substantive).
Semantics: a system-published (no-member) active version degrades dispatch to
unattributed → owner_fallback, never fabricating a human.
Tests: republish-reattributes (member A → member B supersedes → dispatch resolves to
B; system publisher → unattributed). Full service/attribution/handler/migration/
scheduler/cmd suites pass on a DB migrated through 161; build/vet/gofmt clean.
Also merges origin/main (unrelated frontend feature #5074).
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): make trigger-create rule-version republish atomic (MUL-4302)
Addresses Elon's final Phase 1 blocking finding: CreateAutopilotTrigger recorded the
rule-version republish best-effort AFTER the trigger insert. If member B added a
schedule/webhook trigger to member A's autopilot and the version write failed, future
schedule/webhook dispatches would keep attributing to A — violating the rule_owner
invariant that the last member to substantively change the rule owns future runs
("no immediate daemon claim" doesn't save it, since the miss surfaces at the LATER
trigger firing).
Both create paths now write the version in the SAME tx as the trigger INSERT:
- schedule create: wrap CreateAutopilotTrigger + recordAutopilotRuleVersion in one tx.
- webhook create: each mint-with-retry attempt runs in its own tx (insert + version
commit together; a token collision rolls that attempt back and retries with a fresh
token; a version-write failure rolls the trigger back). Passes ap + the acting
member id into the helper.
- removed the best-effort recordTriggerRuleVersionBestEffort helper (and the now-unused
slog import).
Test: TestCreateTrigger_RepublishesRuleVersionAtomically drives both create paths
through the handler and asserts a rule version is published by the acting member.
Existing webhook/trigger/archive handler tests still pass. Also merges origin/main
(unrelated avatar feature #5074). Full service/attribution/handler/migration/
scheduler/cmd suites pass on a DB migrated through 161; build/vet/gofmt clean.
Co-authored-by: multica-agent <github@multica.ai>
* feat(attribution): Phase 2.1 — surface run attribution on the task API (MUL-4302 §9)
First Phase 2 (visibility) increment: the agent-task API now returns the resolved
accountable-human provenance so the UI can render an "on behalf of" badge.
- AgentTaskResponse gains an `attribution` object: source label (never blank —
pre-migration NULL renders "unattributed") + `precise` flag (false for the degraded
owner_fallback / backfill / unattributed sources), the initiator (accountable) and
originator (authorization) user refs, the evidence {kind, ref_id} pointer, and the
rule_version / delegated / retry / rerun lineage ids.
- The label + evidence + raw ids are built in the PURE taskToResponse (no DB), so
every task response carries them. Names are hydrated separately, only on the
user-facing surfaces (ListAgentTasks, ListWorkspaceAgentTaskSnapshot, RerunIssue,
CancelTaskByUser) — daemon-claim paths stay lean.
- Hydration resolves initiator/originator from the GLOBAL user table (departed-member
safe) via a new batch GetUsersByIDs query (no N+1); best-effort, so a lookup hiccup
leaves the raw ids intact.
Tests: pure taskAttributionBase (direct_human / rule_owner NULL-originator /
owner_fallback degraded / pre-migration→unattributed) + DB hydration (fills known
ref, leaves unknown id un-filled, skips nil). Full handler/service/attribution/
migration/scheduler/cmd suites pass on a DB migrated through 161; build/vet/gofmt
clean. The field is additive — the frontend's parseWithFallback ignores unknown keys,
so nothing breaks until the UI increment consumes it.
Also merges origin/main (unrelated editor feature #5090).
Remaining Phase 2 (next increments, same PR): frontend zod schema + "on behalf of"
badge + evidence-chain jump; append-only correction events (write + display).
Co-authored-by: multica-agent <github@multica.ai>
* feat(attribution): Phase 2.2 — on-behalf-of badge in the execution log (MUL-4302 §9)
Surface the accountable human on every agent run row:
- AttributionBadge composes Badge + ActorAvatar, shows "on behalf of <member>"
with the resolution source as a tooltip; degraded (non-precise) attribution
gets a warning tone, and an unresolved initiator renders an explicit
"no responsible member" chip.
- Wire the badge into both active and past rows of the execution log.
- Mirror the attribution shape into AgentTaskResponseSchema (defensive, .loose())
so the cancel-task path carries it through zod; add parse tests.
- Export TaskAttribution/AttributionUser/TaskEvidence from @multica/core/types
and add the attribution block to all four issues.json locales.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): hydrate initiator names on issue-facing task endpoints + bound the badge (MUL-4302 §9)
Address Elon's PR #5150 review:
- ListTasksByIssue (the execution-log data source), GetActiveTaskForIssue and the
issue-scoped CancelTask now call hydrateTaskAttributions, so the "on behalf of
<member>" badge shows the real member name on issue detail instead of falling
back to "someone". Mirrors the existing ListAgentTasks / snapshot behavior.
- AttributionBadge: cap width (max-w-40, min-w-0) and truncate the name span so a
long name / narrow right column can't squeeze out trigger/status/actions; keep
the avatar shrink-0.
- Add a handler test asserting the issue task list returns a hydrated
attribution.initiator.name.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): use semantic AvatarSize 'xs' for the badge avatar
main refactored ActorAvatar.size from a raw pixel number to the semantic
AvatarSize union (packages/ui/lib/avatar-size). Switch the on-behalf-of badge
avatar from size={14} to size="xs" (16px) after merging main.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): stage-cascade falls back to parent-issue provenance, not agent owner (MUL-4302)
When closing the last sub-issue in a Stage wakes the parent's assignee agent, the
run was enqueued via a system-authored child-done comment with no actor, which the
resolver classified as unattributed and then degraded to owner_fallback (the agent's
own owner). That is the wrong accountable human: the woken run should be accountable
to whoever caused the parent issue to exist.
attributionForIssueTask now detects a system-authored trigger comment and falls
through to the parent issue's own provenance — the same creator / agent_create-origin
/ autopilot-origin chain a direct enqueue resolves (so an agent-decomposed parent
attributes via delegation to the human who drove it; a member-created parent to that
member; an autopilot parent to the rule publisher). owner_fallback is now only the
last resort when the parent provenance itself has no human.
- Extract attributionFromComment so attributionForIssueTask can inspect author_type
without a second GetComment; authorization resolution stays byte-identical.
- Add a DB-backed test asserting a system child-done comment resolves to the parent
issue's origin human (delegation), not owner_fallback.
Co-authored-by: multica-agent <github@multica.ai>
* feat(attribution): autopilot runs attribute to the firing trigger's creator (MUL-4302)
Per Bohan: an autopilot schedule/webhook run should be accountable to the human
who created the SPECIFIC trigger that fired it, not the rule publisher. (Manual
triggers already attribute to the invoking member via direct_human — unchanged.)
- Migration 162: add autopilot_trigger.created_by_type/created_by_id (nullable, no
FK/cascade). Capture the creating member at both trigger-create sites (schedule +
webhook).
- New precise source trigger_owner: originator stays NULL (an autonomous fire
carries no human authorization — same authz-safe divergence as rule_owner),
accountable = the trigger's member creator.
- triggerOwnerAttribution resolves run.trigger_id → creator; wired into run_only
dispatch and the create_issue path (bridging issue → active run → trigger_id).
Legacy triggers with no recorded creator, and agent-created triggers, degrade to
rule_owner then owner_fallback — nothing regresses.
- Frontend: trigger_owner source label in all four locales + badge switch case.
- Tests: attribution TriggerOwner unit + Precise/invariant; DB-backed resolver
tests (member creator → trigger_owner; creatorless → rule_owner fallback).
Co-authored-by: multica-agent <github@multica.ai>
* chore(attribution): re-trigger CI (dropped synchronize event on 249090260)
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): mirror accountable_user_id on comment-coalescing merge (MUL-4302)
The one-way invariant is 'originator_user_id IS NOT NULL ⟹ accountable_user_id =
originator_user_id', enforced at finalizeAttribution for enqueues and preserved by
the retry-clone (copies both columns). But MergeCommentIntoPendingTask (main #5192)
re-stamps originator_user_id to the newly-coalesced comment's human WITHOUT touching
accountable_user_id — so folding member B's comment into member A's queued task left
originator=B / accountable=A, violating the invariant. Re-stamp accountable to mirror
the new originator (same thing finalizeAttribution does). Add a DB-backed regression
test.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): Elon's 3 must-fixes + DB cross-column invariant CHECK (MUL-4302)
Bohan approved Elon's plan; this closes the three attribution boundaries he flagged
and locks the one-way invariant at the DB.
1. Delegation now inherits the parent's ACCOUNTABLE, not just its originator. An
autopilot-rooted chain (parent originator NULL, accountable = trigger creator)
@mentioning an agent / creating a sub-issue used to drop to unattributed →
owner_fallback and fail-closed workspaces wrongly rejected the fan-out. Added
ParentAccountable/OriginAccountable to CommentFacts/DirectFacts; ClassifyComment/
ClassifyDirect copy accountable down (source=delegation, precise, originator NULL)
so the chain root stays stable at any depth (§3.2).
2. The direct-chat send path (SendDirectChatMessage, MUL-4351) wrote only
originator_user_id — no accountable/source/evidence, a NULL-source bypass. It now
stamps the full direct_human attribution like EnqueueChatTask.
3. Comment-coalescing merge re-attribution is now ATOMIC: MergeCommentIntoPendingTask
re-stamps the whole snapshot (person columns + source + delegation lineage + rule
version + evidence) of the new comment, not just the two person fields, so a merged
run never shows B accountable while pointing at A's stale source/evidence.
4. Migration 169: NOT VALID CHECK (originator_user_id IS NULL OR (accountable_user_id
IS NOT NULL AND accountable_user_id = originator_user_id)). Enforces the invariant
on every new write (the class of bug #5192 introduced); historical rows not blocked,
VALIDATE after Phase 3 backfill. Updated test fixtures that seeded originator-only
rows to also set accountable.
Merged latest main (renumbered attribution migrations 163–168 after main took 161/162;
merged the retry-clone chat_input_task_id + attribution columns). Verified: go build/
vet, attribution/service/handler/cmd-server tests on a migrated DB, frontend
typecheck/lint/tests.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): trigger responsibility transfers to effective publisher; fail-closed comment merge
Elon final-review must-fix 1 (MUL-4302): trigger_owner now resolves to the
member CURRENTLY responsible for the firing trigger's effective config, not the
fixed creator. Per-trigger published_by on autopilot_trigger, seeded to the
creator and re-stamped to the editor on a substantive edit — a trigger-scoped
edit bumps only that row (UpdateAutopilotTrigger), an autopilot-level edit bumps
all its triggers (UpdateAutopilot). Editing one trigger never reassigns another.
Adds real dispatchRunOnly transfer test + resolver-level isolation test.
Must-fix 3: AttributionForMergedComment reuses applyAttributionFallback and
returns ErrAttributionFailClosed; the merge caller refuses on fail-closed,
keeping the queued task's original precise snapshot instead of degrading it to
owner_fallback. Adds regression test.
Renumbered attribution migrations to 166-172 after merging main.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): make migration 172 invariant CHECK upgrade-safe (Option A)
Elon final-review must-fix 2 (MUL-4302), rollout chosen by Bohan. The NOT VALID
CHECK still checks a pre-existing row on any later UPDATE (even one not touching
attribution columns), so cross-deployment stale queued/running tasks (originator
set, accountable NULL from before migration 167) would fail on their next
claim/complete/cancel. Exempt exactly those legacy rows via 'originator_source
IS NULL' — that column was added in 166 with no backfill, so it is NULL only on
pre-migration rows and non-NULL on every attribution-aware write. New writes
stay fully enforced; the #5192 bypass class (source always set) is unaffected.
Phase 3 backfills legacy rows then drops+re-adds the strict form + VALIDATE.
Adds TestAttributionInvariantCheck_ExemptsLegacyRows (legacy row survives a
status UPDATE) and updates the reject-bypass test to the enforced regime.
Co-authored-by: multica-agent <github@multica.ai>
* fix(attribution): pin substantive/cosmetic edit boundary for trigger transfer
Elon re-review must-fix 1: an autopilot-level edit only transfers trigger_owner
responsibility when it changes what the automation instructs or who/whether it
runs. autopilotRuleSubstantiveChange now includes description (the run Prompt)
and issue_title_template; title and project_id stay cosmetic/routing.
UpdateAutopilotTrigger no longer transfers on every PATCH — it compares the
persisted before/after and transfers only on a real cron/timezone/enabled/
event_filters change, not a label-only or no-op PATCH. Adds real handler tests
(prompt->all, title->none, cron->one+isolation, label->none, no-op->none).
Must-fix 3: real merge-path regression (TestMergeCommentIntoPendingTask_
FailClosedKeepsOriginalSnapshot) drives mergeCommentIntoPendingTask and asserts
a fail-closed workspace preserves the queued task's full snapshot; fail-open
control completes the owner_fallback merge.
Docs: migration 172 comment reworded to legacy-writer/unbackfilled-lineage
semantics (source NULL is not strictly pre-migration); PR description synced.
Migration renumber vs latest main (must-fix 2) deferred to pre-launch per Bohan.
Co-authored-by: multica-agent <github@multica.ai>
* chore(attribution): renumber migrations to 167-173 after syncing main
Merged latest main (which took 166_project_dates) and shifted the attribution
migration series off the 166 collision: 166->167 agent_task_attribution,
167->168 accountable_user, 168->169 rule_version, 169->170 rule_version_index,
170->171 fail_closed, 171->172 trigger_publisher, 172->173 invariant_check.
Updated the internal cross-references in the migration comments accordingly.
Fixes TestMigrationNumericPrefixesStayUniqueAfterLegacySet on the merge tree.
Co-authored-by: multica-agent <github@multica.ai>
* feat(admission): unify dispatch outcome + close rerun/chat/autopilot invoke holes (MUL-4525)
P0 first increment toward a platform-wide execution-admission contract so a
user who names an execution target always gets a definite result and never a
silent no-op, and so blocked targets are reported without leaking private-agent
details.
Backend:
- New shared contract (handler/admission.go): DispatchOutcome / DispatchStatus
(queued/coalesced/deferred/blocked) + stable, enumeration-safe
DispatchReasonCode set, plus writeDispatchBlocked() whose legacy `error`
string never reveals target existence.
- Rerun (task.go / task_lifecycle.go): re-validate the operator can invoke the
RESOLVED target agent (historical agent for a task_id rerun) before any
cancel/enqueue; blocked returns a structured 403 and mutates nothing
(ErrRerunInvokeNotAllowed).
- Chat send (chat.go): re-run canInvokeAgent on every send, not just the softer
canAccessPrivateAgent view gate; a revoked permission blocks before the
message/attachments/task persist.
- Autopilot manual "run now" (service/autopilot.go): admission now keys on the
current CLICKER, not the autopilot creator — clicker admission and clicker
attribution no longer fork. Automation (schedule/webhook) still falls back to
the creator gate. Added reason_code to the run response for the UI.
Frontend:
- triggerAutopilot response is schema-parsed; handleRunNow branches on run
status and shows a localized, reason_code-based warning for skipped/failed
instead of a false-success toast.
- Chat send and rerun surface the structured 403 reason_code as localized
toasts (dispatchReasonCode helper) instead of a generic failure.
- Additive fields only; older clients keep working. i18n added to all 4 locales.
Tests: rerun fail-before-mutation gate, autopilot clicker-vs-creator fork
(service + handler), reason-code classification, and a malformed-response
schema test. Backend handler+service suites and FE typecheck/lint green.
Co-authored-by: multica-agent <github@multica.ai>
* test(cmd/server): thread nil invoke gate through RerunIssue call sites (MUL-4525)
Co-authored-by: multica-agent <github@multica.ai>
* fix(admission): typed reason codes + run-now whitelist + real security tests (MUL-4525)
Addresses Elon's review of the P0 first increment (must-fix 1–3).
1. Run now no longer has a false-success branch. handleRunNow now classifies on
a whitelist via a pure runNowToastKind(): only issue_created/running →
success; skipped → warning; failed and any unknown/future status → error. Add
run-now-toast unit test over all five status classes plus reason-code → key
mapping.
2. reason_code is a typed value decided at the admission source, not
reverse-engineered from English failure text. New leaf package
internal/dispatch holds the canonical ReasonCode enum (shared by handler +
service so they can never drift). shouldSkipDispatch / errDispatchSkipped /
the fail path now carry a typed code through DispatchAutopilotManual straight
into the response; the substring classifier is deleted. Fixes the two missed
branches: attribution fail-closed → attribution_blocked (typed errors.Is),
"agent has no runtime bound" → runtime_offline. Regression tests for both.
3. Security acceptance tests exercise the REAL handlers, not injected callbacks:
- Chat: create session while invokable → revoke invoke (flip to private, keep
owner-view) → send returns 403 + reason_code with zero chat_message / task
writes.
- Rerun: private historical agent through RerunIssue + canInvokeAgent — a
non-invoking workspace owner is refused 403 + reason_code and mutates
nothing (fail-before-mutation); the agent owner is allowed 202.
No migration; reason_code is a decision-time value only the manual "run now"
response carries. Additive on the wire. Backend build/vet/handler+service
suites and FE typecheck/lint/vitest green. (Migration-prefix collision with main
remains the deferred pre-merge renumber.)
Co-authored-by: multica-agent <github@multica.ai>
* test(admission): make must-fix 3 acceptance tests prove the invariant (MUL-4525)
Addresses Elon's round-3 narrow review — the two security tests were not yet
falsifiable against the bugs they must catch.
- Rerun: after enqueuing the historical task, reassign the issue to a SECOND
agent that the denied user CAN invoke. Now the current assignee and the
task_id agent differ, so a rerun that wrongly validated the current assignee
would let the denied user through — the 403 proves the gate is keyed on the
historical private agent. The allow case now asserts the reran task's agent_id
is the historical agent, not the current assignee.
- Chat: the blocked send now carries a valid, still-unbound attachment. After
the 403 the test asserts the attachment's chat_session_id and chat_message_id
are both still NULL, guarding against anyone moving attachment binding ahead
of the invoke gate.
Test-only. Full internal/handler Go suite green.
Co-authored-by: multica-agent <github@multica.ai>
* feat(comments): surface blocked @mention trigger_outcomes instead of silent no-op (MUL-4525 §2)
A comment that @mentions an agent/squad the author cannot invoke used to save
with zero feedback — the user assumed a bug. Now the explicit-mention path
reports a per-target outcome on both preview and create/edit.
Backend (server/internal/handler/comment.go):
- resolveMentionedAgentCommentTriggers collects blocked outcomes instead of a
silent `continue`. The invoke gate is evaluated BEFORE any archived/runtime
state is read, so a caller who cannot invoke a private target only ever sees
the generic invocation_not_allowed and can never enumerate its existence.
- enqueueCommentAgentTriggers returns queued/coalesced/deferred/blocked per
explicit mention; enqueue errors are typed (attribution_blocked via
errors.Is), not swallowed. Implicit routing (assignee/thread/conversation)
carries no outcome — the user never named those targets.
- trigger-preview returns `blocked[]`; create/edit return additive
`trigger_outcomes[]`. One blocked mention never fails the comment.
Frontend:
- Composer shows a warning chip for blocked mentions before sending; after
sending, a "posted, but N not triggered" toast (blocked-only; coalesced/
deferred are success-shaped). Additive schema + defensive parse; i18n ×4.
Tests: handler partial-success + enumeration-safety acceptance tests; core
outcome-parse + preview-schema tests; hook/parity updated. Backend
handler+service suites and FE typecheck/lint/vitest green.
Co-authored-by: multica-agent <github@multica.ai>
* i18n(admission): clearer, consistent blocked-trigger copy (MUL-4525)
Reword the awkward "you are not allowed to run this autopilot's assignee" and
polish all MUL-4525 blocked/partial copy across en/zh-Hans/ja/ko:
- Unify on "you don't have permission to use this <agent|target>" (zh: 没有…的
使用权限) for autopilot Run now, comment mentions, rerun, and chat send —
replacing the various "not allowed to run/trigger" phrasings.
- Align zh to the glossary term 智能体 (was mixed "Agent"), matching the
surrounding UI voice (e.g. agent_link_no_access).
- Drop jargon: "blocked by an admission policy"/"被准入策略拦截" → "the run was
blocked"/"本次运行已被拦截"; "attributed"/"归因" → plainer wording.
- Comment copy counts "mentions" (was "targets") for consistency with the chip.
Backend dispatchBlockedFallbackMessage (old-client English fallback) reworded to
match; its enumeration-safety test assertion updated. Copy-only — no key/logic
changes; parity + typecheck green.
Co-authored-by: multica-agent <github@multica.ai>
* fix(comments): one outcome per explicit mention + FE success whitelist (MUL-4525)
Addresses Elon's round-2 review of the §2 comment trigger_outcomes.
1. Separate execution dedup from per-target outcomes. resolveMentionedAgent-
CommentTriggers now returns triggers (deduped by executing agent) AND one
commentMentionTarget per EXPLICIT mention. enqueueCommentAgentTriggers returns
a per-executing-agent result map; commentTriggerOutcomes fans each agent's
status to every target that resolved to it. So @Agent A + @Squad S(leader=A)
coalesces to ONE task but yields TWO outcomes. The squad-leader self-suppress
branch now returns a definite `deferred` outcome instead of no result. New
CreateComment test asserts 1 task, 2 outcomes.
2. Frontend no longer treats an unknown status as success. unhandledComment-
TriggerOutcomes whitelists queued/coalesced/deferred as handled; blocked and
any unknown/future/empty status warn (mirrors the Run now whitelist). The
preview schema's `blocked` now drops malformed entries INDIVIDUALLY instead of
z.array(...).catch([]) discarding the whole set. Regression tests for the
unknown status and the per-item drop.
Backend handler suite + go vet, FE typecheck/lint/vitest green.
Co-authored-by: multica-agent <github@multica.ai>
* fix(comments): honest role + status in trigger_outcomes fan-out (MUL-4525)
Addresses Elon's round-3 review of the §2 fan-out.
1. Execution merge preserves the squad-leader role instead of first-mention-
wins. The dedup now UPGRADES an already-added plain @agent trigger to a
@squad-leader trigger for the same agent, so @Agent A + @Squad S(leader=A)
always runs as a leader task (is_leader_task + squad_id=S) regardless of
mention order — the daemon still injects S's briefing. When two DIFFERENT
squads share one leader, the single run carries one squad's context and the
other squad is reported `coalesced` (folded), never a second `queued`. The
enqueue result now records the executed squad so the fan-out can tell them
apart. Tests assert the task role in both orders and the two-squad split.
2. Squad-leader self-suppression no longer fakes success. The self-trigger
guard keys on the latest task ROLE with no status filter, so a long-completed
task also suppresses; reporting `deferred/already_active` when nothing is
active was a false success. The branch now reports `deferred` only when a
real non-terminal task is active (its reconcile covers the comment), else a
non-success `blocked` + new `already_handled` reason. Fixed the reversed
helper-semantics comment. New handler test covers the completed-task branch.
Backend handler+service suites and go vet green.
Co-authored-by: multica-agent <github@multica.ai>
* fix(comments): fail-closed active-task check, never fake deferred (MUL-4525)
Elon round-4 must-fix: hasActiveTaskForIssueAndAgent swallowed DB errors by
returning true, so both call sites could turn a query failure into a
success-shaped `deferred/already_active` — a silent false success, exactly what
this issue forbids for admission-query failures.
- hasActiveTaskForIssueAndAgent now returns (bool, error).
- Two pure decision helpers govern the branches, fail closed on error:
- decidePostMergeMiss: on query error, do NOT enqueue a fresh task (duplicate
concurrent-run risk) AND report non-success blocked/internal_error; a
confirmed active task defers; a confirmed-none enqueues fresh.
- decideSuppressedLeaderOutcome: on query error, blocked/internal_error; a
confirmed active run defers; else self_trigger_suppressed. Never a fabricated
deferred.
- Renamed reason already_handled -> self_trigger_suppressed (Elon non-blocking
note): the old name implied the new comment was already processed, but the
real meaning is a suppressed self-trigger.
Deterministic unit tests cover the query-failure branch at both call sites
(no fresh enqueue, non-success outcome) — a real DB fault can't be forced
through valid handler inputs, and the decision is what governs the behavior.
Backend handler+service suites and go vet green.
Co-authored-by: multica-agent <github@multica.ai>
* fix(comments): honest merge outcome — refused merge is blocked, not fake coalesced (MUL-4525)
A pending-task merge previously reported success (coalesced) even when it
was refused or failed: attribution fail-closed and unknown DB errors both
returned handled=true, so the caller recorded coalesced for a merge that
never happened. mergeCommentIntoPendingTask now returns a distinguishable
commentMergeResult; commentMergeTerminalOutcome maps a real merge to
coalesced, a fail-closed refusal to blocked/attribution_blocked, and any
other failure to blocked/internal_error. Only "no queued task to fold"
falls through to the active-task decision. Adds pure coverage of the
mapping plus a fail-closed regression asserting the non-success outcome
and unchanged task count.
Co-authored-by: multica-agent <github@multica.ai>
* fix(comments): name blocked @mentions in preview + toast instead of a vague count (MUL-4525)
The blocked-trigger preview showed a red "1 mention won't trigger" with no
name, and the post-send toast said "but 1 mention wasn't triggered" — the
user can't tell which target or why. Now each blocked mention renders its own
chip named from the mention markup the user typed ("Go · No permission"),
with an error indicator and a short reason; the toast names the single target
too. The wire outcome still omits the target name (enumeration-safety) — the
label comes from the user's own draft, so nothing new is disclosed.
Shares a blocked-trigger-copy module (long + short reason labels) between the
chip and the toast, and a pure mentionLabelsByTarget/parseMentions helper in
core (fresh regex per call — a shared global leaked lastIndex). Adds core +
chip tests; drops the now-unused trigger_blocked_count keys across locales.
Co-authored-by: multica-agent <github@multica.ai>
* feat(attribution): accountable-member avatar on agent task rows + transcript header (MUL-4302)
Surface who each agent run is on behalf of where runs are actually
browsed:
- Agent detail activity tab: an avatar-only AttributionBadge on every
task row's meta line (Now + Recent work), tooltip carries the name +
resolution source.
- Execution-record (transcript) dialog header: the full on-behalf-of
badge next to the status pill.
Adds a compact variant="avatar" mode to AttributionBadge, reusing its
source-label mapping and degraded-attribution tone. Renders nothing when
a run has no resolved accountable member.
Co-authored-by: multica-agent <github@multica.ai>
---------
Co-authored-by: J <j@multica.ai>
Co-authored-by: multica-agent <github@multica.ai>
1284 lines
62 KiB
Go
1284 lines
62 KiB
Go
package service
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/jackc/pgx/v5/pgtype"
|
||
"github.com/jackc/pgx/v5/pgxpool"
|
||
"github.com/multica-ai/multica/server/internal/attribution"
|
||
"github.com/multica-ai/multica/server/internal/events"
|
||
"github.com/multica-ai/multica/server/internal/util"
|
||
db "github.com/multica-ai/multica/server/pkg/db/generated"
|
||
)
|
||
|
||
// seedAttributionFixture creates the minimal user/workspace/member/runtime/agent
|
||
// graph plus a member-created issue assigned to the agent, and returns the ids
|
||
// needed to enqueue a run. Everything is cleaned up via t.Cleanup.
|
||
func seedAttributionFixture(t *testing.T, pool *pgxpool.Pool) (workspaceID, userID, agentID, issueID string) {
|
||
t.Helper()
|
||
ctx := context.Background()
|
||
suffix := time.Now().UnixNano()
|
||
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Attr User', $1) RETURNING id`,
|
||
fmt.Sprintf("attr-%d@multica.test", suffix)).Scan(&userID); err != nil {
|
||
t.Fatalf("seed user: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID) })
|
||
|
||
if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug) VALUES ('attr ws', $1) RETURNING id`,
|
||
fmt.Sprintf("attr-%d", suffix)).Scan(&workspaceID); err != nil {
|
||
t.Fatalf("seed workspace: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID) })
|
||
|
||
if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`,
|
||
workspaceID, userID); err != nil {
|
||
t.Fatalf("seed member: %v", err)
|
||
}
|
||
|
||
var runtimeID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id)
|
||
VALUES ($1, 'attr-runtime', 'cloud', 'codex', 'online', '', '{}'::jsonb, $2)
|
||
RETURNING id`, workspaceID, userID).Scan(&runtimeID); err != nil {
|
||
t.Fatalf("seed runtime: %v", err)
|
||
}
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config, runtime_id, visibility,
|
||
max_concurrent_tasks, owner_id, instructions, custom_env, custom_args)
|
||
VALUES ($1, 'attr-agent', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3, '', '{}'::jsonb, '[]'::jsonb)
|
||
RETURNING id`, workspaceID, runtimeID, userID).Scan(&agentID); err != nil {
|
||
t.Fatalf("seed agent: %v", err)
|
||
}
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority)
|
||
VALUES ($1, 'attr issue', 'member', $2, 'agent', $3, 'medium')
|
||
RETURNING id`, workspaceID, userID, agentID).Scan(&issueID); err != nil {
|
||
t.Fatalf("seed issue: %v", err)
|
||
}
|
||
return workspaceID, userID, agentID, issueID
|
||
}
|
||
|
||
// TestEnqueueTaskForIssueStampsDirectHumanAttribution is the acceptance test for
|
||
// the Phase 1 foundation (MUL-4302 §11): a member-assigned run must land with a
|
||
// non-empty, correct attribution — source=direct_human, the accountable human
|
||
// equal to the issue creator, and evidence pointing back at the issue.
|
||
func TestEnqueueTaskForIssueStampsDirectHumanAttribution(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, userID, agentID, issueID := seedAttributionFixture(t, pool)
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
task, err := svc.EnqueueTaskForIssue(ctx, db.Issue{
|
||
ID: util.MustParseUUID(issueID),
|
||
AssigneeID: util.MustParseUUID(agentID),
|
||
Priority: "medium",
|
||
CreatorType: "member",
|
||
CreatorID: util.MustParseUUID(userID),
|
||
WorkspaceID: util.MustParseUUID(workspaceID),
|
||
AssigneeType: pgtype.Text{String: "agent", Valid: true},
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("EnqueueTaskForIssue: %v", err)
|
||
}
|
||
|
||
// Read the stored row so we assert what actually persisted, not just the
|
||
// returned struct.
|
||
var source pgtype.Text
|
||
var originator, accountable, evidenceRef pgtype.UUID
|
||
var evidenceKind pgtype.Text
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id, trigger_evidence_kind, trigger_evidence_ref_id
|
||
FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &evidenceKind, &evidenceRef); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
|
||
if source.String != string(attribution.SourceDirectHuman) {
|
||
t.Errorf("originator_source = %q, want direct_human", source.String)
|
||
}
|
||
if !originator.Valid || originator.Bytes != util.MustParseUUID(userID).Bytes {
|
||
t.Errorf("originator_user_id = %s, want %s", util.UUIDToString(originator), userID)
|
||
}
|
||
// MUL-4302 §11 invariant at the DB layer: a non-NULL originator implies the
|
||
// accountable human equals it.
|
||
if !accountable.Valid || accountable.Bytes != originator.Bytes {
|
||
t.Errorf("accountable_user_id = %s, want == originator %s", util.UUIDToString(accountable), util.UUIDToString(originator))
|
||
}
|
||
if evidenceKind.String != string(attribution.EvidenceIssueAssignment) {
|
||
t.Errorf("trigger_evidence_kind = %q, want issue_assignment", evidenceKind.String)
|
||
}
|
||
if !evidenceRef.Valid || evidenceRef.Bytes != util.MustParseUUID(issueID).Bytes {
|
||
t.Errorf("trigger_evidence_ref_id = %s, want issue %s", util.UUIDToString(evidenceRef), issueID)
|
||
}
|
||
}
|
||
|
||
// TestEnqueueTaskForIssueWithHandoffAttributesToActor is the acceptance test for
|
||
// the assign/promote actor fix (MUL-4302 §4): when a member assigns an issue that
|
||
// a DIFFERENT member created, the run's accountable human — and, honoring the
|
||
// invariant, its originator — is the assigning member (the actor), not the issue
|
||
// creator. The evidence still points at the issue.
|
||
func TestEnqueueTaskForIssueWithHandoffAttributesToActor(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, creatorID, agentID, issueID := seedAttributionFixture(t, pool)
|
||
|
||
// A second member in the same workspace performs the assign.
|
||
var actorID string
|
||
suffix := time.Now().UnixNano()
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Actor', $1) RETURNING id`,
|
||
fmt.Sprintf("actor-%d@multica.test", suffix)).Scan(&actorID); err != nil {
|
||
t.Fatalf("seed actor user: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, actorID) })
|
||
if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
|
||
workspaceID, actorID); err != nil {
|
||
t.Fatalf("seed actor member: %v", err)
|
||
}
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
task, err := svc.EnqueueTaskForIssueWithHandoff(ctx, db.Issue{
|
||
ID: util.MustParseUUID(issueID),
|
||
AssigneeID: util.MustParseUUID(agentID),
|
||
Priority: "medium",
|
||
CreatorType: "member",
|
||
CreatorID: util.MustParseUUID(creatorID),
|
||
WorkspaceID: util.MustParseUUID(workspaceID),
|
||
AssigneeType: pgtype.Text{String: "agent", Valid: true},
|
||
}, "", util.MustParseUUID(actorID))
|
||
if err != nil {
|
||
t.Fatalf("EnqueueTaskForIssueWithHandoff: %v", err)
|
||
}
|
||
|
||
var source pgtype.Text
|
||
var originator, accountable pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id
|
||
FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
|
||
if source.String != string(attribution.SourceDirectHuman) {
|
||
t.Errorf("originator_source = %q, want direct_human", source.String)
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != util.MustParseUUID(actorID).Bytes {
|
||
t.Errorf("accountable_user_id = %s, want actor %s (not creator %s)", util.UUIDToString(accountable), actorID, creatorID)
|
||
}
|
||
// Invariant: originator mirrors accountable, so it is the actor too — the
|
||
// assigning member lends the authority, not the issue creator.
|
||
if !originator.Valid || originator.Bytes != accountable.Bytes {
|
||
t.Errorf("originator_user_id = %s, want == accountable (actor) %s", util.UUIDToString(originator), util.UUIDToString(accountable))
|
||
}
|
||
}
|
||
|
||
// TestMergeCommentIntoPendingTask_KeepsAccountableEqualsOriginator guards the
|
||
// MUL-4302 one-way invariant across the comment-coalescing merge (main #5192 ×
|
||
// attribution): when a coalescing run re-stamps originator_user_id to the newly
|
||
// arrived comment's human, accountable_user_id must mirror it. Otherwise folding
|
||
// member B's comment into member A's queued task leaves originator=B / accountable=A.
|
||
func TestMergeCommentIntoPendingTask_KeepsAccountableEqualsOriginator(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, userA, agentID, issueID := seedAttributionFixture(t, pool)
|
||
|
||
// A second member B whose comment will be coalesced in.
|
||
var userB string
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Attr User B', $1) RETURNING id`,
|
||
fmt.Sprintf("attr-b-%d@multica.test", time.Now().UnixNano())).Scan(&userB); err != nil {
|
||
t.Fatalf("seed user B: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userB) })
|
||
if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`, workspaceID, userB); err != nil {
|
||
t.Fatalf("add member B: %v", err)
|
||
}
|
||
|
||
// A queued task attributed to A with a STALE source label + no evidence, so the
|
||
// merge has something to prove it re-stamped the whole snapshot, not just people.
|
||
var taskID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id, accountable_user_id, originator_source)
|
||
VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3, $3, 'delegation')
|
||
RETURNING id`, agentID, issueID, userA).Scan(&taskID); err != nil {
|
||
t.Fatalf("seed queued task: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
|
||
|
||
// B's newly-arrived comment on the same issue.
|
||
var commentID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
|
||
VALUES ($1, $2, 'member', $3, 'B comment') RETURNING id`, issueID, workspaceID, userB).Scan(&commentID); err != nil {
|
||
t.Fatalf("seed comment: %v", err)
|
||
}
|
||
|
||
// Re-stamp the FULL snapshot for B's member comment (direct_human + comment
|
||
// evidence), as the caller does.
|
||
if _, err := q.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
|
||
IssueID: util.MustParseUUID(issueID),
|
||
AgentID: util.MustParseUUID(agentID),
|
||
NewTriggerCommentID: util.MustParseUUID(commentID),
|
||
NewOriginatorUserID: util.MustParseUUID(userB),
|
||
NewAccountableUserID: util.MustParseUUID(userB),
|
||
NewOriginatorSource: pgtype.Text{String: "direct_human", Valid: true},
|
||
NewTriggerEvidenceKind: pgtype.Text{String: "comment", Valid: true},
|
||
NewTriggerEvidenceRefID: util.MustParseUUID(commentID),
|
||
}); err != nil {
|
||
t.Fatalf("MergeCommentIntoPendingTask: %v", err)
|
||
}
|
||
|
||
var originator, accountable pgtype.UUID
|
||
var source, evidenceKind pgtype.Text
|
||
if err := pool.QueryRow(ctx,
|
||
`SELECT originator_user_id, accountable_user_id, originator_source, trigger_evidence_kind FROM agent_task_queue WHERE id = $1`, taskID,
|
||
).Scan(&originator, &accountable, &source, &evidenceKind); err != nil {
|
||
t.Fatalf("read task: %v", err)
|
||
}
|
||
if !originator.Valid || originator.Bytes != util.MustParseUUID(userB).Bytes {
|
||
t.Errorf("originator = %s, want re-stamped to B %s", util.UUIDToString(originator), userB)
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != originator.Bytes {
|
||
t.Errorf("accountable = %s, want == originator (B); one-way invariant violated on merge", util.UUIDToString(accountable))
|
||
}
|
||
// Full-snapshot re-stamp: the stale 'delegation' source + NULL evidence must move
|
||
// to the new comment's 'direct_human' + comment evidence, not linger.
|
||
if source.String != "direct_human" {
|
||
t.Errorf("originator_source = %q, want re-stamped to direct_human (stale snapshot left behind)", source.String)
|
||
}
|
||
if evidenceKind.String != "comment" {
|
||
t.Errorf("trigger_evidence_kind = %q, want re-stamped to comment", evidenceKind.String)
|
||
}
|
||
}
|
||
|
||
// TestAttributionForMergedComment_HonorsFailClosedPolicy is Elon's must-fix
|
||
// regression: folding a comment that resolves to NO precise human into a queued task
|
||
// re-opens the fail-closed decision. On a fail-closed workspace the merge must be
|
||
// REFUSED (ErrAttributionFailClosed) so the queued task keeps its original precise
|
||
// snapshot instead of being re-stamped to a degraded owner_fallback; on a fail-open
|
||
// workspace the same comment degrades to owner_fallback (accountable = agent owner)
|
||
// with no error, exactly as a fresh enqueue would (MUL-4302).
|
||
func TestAttributionForMergedComment_HonorsFailClosedPolicy(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, ownerID, agentID, issueID := seedAttributionFixture(t, pool)
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
agent, err := q.GetAgent(ctx, util.MustParseUUID(agentID))
|
||
if err != nil {
|
||
t.Fatalf("get agent: %v", err)
|
||
}
|
||
|
||
// An agent-authored comment with no source-task lineage → no precise human.
|
||
var commentID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
|
||
VALUES ($1, $2, 'agent', $3, 'autonomous ping') RETURNING id`,
|
||
issueID, workspaceID, agentID).Scan(&commentID); err != nil {
|
||
t.Fatalf("seed comment: %v", err)
|
||
}
|
||
|
||
// Fail-CLOSED: the merge must be refused, not degraded.
|
||
if _, err := pool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = true WHERE id = $1`, workspaceID); err != nil {
|
||
t.Fatalf("set fail-closed: %v", err)
|
||
}
|
||
if _, err := svc.AttributionForMergedComment(ctx, util.MustParseUUID(workspaceID), util.MustParseUUID(commentID), false, agent); !errors.Is(err, ErrAttributionFailClosed) {
|
||
t.Fatalf("fail-closed merge must return ErrAttributionFailClosed, got %v", err)
|
||
}
|
||
|
||
// Fail-OPEN (default): the same comment degrades to owner_fallback, no error.
|
||
if _, err := pool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = false WHERE id = $1`, workspaceID); err != nil {
|
||
t.Fatalf("clear fail-closed: %v", err)
|
||
}
|
||
attr, err := svc.AttributionForMergedComment(ctx, util.MustParseUUID(workspaceID), util.MustParseUUID(commentID), false, agent)
|
||
if err != nil {
|
||
t.Fatalf("fail-open merge must not error, got %v", err)
|
||
}
|
||
if attr.Source != attribution.SourceOwnerFallback {
|
||
t.Errorf("fail-open unattributable merge source = %q, want owner_fallback", attr.Source)
|
||
}
|
||
if !attr.AccountableUserID.Valid || attr.AccountableUserID.Bytes != util.MustParseUUID(ownerID).Bytes {
|
||
t.Errorf("owner_fallback accountable = %s, want agent owner %s", util.UUIDToString(attr.AccountableUserID), ownerID)
|
||
}
|
||
if attr.UserID.Valid {
|
||
t.Errorf("owner_fallback must not set originator (authorization stays NULL), got %s", util.UUIDToString(attr.UserID))
|
||
}
|
||
}
|
||
|
||
// TestAttributionInvariantCheck_RejectsBypass verifies the DB-level cross-column
|
||
// CHECK (MUL-4302): a write in the ENFORCED regime (originator_source non-NULL — every
|
||
// real enqueue / coalesce path stamps it) that sets originator_user_id but leaves
|
||
// accountable_user_id NULL — or different — is rejected at the database, so a future
|
||
// code path that bypasses finalizeAttribution fails loudly instead of silently
|
||
// mis-attributing an audited run (the #5192 comment-merge bug class). The legacy-row
|
||
// exemption (originator_source IS NULL) is covered by
|
||
// TestAttributionInvariantCheck_ExemptsLegacyRows.
|
||
func TestAttributionInvariantCheck_RejectsBypass(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
_, userA, agentID, issueID := seedAttributionFixture(t, pool)
|
||
|
||
// originator set, accountable NULL, source set (enforced) → must violate the check.
|
||
if _, err := pool.Exec(ctx, `
|
||
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id, originator_source)
|
||
VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3, 'comment_source')`,
|
||
agentID, issueID, userA); err == nil {
|
||
t.Fatal("expected the CHECK to reject originator set with NULL accountable, but insert succeeded")
|
||
}
|
||
|
||
// originator != accountable → also rejected.
|
||
var userB string
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Check B', $1) RETURNING id`,
|
||
fmt.Sprintf("check-b-%d@multica.test", time.Now().UnixNano())).Scan(&userB); err != nil {
|
||
t.Fatalf("seed user B: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userB) })
|
||
if _, err := pool.Exec(ctx, `
|
||
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id, accountable_user_id, originator_source)
|
||
VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3, $4, 'comment_source')`,
|
||
agentID, issueID, userA, userB); err == nil {
|
||
t.Fatal("expected the CHECK to reject originator != accountable, but insert succeeded")
|
||
}
|
||
|
||
// The legitimate shape (equal) is accepted.
|
||
var okTaskID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id, accountable_user_id, originator_source)
|
||
VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3, $3, 'direct_human') RETURNING id`,
|
||
agentID, issueID, userA).Scan(&okTaskID); err != nil {
|
||
t.Fatalf("equal originator/accountable must be accepted, got %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, okTaskID) })
|
||
}
|
||
|
||
// TestAttributionInvariantCheck_ExemptsLegacyRows is the upgrade-safety test Elon
|
||
// required (MUL-4302, Option A): a pre-migration row — originator set, accountable
|
||
// NULL, and originator_source NULL (its column did not exist yet) — must survive the
|
||
// NOT VALID CHECK and, crucially, must still accept a later status UPDATE by the new
|
||
// backend (claim / complete / cancel), even though that UPDATE does not touch the
|
||
// attribution columns. This reproduces the cross-deployment stale-task scenario the
|
||
// two-phase rollout protects; without the `originator_source IS NULL` exemption the
|
||
// UPDATE would fail the CHECK on the whole updated row.
|
||
func TestAttributionInvariantCheck_ExemptsLegacyRows(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
_, userA, agentID, issueID := seedAttributionFixture(t, pool)
|
||
|
||
// A legacy-shaped row: originator set, accountable + source NULL. The exemption
|
||
// admits it (as it admits the real pre-migration rows the migration cannot rewrite).
|
||
var legacyID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id)
|
||
VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3) RETURNING id`,
|
||
agentID, issueID, userA).Scan(&legacyID); err != nil {
|
||
t.Fatalf("legacy-shaped row must be admitted by the exemption, got %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, legacyID) })
|
||
|
||
// The status transitions the new backend performs on such a stale task must all
|
||
// succeed — this is exactly what a bare invariant CHECK would have broken.
|
||
for _, status := range []string{"running", "completed", "cancelled"} {
|
||
if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = $2 WHERE id = $1`, legacyID, status); err != nil {
|
||
t.Fatalf("status UPDATE to %q on a legacy row must succeed, got %v", status, err)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestTriggerOwnerAttribution_ScheduleTriggerCreator is the acceptance test for
|
||
// trigger_owner (MUL-4302; Bohan): an autopilot schedule/webhook run is accountable
|
||
// to the member who CREATED the firing trigger, with originator NULL (no human
|
||
// authorized the autonomous fire).
|
||
func TestTriggerOwnerAttribution_ScheduleTriggerCreator(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, creatorID, agentID, _ := seedAttributionFixture(t, pool)
|
||
|
||
var autopilotID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)
|
||
VALUES ($1, 'trigger-owner-ap', $2, 'run_only', 'member', $3) RETURNING id`,
|
||
workspaceID, agentID, creatorID).Scan(&autopilotID); err != nil {
|
||
t.Fatalf("seed autopilot: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
|
||
|
||
// Schedule trigger whose responsible publisher is the creating member.
|
||
var triggerID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)
|
||
VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2) RETURNING id`,
|
||
autopilotID, creatorID).Scan(&triggerID); err != nil {
|
||
t.Fatalf("seed trigger: %v", err)
|
||
}
|
||
|
||
got := triggerOwnerAttribution(ctx, q,
|
||
util.MustParseUUID(triggerID), util.MustParseUUID(workspaceID), util.MustParseUUID(autopilotID),
|
||
attribution.EvidenceAutopilotRun, util.MustParseUUID(autopilotID))
|
||
if got.Source != attribution.SourceTriggerOwner {
|
||
t.Fatalf("source = %q, want trigger_owner", got.Source)
|
||
}
|
||
if got.UserID.Valid {
|
||
t.Errorf("trigger_owner is audit-only; originator must stay NULL, got %s", util.UUIDToString(got.UserID))
|
||
}
|
||
if !got.AccountableUserID.Valid || got.AccountableUserID.Bytes != util.MustParseUUID(creatorID).Bytes {
|
||
t.Errorf("accountable = %s, want trigger creator %s", util.UUIDToString(got.AccountableUserID), creatorID)
|
||
}
|
||
}
|
||
|
||
// TestTriggerOwnerAttribution_LegacyTriggerFallsBackToRuleOwner verifies the
|
||
// backward-compat path Bohan signed off on: a trigger with no recorded creator
|
||
// (created before this migration) degrades to the rule publisher (rule_owner),
|
||
// never fabricating a human.
|
||
func TestTriggerOwnerAttribution_LegacyTriggerFallsBackToRuleOwner(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
|
||
|
||
var autopilotID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)
|
||
VALUES ($1, 'legacy-trigger-ap', $2, 'run_only', 'member', $3) RETURNING id`,
|
||
workspaceID, agentID, publisherID).Scan(&autopilotID); err != nil {
|
||
t.Fatalf("seed autopilot: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
|
||
|
||
// Trigger with NO creator recorded (pre-migration style).
|
||
var triggerID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression)
|
||
VALUES ($1, 'schedule', true, '0 * * * *') RETURNING id`,
|
||
autopilotID).Scan(&triggerID); err != nil {
|
||
t.Fatalf("seed trigger: %v", err)
|
||
}
|
||
// Active rule version so the fallback resolves to rule_owner (the publisher).
|
||
if _, err := pool.Exec(ctx, `
|
||
INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
|
||
VALUES ($1, $2, 'member', $3)`, autopilotID, workspaceID, publisherID); err != nil {
|
||
t.Fatalf("seed rule version: %v", err)
|
||
}
|
||
|
||
got := triggerOwnerAttribution(ctx, q,
|
||
util.MustParseUUID(triggerID), util.MustParseUUID(workspaceID), util.MustParseUUID(autopilotID),
|
||
attribution.EvidenceAutopilotRun, util.MustParseUUID(autopilotID))
|
||
if got.Source != attribution.SourceRuleOwner {
|
||
t.Fatalf("source = %q, want rule_owner (legacy trigger falls back)", got.Source)
|
||
}
|
||
if !got.AccountableUserID.Valid || got.AccountableUserID.Bytes != util.MustParseUUID(publisherID).Bytes {
|
||
t.Errorf("accountable = %s, want rule publisher %s", util.UUIDToString(got.AccountableUserID), publisherID)
|
||
}
|
||
}
|
||
|
||
// seedExtraMember inserts a standalone user + workspace member and returns the
|
||
// user id, so a test can model an EDITOR distinct from the trigger creator.
|
||
func seedExtraMember(t *testing.T, pool *pgxpool.Pool, workspaceID, label string) string {
|
||
t.Helper()
|
||
ctx := context.Background()
|
||
suffix := time.Now().UnixNano()
|
||
var userID string
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
|
||
label, fmt.Sprintf("%s-%d@multica.test", label, suffix)).Scan(&userID); err != nil {
|
||
t.Fatalf("seed %s user: %v", label, err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID) })
|
||
if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
|
||
workspaceID, userID); err != nil {
|
||
t.Fatalf("seed %s member: %v", label, err)
|
||
}
|
||
return userID
|
||
}
|
||
|
||
// TestTriggerOwnerAttribution_TransfersToSubstantiveEditor is Elon's must-fix
|
||
// acceptance test: it drives the REAL triggerOwnerAttribution resolver (not the
|
||
// ruleOwnerAttribution helper) across the SAME queries the handlers use, and proves
|
||
// both halves of the pinned model — (1) responsibility TRANSFERS from the creator to
|
||
// whoever substantively edits the trigger, and (2) a trigger-scoped edit re-stamps
|
||
// ONLY that trigger, never a sibling. It also proves an autopilot-level edit bumps
|
||
// every trigger together (MUL-4302).
|
||
func TestTriggerOwnerAttribution_TransfersToSubstantiveEditor(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, creatorA, agentID, _ := seedAttributionFixture(t, pool)
|
||
editorB := seedExtraMember(t, pool, workspaceID, "editor-b")
|
||
editorC := seedExtraMember(t, pool, workspaceID, "editor-c")
|
||
|
||
var autopilotID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)
|
||
VALUES ($1, 'transfer-ap', $2, 'run_only', 'member', $3) RETURNING id`,
|
||
workspaceID, agentID, creatorA).Scan(&autopilotID); err != nil {
|
||
t.Fatalf("seed autopilot: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
|
||
|
||
// Two triggers, both initially published by creator A (the create-site default).
|
||
seedTrigger := func(cron string) string {
|
||
var id string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)
|
||
VALUES ($1, 'schedule', true, $2, 'member', $3) RETURNING id`,
|
||
autopilotID, cron, creatorA).Scan(&id); err != nil {
|
||
t.Fatalf("seed trigger: %v", err)
|
||
}
|
||
return id
|
||
}
|
||
trigger1 := seedTrigger("0 * * * *")
|
||
trigger2 := seedTrigger("0 0 * * *")
|
||
|
||
accountableOf := func(triggerID string) string {
|
||
got := triggerOwnerAttribution(ctx, q,
|
||
util.MustParseUUID(triggerID), util.MustParseUUID(workspaceID), util.MustParseUUID(autopilotID),
|
||
attribution.EvidenceAutopilotRun, util.MustParseUUID(autopilotID))
|
||
if got.Source != attribution.SourceTriggerOwner {
|
||
t.Fatalf("trigger %s: source = %q, want trigger_owner", triggerID, got.Source)
|
||
}
|
||
if got.UserID.Valid {
|
||
t.Fatalf("trigger_owner is audit-only; originator must stay NULL, got %s", util.UUIDToString(got.UserID))
|
||
}
|
||
return util.UUIDToString(got.AccountableUserID)
|
||
}
|
||
|
||
// Baseline: both triggers attribute to creator A.
|
||
if a := accountableOf(trigger1); a != creatorA {
|
||
t.Fatalf("trigger1 baseline accountable = %s, want creator %s", a, creatorA)
|
||
}
|
||
if a := accountableOf(trigger2); a != creatorA {
|
||
t.Fatalf("trigger2 baseline accountable = %s, want creator %s", a, creatorA)
|
||
}
|
||
|
||
// B substantively edits trigger1 — the SAME query UpdateAutopilotTrigger runs.
|
||
if err := q.SetAutopilotTriggerPublisher(ctx, db.SetAutopilotTriggerPublisherParams{
|
||
ID: util.MustParseUUID(trigger1),
|
||
PublishedByType: pgtype.Text{String: "member", Valid: true},
|
||
PublishedByID: util.MustParseUUID(editorB),
|
||
}); err != nil {
|
||
t.Fatalf("SetAutopilotTriggerPublisher: %v", err)
|
||
}
|
||
|
||
// Transfer: trigger1 now attributes to editor B, NOT the original creator.
|
||
if a := accountableOf(trigger1); a != editorB {
|
||
t.Fatalf("after edit, trigger1 accountable = %s, want editor %s (responsibility must transfer)", a, editorB)
|
||
}
|
||
// Isolation: editing trigger1 must NOT move trigger2 — it stays with creator A.
|
||
if a := accountableOf(trigger2); a != creatorA {
|
||
t.Fatalf("trigger2 accountable = %s, want creator %s (editing a sibling must not transfer)", a, creatorA)
|
||
}
|
||
|
||
// C makes an autopilot-level substantive edit — the SAME bump-all query
|
||
// UpdateAutopilot runs — which governs every trigger of the autopilot.
|
||
if err := q.SetAutopilotTriggerPublishersByAutopilot(ctx, db.SetAutopilotTriggerPublishersByAutopilotParams{
|
||
AutopilotID: util.MustParseUUID(autopilotID),
|
||
PublishedByType: pgtype.Text{String: "member", Valid: true},
|
||
PublishedByID: util.MustParseUUID(editorC),
|
||
}); err != nil {
|
||
t.Fatalf("SetAutopilotTriggerPublishersByAutopilot: %v", err)
|
||
}
|
||
if a := accountableOf(trigger1); a != editorC {
|
||
t.Fatalf("after autopilot-level edit, trigger1 accountable = %s, want %s", a, editorC)
|
||
}
|
||
if a := accountableOf(trigger2); a != editorC {
|
||
t.Fatalf("after autopilot-level edit, trigger2 accountable = %s, want %s", a, editorC)
|
||
}
|
||
}
|
||
|
||
// TestEnqueueTaskForIssueAutopilotOriginStampsRuleOwner is the acceptance test for
|
||
// rule_owner (MUL-4302 §3.4): an autopilot-origin issue's run has NO authorizing
|
||
// human (originator_user_id stays NULL) but IS accountable to the publisher of the
|
||
// autopilot's active rule version, with rule_version_id recording the snapshot.
|
||
// This is the accountable-diverges-from-originator case.
|
||
func TestEnqueueTaskForIssueAutopilotOriginStampsRuleOwner(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
|
||
|
||
// A synthetic autopilot id (no FK) with an active rule version published by the
|
||
// member. gen_random_uuid() gives the autopilot id back so the issue can point
|
||
// its origin at it.
|
||
var ruleVersionID, autopilotID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
|
||
VALUES (gen_random_uuid(), $1, 'member', $2) RETURNING id, autopilot_id`,
|
||
workspaceID, publisherID).Scan(&ruleVersionID, &autopilotID); err != nil {
|
||
t.Fatalf("seed rule version: %v", err)
|
||
}
|
||
|
||
var issueID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority, number, origin_type, origin_id)
|
||
VALUES ($1, 'autopilot issue', 'agent', $2, 'agent', $2, 'medium', 9001, 'autopilot', $3) RETURNING id`,
|
||
workspaceID, agentID, autopilotID).Scan(&issueID); err != nil {
|
||
t.Fatalf("seed autopilot-origin issue: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
task, err := svc.EnqueueTaskForIssue(ctx, db.Issue{
|
||
ID: util.MustParseUUID(issueID),
|
||
AssigneeID: util.MustParseUUID(agentID),
|
||
Priority: "medium",
|
||
CreatorType: "agent",
|
||
CreatorID: util.MustParseUUID(agentID),
|
||
WorkspaceID: util.MustParseUUID(workspaceID),
|
||
AssigneeType: pgtype.Text{String: "agent", Valid: true},
|
||
OriginType: pgtype.Text{String: "autopilot", Valid: true},
|
||
OriginID: util.MustParseUUID(autopilotID),
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("EnqueueTaskForIssue: %v", err)
|
||
}
|
||
|
||
var source pgtype.Text
|
||
var originator, accountable, ruleVersion pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id, rule_version_id
|
||
FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &ruleVersion); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
|
||
if source.String != string(attribution.SourceRuleOwner) {
|
||
t.Errorf("originator_source = %q, want rule_owner", source.String)
|
||
}
|
||
if originator.Valid {
|
||
t.Errorf("autopilot run must NOT set originator (authorization stays NULL), got %s", util.UUIDToString(originator))
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != util.MustParseUUID(publisherID).Bytes {
|
||
t.Errorf("accountable_user_id = %s, want rule publisher %s", util.UUIDToString(accountable), publisherID)
|
||
}
|
||
if !ruleVersion.Valid || ruleVersion.Bytes != util.MustParseUUID(ruleVersionID).Bytes {
|
||
t.Errorf("rule_version_id = %s, want %s", util.UUIDToString(ruleVersion), ruleVersionID)
|
||
}
|
||
}
|
||
|
||
// TestEnqueueTaskForIssueAutopilotOriginWithoutVersionDegrades verifies that an
|
||
// autopilot-origin issue whose autopilot has NO published rule version degrades to
|
||
// unattributed (never fabricating a human) rather than crashing or bypassing.
|
||
// TestEnqueueTaskForIssueAutopilotOriginWithoutVersionOwnerFallback: an
|
||
// autopilot-origin issue whose autopilot has no published rule version resolves to
|
||
// unattributed, then the default (non-fail-closed) workspace policy degrades it to
|
||
// owner_fallback — accountable = agent owner, originator still NULL — so no run is
|
||
// left without an accountable human (MUL-4302 §3.5).
|
||
func TestEnqueueTaskForIssueAutopilotOriginWithoutVersionOwnerFallback(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, ownerID, agentID, _ := seedAttributionFixture(t, pool)
|
||
|
||
var issueID, autopilotID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority, number, origin_type, origin_id)
|
||
VALUES ($1, 'autopilot issue', 'agent', $2, 'agent', $2, 'medium', 9002, 'autopilot', gen_random_uuid()) RETURNING id, origin_id`,
|
||
workspaceID, agentID).Scan(&issueID, &autopilotID); err != nil {
|
||
t.Fatalf("seed autopilot-origin issue: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
task, err := svc.EnqueueTaskForIssue(ctx, db.Issue{
|
||
ID: util.MustParseUUID(issueID),
|
||
AssigneeID: util.MustParseUUID(agentID),
|
||
Priority: "medium",
|
||
CreatorType: "agent",
|
||
CreatorID: util.MustParseUUID(agentID),
|
||
WorkspaceID: util.MustParseUUID(workspaceID),
|
||
AssigneeType: pgtype.Text{String: "agent", Valid: true},
|
||
OriginType: pgtype.Text{String: "autopilot", Valid: true},
|
||
OriginID: util.MustParseUUID(autopilotID),
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("EnqueueTaskForIssue: %v", err)
|
||
}
|
||
|
||
var source pgtype.Text
|
||
var originator, accountable pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id FROM agent_task_queue WHERE id = $1`,
|
||
task.ID).Scan(&source, &originator, &accountable); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
if source.String != string(attribution.SourceOwnerFallback) {
|
||
t.Errorf("originator_source = %q, want owner_fallback", source.String)
|
||
}
|
||
if originator.Valid {
|
||
t.Errorf("owner_fallback is audit-only; originator must stay NULL, got %s", util.UUIDToString(originator))
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != util.MustParseUUID(ownerID).Bytes {
|
||
t.Errorf("accountable_user_id = %s, want agent owner %s", util.UUIDToString(accountable), ownerID)
|
||
}
|
||
}
|
||
|
||
// TestEnqueueTaskFailClosedRefusesUnattributed: with the workspace opted into
|
||
// fail-closed, an unattributable run (autopilot-origin issue, no rule version) is
|
||
// REFUSED at enqueue (ErrAttributionFailClosed) rather than degraded to
|
||
// owner_fallback (MUL-4302 §3.5).
|
||
func TestEnqueueTaskFailClosedRefusesUnattributed(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, _, agentID, _ := seedAttributionFixture(t, pool)
|
||
if _, err := pool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = TRUE WHERE id = $1`, workspaceID); err != nil {
|
||
t.Fatalf("set fail-closed: %v", err)
|
||
}
|
||
|
||
var issueID, autopilotID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority, number, origin_type, origin_id)
|
||
VALUES ($1, 'autopilot issue', 'agent', $2, 'agent', $2, 'medium', 9003, 'autopilot', gen_random_uuid()) RETURNING id, origin_id`,
|
||
workspaceID, agentID).Scan(&issueID, &autopilotID); err != nil {
|
||
t.Fatalf("seed autopilot-origin issue: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
_, err := svc.EnqueueTaskForIssue(ctx, db.Issue{
|
||
ID: util.MustParseUUID(issueID),
|
||
AssigneeID: util.MustParseUUID(agentID),
|
||
Priority: "medium",
|
||
CreatorType: "agent",
|
||
CreatorID: util.MustParseUUID(agentID),
|
||
WorkspaceID: util.MustParseUUID(workspaceID),
|
||
AssigneeType: pgtype.Text{String: "agent", Valid: true},
|
||
OriginType: pgtype.Text{String: "autopilot", Valid: true},
|
||
OriginID: util.MustParseUUID(autopilotID),
|
||
})
|
||
if !errors.Is(err, ErrAttributionFailClosed) {
|
||
t.Fatalf("EnqueueTaskForIssue error = %v, want ErrAttributionFailClosed", err)
|
||
}
|
||
// No task row should have been created for the issue.
|
||
var count int
|
||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issueID).Scan(&count); err != nil {
|
||
t.Fatalf("count tasks: %v", err)
|
||
}
|
||
if count != 0 {
|
||
t.Errorf("fail-closed must not enqueue any task, found %d", count)
|
||
}
|
||
}
|
||
|
||
// seedRunOnlyAutopilot creates an active run_only autopilot (agent-assigned) plus a
|
||
// running autopilot_run for it, and returns their ids. Used to exercise
|
||
// dispatchRunOnly's direct CreateAutopilotTask path.
|
||
func seedRunOnlyAutopilot(t *testing.T, pool *pgxpool.Pool, workspaceID, agentID, creatorID string) (autopilotID, runID string) {
|
||
t.Helper()
|
||
ctx := context.Background()
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot (workspace_id, title, assignee_type, assignee_id, status, execution_mode, created_by_type, created_by_id)
|
||
VALUES ($1, 'run-only ap', 'agent', $2, 'active', 'run_only', 'member', $3) RETURNING id`,
|
||
workspaceID, agentID, creatorID).Scan(&autopilotID); err != nil {
|
||
t.Fatalf("seed autopilot: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_run (autopilot_id, source, status) VALUES ($1, 'manual', 'running') RETURNING id`,
|
||
autopilotID).Scan(&runID); err != nil {
|
||
t.Fatalf("seed autopilot run: %v", err)
|
||
}
|
||
return autopilotID, runID
|
||
}
|
||
|
||
// TestDispatchRunOnlyScheduleStampsRuleOwnerRow is the run_only row assertion Elon
|
||
// asked for: the direct CreateAutopilotTask path (no member actor → schedule-like)
|
||
// must persist rule_owner on the queue row — originator NULL, accountable = the
|
||
// active rule version publisher, rule_version_id set.
|
||
func TestDispatchRunOnlyScheduleStampsRuleOwnerRow(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
|
||
autopilotID, runID := seedRunOnlyAutopilot(t, pool, workspaceID, agentID, publisherID)
|
||
|
||
var ruleVersionID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
|
||
VALUES ($1, $2, 'member', $3) RETURNING id`, autopilotID, workspaceID, publisherID).Scan(&ruleVersionID); err != nil {
|
||
t.Fatalf("seed rule version: %v", err)
|
||
}
|
||
|
||
svc := &AutopilotService{Queries: q, TxStarter: pool, Bus: events.New(), TaskSvc: &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}}
|
||
ap, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotID))
|
||
if err != nil {
|
||
t.Fatalf("get autopilot: %v", err)
|
||
}
|
||
run, err := q.GetAutopilotRun(ctx, util.MustParseUUID(runID))
|
||
if err != nil {
|
||
t.Fatalf("get run: %v", err)
|
||
}
|
||
// No member actor → schedule/webhook-style rule_owner attribution.
|
||
if err := svc.dispatchRunOnly(ctx, ap, &run, pgtype.UUID{}); err != nil {
|
||
t.Fatalf("dispatchRunOnly: %v", err)
|
||
}
|
||
|
||
var source pgtype.Text
|
||
var originator, accountable, ruleVersion pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id, rule_version_id
|
||
FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID).Scan(&source, &originator, &accountable, &ruleVersion); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
if source.String != string(attribution.SourceRuleOwner) {
|
||
t.Errorf("originator_source = %q, want rule_owner", source.String)
|
||
}
|
||
if originator.Valid {
|
||
t.Errorf("run_only autopilot must NOT set originator, got %s", util.UUIDToString(originator))
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != util.MustParseUUID(publisherID).Bytes {
|
||
t.Errorf("accountable_user_id = %s, want publisher %s", util.UUIDToString(accountable), publisherID)
|
||
}
|
||
if !ruleVersion.Valid || ruleVersion.Bytes != util.MustParseUUID(ruleVersionID).Bytes {
|
||
t.Errorf("rule_version_id = %s, want %s", util.UUIDToString(ruleVersion), ruleVersionID)
|
||
}
|
||
}
|
||
|
||
// TestDispatchRunOnlyManualStampsDirectHuman verifies the blocking-finding fix on the
|
||
// run_only path: a MANUAL trigger attributes direct_human to the triggering member —
|
||
// originator == accountable == actor, no rule_version — even when the autopilot has a
|
||
// published rule owned by someone else (MUL-4302 §4).
|
||
func TestDispatchRunOnlyManualStampsDirectHuman(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
|
||
autopilotID, runID := seedRunOnlyAutopilot(t, pool, workspaceID, agentID, publisherID)
|
||
|
||
// A rule version published by the creator exists; the manual actor is a
|
||
// DIFFERENT member, who must win.
|
||
if _, err := pool.Exec(ctx, `
|
||
INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
|
||
VALUES ($1, $2, 'member', $3)`, autopilotID, workspaceID, publisherID); err != nil {
|
||
t.Fatalf("seed rule version: %v", err)
|
||
}
|
||
var actorID string
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Trigger', $1) RETURNING id`,
|
||
fmt.Sprintf("trigger-%d@multica.test", time.Now().UnixNano())).Scan(&actorID); err != nil {
|
||
t.Fatalf("seed actor: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, actorID) })
|
||
if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
|
||
workspaceID, actorID); err != nil {
|
||
t.Fatalf("seed actor member: %v", err)
|
||
}
|
||
|
||
svc := &AutopilotService{Queries: q, TxStarter: pool, Bus: events.New(), TaskSvc: &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}}
|
||
ap, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotID))
|
||
if err != nil {
|
||
t.Fatalf("get autopilot: %v", err)
|
||
}
|
||
run, err := q.GetAutopilotRun(ctx, util.MustParseUUID(runID))
|
||
if err != nil {
|
||
t.Fatalf("get run: %v", err)
|
||
}
|
||
if err := svc.dispatchRunOnly(ctx, ap, &run, util.MustParseUUID(actorID)); err != nil {
|
||
t.Fatalf("dispatchRunOnly: %v", err)
|
||
}
|
||
|
||
var source pgtype.Text
|
||
var originator, accountable, ruleVersion pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id, rule_version_id
|
||
FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID).Scan(&source, &originator, &accountable, &ruleVersion); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
if source.String != string(attribution.SourceDirectHuman) {
|
||
t.Errorf("originator_source = %q, want direct_human", source.String)
|
||
}
|
||
if !originator.Valid || originator.Bytes != util.MustParseUUID(actorID).Bytes {
|
||
t.Errorf("originator_user_id = %s, want triggering member %s", util.UUIDToString(originator), actorID)
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != originator.Bytes {
|
||
t.Errorf("accountable_user_id = %s, want == originator (actor)", util.UUIDToString(accountable))
|
||
}
|
||
if ruleVersion.Valid {
|
||
t.Errorf("manual direct_human must not set rule_version_id, got %s", util.UUIDToString(ruleVersion))
|
||
}
|
||
}
|
||
|
||
// TestDispatchRunOnlyScheduleTransfersToEditor is Elon's must-fix REAL dispatch test:
|
||
// it drives dispatchRunOnly end to end (schedule-style, no member actor) and asserts
|
||
// the PERSISTED agent_task_queue row's accountable_user_id follows the trigger's
|
||
// current responsible publisher after a substantive edit — the creator seeds it, then
|
||
// a later editor's re-stamp (the same SetAutopilotTriggerPublisher the UpdateTrigger
|
||
// handler runs) makes future runs attribute to the editor, with originator still NULL
|
||
// (MUL-4302). The resolver-level before/after and per-trigger isolation are covered by
|
||
// TestTriggerOwnerAttribution_TransfersToSubstantiveEditor.
|
||
func TestDispatchRunOnlyScheduleTransfersToEditor(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, creatorA, agentID, _ := seedAttributionFixture(t, pool)
|
||
editorB := seedExtraMember(t, pool, workspaceID, "dispatch-editor-b")
|
||
|
||
var autopilotID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot (workspace_id, title, assignee_type, assignee_id, status, execution_mode, created_by_type, created_by_id)
|
||
VALUES ($1, 'dispatch-transfer-ap', 'agent', $2, 'active', 'run_only', 'member', $3) RETURNING id`,
|
||
workspaceID, agentID, creatorA).Scan(&autopilotID); err != nil {
|
||
t.Fatalf("seed autopilot: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
|
||
|
||
// Schedule trigger initially published by creator A, then edited by B.
|
||
var triggerID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)
|
||
VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2) RETURNING id`,
|
||
autopilotID, creatorA).Scan(&triggerID); err != nil {
|
||
t.Fatalf("seed trigger: %v", err)
|
||
}
|
||
if err := q.SetAutopilotTriggerPublisher(ctx, db.SetAutopilotTriggerPublisherParams{
|
||
ID: util.MustParseUUID(triggerID),
|
||
PublishedByType: pgtype.Text{String: "member", Valid: true},
|
||
PublishedByID: util.MustParseUUID(editorB),
|
||
}); err != nil {
|
||
t.Fatalf("SetAutopilotTriggerPublisher: %v", err)
|
||
}
|
||
|
||
// A running schedule run bound to that trigger — the shape the scheduler dispatches.
|
||
var runID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_run (autopilot_id, trigger_id, source, status)
|
||
VALUES ($1, $2, 'schedule', 'running') RETURNING id`,
|
||
autopilotID, triggerID).Scan(&runID); err != nil {
|
||
t.Fatalf("seed run: %v", err)
|
||
}
|
||
|
||
svc := &AutopilotService{Queries: q, TxStarter: pool, Bus: events.New(), TaskSvc: &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}}
|
||
ap, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotID))
|
||
if err != nil {
|
||
t.Fatalf("get autopilot: %v", err)
|
||
}
|
||
run, err := q.GetAutopilotRun(ctx, util.MustParseUUID(runID))
|
||
if err != nil {
|
||
t.Fatalf("get run: %v", err)
|
||
}
|
||
// No member actor → schedule/webhook-style trigger_owner attribution.
|
||
if err := svc.dispatchRunOnly(ctx, ap, &run, pgtype.UUID{}); err != nil {
|
||
t.Fatalf("dispatchRunOnly: %v", err)
|
||
}
|
||
|
||
var source pgtype.Text
|
||
var originator, accountable pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id
|
||
FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID).Scan(&source, &originator, &accountable); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
if source.String != string(attribution.SourceTriggerOwner) {
|
||
t.Errorf("originator_source = %q, want trigger_owner", source.String)
|
||
}
|
||
if originator.Valid {
|
||
t.Errorf("schedule dispatch must NOT set originator, got %s", util.UUIDToString(originator))
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != util.MustParseUUID(editorB).Bytes {
|
||
t.Errorf("accountable_user_id = %s, want editor %s (dispatch must follow the transferred publisher, not creator %s)",
|
||
util.UUIDToString(accountable), editorB, creatorA)
|
||
}
|
||
}
|
||
|
||
// TestEnqueueTaskForIssueAutopilotManualStampsDirectHuman verifies the manual fix on
|
||
// the create_issue path: enqueuing an autopilot-origin issue WITH a triggering actor
|
||
// (as dispatchCreateIssue does for a manual trigger) attributes direct_human to that
|
||
// actor, not rule_owner — the actor override wins over the autopilot-origin branch.
|
||
func TestEnqueueTaskForIssueAutopilotManualStampsDirectHuman(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
|
||
|
||
var autopilotID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
|
||
VALUES (gen_random_uuid(), $1, 'member', $2) RETURNING autopilot_id`,
|
||
workspaceID, publisherID).Scan(&autopilotID); err != nil {
|
||
t.Fatalf("seed rule version: %v", err)
|
||
}
|
||
var issueID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority, number, origin_type, origin_id)
|
||
VALUES ($1, 'autopilot issue', 'agent', $2, 'agent', $2, 'medium', 9101, 'autopilot', $3) RETURNING id`,
|
||
workspaceID, agentID, autopilotID).Scan(&issueID); err != nil {
|
||
t.Fatalf("seed autopilot-origin issue: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
|
||
|
||
// A distinct triggering member (not the rule publisher) manually triggers.
|
||
var actorID string
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Trigger', $1) RETURNING id`,
|
||
fmt.Sprintf("trig2-%d@multica.test", time.Now().UnixNano())).Scan(&actorID); err != nil {
|
||
t.Fatalf("seed actor: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, actorID) })
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
// dispatchCreateIssue routes a manual trigger through the actor-carrying enqueue.
|
||
task, err := svc.EnqueueTaskForIssueWithHandoff(ctx, db.Issue{
|
||
ID: util.MustParseUUID(issueID),
|
||
AssigneeID: util.MustParseUUID(agentID),
|
||
Priority: "medium",
|
||
CreatorType: "agent",
|
||
CreatorID: util.MustParseUUID(agentID),
|
||
WorkspaceID: util.MustParseUUID(workspaceID),
|
||
AssigneeType: pgtype.Text{String: "agent", Valid: true},
|
||
OriginType: pgtype.Text{String: "autopilot", Valid: true},
|
||
OriginID: util.MustParseUUID(autopilotID),
|
||
}, "", util.MustParseUUID(actorID))
|
||
if err != nil {
|
||
t.Fatalf("EnqueueTaskForIssueWithHandoff: %v", err)
|
||
}
|
||
|
||
var source pgtype.Text
|
||
var originator, accountable, ruleVersion pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id, rule_version_id
|
||
FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &ruleVersion); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
if source.String != string(attribution.SourceDirectHuman) {
|
||
t.Errorf("originator_source = %q, want direct_human", source.String)
|
||
}
|
||
if !originator.Valid || originator.Bytes != util.MustParseUUID(actorID).Bytes {
|
||
t.Errorf("originator_user_id = %s, want actor %s", util.UUIDToString(originator), actorID)
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != originator.Bytes {
|
||
t.Errorf("accountable_user_id = %s, want == originator (actor)", util.UUIDToString(accountable))
|
||
}
|
||
if ruleVersion.Valid {
|
||
t.Errorf("manual direct_human must not set rule_version_id, got %s", util.UUIDToString(ruleVersion))
|
||
}
|
||
}
|
||
|
||
// TestRecordAutopilotRuleVersionRepublishReattributes verifies the final Phase 1
|
||
// item (MUL-4302 §3.4): republishing a rule (as a trigger edit / archive / system
|
||
// pause does) appends a new version, the LATEST version is the active one, and
|
||
// dispatch attribution follows it. So editing member A's autopilot as member B
|
||
// re-attributes subsequent runs to B; a system pause records a 'system' publisher.
|
||
func TestRecordAutopilotRuleVersionRepublishReattributes(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, memberA, agentID, _ := seedAttributionFixture(t, pool)
|
||
autopilotID, _ := seedRunOnlyAutopilot(t, pool, workspaceID, agentID, memberA)
|
||
|
||
var memberB string
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Editor', $1) RETURNING id`,
|
||
fmt.Sprintf("editor-%d@multica.test", time.Now().UnixNano())).Scan(&memberB); err != nil {
|
||
t.Fatalf("seed member B: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, memberB) })
|
||
if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
|
||
workspaceID, memberB); err != nil {
|
||
t.Fatalf("seed member B membership: %v", err)
|
||
}
|
||
|
||
ap, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotID))
|
||
if err != nil {
|
||
t.Fatalf("get autopilot: %v", err)
|
||
}
|
||
verParams := db.GetActiveAutopilotRuleVersionParams{WorkspaceID: ap.WorkspaceID, AutopilotID: ap.ID}
|
||
|
||
// v1: creator (member A) publishes; active + dispatch attribute to A.
|
||
if err := RecordAutopilotRuleVersion(ctx, q, ap, "member", util.MustParseUUID(memberA)); err != nil {
|
||
t.Fatalf("record v1: %v", err)
|
||
}
|
||
active, err := q.GetActiveAutopilotRuleVersion(ctx, verParams)
|
||
if err != nil || active.PublishedByType != "member" || active.PublishedByID.Bytes != util.MustParseUUID(memberA).Bytes {
|
||
t.Fatalf("v1 active = %+v (err %v), want member A", active, err)
|
||
}
|
||
|
||
// v2: member B republishes (e.g. edited a trigger) → latest wins.
|
||
if err := RecordAutopilotRuleVersion(ctx, q, ap, "member", util.MustParseUUID(memberB)); err != nil {
|
||
t.Fatalf("record v2: %v", err)
|
||
}
|
||
attr := ruleOwnerAttribution(ctx, q, ap.WorkspaceID, ap.ID, attribution.EvidenceAutopilotRun, ap.ID)
|
||
if attr.Source != attribution.SourceRuleOwner || attr.AccountableUserID.Bytes != util.MustParseUUID(memberB).Bytes {
|
||
t.Errorf("after republish, dispatch attribution = %+v, want rule_owner accountable = member B", attr)
|
||
}
|
||
|
||
// v3: system auto-pause records a 'system' publisher (no member id).
|
||
if err := RecordAutopilotRuleVersion(ctx, q, ap, "system", pgtype.UUID{}); err != nil {
|
||
t.Fatalf("record v3 (system): %v", err)
|
||
}
|
||
active, err = q.GetActiveAutopilotRuleVersion(ctx, verParams)
|
||
if err != nil || active.PublishedByType != "system" || active.PublishedByID.Valid {
|
||
t.Errorf("v3 active = %+v (err %v), want system publisher with NULL id", active, err)
|
||
}
|
||
// A system-published version has no member → dispatch degrades to unattributed
|
||
// (never fabricates a human).
|
||
sysAttr := ruleOwnerAttribution(ctx, q, ap.WorkspaceID, ap.ID, attribution.EvidenceAutopilotRun, ap.ID)
|
||
if sysAttr.Source != attribution.SourceUnattributed || sysAttr.AccountableUserID.Valid {
|
||
t.Errorf("system-published version must yield unattributed, got %+v", sysAttr)
|
||
}
|
||
}
|
||
|
||
// TestApplyAttributionFallbackRefusesOnMissingOwner: an unattributed run in an
|
||
// OPEN (non-fail-closed) workspace whose agent has no valid owner cannot resolve an
|
||
// accountable human via owner_fallback, so the enqueue is refused rather than
|
||
// creating a NULL-accountable task (MUL-4302 §3.5, Elon must-fix 1).
|
||
func TestApplyAttributionFallbackRefusesOnMissingOwner(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, _, _, _ := seedAttributionFixture(t, pool) // default policy = open
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
unattr := attribution.Unattributed(attribution.EvidenceIssueAssignment, util.MustParseUUID(workspaceID))
|
||
_, err := svc.applyAttributionFallback(ctx, unattr, db.Agent{WorkspaceID: util.MustParseUUID(workspaceID)}) // OwnerID zero
|
||
if !errors.Is(err, ErrAttributionFailClosed) {
|
||
t.Fatalf("missing owner: err = %v, want ErrAttributionFailClosed", err)
|
||
}
|
||
}
|
||
|
||
// TestApplyAttributionFallbackRefusesOnPolicyReadFailure: if the workspace policy
|
||
// cannot be read for an unattributed run, fail CLOSED (refuse) rather than silently
|
||
// running an unattributable task — even when a valid owner is present (Elon must-fix 1).
|
||
func TestApplyAttributionFallbackRefusesOnPolicyReadFailure(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
_, ownerID, _, _ := seedAttributionFixture(t, pool)
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
unattr := attribution.Unattributed(attribution.EvidenceIssueAssignment, pgtype.UUID{})
|
||
missingWs := pgtype.UUID{Bytes: [16]byte{0xDE, 0xAD, 0xBE, 0xEF}, Valid: true} // no such workspace
|
||
_, err := svc.applyAttributionFallback(ctx, unattr, db.Agent{WorkspaceID: missingWs, OwnerID: util.MustParseUUID(ownerID)})
|
||
if !errors.Is(err, ErrAttributionFailClosed) {
|
||
t.Fatalf("policy read failure: err = %v, want ErrAttributionFailClosed", err)
|
||
}
|
||
}
|
||
|
||
// TestApplyAttributionFallbackPreciseUntouched: a precise attribution never reads
|
||
// the policy and passes through unchanged (proven with a nil-Queries service).
|
||
func TestApplyAttributionFallbackPreciseUntouched(t *testing.T) {
|
||
svc := &TaskService{} // no Queries: a policy read would panic/error if attempted
|
||
precise := attribution.DirectHumanRun(pgtype.UUID{Bytes: [16]byte{0x11}, Valid: true}, attribution.EvidenceComment, pgtype.UUID{})
|
||
got, err := svc.applyAttributionFallback(context.Background(), precise, db.Agent{})
|
||
if err != nil {
|
||
t.Fatalf("precise attribution must not error: %v", err)
|
||
}
|
||
if got.Source != attribution.SourceDirectHuman || got != precise {
|
||
t.Errorf("precise attribution must pass through unchanged, got %+v", got)
|
||
}
|
||
}
|
||
|
||
// TestRerunIssueAttributesToRerunningMember is the §5 acceptance test: a manual
|
||
// rerun is a NEW direct_human trigger attributed to the member who re-ran — not the
|
||
// original run's human — and records rerun_of_task_id lineage back to the source.
|
||
func TestRerunIssueAttributesToRerunningMember(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, creatorID, agentID, issueID := seedAttributionFixture(t, pool)
|
||
|
||
// A distinct member performs the rerun.
|
||
var rerunnerID string
|
||
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Rerunner', $1) RETURNING id`,
|
||
fmt.Sprintf("rerunner-%d@multica.test", time.Now().UnixNano())).Scan(&rerunnerID); err != nil {
|
||
t.Fatalf("seed rerunner: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, rerunnerID) })
|
||
if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
|
||
workspaceID, rerunnerID); err != nil {
|
||
t.Fatalf("seed rerunner member: %v", err)
|
||
}
|
||
|
||
issueStruct := db.Issue{
|
||
ID: util.MustParseUUID(issueID),
|
||
AssigneeID: util.MustParseUUID(agentID),
|
||
Priority: "medium",
|
||
CreatorType: "member",
|
||
CreatorID: util.MustParseUUID(creatorID),
|
||
WorkspaceID: util.MustParseUUID(workspaceID),
|
||
AssigneeType: pgtype.Text{String: "agent", Valid: true},
|
||
}
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
// The original run, attributed to the issue creator.
|
||
orig, err := svc.EnqueueTaskForIssue(ctx, issueStruct)
|
||
if err != nil {
|
||
t.Fatalf("EnqueueTaskForIssue (original): %v", err)
|
||
}
|
||
|
||
// The rerun, performed by a different member.
|
||
task, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(rerunnerID), nil)
|
||
if err != nil {
|
||
t.Fatalf("RerunIssue: %v", err)
|
||
}
|
||
|
||
var source pgtype.Text
|
||
var originator, accountable, rerunOf pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id, rerun_of_task_id
|
||
FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &rerunOf); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
if source.String != string(attribution.SourceDirectHuman) {
|
||
t.Errorf("originator_source = %q, want direct_human", source.String)
|
||
}
|
||
if !originator.Valid || originator.Bytes != util.MustParseUUID(rerunnerID).Bytes {
|
||
t.Errorf("originator_user_id = %s, want rerunner %s (not creator %s)", util.UUIDToString(originator), rerunnerID, creatorID)
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != originator.Bytes {
|
||
t.Errorf("accountable_user_id = %s, want == originator (rerunner)", util.UUIDToString(accountable))
|
||
}
|
||
if !rerunOf.Valid || rerunOf.Bytes != orig.ID.Bytes {
|
||
t.Errorf("rerun_of_task_id = %s, want original task %s", util.UUIDToString(rerunOf), util.UUIDToString(orig.ID))
|
||
}
|
||
}
|
||
|
||
// TestEnqueueChatTaskStampsChatEvidence verifies the chat enqueue path is no
|
||
// longer a NULL-source bypass and uses the UNIFORM evidence pair: the sender is a
|
||
// direct_human originator+accountable, and evidence is (kind=chat,
|
||
// ref=chat_session_id) so the attribution UI links to the conversation the same
|
||
// way it does for autopilot_run / issue_assignment (MUL-4302 §2, Elon 2nd-round).
|
||
func TestEnqueueChatTaskStampsChatEvidence(t *testing.T) {
|
||
pool := newResolveOriginatorPool(t)
|
||
ctx := context.Background()
|
||
q := db.New(pool)
|
||
workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
|
||
|
||
var chatSessionID string
|
||
if err := pool.QueryRow(ctx, `
|
||
INSERT INTO chat_session (workspace_id, agent_id, creator_id)
|
||
VALUES ($1, $2, $3) RETURNING id`, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
|
||
t.Fatalf("seed chat session: %v", err)
|
||
}
|
||
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })
|
||
|
||
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
|
||
task, err := svc.EnqueueChatTask(ctx, db.ChatSession{
|
||
ID: util.MustParseUUID(chatSessionID),
|
||
AgentID: util.MustParseUUID(agentID),
|
||
}, util.MustParseUUID(userID), false)
|
||
if err != nil {
|
||
t.Fatalf("EnqueueChatTask: %v", err)
|
||
}
|
||
|
||
var source, evidenceKind pgtype.Text
|
||
var originator, accountable, evidenceRef pgtype.UUID
|
||
if err := pool.QueryRow(ctx, `
|
||
SELECT originator_source, originator_user_id, accountable_user_id, trigger_evidence_kind, trigger_evidence_ref_id
|
||
FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &evidenceKind, &evidenceRef); err != nil {
|
||
t.Fatalf("read stored attribution: %v", err)
|
||
}
|
||
|
||
if source.String != string(attribution.SourceDirectHuman) {
|
||
t.Errorf("originator_source = %q, want direct_human", source.String)
|
||
}
|
||
if !originator.Valid || originator.Bytes != util.MustParseUUID(userID).Bytes {
|
||
t.Errorf("originator_user_id = %s, want sender %s", util.UUIDToString(originator), userID)
|
||
}
|
||
if !accountable.Valid || accountable.Bytes != originator.Bytes {
|
||
t.Errorf("accountable_user_id = %s, want == originator", util.UUIDToString(accountable))
|
||
}
|
||
if evidenceKind.String != string(attribution.EvidenceChat) {
|
||
t.Errorf("trigger_evidence_kind = %q, want chat", evidenceKind.String)
|
||
}
|
||
if !evidenceRef.Valid || evidenceRef.Bytes != util.MustParseUUID(chatSessionID).Bytes {
|
||
t.Errorf("trigger_evidence_ref_id = %s, want chat session %s", util.UUIDToString(evidenceRef), chatSessionID)
|
||
}
|
||
}
|