diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index ab30a1ad78c..405e96a341c 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1357,6 +1357,17 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline `frontend/src/flows/KnowledgeSourceDialog.test.tsx` checks N's side, and the mixed-version gate does not check this rule. +87. **Captured-memory provenance** (migration `125_captured_conflict_provenance.sql`): a + captured service-account token is issued only when every live replica advertises the + resolver capability and its namespace uses `manual_review` as the general conflict + policy. Captured writes check the live capability again, so a mixed rollout pauses them. + While captured rows remain live, N refuses a namespace policy change away from + `manual_review`. N-1 does not read `capture_origin` or the captured policy, but it does + honor `manual_review`; this keeps its resolver and inline `newest_wins` path from + retiring those rows after a rollback. Captured resolver updates remain available on N + through the separate captured policy. `tests/unit/test_provenance.py` covers the live + resolver gate, and the captured conflict tests cover the policy fence. + 86. **Regression suites** (`loom.knowledge_suites`, migration `130_knowledge_suites.sql`): N-1 serves none of the `knowledge.suites.*` ops, and a namespace erasure it runs has no step for the table. So `knowledge.suites.publish` diff --git a/docs/features/memory/captured-conflict-simulation.md b/docs/features/memory/captured-conflict-simulation.md new file mode 100644 index 00000000000..17a50f3eca8 --- /dev/null +++ b/docs/features/memory/captured-conflict-simulation.md @@ -0,0 +1,35 @@ +# Captured conflict simulation + +The seven-day model compares the resolver's default policy with an owner opt-in for settling +high-confidence updates between authenticated captured rows. It uses the production decision +helpers and fixed verdicts; it does not call an LLM or ClickHouse. + +Run it from the repository root: + +```bash +uv run --locked python scripts/ops/simulate_captured_conflicts.py +``` + +## Results + +| Scenario | Captured rows | Human-reviewable pairs, default | Human-reviewable pairs, opt-in | All automatic settlements, default | All automatic settlements, opt-in | Captured-policy settlements, opt-in | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Light | 700 | 372 | 141 | 176 | 407 | 231 | +| Steady | 1,750 | 975 | 328 | 413 | 1,060 | 647 | +| Surge | 3,500 | 1,965 | 645 | 829 | 2,149 | 1,320 | + +In all six runs, backlog growth, false automatic settlements, and settled genuine +contradictions were zero. Each scenario used a review capacity of 2,000 pairs per sitting. +The model produced no failed resolver jobs and left no resolver work pending. + +## Model inputs and limits + +- Seven days of seeded synthetic cases use fixed resolver verdicts and confidence scores. +- Resolver batches contain 40 rows, concurrency is 8, bursts last at most 300 seconds, and a + row gets at most three attempts. +- A daily resolver call cap stands in for the namespace cost-share limit; it is not a provider + price estimate. +- Review capacity is an input, not a measured operator rate. The generated workload contains + no Undo events. +- Synthetic case mixes and fixed verdicts do not represent production distributions. The model + excludes database races, provider latency distributions, and real restore writes. diff --git a/docs/features/memory/conflicts-and-refusal.md b/docs/features/memory/conflicts-and-refusal.md index a670c48b585..dcc230ace32 100644 --- a/docs/features/memory/conflicts-and-refusal.md +++ b/docs/features/memory/conflicts-and-refusal.md @@ -189,6 +189,21 @@ one call to `LOOM_CONFLICT_RESOLVER_MODEL` (`gpt-6.1-sol`). Per pair: The judge sees when each note's statement holds and which session it comes from. +Captured writes carry a server-stamped `capture_origin` from a verified service-account token; +request fields cannot set it. The supported origins are `claude-code` and `codex`. The +namespace's `captured_conflict_policy` defaults to `manual_review`, and its +`captured_conflict_confidence` defaults to 0.98. With `manual_review`, a captured update stays +flagged even when the general namespace policy would retire it. Setting the captured policy to +`resolver_update` lets the resolver retire a same-entity, same-attribute update only when both +rows have trusted capture origins, the same agent and user, and the verdict meets the configured +confidence. An anonymous user's cross-session update still waits for review. Rows without a +trusted origin cannot use this policy. The [captured-conflict simulation](./captured-conflict-simulation.md) +reports a deterministic workload model and its limits. + +Issuing a captured credential requires the namespace's `default_conflict_policy` to be +`manual_review`, and that policy stays in place while captured rows are live. This keeps a +rollback build, which does not read `capture_origin`, from automatically retiring those rows. + It also re-checks pairs flagged before it judged them, so a false flag is cleared once (a definition's flags excepted: it is never judged, only its dead flags released). A pinned row is never touched, a row that changed since it was judged is left to its @@ -205,6 +220,13 @@ applies `conflicts.resolve`. Three more tabs appear when they have content: **Le ([learnings](./procedures-and-learnings.md#learnings-review-queue)), **Auto-resolved** (below) and **Exceptions** (the allowlist). See [the dashboard](../dashboard.md). +The queue summary and `mentor.brief` report **conflicted rows**, grouped by whether a resolver +judgement is owed, the resolver judged but left the conflict open, or only cosine similarity +flagged the row. A row count is not a count of distinct pairs: a conflict can be linked in both +directions or belong to a larger cluster. The summary separates authenticated plugin captures, +caller-written rows, and rows with unknown provenance. The plugin's SessionStart notice uses the +scoped `conflicts.list` count and links to that namespace's queue. + ### Automatic retirements When Loom retires memories on its own, each path that retired rows records them as diff --git a/docs/reference/operations.md b/docs/reference/operations.md index bd584df54a0..ef9648d8642 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -125,7 +125,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal -426 operations in 46 groups. Every op is served at `POST /v1/` and, unless its line says otherwise, as the MCP tool `loom_` (dots become underscores). +427 operations in 46 groups. Every op is served at `POST /v1/` and, unless its line says otherwise, as the MCP tool `loom_` (dots become underscores). Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`; an op marked `hidden` is not served over MCP, except where its line on its group's page names the one place that serves it; **Audit** marks ops that leave an `audit_log` row. @@ -263,6 +263,7 @@ Fields for every `conflicts` op: [operations/conflicts.md](operations/conflicts. | --- | --- | --- | --- | --- | --- | | [`conflicts.allowlist_list`](operations/conflicts.md#conflictsallowlist_list) | List (memory_key, memory_key) pairs marked as known-non-conflicting so the conflicts worker stops flagging them. | viewer | read | hidden | | | [`conflicts.allowlist_remove`](operations/conflicts.md#conflictsallowlist_remove) | Revoke an allow decision; the pair will re-flag on future writes. | admin | idempotent | hidden | yes | +| [`conflicts.bulk_accept`](operations/conflicts.md#conflictsbulk_accept) | Accept current hash-only resolver update suggestions independently. | admin | idempotent | hidden | yes | | [`conflicts.list`](operations/conflicts.md#conflictslist) | List unresolved conflicts where two memories contradict each other. | viewer | read | hidden | | | [`conflicts.propose_revision`](operations/conflicts.md#conflictspropose_revision) | Return non-destructive revise/contract/allow suggestions. | viewer | read | hidden | | | [`conflicts.resolve`](operations/conflicts.md#conflictsresolve) | Pick the winner of a conflict (keep A, keep B, keep both, merge). | admin | idempotent | hidden | yes | diff --git a/docs/reference/operations/conflicts.md b/docs/reference/operations/conflicts.md index 3ed1b58b0c0..f61c7690757 100644 --- a/docs/reference/operations/conflicts.md +++ b/docs/reference/operations/conflicts.md @@ -43,6 +43,26 @@ Revoke an allow decision; the pair will re-flag on future writes. | --- | --- | --- | | `removed` | `bool` | False when no live allowed pair matched. | +## `conflicts.bulk_accept` + +Accept current hash-only resolver update suggestions independently. + +`POST /v1/conflicts.bulk_accept` · MCP `loom_conflicts_bulk_accept` · role `admin` · idempotent · audited · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The tenant (first element of the identity tuple). | +| `namespace` | `str` | required | The namespace the op reads or writes. | +| `items` | `list[ConflictsResolverAcceptItem]` | required | Bounded so a request cannot monopolize the resolver or audit store. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `results` | `list[_ConflictBulkResult]` | | +| `requested` | `int` | | +| `resolved` | `int` | | +| `stale` | `int` | | +| `failed` | `int` | | + ## `conflicts.list` List unresolved conflicts where two memories contradict each other. @@ -66,6 +86,7 @@ List unresolved conflicts where two memories contradict each other. | `next_before_version` | `int \| None` | Pass as `before_version` for the next page; null on the last page. | | `total` | `int \| None` | The live conflicted count for the namespace; set on a count_only call. | | `proposals` | `int \| None` | The pending proposals in the same scope, from the same read; set on a count_only call. | +| `backlog` | `ConflictBacklog \| None` | Row-based backlog split, present on `count_only`; reciprocal links are not pairs. | | `keys` | `list[str] \| None` | The conflicted memory keys of the namespace; set on a keys_only call. | ## `conflicts.propose_revision` diff --git a/docs/reference/operations/mentor.md b/docs/reference/operations/mentor.md index d6d95ea9104..2917379ef4e 100644 --- a/docs/reference/operations/mentor.md +++ b/docs/reference/operations/mentor.md @@ -31,6 +31,7 @@ One agent's usage profile and the store's hints. | `sessions` | `int` | Distinct client-named sessions of this agent in the window (`-` and `*` not counted). | | `usage` | `dict[str, int]` | Calls per operation by this agent in the window, leaving out a `memory.get` of a repository's test cost row (key `repo:/test-cost/pytest`), which a coding-agent plugin's prompt hook sends under the agent. | | `planes` | `list[MentorPlane]` | Every plane the mentor knows, with this agent's calls to it (the sum of its ops' `usage` counts) and whether it is available. | +| `conflict_backlog` | `dict[str, dict[str, int]]` | Conflicted memory rows in this namespace, grouped by resolver state and trustworthy provenance. | | `hints` | `list[MentorHint]` | The rules that fired for this agent, each with the counts that fired it; empty when none. | | `adoption` | `list[MentorAdoption]` | Per hint code, sessions it was shown in and followed in, most shown first; empty when no hint reached the agent or the read failed. | | `usage_evidence` | `list[UsageRung]` | The agent's use of Loom in the window, one rung each, weakest claim first: from a call made to a graded run. | diff --git a/docs/reference/operations/namespace.md b/docs/reference/operations/namespace.md index 0967567d924..78b4d4aa46b 100644 --- a/docs/reference/operations/namespace.md +++ b/docs/reference/operations/namespace.md @@ -129,7 +129,9 @@ Fetch one namespace's metadata + settings (owner, visibility, feature flags, ret | `rerank_endpoint` | `str \| None` | The reranker `memory.search` uses (a builtin or a configured endpoint's name); empty when none. | | `classify_endpoint` | `str \| None` | URL `memory.set(classify=true)` calls to classify a write; empty when none. | | `default_conflict_policy` | `str \| None` | How close writes are settled: `auto_reinforce` (the default when unset), `manual_review`, `newest_wins` or `append_only`. | -| `proposal_policy` | `ProposalPolicy \| None` | The owner's rule for proposals (`memory.set proposed=true`): under mode `auto`, `run.grade` rejects one once its failed graded runs reach `reject_after_fails` (0 = never), and no policy accepts one; the manual default when unset. | +| `captured_conflict_policy` | `str` | | +| `captured_conflict_confidence` | `float` | | +| `proposal_policy` | `ProposalPolicy \| None` | How proposals (`memory.set proposed=true`) are decided; the manual default when unset. | | `code_change_policy` | `Literal['retire_removed', 'flag', 'revise'] \| None` | How reads treat the namespace's code-linked memories when their code changes: `retire_removed` (the default), `flag` or `revise`. | | `curator_mode` | `str \| None` | Whether the curator's scheduled pass reads the namespace: `off` for a row that never set a mode, else the stored word (`findings`, `assist`, or a mode a newer build stored, served as it is). | | `tag_registry` | `list[dict[str, Any]] \| None` | Per-tag configuration rows (retention, dedup threshold, hot quota, conflict policy); empty when none are registered. | @@ -382,6 +384,8 @@ Create a shared memory workspace within an org; caller becomes admin. | `classify_prompt_template` | `str \| None` | `None` | Text forwarded as `prompt_template` in every call to `classify_endpoint`. | | `tag_registry` | `list[NamespaceTypeConfig]` | *(computed)* | Per-tag TTL + dedup_threshold registry, matched on tags at memory.set time. | | `default_conflict_policy` | `Literal['auto_reinforce', 'manual_review', 'newest_wins', 'append_only'] \| None` | `None` | fresh: auto_reinforce | +| `captured_conflict_policy` | `Literal['manual_review', 'resolver_update'] \| None` | `None` | Captured integration conflicts stay human-reviewable unless the owner opts in. | +| `captured_conflict_confidence` | `float \| None` | `None` | Minimum resolver confidence for an opted-in captured-to-captured update. | | `proposal_policy` | `ProposalPolicy \| None` | `None` | The owner's rule for proposals (facts written with memory.set proposed=true): under mode `auto`, `run.grade` rejects one once its failed graded runs reach `reject_after_fails` (0 = never), and no policy accepts one. | | `code_change_policy` | `Literal['retire_removed', 'flag', 'revise'] \| None` | `None` | How reads treat this namespace's code-linked memories when their code changes: `retire_removed` (the default: search leaves out a memory whose code is all gone, and serves it again when the code returns), `flag` (only the links are marked)… | | `curator_mode` | `Literal['off', 'findings', 'assist'] \| None` | `None` | `off`, `findings` or `assist`, which calls a model: In this mode the curator sends content of this namespace to the deployment's model provider: the namespace's guide and the text of each pending proposal of its shared scope that is not… | diff --git a/docs/reference/status.md b/docs/reference/status.md index cb4331c2ae7..8c650de5ecf 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -426 operations, 312 of them experimental. +427 operations, 313 of them experimental. | Group | Stable | Experimental | | --- | --- | --- | @@ -37,7 +37,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). | `calibration` | 0 | [`calibration.get`](operations/calibration.md#calibrationget) | | `code` | 28 | [`code.backport_gap`](operations/code.md#codebackport_gap), [`code.backport_gaps`](operations/code.md#codebackport_gaps), [`code.bisect_candidates`](operations/code.md#codebisect_candidates), [`code.blame_range`](operations/code.md#codeblame_range), [`code.callees`](operations/code.md#codecallees), [`code.conventions`](operations/code.md#codeconventions), [`code.coverage_claim`](operations/code.md#codecoverage_claim), [`code.edit_context`](operations/code.md#codeedit_context), [`code.examples`](operations/code.md#codeexamples), [`code.files`](operations/code.md#codefiles), [`code.first_build`](operations/code.md#codefirst_build), [`code.map`](operations/code.md#codemap), [`code.outline`](operations/code.md#codeoutline), [`code.path_guards`](operations/code.md#codepath_guards), [`code.pr_check`](operations/code.md#codepr_check), [`code.read`](operations/code.md#coderead), [`code.reindex`](operations/code.md#codereindex), [`code.repo.set_access`](operations/code.md#codereposet_access), [`code.repo.set_source`](operations/code.md#codereposet_source), [`code.review_brief`](operations/code.md#codereview_brief), [`code.setting_facts`](operations/code.md#codesetting_facts), [`code.symbol_history`](operations/code.md#codesymbol_history), [`code.test_gate`](operations/code.md#codetest_gate), [`code.test_home`](operations/code.md#codetest_home), [`code.tests_for`](operations/code.md#codetests_for), [`code.verify_citations`](operations/code.md#codeverify_citations) | | `collection` | 0 | [`collection.budget_set`](operations/collection.md#collectionbudget_set), [`collection.create`](operations/collection.md#collectioncreate), [`collection.delete`](operations/collection.md#collectiondelete), [`collection.list`](operations/collection.md#collectionlist), [`collection.move`](operations/collection.md#collectionmove) | -| `conflicts` | 2 | [`conflicts.allowlist_list`](operations/conflicts.md#conflictsallowlist_list), [`conflicts.allowlist_remove`](operations/conflicts.md#conflictsallowlist_remove), [`conflicts.propose_revision`](operations/conflicts.md#conflictspropose_revision) | +| `conflicts` | 2 | [`conflicts.allowlist_list`](operations/conflicts.md#conflictsallowlist_list), [`conflicts.allowlist_remove`](operations/conflicts.md#conflictsallowlist_remove), [`conflicts.bulk_accept`](operations/conflicts.md#conflictsbulk_accept), [`conflicts.propose_revision`](operations/conflicts.md#conflictspropose_revision) | | `connection` | 0 | [`connection.disconnect`](operations/connection.md#connectiondisconnect), [`connection.list`](operations/connection.md#connectionlist) | | `consolidations` | 0 | [`consolidations.list`](operations/consolidations.md#consolidationslist) | | `context` | 1 | [`context.fetch`](operations/context.md#contextfetch), [`context.offload`](operations/context.md#contextoffload) | diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 6424b26845b..ec9f11cc60d 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -709,6 +709,7 @@ export interface ConflictRow { content_sha256: string; // A high row comes without its value; the inspector reads it by key. sensitivity?: string; + capture_origin?: "claude-code" | "codex" | ""; } /** The namespace's Review queue counts from one read: `total` conflicted and `proposals` @@ -729,6 +730,19 @@ export function countReview( export interface ReviewCounts { total?: number | null; proposals?: number | null; + backlog?: ConflictBacklog | null; +} + +export interface ConflictSourceCounts { + plugin_captured: number; + caller_written: number; + unknown: number; +} + +export interface ConflictBacklog { + pending_judgement: ConflictSourceCounts; + resolver_judged: ConflictSourceCounts; + cosine_only: ConflictSourceCounts; } // ===== cost.budget_status ===== @@ -981,6 +995,7 @@ export interface TokenCreated { created_at: string; expires_at: string | null; mcp_url: string; + capture_origin?: "claude-code" | "codex" | null; } export interface BrowseEntry { diff --git a/frontend/src/api/admin.cost.test.ts b/frontend/src/api/admin.cost.test.ts index adc98d73739..ba76c201896 100644 --- a/frontend/src/api/admin.cost.test.ts +++ b/frontend/src/api/admin.cost.test.ts @@ -1,9 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // The cost clients' "last N days" is N UTC dates, today included. -const post = vi.hoisted(() => vi.fn(async () => ({ rows: [] }))); +const post = vi.hoisted(() => + vi.fn(async (_path: string, _body?: unknown, _signal?: AbortSignal) => ({ rows: [] })), +); vi.mock("../api", async (importOriginal) => ({ ...(await importOriginal()), post })); -import { getAgentSpend, listCostRollup } from "./admin"; +import { getAgentSpend, listCostRollup, reregisterNamespace } from "./admin"; const id = { org: "acme", namespace: "team" }; @@ -25,3 +27,24 @@ describe("cost windows", () => { expect(post).toHaveBeenCalledWith("/v1/cost.agent_summary", week, undefined); }); }); + +it("does not resend stale captured-conflict settings on an unrelated save", async () => { + const ns = { + namespace: "team", + owner_email: "owner@example.com", + description: "old", + tags: [], + active: true, + consolidation_enabled: false, + conflict_threshold: null, + captured_conflict_policy: "resolver_update" as const, + captured_conflict_confidence: 0.99, + created_at: "", + updated_at: "", + }; + await reregisterNamespace(id, ns, { description: "new" }); + const body = post.mock.calls.at(-1)?.[1]; + expect(body).toMatchObject({ description: "new" }); + expect(body).not.toHaveProperty("captured_conflict_policy"); + expect(body).not.toHaveProperty("captured_conflict_confidence"); +}); diff --git a/frontend/src/api/admin.ts b/frontend/src/api/admin.ts index 2dc59e5b396..9ddebaaeb14 100644 --- a/frontend/src/api/admin.ts +++ b/frontend/src/api/admin.ts @@ -286,6 +286,8 @@ export interface NamespaceInfo { budget_alert_inbox?: string; consolidation_enabled: boolean; conflict_threshold: number | null; + captured_conflict_policy?: "manual_review" | "resolver_update"; + captured_conflict_confidence?: number; visibility?: "private" | "public"; requires_approval?: boolean; /** The stored join word and the resolved one. */ @@ -335,6 +337,8 @@ export interface NamespaceRegisterFields { budget_alert_inbox?: string; consolidation_enabled?: boolean; conflict_threshold?: number | null; + captured_conflict_policy?: "manual_review" | "resolver_update"; + captured_conflict_confidence?: number; requires_approval?: boolean; /** Omit to keep the stored value. */ join_policy?: "inherit" | "open" | "approval" | "closed"; @@ -376,6 +380,12 @@ export async function registerNamespace( if (opts.conflict_threshold !== undefined) { body["conflict_threshold"] = opts.conflict_threshold; } + if (opts.captured_conflict_policy !== undefined) { + body["captured_conflict_policy"] = opts.captured_conflict_policy; + } + if (opts.captured_conflict_confidence !== undefined) { + body["captured_conflict_confidence"] = opts.captured_conflict_confidence; + } // Sent only when explicitly set. Omitting it means "unchanged" server-side, so // an unrelated settings save cannot silently reset a privacy choice. if (opts.capture_generation_io !== undefined) { diff --git a/frontend/src/api/audit.ts b/frontend/src/api/audit.ts index 49569e08425..2f76850d156 100644 --- a/frontend/src/api/audit.ts +++ b/frontend/src/api/audit.ts @@ -13,6 +13,7 @@ export interface AuditEntry { /** JSON text of the operation's input (`AuditListRow.subject`); parse before reading. */ subject: string; request_id: string; + row_hash?: string; } export async function listAuditLog( diff --git a/frontend/src/api/conflicts.ts b/frontend/src/api/conflicts.ts index 5ab26fc6200..cee4dce824b 100644 --- a/frontend/src/api/conflicts.ts +++ b/frontend/src/api/conflicts.ts @@ -1,9 +1,38 @@ -// The conflict rows and their keys, behind the `api.ts` barrel. The Review queue, the -// Memories page and the memory drawer call them; the count the sidebar polls (`countReview`) -// stays in `api.ts`, and the decision on a conflict is in `api/review.ts`. import { post } from "../api"; import type { ConflictRow, Identity, RequestOpts } from "../api"; +export interface ResolverAcceptItem { + memory_id: string; + peer_id: string; + memory_sha256: string; + peer_sha256: string; + suggestion_hash: string; +} + +export interface ResolverAcceptResult { + memory_id: string; + peer_id: string; + status: "resolved" | "stale" | "failed"; + reason?: string; +} + +/** Accept a bounded batch of current resolver update suggestions. */ +export async function acceptResolverSuggestions( + id: Pick, + items: ResolverAcceptItem[], + opts: RequestOpts = {}, +): Promise<{ + results: ResolverAcceptResult[]; + requested: number; + resolved: number; + stale: number; + failed: number; +}> { + return post("/v1/conflicts.bulk_accept", { org: id.org, namespace: id.namespace, items }, opts.signal); +} +// The conflict rows and their keys, behind the `api.ts` barrel. The Review queue, the +// Memories page and the memory drawer call them; the count the sidebar polls (`countReview`) +// stays in `api.ts`, and the decision on a conflict is in `api/review.ts`. export async function listConflicts( id: Pick, opts: { limit?: number; before_version?: number } & RequestOpts = {}, diff --git a/frontend/src/api/tokens.ts b/frontend/src/api/tokens.ts index 3518966aa1b..7ef1338fc06 100644 --- a/frontend/src/api/tokens.ts +++ b/frontend/src/api/tokens.ts @@ -16,6 +16,8 @@ export async function createToken(opts: { ttl_days: number | null; /** A list's save target, one of its memory namespaces it writes; not sent with `*`. */ saves_to?: string; + /** Signed server-issued provenance for a single-namespace coding-agent credential. */ + capture_origin?: "claude-code" | "codex"; }): Promise { const r = await post & Pick>( "/v1/me/service_accounts.create", diff --git a/frontend/src/flows/NamespaceSettingsDialog.tsx b/frontend/src/flows/NamespaceSettingsDialog.tsx index 3df1852c4ea..14525df8bbc 100644 --- a/frontend/src/flows/NamespaceSettingsDialog.tsx +++ b/frontend/src/flows/NamespaceSettingsDialog.tsx @@ -77,6 +77,8 @@ export function NamespaceSettingsDialog({ open, onOpenChange, org, namespace, la // for; null (or another namespace's draft) shows the stored cap. const [capEdit, setCapEdit] = useState<{ key: string; text: string } | null>(null); const capDraft = capEdit?.key === key ? capEdit.text : null; + const [captureConfidenceEdit, setCaptureConfidenceEdit] = useState<{ key: string; text: string } | null>(null); + const captureConfidenceDraft = captureConfidenceEdit?.key === key ? captureConfidenceEdit.text : null; useAbortableEffect( async (signal, live) => { @@ -89,6 +91,7 @@ export function NamespaceSettingsDialog({ open, onOpenChange, org, namespace, la setLoaded({ key, info }); setDescDraft(info?.description || ""); setDescDirty(false); + setCaptureConfidenceEdit(null); }, [open, org, namespace], ); @@ -139,6 +142,9 @@ export function NamespaceSettingsDialog({ open, onOpenChange, org, namespace, la setDescDraft(next?.description || ""); setDescDirty(false); } + if (patch.captured_conflict_confidence !== undefined) { + setCaptureConfidenceEdit(null); + } } catch (e) { toastError("Save failed", e); } finally { @@ -157,6 +163,21 @@ export function NamespaceSettingsDialog({ open, onOpenChange, org, namespace, la setCapEdit(null); }; + const commitCaptureConfidence = async () => { + if (captureConfidenceDraft === null || !ns) return; + const value = Number(captureConfidenceDraft); + if ( + captureConfidenceDraft.trim() !== "" && + Number.isFinite(value) && + value >= 0.5 && + value <= 1 && + value !== (ns.captured_conflict_confidence ?? 0.98) + ) { + await save({ captured_conflict_confidence: value }); + } + setCaptureConfidenceEdit(null); + }; + const onDelete = async () => { if ( !(await confirmAction({ @@ -246,6 +267,50 @@ export function NamespaceSettingsDialog({ open, onOpenChange, org, namespace, la {!isRepo && ( <> +
+ (null); const mine = useMemo(() => rows?.filter((r) => r.status !== "pending") ?? null, [rows]); const [reach, setReach] = useState("everything"); + const [captureOrigin, setCaptureOrigin] = useState(""); const [name, setName] = useState(""); const [ttlDays, setTtlDays] = useState("90"); const [busy, setBusy] = useState(false); @@ -653,6 +669,7 @@ function TokenForm({ setSelectedNs((prev) => prev.filter((x) => x !== ns)); setNsRole(({ [ns]: _, ...rest }) => rest); } else { + if (captureOrigin && selectedNs.length > 0) return; setSelectedNs((prev) => [...prev, ns]); setNsRole((m) => ({ ...m, [ns]: grantRoleOf(mine, ns) })); } @@ -729,17 +746,29 @@ function TokenForm({ namespaces = [...(everythingHome ? [everythingHome] : []), "*", ...restricted]; } else { if (selectedNs.length === 0) return; + if (captureOrigin && selectedNs.length !== 1) { + toast("Choose exactly one namespace for a capture token", "error"); + return; + } // Ordered = read priority; repositories are read-only. namespaces = selectedNs.map((ns) => ({ namespace: ns, - role: isRepo(ns) ? "viewer" : nsRole[ns], + role: captureOrigin ? "writer" : isRepo(ns) ? "viewer" : nsRole[ns], })); } // A list token's target goes as `saves_to`; with none, the field is left out. const savesTo = reach === "listed" && listSaves ? { saves_to: listSaves } : {}; setBusy(true); try { - onCreated(await createToken({ name: name.trim() || undefined, namespaces, ttl_days: ttl, ...savesTo })); + onCreated( + await createToken({ + name: name.trim() || undefined, + namespaces, + ttl_days: ttl, + ...savesTo, + ...(captureOrigin ? { capture_origin: captureOrigin } : {}), + }), + ); setName(""); } catch (e) { toastError("Failed", e); @@ -777,6 +806,24 @@ function TokenForm({ label="Can read" value={reach} onChange={setReach} options={REACH_OPTIONS} /> + + label="Credential type" + value={captureOrigin} + onChange={(value) => { + setCaptureOrigin(value); + if (value) { + setReach("listed"); + setSelectedNs((current) => current.slice(0, 1)); + } + }} + options={CAPTURE_OPTIONS} + /> + {captureOrigin && ( +

+ A capture token needs sign-in enabled, one namespace and writer access. A namespace admin issues it. +

+ )} + {reach === "everything" ? ( { getMemoryById: vi.fn(), listProposals: vi.fn(async () => ({ proposals: [], total: 0 })), proposeRevision: vi.fn(), + listAuditLog: vi.fn(async () => ({ rows: [] })), listMemoryDuplicates: vi.fn(async () => ({ clusters: [] })), listDocumentDuplicates: vi.fn(async () => ({ doc_clusters: [] })), listMemoryAgents: vi.fn(async () => []), @@ -54,6 +56,9 @@ vi.mock("../../api/audit", async (importOriginal) => ({ ...(await importOriginal()), hasAutoResolved: vi.fn(), })); +vi.mock("../../api/conflicts", () => ({ + acceptResolverSuggestions: vi.fn(async () => ({ results: [], requested: 0, resolved: 0, stale: 0, failed: 0 })), +})); // The count of the skill drafts that wait is shared with the sidebar too: none waits. vi.mock("../../api/skillDrafts", async (importOriginal) => ({ ...(await importOriginal()), @@ -79,9 +84,10 @@ vi.mock("../../api/definitions", () => ({ })); // The Curator tab's read, which no other tab makes. vi.mock("../../api/curator", () => ({ curatorStatus: vi.fn(async () => ({})) })); +const confirmAction = vi.hoisted(() => vi.fn(async () => true)); +vi.mock("../../components/ConfirmDialog", () => ({ confirmAction })); // A proposal's review reads its suite checks: no suite covers the key. vi.mock("../../api/suiteResults", () => ({ readSuiteResults: vi.fn(async () => ({ covered: false })) })); -vi.mock("../../components/ConfirmDialog", () => ({ confirmAction: async () => true })); const toast = vi.hoisted(() => vi.fn()); vi.mock("../../components/Toast", async (importOriginal) => ({ ...(await importOriginal()), @@ -96,6 +102,7 @@ import { countReview, getMemoryById, listAllowlist, + listAuditLog, listAutoResolved, listConflicts, listLearnings, @@ -110,6 +117,7 @@ import { restoreMemory, reviewLearning, } from "../../api"; +import { acceptResolverSuggestions } from "../../api/conflicts"; const ORG = "dev"; const WAIT = { timeout: 5000 }; @@ -216,6 +224,13 @@ describe("ReviewQueue", () => { beforeEach(() => { window.history.replaceState(null, "", QUEUE); vi.mocked(listConflicts).mockReset(); + vi.mocked(countReview).mockReset(); + vi.mocked(countReview).mockResolvedValue({ total: 0 }); + vi.mocked(listAuditLog).mockReset(); + vi.mocked(listAuditLog).mockResolvedValue({ rows: [] }); + vi.mocked(acceptResolverSuggestions).mockReset(); + confirmAction.mockReset(); + confirmAction.mockResolvedValue(true); vi.mocked(listAllowlist).mockReset(); vi.mocked(listLearnings).mockReset(); vi.mocked(listProposals).mockReset(); @@ -247,6 +262,332 @@ describe("ReviewQueue", () => { async (id) => (await listAutoResolved(id, { limit: 5 })).rows.length > 0, ); }); + + it("accepts selected current resolver suggestions and reports partial outcomes", async () => { + const hashA = "a".repeat(64); + const hashB = "b".repeat(64); + const hashC = "d".repeat(64); + const hashD = "e".repeat(64); + vi.mocked(listConflicts).mockResolvedValue({ + rows: [ + { + ...conflict("a"), + memory_id: "a", + conflict_with: ["b"], + content_sha256: hashA, + value: "new", + capture_origin: "codex", + }, + { + ...conflict("b"), + memory_id: "b", + conflict_with: ["a"], + content_sha256: hashB, + value: "old", + capture_origin: "codex", + }, + { + ...conflict("c"), + memory_id: "c", + conflict_with: ["d"], + content_sha256: hashC, + value: "newer", + capture_origin: "claude-code", + }, + { + ...conflict("d"), + memory_id: "d", + conflict_with: ["c"], + content_sha256: hashD, + value: "older", + capture_origin: "claude-code", + }, + ], + next_before_version: null, + }); + vi.mocked(listAuditLog).mockResolvedValue({ + rows: [ + { + ts: "2026-09-20T00:00:00Z", + event_type: "memory.conflict_resolver", + actor: "process:loom", + request_id: "", + row_hash: "c".repeat(64), + subject: JSON.stringify({ + memory_id: "a", + content_sha256: hashA, + pairs: [ + { + peer_id: "b", + peer_sha256: hashB, + memory_sha256: hashA, + action: "flag", + verdict: "update", + confidence: 0.99, + same_entity: true, + same_attribute: true, + }, + ], + }), + }, + { + ts: "2026-09-20T00:00:00Z", + event_type: "memory.conflict_resolver", + actor: "process:loom", + request_id: "", + row_hash: "f".repeat(64), + subject: JSON.stringify({ + memory_id: "c", + content_sha256: hashC, + pairs: [ + { + peer_id: "d", + peer_sha256: hashD, + memory_sha256: hashC, + action: "flag", + verdict: "update", + confidence: 0.98, + same_entity: true, + same_attribute: true, + }, + ], + }), + }, + ], + }); + vi.mocked(acceptResolverSuggestions).mockResolvedValue({ + requested: 2, + resolved: 1, + stale: 1, + failed: 0, + results: [ + { memory_id: "a", peer_id: "b", status: "resolved" }, + { memory_id: "c", peer_id: "d", status: "stale", reason: "Memory revision changed" }, + ], + }); + seed("ns-a", "admin"); + const user = userEvent.setup(); + render(); + await waitFor(() => expect(listConflicts).toHaveBeenCalled(), WAIT); + await waitFor(() => expect(listAuditLog).toHaveBeenCalled(), WAIT); + await screen.findByText("Resolver update suggestions", {}, WAIT); + await user.click(screen.getByRole("button", { name: "Select all eligible" })); + await user.click(screen.getByRole("button", { name: "Accept selected" })); + await waitFor(() => expect(acceptResolverSuggestions).toHaveBeenCalledTimes(1), WAIT); + expect(acceptResolverSuggestions).toHaveBeenCalledWith({ org: ORG, namespace: "ns-a" }, [ + { memory_id: "a", peer_id: "b", memory_sha256: hashA, peer_sha256: hashB, suggestion_hash: "c".repeat(64) }, + { memory_id: "c", peer_id: "d", memory_sha256: hashC, peer_sha256: hashD, suggestion_hash: "f".repeat(64) }, + ]); + expect(await screen.findByText(/stale/)).toBeInTheDocument(); + expect(await screen.findByText("value of newer")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "c" })).toHaveAttribute("aria-current", "true"); + expect(listConflicts).toHaveBeenCalledTimes(1); + }, 20000); + + it("offers only the latest direction for a pair and ignores counts that overlap acceptance", async () => { + const hashA = "a".repeat(64); + const hashB = "b".repeat(64); + let finishOldCount: (result: ReviewCounts) => void = () => {}; + vi.mocked(countReview) + .mockImplementationOnce(() => new Promise((resolve) => (finishOldCount = resolve))) + .mockResolvedValue({ total: 1 }); + vi.mocked(listConflicts).mockResolvedValue({ + rows: [ + { ...conflict("a"), memory_id: "a", conflict_with: ["b"], content_sha256: hashA }, + { ...conflict("b"), memory_id: "b", conflict_with: ["a"], content_sha256: hashB }, + { ...conflict("c"), memory_id: "c", conflict_with: [], content_sha256: "c".repeat(64) }, + ], + next_before_version: null, + }); + const auditEvent = (memoryId: string, peerId: string, memorySha: string, peerSha: string, rowHash: string) => ({ + ts: "2026-09-20T00:00:00Z", + event_type: "memory.conflict_resolver", + actor: "process:loom", + request_id: "", + row_hash: rowHash, + subject: JSON.stringify({ + memory_id: memoryId, + content_sha256: memorySha, + pairs: [ + { + peer_id: peerId, + peer_sha256: peerSha, + memory_sha256: memorySha, + action: "flag", + verdict: "update", + confidence: 0.99, + same_entity: true, + same_attribute: true, + }, + ], + }), + }); + // listAuditLog returns newest first. The newer judgement favors B; the older reverse + // direction must not make the same pair selectable a second time. + vi.mocked(listAuditLog).mockResolvedValue({ + rows: [ + auditEvent("b", "a", hashB, hashA, "d".repeat(64)), + auditEvent("a", "b", hashA, hashB, "c".repeat(64)), + ], + }); + vi.mocked(acceptResolverSuggestions).mockResolvedValue({ + requested: 1, + resolved: 1, + stale: 0, + failed: 0, + results: [{ memory_id: "b", peer_id: "a", status: "resolved" }], + }); + seed("ns-a", "admin"); + const user = userEvent.setup(); + render(); + await screen.findByText("Resolver update suggestions", {}, WAIT); + expect(screen.getAllByRole("checkbox")).toHaveLength(1); + await user.click(screen.getByRole("button", { name: "Select all eligible" })); + await user.click(screen.getByRole("button", { name: "Accept selected" })); + await waitFor( + () => + expect(acceptResolverSuggestions).toHaveBeenCalledWith( + { org: ORG, namespace: "ns-a" }, + [{ memory_id: "b", peer_id: "a", memory_sha256: hashB, peer_sha256: hashA, suggestion_hash: "d".repeat(64) }], + ), + WAIT, + ); + await waitFor(() => expect(screen.getByText("1 of 1 loaded")).toBeInTheDocument(), WAIT); + + // This request began before acceptance and may include the retired pair. It must not + // overwrite the fresh post-decision count. + await act(async () => finishOldCount({ total: 3 })); + expect(screen.getByText("1 of 1 loaded")).toBeInTheDocument(); + }); + + it("does not send a confirmed bulk action after the namespace visit changes", async () => { + const hashA = "a".repeat(64); + const hashB = "b".repeat(64); + vi.mocked(listConflicts).mockImplementation(async (id) => ({ + rows: [ + { ...conflict(`${id.namespace}/a`), memory_id: "a", conflict_with: ["b"], content_sha256: hashA }, + { ...conflict(`${id.namespace}/b`), memory_id: "b", conflict_with: ["a"], content_sha256: hashB }, + ], + next_before_version: null, + })); + vi.mocked(listAuditLog).mockResolvedValue({ + rows: [ + { + ts: "2026-09-20T00:00:00Z", + event_type: "memory.conflict_resolver", + actor: "process:loom", + request_id: "", + row_hash: "c".repeat(64), + subject: JSON.stringify({ + memory_id: "a", + content_sha256: hashA, + pairs: [ + { + peer_id: "b", + peer_sha256: hashB, + memory_sha256: hashA, + action: "flag", + verdict: "update", + confidence: 0.99, + same_entity: true, + same_attribute: true, + }, + ], + }), + }, + ], + }); + let finishConfirm: (yes: boolean) => void = () => {}; + confirmAction.mockImplementationOnce(() => new Promise((resolve) => (finishConfirm = resolve))); + seed("ns-a", "admin"); + const user = userEvent.setup(); + render(); + await screen.findByText("Resolver update suggestions", {}, WAIT); + await user.click(screen.getByRole("button", { name: "Select all eligible" })); + await user.click(screen.getByRole("button", { name: "Accept selected" })); + await waitFor(() => expect(confirmAction).toHaveBeenCalled(), WAIT); + + seed("ns-b", "admin"); + await waitFor( + () => expect(listConflicts).toHaveBeenCalledWith({ org: ORG, namespace: "ns-b" }, expect.anything()), + WAIT, + ); + await act(async () => finishConfirm(true)); + expect(acceptResolverSuggestions).not.toHaveBeenCalled(); + }); + + it("drops a bulk result that lands after switching namespaces", async () => { + const hashA = "a".repeat(64); + const hashB = "b".repeat(64); + vi.mocked(listConflicts).mockImplementation(async (id) => ({ + rows: [ + { ...conflict(`${id.namespace}/a`), memory_id: "a", conflict_with: ["b"], content_sha256: hashA }, + { ...conflict(`${id.namespace}/b`), memory_id: "b", conflict_with: ["a"], content_sha256: hashB }, + ], + next_before_version: null, + })); + vi.mocked(listAuditLog).mockResolvedValue({ + rows: [ + { + ts: "2026-09-20T00:00:00Z", + event_type: "memory.conflict_resolver", + actor: "process:loom", + request_id: "", + row_hash: "c".repeat(64), + subject: JSON.stringify({ + memory_id: "a", + content_sha256: hashA, + pairs: [ + { + peer_id: "b", + peer_sha256: hashB, + memory_sha256: hashA, + action: "flag", + verdict: "update", + confidence: 0.99, + same_entity: true, + same_attribute: true, + }, + ], + }), + }, + ], + }); + let finishRequest: (result: ResolverAcceptResult) => void = () => {}; + vi.mocked(acceptResolverSuggestions).mockImplementationOnce( + () => new Promise((resolve) => (finishRequest = resolve)), + ); + seed("ns-a", "admin"); + const user = userEvent.setup(); + render(); + await screen.findByText("Resolver update suggestions", {}, WAIT); + await user.click(screen.getByRole("button", { name: "Select all eligible" })); + await user.click(screen.getByRole("button", { name: "Accept selected" })); + await waitFor( + () => + expect(acceptResolverSuggestions).toHaveBeenCalledWith( + { org: ORG, namespace: "ns-a" }, + expect.any(Array), + ), + WAIT, + ); + + seed("ns-b", "admin"); + await waitFor( + () => expect(listConflicts).toHaveBeenCalledWith({ org: ORG, namespace: "ns-b" }, expect.anything()), + WAIT, + ); + await act(async () => + finishRequest({ + requested: 1, + resolved: 1, + stale: 0, + failed: 0, + results: [{ memory_id: "a", peer_id: "b", status: "resolved" }], + }), + ); + expect(screen.queryByText("a: resolved")).toBeNull(); + }); afterEach(() => { cleanup(); useStore.setState({ whoami: null, myNamespaces: null }); @@ -293,6 +634,23 @@ describe("ReviewQueue", () => { expect(screen.getByRole("tab", { name: /Conflicts/ })).toHaveAttribute("aria-selected", "true"); }); + it("renders the resolver and provenance backlog as row counts", async () => { + vi.mocked(listConflicts).mockResolvedValue({ rows: [], next_before_version: null }); + vi.mocked(countReview).mockResolvedValue({ + total: 3, + backlog: { + pending_judgement: { plugin_captured: 2, caller_written: 1, unknown: 0 }, + resolver_judged: { plugin_captured: 0, caller_written: 0, unknown: 1 }, + cosine_only: { plugin_captured: 0, caller_written: 0, unknown: 0 }, + }, + }); + seed("ns-a", "admin"); + render(); + expect(await screen.findByText("Conflict backlog · conflicted rows", {}, WAIT)).toBeVisible(); + expect(screen.getByText("2 captured · 1 caller-written · 0 unknown")).toBeVisible(); + expect(screen.getByText("These are row counts. A conflict pair may contain more than one row.")).toBeVisible(); + }); + it("stays on Conflicts while a conflict is open, whatever else waits", async () => { vi.mocked(listConflicts).mockResolvedValue({ rows: [conflict("city")], next_before_version: null }); vi.mocked(countReview).mockResolvedValue({ total: 1, proposals: 2 }); @@ -1195,6 +1553,31 @@ describe("ReviewQueue", () => { expect(within(table).getByRole("button", { name: "k/one" })).toHaveAttribute("aria-current", "true"); }); + it("keeps the loaded queue position and decision reason after resolving a conflict", async () => { + vi.mocked(listConflicts).mockImplementation(async (_id, opts) => + opts?.before_version + ? { rows: [conflict("k/three")], next_before_version: null } + : { rows: [conflict("k/one"), conflict("k/two")], next_before_version: 7 }, + ); + vi.mocked(resolveConflict).mockResolvedValueOnce({ resolved: true, affected_memory_ids: [] }); + seed("ns-a", "admin"); + const user = userEvent.setup(); + render(); + await screen.findByText("value of k/one", {}, WAIT); + const table = screen.getByRole("table", { name: "Conflicts" }); + await user.click(screen.getByRole("button", { name: "Load more" })); + await user.click(within(table).getByRole("button", { name: "k/two" })); + const reason = screen.getByRole("textbox", { name: "Reason for the decision" }); + await user.type(reason, "same entity, current value is correct"); + await user.click(screen.getByRole("button", { name: /Keep A/ })); + await waitFor(() => expect(within(table).queryByRole("button", { name: "k/two" })).toBeNull(), WAIT); + expect(within(table).getByRole("button", { name: "k/one" })).toHaveAttribute("aria-current", "true"); + expect(screen.getByRole("textbox", { name: "Reason for the decision" })).toHaveValue( + "same entity, current value is correct", + ); + expect(listConflicts).toHaveBeenCalledTimes(2); + }); + it("peers a resolve wrote while the queue is read again stay out of that read", async () => { let reread: (v: { rows: ConflictRow[]; next_before_version: null }) => void = () => {}; let aReads = 0; @@ -2404,15 +2787,26 @@ describe("ReviewQueue", () => { expect(screen.getByLabelText("Loading conflicts")).toBeInTheDocument(); }); - it("deciding the only conflict, with none past it, says 'No conflicts' without reading again", async () => { - vi.mocked(countReview).mockResolvedValue({ total: 1 }); + it("refreshes the backlog to explicit zero after deciding the only conflict", async () => { + vi.mocked(countReview) + .mockResolvedValueOnce({ total: 1 }) + .mockResolvedValue({ + total: 0, + backlog: { + pending_judgement: { plugin_captured: 0, caller_written: 0, unknown: 0 }, + resolver_judged: { plugin_captured: 0, caller_written: 0, unknown: 0 }, + cosine_only: { plugin_captured: 0, caller_written: 0, unknown: 0 }, + }, + }); vi.mocked(listConflicts).mockResolvedValue({ rows: [conflict("k/one")], next_before_version: null }); seed("ns-a", "admin"); render(); await screen.findByText("value of k/one", {}, WAIT); await userEvent.click(screen.getByRole("button", { name: /Keep A/ })); expect(await screen.findByText("No conflicts", {}, WAIT)).toBeInTheDocument(); - expect(listConflicts).toHaveBeenCalledTimes(1); + expect(await screen.findByText("Conflict backlog · conflicted rows", {}, WAIT)).toBeInTheDocument(); + await waitFor(() => expect(listConflicts).toHaveBeenCalledTimes(2), WAIT); + expect(screen.getByText(/0 captured/)).toBeInTheDocument(); }); it("holds the queue's picks and the reason while a decision is out", async () => { diff --git a/frontend/src/views/admin/ReviewQueue.tsx b/frontend/src/views/admin/ReviewQueue.tsx index e9a16f59672..35e05d70701 100644 --- a/frontend/src/views/admin/ReviewQueue.tsx +++ b/frontend/src/views/admin/ReviewQueue.tsx @@ -24,13 +24,18 @@ import { type AutoResolvedRow, type ConflictRow, type ReviewCounts, + type ConflictBacklog, type AllowlistRow, type ResolveDecision, type LearningEntry, type LearningStatus, proposeRevision, type RevisionSuggestion, + listAuditLog, + parseAuditSubject, + type AuditEntry, } from "../../api"; +import { acceptResolverSuggestions, type ResolverAcceptItem, type ResolverAcceptResult } from "../../api/conflicts"; import { CuratorPanel } from "./Curator"; import { DefinitionsPanel } from "./Definitions"; import { DuplicatesPanel } from "./Duplicates"; @@ -458,6 +463,11 @@ export function ReviewQueue() { // ─── Conflicts panel ─────────────────────────────────────────────────── const CONFLICT_PAGE = 50; +const EMPTY_CONFLICT_BACKLOG: ConflictBacklog = { + pending_judgement: { plugin_captured: 0, caller_written: 0, unknown: 0 }, + resolver_judged: { plugin_captured: 0, caller_written: 0, unknown: 0 }, + cosine_only: { plugin_captured: 0, caller_written: 0, unknown: 0 }, +}; function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void }) { const identity = useIdentity(); @@ -468,6 +478,10 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void // holds in all. const [next, setNext] = useState(null); const [total, setTotal] = useState(null); + const [backlog, setBacklog] = useState(null); + const [resolverEvents, setResolverEvents] = useState([]); + const [bulkSelected, setBulkSelected] = useState>(new Set()); + const [bulkResults, setBulkResults] = useState(null); const [loadingMore, setLoadingMore] = useState(false); const [error, setError] = useState(null); const [index, setIndex] = useState(0); @@ -491,8 +505,10 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void setQueueFor(queueKey); setRows(null); setTotal(null); + setBacklog(null); setNext(null); setError(null); + setBulkResults(null); // A decision or a Load more still out was the old queue's: its controls are free here. setBusy(false); setLoadingMore(false); @@ -519,6 +535,7 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void // count, each count read out collects the rows decisions take meanwhile instead and // subtracts them from its answer. const countsOut = useRef(new Set<{ taken: number; stale: boolean }>()); + const countRefresh = useRef(0); // The namespace on screen as of the latest render, for a resolve's count. const queueNow = useRef(queueKey); queueNow.current = queueKey; @@ -530,6 +547,8 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void (signal, live) => { focusAdded.current = null; setError(null); + setResolverEvents([]); + setBulkSelected(new Set()); const goneHere = new Set(); readsOut.current.add(goneHere); listConflicts({ org: identity.org, namespace: identity.namespace }, { limit: CONFLICT_PAGE, signal }) @@ -545,12 +564,28 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void if (live()) setError(e); }) .finally(() => readsOut.current.delete(goneHere)); + listAuditLog( + { org: identity.org, namespace: identity.namespace }, + { + limit: 500, + event_type: "memory.conflict_resolver", + fields: ["ts", "event_type", "actor", "subject", "request_id", "row_hash"], + signal, + }, + ) + .then((r) => { + if (live()) setResolverEvents(r.rows || []); + }) + .catch(() => { + if (live()) setResolverEvents([]); + }); const countHere = { taken: 0, stale: false }; countsOut.current.add(countHere); countReview({ org: identity.org, namespace: identity.namespace }, { fresh: true, signal }) .then((r) => { if (!live()) return; if (!countHere.stale) setTotal(Math.max((r.total ?? 0) - countHere.taken, 0)); + if (!countHere.stale && countHere.taken === 0) setBacklog(r.backlog ?? null); onCount(countHere.stale || countHere.taken > 0 ? null : r); }) .catch(() => { @@ -569,6 +604,41 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void if (rows.length === 0 && next !== null) setReload((n) => n + 1); }, [rows, next]); + const bulkOutcome = bulkResults && ( +
+ {bulkResults.map((r) => `${r.memory_id.slice(0, 8)}: ${r.status}${r.reason ? ` (${r.reason})` : ""}`).join(" · ")} +
+ ); + + const removeResolvedRows = (gone: Set) => { + for (const out of readsOut.current) for (const id of gone) out.add(id); + const shown = rowsNow.current ?? []; + for (const c of shown) if (gone.has(c.memory_id)) decidedAt.current.set(c.memory_id, c.version); + const dropped = shown.filter((c) => gone.has(c.memory_id)).length; + const before = (i: number) => shown.slice(0, i).filter((c) => gone.has(c.memory_id)).length; + setRows((prev) => prev && prev.filter((c) => !gone.has(c.memory_id))); + setIndex((i) => Math.max(Math.min(i - before(i), shown.length - dropped - 1), 0)); + return dropped; + }; + + const refreshCounts = (myVisit: number, myQueue: string) => { + const request = ++countRefresh.current; + const countHere = { taken: 0, stale: false }; + countsOut.current.add(countHere); + countReview({ org: identity.org, namespace: identity.namespace }, { fresh: true }) + .then((r) => { + if (visit.current !== myVisit || queueNow.current !== myQueue || request !== countRefresh.current) return; + if (!countHere.stale) setTotal(Math.max((r.total ?? 0) - countHere.taken, 0)); + if (!countHere.stale && countHere.taken === 0) setBacklog(r.backlog ?? null); + onCount(countHere.stale || countHere.taken > 0 ? null : r); + }) + .catch(() => { + if (visit.current === myVisit && queueNow.current === myQueue && request === countRefresh.current) + setBacklog(null); + }) + .finally(() => countsOut.current.delete(countHere)); + }; + useEffect(() => { const at = focusAdded.current; if (at === null || loadingMore) return; @@ -608,19 +678,35 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void }; if (error) { - return setReload((n) => n + 1)} />; + return ( + <> + + {bulkOutcome} + setReload((n) => n + 1)} /> + + ); } // Emptied with more past it: the reload is reading them, so the queue is loading, not empty. if (rows === null || (rows.length === 0 && next !== null)) - return {}} loading />; + return ( + <> + + {bulkOutcome} + {}} loading /> + + ); if (rows.length === 0) { return ( - + <> + + {bulkOutcome} + + ); } @@ -628,6 +714,115 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void const at = Math.min(index, rows.length - 1); const current = rows[at]; + const byId = new Map(rows.map((r) => [r.memory_id, r])); + const suggestions: (ResolverAcceptItem & { + key: string; + target: ConflictRow; + peer: ConflictRow; + confidence: number; + })[] = []; + // Audit rows arrive newest first. Resolver decisions are stored once per judged row, + // so use the unordered pair to keep only the latest direction of each decision. + const latestPairSeen = new Set(); + for (const event of resolverEvents) { + if (!event.row_hash) continue; + const subject = parseAuditSubject(event.subject); + const memoryId = String(subject.memory_id || ""); + const judgedSha = String(subject.content_sha256 || ""); + const pairs = Array.isArray(subject.pairs) ? subject.pairs : []; + for (const raw of pairs) { + if (!raw || typeof raw !== "object") continue; + const p = raw as Record; + const peerId = String(p.peer_id || ""); + const pairKey = [memoryId, peerId].sort().join("/"); + if (latestPairSeen.has(pairKey)) continue; + latestPairSeen.add(pairKey); + const target = byId.get(memoryId); + const peer = byId.get(peerId); + const confidence = Number(p.confidence); + if ( + !target || + !peer || + target.pinned || + peer.pinned || + target.sensitivity === "high" || + peer.sensitivity === "high" || + !target.conflict_with.includes(peerId) || + !peer.conflict_with.includes(memoryId) || + p.action !== "flag" || + p.verdict !== "update" || + p.same_entity !== true || + p.same_attribute !== true || + judgedSha !== target.content_sha256 || + p.memory_sha256 !== target.content_sha256 || + p.peer_sha256 !== peer.content_sha256 || + !Number.isFinite(confidence) + ) + continue; + const key = `${memoryId}/${peerId}/${event.row_hash}`; + suggestions.push({ + key, + target, + peer, + confidence, + memory_id: memoryId, + peer_id: peerId, + memory_sha256: target.content_sha256, + peer_sha256: peer.content_sha256, + suggestion_hash: event.row_hash, + }); + } + } + const uniqueSuggestions = [...new Map(suggestions.map((s) => [s.key, s])).values()]; + const selectableSuggestions = uniqueSuggestions.slice(0, 100); + + const acceptSelected = async () => { + if (resolveReason || busy) return; + const myVisit = visit.current; + const myQueue = queueKey; + const myOrg = identity.org; + const myNamespace = identity.namespace; + const items = selectableSuggestions.filter((s) => bulkSelected.has(s.key)); + if (!items.length) return; + const yes = await confirmAction({ + title: `Accept ${items.length} resolver suggestion${items.length === 1 ? "" : "s"}?`, + message: + "Each suggestion is rechecked against the latest resolver audit and both current memory revisions. Changed or protected conflicts will be left for review.", + confirmLabel: "Accept suggestions", + }); + if (!yes || visit.current !== myVisit || queueNow.current !== myQueue) return; + setBusy(true); + try { + const result = await acceptResolverSuggestions( + { org: myOrg, namespace: myNamespace }, + items.map(({ key: _key, target: _target, peer: _peer, confidence: _confidence, ...item }) => item), + ); + if (visit.current !== myVisit || queueNow.current !== myQueue) return; + setBulkResults(result.results); + setBulkSelected(new Set()); + toast( + `${result.resolved} accepted · ${result.stale} stale · ${result.failed} failed`, + result.resolved ? "ok" : "error", + ); + if (result.resolved) { + setBacklog(null); + const gone = new Set(result.results.flatMap((r) => (r.status === "resolved" ? [r.memory_id, r.peer_id] : []))); + const dropped = removeResolvedRows(gone); + if (dropped > 0) decided.current = true; + setTotal((total) => (total === null ? total : Math.max(total - dropped, 0))); + // A count already in flight may have observed either side of this write. Discard + // every older answer and let the fresh read below become authoritative. + for (const out of countsOut.current) out.stale = true; + refreshCounts(myVisit, myQueue); + } + } catch (e) { + if (visit.current !== myVisit || queueNow.current !== myQueue) return; + toastError("Couldn't accept resolver suggestions", e); + } finally { + if (visit.current === myVisit && queueNow.current === myQueue) setBusy(false); + } + }; + const peerId = current.conflict_with?.[0]; // The server's count is cached for a minute; it is never less than the rows on hand. const held = total === null ? null : Math.max(total, rows.length); @@ -651,26 +846,19 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void if (visit.current === myVisit) setReload((n) => n + 1); return; } + const sameVisit = visit.current === myVisit && queueNow.current === myQueue; + if (sameVisit) { + setBacklog(null); + } toast("Resolved", "ok"); // The decided row and the peers the resolve wrote (affected_memory_ids: tombstoned or // made active) leave every list, on any visit; ids are org-wide, so no other queue // loses a row. Each is remembered at the version on screen, so a later re-flag shows. const gone = new Set([current.memory_id, ...res.affected_memory_ids]); - for (const out of readsOut.current) for (const id of gone) out.add(id); decidedAt.current.set(current.memory_id, current.version); - const shown = rowsNow.current ?? []; - for (const c of shown) if (gone.has(c.memory_id)) decidedAt.current.set(c.memory_id, c.version); - const dropped = shown.filter((c) => gone.has(c.memory_id)).length; - // Rows dropped before a position move it up by as many: the conflict open now stays - // open, and after this visit's own decision the next one takes its place. - const before = (i: number) => shown.slice(0, i).filter((c) => gone.has(c.memory_id)).length; + // An emptied page with more past it reads the queue again (the decided flag). decided.current = true; - setRows((prev) => prev && prev.filter((c) => !gone.has(c.memory_id))); - // Kept on a row: a decision on the last one opens the one before it, so a Load more - // after it does not move the open conflict. - const left = shown.length - dropped; - setIndex((i) => Math.max(Math.min(i - before(i), left - 1), 0)); - const sameVisit = visit.current === myVisit; + const dropped = removeResolvedRows(gone); if (typeof res.total === "number" && queueNow.current === myQueue) { // The resolve's own count, made after its writes, for the namespace on screen. const total = res.total; @@ -688,7 +876,7 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void // Another visit: the reason is not this decision's. An emptied page with more past // it reads the queue again (the decided flag). if (!sameVisit) return; - setReason(""); + refreshCounts(myVisit, myQueue); } catch (e) { toastError("Couldn't resolve the conflict", e); } finally { @@ -701,6 +889,75 @@ function ConflictsPanel({ onCount }: { onCount: (r: ReviewCounts | null) => void
Conflict {at + 1} of {(held ?? rows.length).toLocaleString()} · resolve in order
+ + {selectableSuggestions.length > 0 && ( + + +

+ Only current, flagged update judgements with matching memory revisions are selectable. +

+
+ + + {bulkSelected.size} selected + void acceptSelected()} + > + Accept selected + +
+
    + {selectableSuggestions.map((s) => ( +
  • + +
  • + ))} +
+ {bulkOutcome} +
+ )}
void ); } +function BacklogSummary({ backlog }: { backlog: ConflictBacklog | null }) { + if (!backlog) return null; + const states = [ + ["Awaiting resolver judgement", backlog.pending_judgement], + ["Resolver judged, still conflicted", backlog.resolver_judged], + ["Cosine-only", backlog.cosine_only], + ] as const; + return ( + +

Conflict backlog · conflicted rows

+
+ {states.map(([label, counts]) => ( +
+

{label}

+

+ {counts.plugin_captured.toLocaleString()} captured · {counts.caller_written.toLocaleString()}{" "} + caller-written · {counts.unknown.toLocaleString()} unknown +

+
+ ))} +
+

+ These are row counts. A conflict pair may contain more than one row. +

+
+ ); +} + /** A suggestion in the words of the buttons above it; every suggestion is about A, the * conflict on screen. */ const SUGGESTION_LABEL: Record = { diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 3713cd5752c..79d22816258 100644 --- a/integrations/claude-code-plugin/.claude-plugin/plugin.json +++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "loom", "displayName": "ClickHouse Loom", - "version": "1.2.190", + "version": "1.2.192", "description": "Shared long-term memory and code intelligence for Claude Code, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 3f01858ca1a..72bf8f03435 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -147,6 +147,7 @@ receives on stdout. | Event | Script | Reads | Output | Side effects | Off | | ------------------------------------------------------------- | --------------------- | ---------------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | | SessionStart | loom-session-start | cwd, session_id, source | primer text | context.pack, code.repos/index_status/map, task.counts, namespace.get, session.brief_list, collection.list; GET /v1/health: its round trip is cached as the RTT bound, its `version` feeds the server version warning; in a checkout that configures pytest, one line in the file `CLAUDE_ENV_FILE` names and an empty result file | `LOOM_INJECT_CONTEXT=false` | +| SessionStart | loom-review-notice | cwd, session_id, source | systemMessage when the review count changes | conflicts.list (count only); stores the last notice per server and namespace | memory mode | | UserPromptSubmit | loom-record | the payload | JSON additionalContext | keeps the run's begin in the run state; starts one detached process, which runs the event's `detached` rows; runs the event's `in loom-record` rows itself and prints their context as one answer | each script's own | | UserPromptSubmit, in loom-record | loom-prompt-pack | prompt, cwd, session_id | its context | code.search, or code.symbol, code.callers or code.impact for a named definition; no request with the pointers off; under `auto` none of those unless the server holds the checkout's own repository, and one code.repos where no lookup has answered; for a test line one `git ls-files`, and the test is noted in the test gate's session state; under a bug report's pointers, in a session that has the test report, one memory.get of the test cost row, unless the session keeps it | `LOOM_PROMPT_PACK=off` | | UserPromptSubmit, in loom-record | loom-prompt-recall | prompt, cwd, session_id | its context | context.pack | `LOOM_PROMPT_RECALL=off` | @@ -273,6 +274,7 @@ record: the run and its usage counters. | loom-session-brief | memory | | loom-session-memory | memory | | loom-session-start | memory (pack, tag, task, brief, collections and recording lines); code (scope, map) | +| loom-review-notice | memory | | loom-test-gate | code | | loom-test-report | ledger: reads the session's own test report in every mode and sends nothing; memory: notes what a run of one test file cost | | loom-usage | ledger | diff --git a/integrations/claude-code-plugin/hooks/hooks.json b/integrations/claude-code-plugin/hooks/hooks.json index 8097b5ec893..193c21db7c1 100644 --- a/integrations/claude-code-plugin/hooks/hooks.json +++ b/integrations/claude-code-plugin/hooks/hooks.json @@ -7,6 +7,11 @@ "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/hooks/loom-session-start.mjs", "SessionStart"] + }, + { + "type": "command", + "command": "node", + "args": ["${CLAUDE_PLUGIN_ROOT}/hooks/loom-review-notice.mjs", "SessionStart"] } ] } diff --git a/integrations/claude-code-plugin/hooks/loom-review-notice.mjs b/integrations/claude-code-plugin/hooks/loom-review-notice.mjs new file mode 100644 index 00000000000..68f5cd8cab5 --- /dev/null +++ b/integrations/claude-code-plugin/hooks/loom-review-notice.mjs @@ -0,0 +1,47 @@ +// A synchronous SessionStart hook for a human-visible notice. The ordinary +// SessionStart hook prints agent context; this hook uses Claude Code's +// user-visible systemMessage field instead. + +import { + postBounded, + planeEnabled, + readStdinJson, + resolveScope, + resolveServerUrl, + resolveToken, + runHookMain, +} from "../lib/loom-client.mjs"; +import { reviewNotice } from "../lib/review-notice.mjs"; +import { readJsonFile, tmpStatePath, writeJsonFile } from "../lib/tmp-state.mjs"; + +async function main() { + if (!planeEnabled("memory")) return; + const token = resolveToken(); + if (!token) return; + + const payload = await readStdinJson(); + const scope = resolveScope(payload.cwd); + if (!scope.org || !scope.namespace) return; + + const serverUrl = resolveServerUrl(); + const key = `${serverUrl}|${scope.org}|${scope.namespace}`; + const path = tmpStatePath("review-notice", key); + const previous = readJsonFile(path, null); + const counts = await postBounded( + "conflicts.list", + { org: scope.org, namespace: scope.namespace, count_only: true }, + { token, serverUrl }, + ); + const notice = reviewNotice({ + count: counts?.total, + serverUrl, + namespace: scope.namespace, + previous, + }); + if (!notice) return; + + writeJsonFile(path, notice.state); + process.stdout.write(`${JSON.stringify({ systemMessage: notice.message })}\n`); +} + +runHookMain(main); diff --git a/integrations/claude-code-plugin/lib/loom-client.mjs b/integrations/claude-code-plugin/lib/loom-client.mjs index 85e670c0200..e319b3975ea 100644 --- a/integrations/claude-code-plugin/lib/loom-client.mjs +++ b/integrations/claude-code-plugin/lib/loom-client.mjs @@ -1481,9 +1481,11 @@ export function readStdinText() { return new Promise((resolve) => { let raw = ""; let settled = false; + let timer; const done = () => { if (settled) return; settled = true; + clearTimeout(timer); resolve(raw); }; try { @@ -1501,7 +1503,7 @@ export function readStdinText() { } catch { done(); } - setTimeout(done, 1000).unref(); + timer = setTimeout(done, 1000); }); } diff --git a/integrations/claude-code-plugin/lib/review-notice.mjs b/integrations/claude-code-plugin/lib/review-notice.mjs new file mode 100644 index 00000000000..faf140863e6 --- /dev/null +++ b/integrations/claude-code-plugin/lib/review-notice.mjs @@ -0,0 +1,31 @@ +// The human-facing SessionStart notice is separate from the primer injected into +// the agent's context. Keep the workload terminology row-based: conflicts.list +// counts conflicted memory rows, not independent pairs. + +export const REVIEW_NOTICE_INTERVAL_MS = 24 * 60 * 60 * 1000; + +export function reviewNotice({ count, serverUrl, namespace, previous, now = Date.now() }) { + const rows = Number(count); + if (!Number.isSafeInteger(rows) || rows <= 0 || !namespace) return null; + + const priorRows = Number(previous?.count); + const priorAt = Number(previous?.notified_at); + if (priorRows === rows && Number.isFinite(priorAt) && priorAt <= now && now - priorAt < REVIEW_NOTICE_INTERVAL_MS) { + return null; + } + + let reviewUrl; + try { + reviewUrl = new URL("/admin/review_queue", serverUrl); + reviewUrl.searchParams.set("namespace", namespace); + } catch { + return null; + } + + return { + message: + `Loom memory review needed: ${rows.toLocaleString()} conflicted rows need attention. ` + + `Review the namespace queue: ${reviewUrl.toString()}`, + state: { count: rows, notified_at: now }, + }; +} diff --git a/integrations/claude-code-plugin/tests/hooks-json.test.mjs b/integrations/claude-code-plugin/tests/hooks-json.test.mjs index 673a13f7497..c22e78c6d9c 100644 --- a/integrations/claude-code-plugin/tests/hooks-json.test.mjs +++ b/integrations/claude-code-plugin/tests/hooks-json.test.mjs @@ -39,15 +39,17 @@ const TOOLS = [ "mcp__other__tool", ]; -test("the host starts at most one process per event, and per tool call before and after it", () => { +test("the host starts at most one process per event, except the two SessionStart notices", () => { // Hooks of one event run side by side, each a node process the host waits // for: a second one costs a session a process start whatever it does. for (const event of Object.keys(manifest.hooks)) { const perTool = /ToolUse/.test(event); for (const tool of perTool ? TOOLS : [undefined]) { - assert.ok(wired(event, tool).length <= 1, `${event} ${tool || ""}: ${wired(event, tool)}`); + const limit = event === "SessionStart" ? 2 : 1; + assert.ok(wired(event, tool).length <= limit, `${event} ${tool || ""}: ${wired(event, tool)}`); } } + assert.deepEqual(wired("SessionStart"), ["loom-session-start", "loom-review-notice"]); for (const event of ["UserPromptSubmit", "PostToolUseFailure", "PreCompact", "Stop", "SessionEnd"]) { assert.deepEqual(wired(event), ["loom-record"], event); } diff --git a/integrations/claude-code-plugin/tests/plugin-modes.test.mjs b/integrations/claude-code-plugin/tests/plugin-modes.test.mjs index 74fdd3dd29a..2f96614c1b7 100644 --- a/integrations/claude-code-plugin/tests/plugin-modes.test.mjs +++ b/integrations/claude-code-plugin/tests/plugin-modes.test.mjs @@ -80,6 +80,7 @@ const MEMORY = [ "collection.list", "context.pack", "conversation.append", + "conflicts.list", "memory.for_file", "memory.set_from_messages", "namespace.audit", diff --git a/integrations/claude-code-plugin/tests/review-notice.test.mjs b/integrations/claude-code-plugin/tests/review-notice.test.mjs new file mode 100644 index 00000000000..aff0eb58c3f --- /dev/null +++ b/integrations/claude-code-plugin/tests/review-notice.test.mjs @@ -0,0 +1,110 @@ +import "./temp-home.mjs"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { REVIEW_NOTICE_INTERVAL_MS, reviewNotice } from "../lib/review-notice.mjs"; + +const HOOK = fileURLToPath(new URL("../hooks/loom-review-notice.mjs", import.meta.url)); +const ROOT = fileURLToPath(new URL("../../../", import.meta.url)); + +test("reviewNotice is silent for empty, invalid, or unscoped results", () => { + const base = { serverUrl: "https://loom.example", namespace: "team" }; + assert.equal(reviewNotice({ ...base, count: 0 }), null); + assert.equal(reviewNotice({ ...base, count: "not a count" }), null); + assert.equal(reviewNotice({ serverUrl: base.serverUrl, count: 2 }), null); +}); + +test("reviewNotice links to the namespace queue and calls the number conflicted rows", () => { + const result = reviewNotice({ + count: 8, + serverUrl: "https://loom.example/base/", + namespace: "team space", + now: 10_000, + }); + assert.equal( + result.message, + "Loom memory review needed: 8 conflicted rows need attention. Review the namespace queue: https://loom.example/admin/review_queue?namespace=team+space", + ); + assert.deepEqual(result.state, { count: 8, notified_at: 10_000 }); +}); + +test("reviewNotice throttles an unchanged backlog and reports changed or stale counts", () => { + const base = { + count: 4, + serverUrl: "https://loom.example", + namespace: "team", + previous: { count: 4, notified_at: 50_000 }, + }; + assert.equal(reviewNotice({ ...base, now: 50_001 }), null); + assert.notEqual(reviewNotice({ ...base, count: 5, now: 50_001 }), null); + assert.notEqual(reviewNotice({ ...base, now: 50_000 + REVIEW_NOTICE_INTERVAL_MS }), null); +}); + +test("SessionStart sends a scoped count and emits a throttled user-visible systemMessage", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "loom-review-notice-")); + let count = 3; + let requests = 0; + const server = http.createServer((req, res) => { + requests += 1; + let body = ""; + req.on("data", (part) => (body += part)); + req.on("end", () => { + assert.equal(req.url, "/v1/conflicts.list"); + assert.equal(req.headers.authorization, `Bearer ${token}`); + assert.deepEqual(JSON.parse(body), { + org: "acme", + namespace: "team", + count_only: true, + }); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ total: count })); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const baseUrl = `http://127.0.0.1:${server.address().port}`; + const token = `x.${Buffer.from(JSON.stringify({ org: "acme", namespaces: ["team"] })).toString("base64url")}.x`; + const env = { + ...process.env, + HOME: home, + USERPROFILE: home, + TMPDIR: home, + LOOM_API_KEY: token, + LOOM_BASE_URL: baseUrl, + LOOM_ORG: "acme", + LOOM_NAMESPACE: "team", + LOOM_HOOK_TIMEOUT_MS: "1500", + }; + const invoke = () => + new Promise((resolve, reject) => { + const child = spawn(process.execPath, [HOOK, "SessionStart"], { env, stdio: ["pipe", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", (part) => (stdout += part)); + child.stderr.setEncoding("utf8").on("data", (part) => (stderr += part)); + child.on("error", reject); + child.on("close", (code) => (code === 0 ? resolve({ stdout, stderr }) : reject(new Error(stderr)))); + child.stdin.end(JSON.stringify({ cwd: ROOT })); + }); + try { + const first = await invoke(); + const output = JSON.parse(first.stdout); + assert.match(output.systemMessage, /3 conflicted rows/); + assert.match(output.systemMessage, /\/admin\/review_queue\?namespace=team/); + assert.equal(output.hookSpecificOutput, undefined); + + const repeated = await invoke(); + assert.equal(repeated.stdout, ""); + count = 4; + const changed = await invoke(); + assert.match(JSON.parse(changed.stdout).systemMessage, /4 conflicted rows/); + assert.equal(requests, 3); + } finally { + await new Promise((resolve) => server.close(resolve)); + fs.rmSync(home, { recursive: true, force: true }); + } +}); diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index d12cda0ad62..09fa6bb5a0b 100644 --- a/integrations/codex-plugin/.codex-plugin/plugin.json +++ b/integrations/codex-plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "loom", - "version": "1.2.190", + "version": "1.2.192", "description": "Shared long-term memory and code intelligence for Codex, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/codex-plugin/hooks/hooks.json b/integrations/codex-plugin/hooks/hooks.json index 623504ba5d1..9c68e5ad5c5 100644 --- a/integrations/codex-plugin/hooks/hooks.json +++ b/integrations/codex-plugin/hooks/hooks.json @@ -1,5 +1,5 @@ { - "description": "Loom ambient-capture hooks for Codex. The scripts under hooks/ and lib/ are byte-identical to the Claude Code plugin's (checked by `python scripts/codegen/agent_plugin_sync.py --check`); only this wiring differs. Each command names the client as the script's third argument (`codex`), which sets the default agent label, the run-id prefix (cx-), the `source:codex` tag and the consumer label. What differs from the Claude Code wiring, and why: - Codex has no Read or Grep tool: it reads files and searches through its shell tool, whose input may be an argv array. loom-code-shunt watches the shell tool only (its `cat` / `rg` / `grep` branch); the whole-file-Read branch has nothing to match. After a shell call loom-file-context looks up the files the command read. - Codex edits files with apply_patch: loom-file-context and loom-blast-radius read the target path out of the patch text. - Codex may hand the hooks no transcript (`transcript_path` null) or one in its own shape. loom-run journals every prompt (UserPromptSubmit), and loom-conversation journals every reply from `last_assistant_message` (Stop); the working-memory note, the run's final text, the conversation plane and the session memory read that journal. loom-usage needs the per-turn token counters only a Claude Code transcript carries, so it is not wired here. - Codex's SessionEnd hook budget is one second: only the fire-and-forget scripts (capture, run close, session memory hand-off) run there; the conversation hook does its work at Stop. - loom-record, which runs an event's recording scripts in one process (a detached one at a prompt, after a tool call, at Stop and at SessionEnd) and the scripts whose answer the host waits for in the hook, is not wired here: it has been measured under Claude Code only, so Codex still starts each script as a hook of its own, and loom-namespace-health asks its audit at the first Stop. - loom-test-report reads the result file pytest writes through the option the SessionStart hook adds to the file Claude Code names for the session's shell (CLAUDE_ENV_FILE). Codex names no such file, so no option is added and no result file exists: the script is not wired here. Each command runs its script through bin/loom-node, which finds Node 18+ when the PATH Codex hands the hook has none; Codex runs a hook through cmd.exe on Windows, where `commandWindows` calls `node` from the system PATH. Identity (org/namespace) is derived from the token — drop a writer JWT in ~/.loom/token or ~/.loom/config.json, or set LOOM_API_KEY. The server is ~/.loom/config.json's url, else the plugin's plugin-defaults.json; LOOM_BASE_URL overrides both. Every knob the Claude Code README lists (LOOM_INJECT_CONTEXT, LOOM_CODE_SHUNT, LOOM_TEST_GATE, …) works here; the test gate holds a stop only with LOOM_TEST_GATE=stop or block.", + "description": "Loom ambient-capture hooks for Codex. The scripts under hooks/ and lib/ are byte-identical to the Claude Code plugin's (checked by `python scripts/codegen/agent_plugin_sync.py --check`); only this wiring differs. Each command names the client as the script's third argument (`codex`), which sets the default agent label, the run-id prefix (cx-), the `source:codex` tag and the consumer label. What differs from the Claude Code wiring, and why: - Codex has no Read or Grep tool: it reads files and searches through its shell tool, whose input may be an argv array. loom-code-shunt watches the shell tool only (its `cat` / `rg` / `grep` branch); the whole-file-Read branch has nothing to match. After a shell call loom-file-context looks up the files the command read. - Codex edits files with apply_patch: loom-file-context and loom-blast-radius read the target path out of the patch text. - Codex may hand the hooks no transcript (`transcript_path` null) or one in its own shape. loom-run journals every prompt (UserPromptSubmit), and loom-conversation journals every reply from `last_assistant_message` (Stop); the working-memory note, the run's final text, the conversation plane and the session memory read that journal. loom-usage needs the per-turn token counters only a Claude Code transcript carries, so it is not wired here. loom-review-notice uses the Claude Code-specific user-visible systemMessage output, so it is not wired here. - Codex's SessionEnd hook budget is one second: only the fire-and-forget scripts (capture, run close, session memory hand-off) run there; the conversation hook does its work at Stop. - loom-record, which runs an event's recording scripts in one process (a detached one at a prompt, after a tool call, at Stop and at SessionEnd) and the scripts whose answer the host waits for in the hook, is not wired here: it has been measured under Claude Code only, so Codex still starts each script as a hook of its own, and loom-namespace-health asks its audit at the first Stop. - loom-test-report reads the result file pytest writes through the option the SessionStart hook adds to the file Claude Code names for the session's shell (CLAUDE_ENV_FILE). Codex names no such file, so no option is added and no result file exists: the script is not wired here. Each command runs its script through bin/loom-node, which finds Node 18+ when the PATH Codex hands the hook has none; Codex runs a hook through cmd.exe on Windows, where `commandWindows` calls `node` from the system PATH. Identity (org/namespace) is derived from the token — drop a writer JWT in ~/.loom/token or ~/.loom/config.json, or set LOOM_API_KEY. The server is ~/.loom/config.json's url, else the plugin's plugin-defaults.json; LOOM_BASE_URL overrides both. Every knob the Claude Code README lists (LOOM_INJECT_CONTEXT, LOOM_CODE_SHUNT, LOOM_TEST_GATE, …) works here; the test gate holds a stop only with LOOM_TEST_GATE=stop or block.", "hooks": { "SessionStart": [ { diff --git a/integrations/codex-plugin/hooks/loom-review-notice.mjs b/integrations/codex-plugin/hooks/loom-review-notice.mjs new file mode 100644 index 00000000000..68f5cd8cab5 --- /dev/null +++ b/integrations/codex-plugin/hooks/loom-review-notice.mjs @@ -0,0 +1,47 @@ +// A synchronous SessionStart hook for a human-visible notice. The ordinary +// SessionStart hook prints agent context; this hook uses Claude Code's +// user-visible systemMessage field instead. + +import { + postBounded, + planeEnabled, + readStdinJson, + resolveScope, + resolveServerUrl, + resolveToken, + runHookMain, +} from "../lib/loom-client.mjs"; +import { reviewNotice } from "../lib/review-notice.mjs"; +import { readJsonFile, tmpStatePath, writeJsonFile } from "../lib/tmp-state.mjs"; + +async function main() { + if (!planeEnabled("memory")) return; + const token = resolveToken(); + if (!token) return; + + const payload = await readStdinJson(); + const scope = resolveScope(payload.cwd); + if (!scope.org || !scope.namespace) return; + + const serverUrl = resolveServerUrl(); + const key = `${serverUrl}|${scope.org}|${scope.namespace}`; + const path = tmpStatePath("review-notice", key); + const previous = readJsonFile(path, null); + const counts = await postBounded( + "conflicts.list", + { org: scope.org, namespace: scope.namespace, count_only: true }, + { token, serverUrl }, + ); + const notice = reviewNotice({ + count: counts?.total, + serverUrl, + namespace: scope.namespace, + previous, + }); + if (!notice) return; + + writeJsonFile(path, notice.state); + process.stdout.write(`${JSON.stringify({ systemMessage: notice.message })}\n`); +} + +runHookMain(main); diff --git a/integrations/codex-plugin/lib/loom-client.mjs b/integrations/codex-plugin/lib/loom-client.mjs index 85e670c0200..e319b3975ea 100644 --- a/integrations/codex-plugin/lib/loom-client.mjs +++ b/integrations/codex-plugin/lib/loom-client.mjs @@ -1481,9 +1481,11 @@ export function readStdinText() { return new Promise((resolve) => { let raw = ""; let settled = false; + let timer; const done = () => { if (settled) return; settled = true; + clearTimeout(timer); resolve(raw); }; try { @@ -1501,7 +1503,7 @@ export function readStdinText() { } catch { done(); } - setTimeout(done, 1000).unref(); + timer = setTimeout(done, 1000); }); } diff --git a/integrations/codex-plugin/lib/review-notice.mjs b/integrations/codex-plugin/lib/review-notice.mjs new file mode 100644 index 00000000000..faf140863e6 --- /dev/null +++ b/integrations/codex-plugin/lib/review-notice.mjs @@ -0,0 +1,31 @@ +// The human-facing SessionStart notice is separate from the primer injected into +// the agent's context. Keep the workload terminology row-based: conflicts.list +// counts conflicted memory rows, not independent pairs. + +export const REVIEW_NOTICE_INTERVAL_MS = 24 * 60 * 60 * 1000; + +export function reviewNotice({ count, serverUrl, namespace, previous, now = Date.now() }) { + const rows = Number(count); + if (!Number.isSafeInteger(rows) || rows <= 0 || !namespace) return null; + + const priorRows = Number(previous?.count); + const priorAt = Number(previous?.notified_at); + if (priorRows === rows && Number.isFinite(priorAt) && priorAt <= now && now - priorAt < REVIEW_NOTICE_INTERVAL_MS) { + return null; + } + + let reviewUrl; + try { + reviewUrl = new URL("/admin/review_queue", serverUrl); + reviewUrl.searchParams.set("namespace", namespace); + } catch { + return null; + } + + return { + message: + `Loom memory review needed: ${rows.toLocaleString()} conflicted rows need attention. ` + + `Review the namespace queue: ${reviewUrl.toString()}`, + state: { count: rows, notified_at: now }, + }; +} diff --git a/schemas/migrations/125_captured_conflict_provenance.sql b/schemas/migrations/125_captured_conflict_provenance.sql new file mode 100644 index 00000000000..d87a6433875 --- /dev/null +++ b/schemas/migrations/125_captured_conflict_provenance.sql @@ -0,0 +1,26 @@ +-- A signed integration credential is the only source of captured-memory provenance. +ALTER TABLE loom.memory + ADD COLUMN IF NOT EXISTS capture_origin LowCardinality(String) DEFAULT ''; +ALTER TABLE loom.memory_versions + ADD COLUMN IF NOT EXISTS capture_origin LowCardinality(String) DEFAULT ''; +ALTER TABLE loom.namespaces + ADD COLUMN IF NOT EXISTS captured_conflict_policy LowCardinality(String) DEFAULT 'manual_review'; +ALTER TABLE loom.namespaces + ADD COLUMN IF NOT EXISTS captured_conflict_confidence Float64 DEFAULT 0.98; +ALTER TABLE loom.namespace_snapshots + ADD COLUMN IF NOT EXISTS captured_origin_map String DEFAULT '{}'; + +-- Modify the insert trigger in place while adding provenance to its query. +ALTER TABLE loom.memory_versions_mv MODIFY QUERY +SELECT + org, namespace, agent, user_id, session_id, memory_key, memory_type, value, + value_json, confidence, source_trace, version, tombstoned_at, created_at, + expires_at, pinned, run_id, entities, memory_id, redacted_at, redaction_reason, + status, requires_review, conflict_with, duplicate_of, evidence_count, recall_count, last_recalled_at, + cross_promoted_from_memory_id, cross_promoted_from_namespace, tags, files, concepts, + superseded_by, rejection_reason, temporal_anchor, temporal_confidence, updated_at, + valid_at, valid_to, invalid_at, char_limit, reinforcement_count, last_reinforced_at, + mentioned_at, source_resource_id, content_sha256, verified_by, verified_at, + verified_sha256, grounding, evidence, sensitivity, actor, source_class, lock_mode, + lock_reason, lock_until, locked_by, locked_at, on_expire, expire_reason, capture_origin +FROM loom.memory; diff --git a/schemas/schema.sql b/schemas/schema.sql index f91ef39d870..8107a0ffeaf 100644 --- a/schemas/schema.sql +++ b/schemas/schema.sql @@ -2612,6 +2612,7 @@ CREATE TABLE IF NOT EXISTS loom.memory `sensitivity` LowCardinality(String) DEFAULT '', `value_preview` String MATERIALIZED substring(value, 1, 2048), `value_len` UInt32 MATERIALIZED length(value), + `capture_origin` LowCardinality(String) DEFAULT '', INDEX type_skip memory_type TYPE set(8) GRANULARITY 4, INDEX pinned_skip pinned TYPE set(2) GRANULARITY 4, INDEX entities_skip entities TYPE bloom_filter(0.01) GRANULARITY 4, @@ -3374,6 +3375,7 @@ CREATE TABLE IF NOT EXISTS loom.memory_versions `sensitivity` LowCardinality(String) DEFAULT '', `value_preview` String MATERIALIZED substring(value, 1, 2048), `value_len` UInt32 MATERIALIZED length(value), + `capture_origin` LowCardinality(String) DEFAULT '', INDEX memory_id_skip memory_id TYPE bloom_filter(0.01) GRANULARITY 4, INDEX memory_key_bloom_idx memory_key TYPE bloom_filter(0.01) GRANULARITY 4 ) @@ -3560,7 +3562,8 @@ CREATE TABLE IF NOT EXISTS loom.namespace_snapshots `memory_count` UInt32 DEFAULT 0, `type_count` UInt32 DEFAULT 0, `grant_count` UInt32 DEFAULT 0, - `audit_tail_count` UInt32 DEFAULT 0 + `audit_tail_count` UInt32 DEFAULT 0, + `captured_origin_map` String DEFAULT '{}' ) ENGINE = MergeTree PARTITION BY org @@ -3664,7 +3667,9 @@ CREATE TABLE IF NOT EXISTS loom.namespaces `released_aliases` Array(String) DEFAULT [], `daily_user_cost_cap_usd` Float64 DEFAULT 0, `budget_alert_inbox` String DEFAULT '', - `curator_mode` LowCardinality(String) DEFAULT '' + `curator_mode` LowCardinality(String) DEFAULT '', + `captured_conflict_policy` LowCardinality(String) DEFAULT 'manual_review', + `captured_conflict_confidence` Float64 DEFAULT 0.98 ) ENGINE = ReplacingMergeTree(updated_at) PARTITION BY org @@ -6283,7 +6288,8 @@ CREATE MATERIALIZED VIEW IF NOT EXISTS loom.memory_versions_mv TO loom.memory_ve `locked_by` String, `locked_at` Nullable(DateTime), `on_expire` LowCardinality(String), - `expire_reason` String + `expire_reason` String, + `capture_origin` LowCardinality(String) ) AS SELECT org, @@ -6347,7 +6353,8 @@ AS SELECT locked_by, locked_at, on_expire, - expire_reason + expire_reason, + capture_origin FROM loom.memory; -- loom.session_brief_revisions_mv diff --git a/scripts/ops/simulate_captured_conflicts.py b/scripts/ops/simulate_captured_conflicts.py new file mode 100644 index 00000000000..f58eecebbba --- /dev/null +++ b/scripts/ops/simulate_captured_conflicts.py @@ -0,0 +1,274 @@ +"""Deterministic seven-day workload model for captured conflict settlement. + +This uses Loom's production resolver decision helpers with fixed verdicts. It does not +call an LLM or ClickHouse; queue service limits and resolver latency are explicit model +inputs so the report does not imply a production capacity guarantee. +""" + +from __future__ import annotations + +import argparse +import json +import random +from dataclasses import asdict, dataclass + +from server.memory.domain import conflict_resolution as cr + +SEED = 2077 +DAYS = 7 +BATCH = 40 # settings.memory_conflict_resolver_batch default +CONCURRENCY = 8 # settings.memory_conflict_resolver_concurrency default +BURST_SECONDS = 300 # settings.memory_conflict_resolver_burst_seconds default +MAX_ATTEMPTS = 3 # settings.memory_conflict_resolver_max_attempts default + + +@dataclass(frozen=True) +class Case: + kind: str + source: str + verdict: str + confidence: float + same_entity: bool = True + same_attribute: bool = True + origin: str = "" + + +@dataclass +class Metrics: + total_captured_rows: int = 0 + conflicted_rows: int = 0 + resolver_pending: int = 0 + resolver_judged: int = 0 + cosine_only: int = 0 + plugin_captured_rows: int = 0 + caller_written_rows: int = 0 + unknown_provenance_rows: int = 0 + automatically_settled: int = 0 + policy_automatically_settled: int = 0 + human_reviewable_pairs: int = 0 + audit_records_created: int = 0 + successful_undos: int = 0 + failed_resolver_jobs: int = 0 + backlog_growth: int = 0 + processing_latency_seconds: float = 0.0 + false_automatic_settlements: int = 0 + genuine_contradictions_settled: int = 0 + retries: int = 0 + caller_auto_settled: int = 0 + + +@dataclass(frozen=True) +class Scenario: + name: str + candidates_per_day: int + daily_resolver_call_cap: int + review_capacity_per_sitting: int + + +def _cases(seed: int, candidates: int, day: int) -> list[Case]: + rng = random.Random(seed + day * 100_003 + candidates) + kinds = [ + ("plugin_update", 24), + ("plugin_contradiction", 10), + ("plugin_repeat", 16), + ("caller_update", 12), + ("unknown_update", 12), + ("low_confidence_update", 8), + ("extracted_fact_update", 7), + ("session_brief_update", 6), + ("cosine_only", 5), + ] + weights = [weight for _, weight in kinds] + out: list[Case] = [] + for _ in range(candidates): + kind = rng.choices([name for name, _ in kinds], weights=weights, k=1)[0] + if kind == "cosine_only": + out.append(Case(kind, "unknown", "", 0)) + elif kind == "plugin_contradiction": + out.append(Case(kind, "plugin", cr.CONTRADICTION, 0.99, origin="codex")) + elif kind == "plugin_repeat": + out.append(Case(kind, "plugin", cr.RESTATEMENT, 0.96, origin="claude-code")) + elif kind == "caller_update": + out.append(Case(kind, "caller", cr.UPDATE, 0.99)) + elif kind == "unknown_update": + out.append(Case(kind, "unknown", cr.UPDATE, 0.99)) + elif kind == "low_confidence_update": + out.append(Case(kind, "plugin", cr.UPDATE, 0.97, origin="codex")) + elif kind in {"extracted_fact_update", "session_brief_update"}: + origin = "claude-code" if rng.random() < 0.5 else "codex" + out.append(Case(kind, "plugin", cr.UPDATE, 0.99, origin=origin)) + else: + out.append(Case(kind, "plugin", cr.UPDATE, 0.99, origin="codex")) + return out + + +def _scenario( + scenario: Scenario, *, seed: int, captured_policy: bool +) -> dict[str, int | float | str]: + m = Metrics(total_captured_rows=scenario.candidates_per_day * DAYS) + owed_queue: list[tuple[Case, int]] = [] + review_backlog = 0 + for day in range(DAYS): + daily = _cases(seed, scenario.candidates_per_day, day) + m.plugin_captured_rows += sum(c.source == "plugin" for c in daily) + m.caller_written_rows += sum(c.source == "caller" for c in daily) + m.unknown_provenance_rows += sum(c.source == "unknown" for c in daily) + m.cosine_only += sum(c.verdict == "" for c in daily) + owed = [c for c in daily if c.verdict] + m.conflicted_rows += len(owed) * 2 + owed_queue.extend((c, 0) for c in owed) + batch_seconds = (BATCH / CONCURRENCY) * 0.8 + burst_call_cap = BATCH * int(BURST_SECONDS // batch_seconds) + # A rolling daily call cap represents cost-share throttling; it is not a dollar + # estimate. The worker also repeatedly batches within its burst window. + call_budget = min(scenario.daily_resolver_call_cap, burst_call_cap) + judged_today: list[Case] = [] + calls = 0 + rng = random.Random(seed + day * 71 + scenario.candidates_per_day) + while owed_queue and calls < call_budget: + c, attempts = owed_queue.pop(0) + calls += 1 + # Controlled transient response: one retry succeeds; it consumes a call slot. + failed_first = rng.random() < 0.01 + if failed_first: + retries = min(MAX_ATTEMPTS - 1, 1) + if retries and calls < call_budget: + calls += retries + m.retries += retries + else: + owed_queue.append((c, attempts + 1)) + continue + judged_today.append(c) + m.resolver_judged += len(judged_today) + m.processing_latency_seconds += (calls / CONCURRENCY) * 0.8 + for c in judged_today: + if c.kind == "plugin_contradiction": + action = cr.action_for( + cr.PeerVerdict( + "peer", c.verdict, c.confidence, c.same_entity, c.same_attribute, "" + ), + policy="auto_reinforce", + retire_at=0.98, + clear_at=0.90, + flag_at=0.95, + ) + if action == cr.FLAG: + review_backlog += 1 + m.audit_records_created += 1 + continue + if c.kind == "plugin_repeat": + m.audit_records_created += 1 + continue + if c.kind == "cosine_only": + continue + verdict = cr.PeerVerdict( + "peer", c.verdict, c.confidence, c.same_entity, c.same_attribute, "" + ) + action = cr.action_for( + verdict, + policy="auto_reinforce", + retire_at=0.98, + clear_at=0.90, + flag_at=0.95, + ) + trusted = c.source == "plugin" and c.origin in {"claude-code", "codex"} + # Production re-checks both rows under key locks. This model holds identity and + # revision constant, and uses the same domain predicate for the opt-in branch. + allowed = captured_policy and cr.captured_update_eligible( + policy="resolver_update", + verdict=c.verdict, + confidence=c.confidence, + threshold=0.98, + same_entity=c.same_entity, + same_attribute=c.same_attribute, + winner_origin=c.origin, + retired_origin=c.origin if trusted else "", + winner_agent="agent-a", + retired_agent="agent-a", + winner_user_id="user-a", + retired_user_id="user-a", + cross_session=False, + ) + if action == cr.RETIRE and trusted and not allowed: + action = cr.FLAG + if allowed: + action = cr.RETIRE + m.policy_automatically_settled += 1 + if action == cr.RETIRE: + m.automatically_settled += 1 + m.audit_records_created += 2 # resolver verdict plus memory.auto_supersede + if c.source == "caller": + m.caller_auto_settled += 1 + if c.verdict == cr.CONTRADICTION: + m.genuine_contradictions_settled += 1 + elif action == cr.FLAG: + review_backlog += 1 + m.audit_records_created += 1 + m.resolver_pending = len(owed_queue) + m.human_reviewable_pairs = review_backlog + m.backlog_growth = max(0, review_backlog - scenario.review_capacity_per_sitting) + return { + "scenario": scenario.name, + **asdict(m), + "review_capacity_per_sitting": scenario.review_capacity_per_sitting, + } + + +def run(seed: int = SEED, review_capacity_per_sitting: int = 2000) -> dict[str, object]: + scenarios = [ + Scenario("light", 100, 120, review_capacity_per_sitting), + Scenario("steady", 250, 280, review_capacity_per_sitting), + Scenario("surge", 500, 520, review_capacity_per_sitting), + ] + default = [_scenario(s, seed=seed, captured_policy=False) for s in scenarios] + opted_in = [_scenario(s, seed=seed, captured_policy=True) for s in scenarios] + for before, after in zip(default, opted_in, strict=True): + assert after["human_reviewable_pairs"] < before["human_reviewable_pairs"] + assert after["genuine_contradictions_settled"] == 0 + assert after["caller_auto_settled"] == before["caller_auto_settled"] + assert after["unknown_provenance_rows"] > 0 + assert after["policy_automatically_settled"] <= after["audit_records_created"] + assert after["backlog_growth"] == 0 + return { + "seed": seed, + "days": DAYS, + "assumptions": { + "fixed_resolver_verdicts": True, + "external_llm_calls": 0, + "batch_size": BATCH, + "concurrency": CONCURRENCY, + "burst_seconds": BURST_SECONDS, + "max_attempts": MAX_ATTEMPTS, + "daily_call_cap_is_cost_share_proxy": True, + "review_capacity_is_user_configured": review_capacity_per_sitting, + "undo_events_in_generated_workload": 0, + }, + "default_policy": default, + "opt_in_capture_policy": opted_in, + "checks": { + "opt_in_reduces_review_backlog": True, + "genuine_contradictions_remain_reviewable": True, + "plugin_policy_does_not_add_caller_auto_settlement": True, + "unknown_provenance_not_trusted_by_plugin_policy": True, + "policy_retirements_have_audit_records": True, + "review_backlog_fits_configured_capacity": True, + }, + "limitations": [ + "Synthetic case mixes and fixed verdicts do not represent production distributions.", + "The worker batch, concurrency, burst and attempt defaults are modeled; a call cap " + "stands in for cost-share reads.", + "The model excludes database races, provider latency distributions and restore writes.", + ], + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--seed", type=int, default=SEED) + parser.add_argument("--review-capacity-per-sitting", type=int, default=2000) + args = parser.parse_args() + print(json.dumps(run(args.seed, args.review_capacity_per_sitting), indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index 7ea04d71099..b3f1ca4d145 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -635,6 +635,12 @@ type CollectionMoveInput = wire.CollectionMoveInput // CollectionMoveOutput is the response from collection.move. type CollectionMoveOutput = wire.CollectionMoveOutput +// ConflictBacklog is a model used by Loom operations. +type ConflictBacklog = wire.ConflictBacklog + +// ConflictBulkResult is a model used by Loom operations. +type ConflictBulkResult = wire.ConflictBulkResult + // ConflictCandidateMemory is a model used by Loom operations. type ConflictCandidateMemory = wire.ConflictCandidateMemory @@ -644,6 +650,9 @@ type ConflictRevisionSuggestion = wire.ConflictRevisionSuggestion // ConflictRow is a model used by Loom operations. type ConflictRow = wire.ConflictRow +// ConflictSourceCounts is a model used by Loom operations. +type ConflictSourceCounts = wire.ConflictSourceCounts + // ConflictsAllowlistListInput is the request to conflicts.allowlist_list. type ConflictsAllowlistListInput = wire.ConflictsAllowlistListInput @@ -656,6 +665,12 @@ type ConflictsAllowlistRemoveInput = wire.ConflictsAllowlistRemoveInput // ConflictsAllowlistRemoveOutput is the response from conflicts.allowlist_remove. type ConflictsAllowlistRemoveOutput = wire.ConflictsAllowlistRemoveOutput +// ConflictsBulkAcceptInput is the request to conflicts.bulk_accept. +type ConflictsBulkAcceptInput = wire.ConflictsBulkAcceptInput + +// ConflictsBulkAcceptOutput is the response from conflicts.bulk_accept. +type ConflictsBulkAcceptOutput = wire.ConflictsBulkAcceptOutput + // ConflictsListInput is the request to conflicts.list. type ConflictsListInput = wire.ConflictsListInput @@ -674,6 +689,9 @@ type ConflictsResolveInput = wire.ConflictsResolveInput // ConflictsResolveOutput is the response from conflicts.resolve. type ConflictsResolveOutput = wire.ConflictsResolveOutput +// ConflictsResolverAcceptItem is a model used by Loom operations. +type ConflictsResolverAcceptItem = wire.ConflictsResolverAcceptItem + // ConnectedAgent is a model used by Loom operations. type ConnectedAgent = wire.ConnectedAgent @@ -5041,6 +5059,17 @@ func (s ConflictsService) AllowlistRemove(ctx context.Context, in ConflictsAllow return callOperation[ConflictsAllowlistRemoveOutput](s.client, ctx, "conflicts.allowlist_remove", in) } +// BulkAccept calls conflicts.bulk_accept. +func (s ConflictsService) BulkAccept(ctx context.Context, in ConflictsBulkAcceptInput) (*ConflictsBulkAcceptOutput, error) { + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[ConflictsBulkAcceptOutput](s.client, ctx, "conflicts.bulk_accept", in) +} + // List calls conflicts.list. // Use WithInput to supply additional request fields. func (s ConflictsService) List(ctx context.Context, opts ...Option[ConflictsListInput]) (*ConflictsListOutput, error) { diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 261e7ee9b42..8171787881c 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -2904,6 +2904,21 @@ type CollectionMoveOutput struct { Moved bool `json:"moved"` } +// ConflictBacklog is a model used by Loom operations. +type ConflictBacklog struct { + PendingJudgement *ConflictSourceCounts `json:"pending_judgement,omitempty"` + ResolverJudged *ConflictSourceCounts `json:"resolver_judged,omitempty"` + CosineOnly *ConflictSourceCounts `json:"cosine_only,omitempty"` +} + +// ConflictBulkResult is a model used by Loom operations. +type ConflictBulkResult struct { + MemoryID string `json:"memory_id"` + PeerID string `json:"peer_id"` + Status string `json:"status"` + Reason *string `json:"reason,omitempty"` +} + // ConflictCandidateMemory is a model used by Loom operations. type ConflictCandidateMemory struct { LocalID int64 `json:"local_id"` @@ -2935,6 +2950,14 @@ type ConflictRow struct { ConflictWith *[]string `json:"conflict_with,omitempty"` ContentSHA256 *string `json:"content_sha256,omitempty"` Sensitivity *string `json:"sensitivity,omitempty"` + CaptureOrigin *string `json:"capture_origin,omitempty"` +} + +// ConflictSourceCounts is a model used by Loom operations. +type ConflictSourceCounts struct { + PluginCaptured *int64 `json:"plugin_captured,omitempty"` + CallerWritten *int64 `json:"caller_written,omitempty"` + Unknown *int64 `json:"unknown,omitempty"` } // ConflictsAllowlistListInput is the request to conflicts.allowlist_list. @@ -2972,6 +2995,26 @@ type ConflictsAllowlistRemoveOutput struct { Removed bool `json:"removed"` } +// ConflictsBulkAcceptInput is the request to conflicts.bulk_accept. +type ConflictsBulkAcceptInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + Items []ConflictsResolverAcceptItem `json:"items"` +} + +// ConflictsBulkAcceptOutput is the response from conflicts.bulk_accept. +type ConflictsBulkAcceptOutput struct { + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` + Results []ConflictBulkResult `json:"results"` + Requested int64 `json:"requested"` + Resolved int64 `json:"resolved"` + Stale int64 `json:"stale"` + Failed int64 `json:"failed"` +} + // ConflictsListInput is the request to conflicts.list. type ConflictsListInput struct { Org string `json:"org"` @@ -2986,15 +3029,16 @@ type ConflictsListInput struct { // ConflictsListOutput is the response from conflicts.list. type ConflictsListOutput struct { - IgnoredArgs *[]string `json:"ignored_args,omitempty"` - DidYouMean *map[string]string `json:"did_you_mean,omitempty"` - Mirrored *bool `json:"mirrored,omitempty"` - Degraded *[]string `json:"degraded,omitempty"` - Rows []ConflictRow `json:"rows"` - NextBeforeVersion Optional[uint64] `json:"next_before_version,omitempty"` - Total Optional[int64] `json:"total,omitempty"` - Proposals Optional[int64] `json:"proposals,omitempty"` - Keys Optional[[]string] `json:"keys,omitempty"` + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` + Rows []ConflictRow `json:"rows"` + NextBeforeVersion Optional[uint64] `json:"next_before_version,omitempty"` + Total Optional[int64] `json:"total,omitempty"` + Proposals Optional[int64] `json:"proposals,omitempty"` + Backlog Optional[ConflictBacklog] `json:"backlog,omitempty"` + Keys Optional[[]string] `json:"keys,omitempty"` } // ConflictsProposeRevisionInput is the request to conflicts.propose_revision. @@ -3041,6 +3085,15 @@ type ConflictsResolveOutput struct { Total Optional[int64] `json:"total,omitempty"` } +// ConflictsResolverAcceptItem is a model used by Loom operations. +type ConflictsResolverAcceptItem struct { + MemoryID string `json:"memory_id"` + PeerID string `json:"peer_id"` + MemorySHA256 string `json:"memory_sha256"` + PeerSHA256 string `json:"peer_sha256"` + SuggestionHash string `json:"suggestion_hash"` +} + // ConnectedAgent is a model used by Loom operations. type ConnectedAgent struct { Agent string `json:"agent"` @@ -7313,21 +7366,24 @@ type MemoryAssignCategoryOutput struct { // MemoryAutoRetirement is a model used by Loom operations. type MemoryAutoRetirement struct { - Ts string `json:"ts"` - Reason string `json:"reason"` - MemoryID string `json:"memory_id"` - MemoryKey string `json:"memory_key"` - Agent *string `json:"agent,omitempty"` - UserID *string `json:"user_id,omitempty"` - SessionID *string `json:"session_id,omitempty"` - SupersededBy *string `json:"superseded_by,omitempty"` - SupersededByKey *string `json:"superseded_by_key,omitempty"` - Label *string `json:"label,omitempty"` - Unconfirmed *bool `json:"unconfirmed,omitempty"` - JudgeVerdict *string `json:"judge_verdict,omitempty"` - JudgeConfidence Optional[float64] `json:"judge_confidence,omitempty"` - JudgeModel *string `json:"judge_model,omitempty"` - JudgePromptVersion *string `json:"judge_prompt_version,omitempty"` + Ts string `json:"ts"` + Reason string `json:"reason"` + MemoryID string `json:"memory_id"` + MemoryKey string `json:"memory_key"` + Agent *string `json:"agent,omitempty"` + UserID *string `json:"user_id,omitempty"` + SessionID *string `json:"session_id,omitempty"` + SupersededBy *string `json:"superseded_by,omitempty"` + SupersededByKey *string `json:"superseded_by_key,omitempty"` + Label *string `json:"label,omitempty"` + Unconfirmed *bool `json:"unconfirmed,omitempty"` + JudgeVerdict *string `json:"judge_verdict,omitempty"` + JudgeConfidence Optional[float64] `json:"judge_confidence,omitempty"` + JudgeModel *string `json:"judge_model,omitempty"` + JudgePromptVersion *string `json:"judge_prompt_version,omitempty"` + AppliedPolicy *string `json:"applied_policy,omitempty"` + WinnerCaptureOrigin *string `json:"winner_capture_origin,omitempty"` + RetiredCaptureOrigin *string `json:"retired_capture_origin,omitempty"` } // MemoryAutoRetirementsInput is the request to memory.auto_retirements. @@ -10091,27 +10147,28 @@ type MentorBriefInput struct { // MentorBriefOutput is the response from mentor.brief. type MentorBriefOutput struct { - IgnoredArgs *[]string `json:"ignored_args,omitempty"` - DidYouMean *map[string]string `json:"did_you_mean,omitempty"` - Mirrored *bool `json:"mirrored,omitempty"` - Degraded *[]string `json:"degraded,omitempty"` - Org string `json:"org"` - Namespace string `json:"namespace"` - Agent string `json:"agent"` - WindowSeconds int64 `json:"window_seconds"` - ComputedAt string `json:"computed_at"` - Sessions int64 `json:"sessions"` - Usage *map[string]int64 `json:"usage,omitempty"` - Planes *[]MentorPlane `json:"planes,omitempty"` - Hints *[]MentorHint `json:"hints,omitempty"` - Adoption *[]MentorAdoption `json:"adoption,omitempty"` - UsageEvidence *[]UsageRung `json:"usage_evidence,omitempty"` - LedgerFrom Optional[string] `json:"ledger_from,omitempty"` - LedgerRetentionDays Optional[int64] `json:"ledger_retention_days,omitempty"` - Agents *[]string `json:"agents,omitempty"` - AgentDefaulted *bool `json:"agent_defaulted,omitempty"` - Skipped *[]string `json:"skipped,omitempty"` - Healthy *bool `json:"healthy,omitempty"` + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` + Org string `json:"org"` + Namespace string `json:"namespace"` + Agent string `json:"agent"` + WindowSeconds int64 `json:"window_seconds"` + ComputedAt string `json:"computed_at"` + Sessions int64 `json:"sessions"` + Usage *map[string]int64 `json:"usage,omitempty"` + Planes *[]MentorPlane `json:"planes,omitempty"` + ConflictBacklog *map[string]map[string]int64 `json:"conflict_backlog,omitempty"` + Hints *[]MentorHint `json:"hints,omitempty"` + Adoption *[]MentorAdoption `json:"adoption,omitempty"` + UsageEvidence *[]UsageRung `json:"usage_evidence,omitempty"` + LedgerFrom Optional[string] `json:"ledger_from,omitempty"` + LedgerRetentionDays Optional[int64] `json:"ledger_retention_days,omitempty"` + Agents *[]string `json:"agents,omitempty"` + AgentDefaulted *bool `json:"agent_defaulted,omitempty"` + Skipped *[]string `json:"skipped,omitempty"` + Healthy *bool `json:"healthy,omitempty"` } // MentorGuideInput is the request to mentor.guide. @@ -10420,6 +10477,8 @@ type NamespaceGetOutput struct { RerankEndpoint Optional[string] `json:"rerank_endpoint,omitempty"` ClassifyEndpoint Optional[string] `json:"classify_endpoint,omitempty"` DefaultConflictPolicy Optional[string] `json:"default_conflict_policy,omitempty"` + CapturedConflictPolicy *string `json:"captured_conflict_policy,omitempty"` + CapturedConflictConfidence *float64 `json:"captured_conflict_confidence,omitempty"` ProposalPolicy Optional[ProposalPolicy] `json:"proposal_policy,omitempty"` CodeChangePolicy Optional[string] `json:"code_change_policy,omitempty"` CuratorMode Optional[string] `json:"curator_mode,omitempty"` @@ -10694,6 +10753,8 @@ type NamespaceRegisterInput struct { ClassifyPromptTemplate Optional[string] `json:"classify_prompt_template,omitempty"` TagRegistry *[]NamespaceTypeConfig `json:"tag_registry,omitempty"` DefaultConflictPolicy Optional[string] `json:"default_conflict_policy,omitempty"` + CapturedConflictPolicy Optional[string] `json:"captured_conflict_policy,omitempty"` + CapturedConflictConfidence Optional[float64] `json:"captured_conflict_confidence,omitempty"` ProposalPolicy Optional[ProposalPolicy] `json:"proposal_policy,omitempty"` CodeChangePolicy Optional[string] `json:"code_change_policy,omitempty"` CuratorMode Optional[string] `json:"curator_mode,omitempty"` @@ -13268,6 +13329,7 @@ type SnapshotMemoryRow struct { LockedAt Optional[string] `json:"locked_at,omitempty"` OnExpire *string `json:"on_expire,omitempty"` ExpireReason *string `json:"expire_reason,omitempty"` + CaptureOrigin *string `json:"capture_origin,omitempty"` Files *[]string `json:"files,omitempty"` Concepts *[]string `json:"concepts,omitempty"` } diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py index 166d8b5b952..e827d121caa 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -673,6 +673,15 @@ async def allowlist_remove( await self._agent.call("conflicts.allowlist_remove", body, **options), ) + async def bulk_accept( + self, body: _ops.ConflictsBulkAcceptBody | None = None, /, **options: Any + ) -> _ops.ConflictsBulkAcceptOutput: + """`conflicts.bulk_accept`.""" + return cast( + "_ops.ConflictsBulkAcceptOutput", + await self._agent.call("conflicts.bulk_accept", body, **options), + ) + async def list( self, body: _ops.ConflictsListBody | None = None, /, **options: Any ) -> _ops.ConflictsListOutput: diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index b9a5d9bf982..26ec4b09754 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -109,6 +109,7 @@ class OpSpec: "collection.move", "conflicts.allowlist_list", "conflicts.allowlist_remove", + "conflicts.bulk_accept", "conflicts.list", "conflicts.propose_revision", "conflicts.resolve", @@ -538,6 +539,7 @@ class OpSpec: "collection.move", "conflicts.allowlist_list", "conflicts.allowlist_remove", + "conflicts.bulk_accept", "conflicts.list", "conflicts.propose_revision", "conflicts.resolve", @@ -1737,6 +1739,18 @@ class OpSpec: True, False, ), + "conflicts.bulk_accept": OpSpec( + "conflicts.bulk_accept", + "ConflictsBulkAcceptInput", + "ConflictsBulkAcceptBody", + "ConflictsBulkAcceptOutput", + True, + "admin", + "experimental", + 5000, + True, + False, + ), "conflicts.list": OpSpec( "conflicts.list", "ConflictsListInput", @@ -9239,6 +9253,41 @@ class ConflictsAllowlistRemoveOutput(TypedDict, total=False): removed: Required[bool] +class ConflictsBulkAcceptInput(TypedDict, total=False): + org: Required[str] + namespace: Required[str] + items: Required[list["ConflictsResolverAcceptItem"]] + + +class ConflictsResolverAcceptItem(TypedDict, total=False): + memory_id: Required[str] + peer_id: Required[str] + memory_sha256: Required[str] + peer_sha256: Required[str] + suggestion_hash: Required[str] + + +class ConflictsBulkAcceptBody(TypedDict, total=False): + org: NotRequired[str] + namespace: NotRequired[str] + items: Required[list["ConflictsResolverAcceptItem"]] + + +class ConflictsBulkAcceptOutput(TypedDict, total=False): + results: Required[list["ConflictBulkResult"]] + requested: Required[int] + resolved: Required[int] + stale: Required[int] + failed: Required[int] + + +class ConflictBulkResult(TypedDict, total=False): + memory_id: Required[str] + peer_id: Required[str] + status: Required[Literal["resolved", "stale", "failed"]] + reason: NotRequired[str] + + class ConflictsListInput(TypedDict, total=False): org: Required[str] namespace: Required[str] @@ -9266,6 +9315,7 @@ class ConflictsListOutput(TypedDict, total=False): next_before_version: NotRequired[Optional[int]] total: NotRequired[Optional[int]] proposals: NotRequired[Optional[int]] + backlog: NotRequired[Optional["ConflictBacklog"]] keys: NotRequired[Optional[list[str]]] @@ -9280,6 +9330,23 @@ class ConflictRow(TypedDict, total=False): conflict_with: Required[list[str]] content_sha256: NotRequired[str] sensitivity: NotRequired[str] + capture_origin: NotRequired[str] + + +class ConflictBacklog(TypedDict, total=False): + "Conflicted rows split by resolver state and conservative provenance." + + pending_judgement: NotRequired["ConflictSourceCounts"] + resolver_judged: NotRequired["ConflictSourceCounts"] + cosine_only: NotRequired["ConflictSourceCounts"] + + +class ConflictSourceCounts(TypedDict, total=False): + "Conflicted row counts for one resolver state, not pair counts." + + plugin_captured: NotRequired[int] + caller_written: NotRequired[int] + unknown: NotRequired[int] class ConflictsProposeRevisionInput(TypedDict, total=False): @@ -15184,6 +15251,9 @@ class MemoryAutoRetirement(TypedDict, total=False): judge_confidence: NotRequired[Optional[float]] judge_model: NotRequired[str] judge_prompt_version: NotRequired[str] + applied_policy: NotRequired[str] + winner_capture_origin: NotRequired[str] + retired_capture_origin: NotRequired[str] class MemoryBacklinksInput(TypedDict, total=False): @@ -19244,6 +19314,7 @@ class MentorBriefOutput(TypedDict, total=False): sessions: Required[int] usage: NotRequired[dict[str, int]] planes: NotRequired[list["MentorPlane"]] + conflict_backlog: NotRequired[dict[str, dict[str, int]]] hints: NotRequired[list["MentorHint"]] adoption: NotRequired[list["MentorAdoption"]] usage_evidence: NotRequired[list["UsageRung"]] @@ -19502,6 +19573,8 @@ class NamespaceGetOutput(TypedDict, total=False): rerank_endpoint: NotRequired[Optional[str]] classify_endpoint: NotRequired[Optional[str]] default_conflict_policy: NotRequired[Optional[str]] + captured_conflict_policy: NotRequired[str] + captured_conflict_confidence: NotRequired[float] proposal_policy: NotRequired[Optional["ProposalPolicy"]] code_change_policy: NotRequired[Optional[Literal["retire_removed", "flag", "revise"]]] curator_mode: NotRequired[Optional[str]] @@ -19862,6 +19935,8 @@ class NamespaceRegisterInput(TypedDict, total=False): default_conflict_policy: NotRequired[ Optional[Literal["auto_reinforce", "manual_review", "newest_wins", "append_only"]] ] + captured_conflict_policy: NotRequired[Optional[Literal["manual_review", "resolver_update"]]] + captured_conflict_confidence: NotRequired[Optional[float]] proposal_policy: NotRequired[Optional["ProposalPolicy"]] code_change_policy: NotRequired[Optional[Literal["retire_removed", "flag", "revise"]]] curator_mode: NotRequired[Optional[Literal["off", "findings", "assist"]]] @@ -19938,6 +20013,8 @@ class NamespaceRegisterBody(TypedDict, total=False): default_conflict_policy: NotRequired[ Optional[Literal["auto_reinforce", "manual_review", "newest_wins", "append_only"]] ] + captured_conflict_policy: NotRequired[Optional[Literal["manual_review", "resolver_update"]]] + captured_conflict_confidence: NotRequired[Optional[float]] proposal_policy: NotRequired[Optional["ProposalPolicy"]] code_change_policy: NotRequired[Optional[Literal["retire_removed", "flag", "revise"]]] curator_mode: NotRequired[Optional[Literal["off", "findings", "assist"]]] @@ -20097,6 +20174,7 @@ class SnapshotMemoryRow(TypedDict, total=False): locked_at: NotRequired[Optional[str]] on_expire: NotRequired[str] expire_reason: NotRequired[str] + capture_origin: NotRequired[str] files: NotRequired[list[str]] concepts: NotRequired[list[str]] diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 3bcad5a9511..c4e1b94585b 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -8,7 +8,7 @@ module Loom # Every served operation: its spec in OPS, and one method per op on the class # of its group (`client.memory.set(...)` is `memory.set`). module Generated - OP_COUNT = 426 + OP_COUNT = 427 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -82,6 +82,7 @@ module Generated "collection.move" => OpSpec.new("collection.move", "collection", "move", true, false, "admin", "experimental", %w[org namespace parent].freeze, %w[org namespace].freeze), "conflicts.allowlist_list" => OpSpec.new("conflicts.allowlist_list", "conflicts", "allowlist_list", true, true, "viewer", "experimental", %w[org namespace limit].freeze, %w[org namespace].freeze), "conflicts.allowlist_remove" => OpSpec.new("conflicts.allowlist_remove", "conflicts", "allowlist_remove", true, false, "admin", "experimental", %w[org namespace memory_key_a memory_key_b removed_by reason].freeze, %w[org namespace memory_key_a memory_key_b].freeze), + "conflicts.bulk_accept" => OpSpec.new("conflicts.bulk_accept", "conflicts", "bulk_accept", true, false, "admin", "experimental", %w[org namespace items].freeze, %w[org namespace items].freeze), "conflicts.list" => OpSpec.new("conflicts.list", "conflicts", "list", true, true, "viewer", "stable", %w[org namespace limit before_version count_only fresh keys_only fields].freeze, %w[org namespace].freeze), "conflicts.propose_revision" => OpSpec.new("conflicts.propose_revision", "conflicts", "propose_revision", true, true, "viewer", "experimental", %w[org namespace memory_id peer_id].freeze, %w[org namespace memory_id].freeze), "conflicts.resolve" => OpSpec.new("conflicts.resolve", "conflicts", "resolve", true, false, "admin", "stable", %w[org namespace memory_id decision peer_id reason resolved_by].freeze, %w[org namespace memory_id decision].freeze), @@ -321,7 +322,7 @@ module Generated "namespace.list_mine" => OpSpec.new("namespace.list_mine", "namespace", "list_mine", true, true, "viewer", "stable", %w[org subject].freeze, %w[org].freeze), "namespace.list_ontology" => OpSpec.new("namespace.list_ontology", "namespace", "list_ontology", true, true, "viewer", "experimental", %w[org namespace kind status].freeze, %w[org namespace].freeze), "namespace.mark_seen" => OpSpec.new("namespace.mark_seen", "namespace", "mark_seen", true, false, "viewer", "experimental", %w[org namespace subject].freeze, %w[org namespace].freeze), - "namespace.register" => OpSpec.new("namespace.register", "namespace", "register", true, false, "viewer", "stable", %w[org namespace owner_email description kind tags traffic_class active conversation_logging_enabled capture_generation_io coverage_sweep consolidation_enabled daily_cost_cap_usd daily_user_cost_cap_usd budget_alert_inbox conflict_threshold retention_days warm_days visibility requires_approval join_policy retrieval_defaults rerank_endpoint rerank_prompt_template classify_endpoint classify_prompt_template tag_registry default_conflict_policy proposal_policy code_change_policy curator_mode].freeze, %w[org namespace owner_email].freeze), + "namespace.register" => OpSpec.new("namespace.register", "namespace", "register", true, false, "viewer", "stable", %w[org namespace owner_email description kind tags traffic_class active conversation_logging_enabled capture_generation_io coverage_sweep consolidation_enabled daily_cost_cap_usd daily_user_cost_cap_usd budget_alert_inbox conflict_threshold retention_days warm_days visibility requires_approval join_policy retrieval_defaults rerank_endpoint rerank_prompt_template classify_endpoint classify_prompt_template tag_registry default_conflict_policy captured_conflict_policy captured_conflict_confidence proposal_policy code_change_policy curator_mode].freeze, %w[org namespace owner_email].freeze), "namespace.register_category" => OpSpec.new("namespace.register_category", "namespace", "register_category", false, false, "writer", "experimental", %w[org namespace name description summary].freeze, %w[org namespace name].freeze), "namespace.register_ontology" => OpSpec.new("namespace.register_ontology", "namespace", "register_ontology", true, false, "admin", "stable", %w[org namespace kind name description status cardinality].freeze, %w[org namespace kind name].freeze), "namespace.restore" => OpSpec.new("namespace.restore", "namespace", "restore", true, false, "viewer", "experimental", %w[org target_namespace payload rebind_agent].freeze, %w[org target_namespace payload].freeze), @@ -894,6 +895,12 @@ def allowlist_remove(body = nil, request_options: nil, **fields) call_op("conflicts.allowlist_remove", body, fields, request_options) end + # `conflicts.bulk_accept` (admin, writes, Idempotency-Key, experimental). + # Required: org, namespace, items. + def bulk_accept(body = nil, request_options: nil, **fields) + call_op("conflicts.bulk_accept", body, fields, request_options) + end + # `conflicts.list` (viewer, read-only). # Required: org, namespace. def list(body = nil, request_options: nil, **fields) diff --git a/sdk/rust/src/blocking_operations.rs b/sdk/rust/src/blocking_operations.rs index fb1aaff94c8..a5410f7297d 100644 --- a/sdk/rust/src/blocking_operations.rs +++ b/sdk/rust/src/blocking_operations.rs @@ -3221,6 +3221,23 @@ impl crate::blocking::Client { ) -> Result, crate::CallFailure> { self.call("conflicts.resolve", &request, options) } + /// Call `conflicts.bulk_accept`. + pub fn conflicts_bulk_accept( + &self, + request: crate::ConflictsBulkAcceptInput, + ) -> Result { + self.conflicts_bulk_accept_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `conflicts.bulk_accept` with per-request options and metadata. + pub fn conflicts_bulk_accept_with_options( + &self, + request: crate::ConflictsBulkAcceptInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("conflicts.bulk_accept", &request, options) + } /// Call `conflicts.allowlist_list`. pub fn conflicts_allowlist_list( &self, diff --git a/sdk/rust/src/operations.rs b/sdk/rust/src/operations.rs index cf239b386ac..d43985feddb 100644 --- a/sdk/rust/src/operations.rs +++ b/sdk/rust/src/operations.rs @@ -3464,6 +3464,24 @@ impl crate::Client { ) -> Result, crate::CallFailure> { self.call("conflicts.resolve", &request, options).await } + /// Call `conflicts.bulk_accept`. + pub async fn conflicts_bulk_accept( + &self, + request: crate::ConflictsBulkAcceptInput, + ) -> Result { + self.conflicts_bulk_accept_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `conflicts.bulk_accept` with per-request options and metadata. + pub async fn conflicts_bulk_accept_with_options( + &self, + request: crate::ConflictsBulkAcceptInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("conflicts.bulk_accept", &request, options).await + } /// Call `conflicts.allowlist_list`. pub async fn conflicts_allowlist_list( &self, diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index d442d2b54eb..1ad8d53a0f0 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -1160,6 +1160,13 @@ pub(crate) const OP_POLICIES: &[OperationPolicy] = &[ &[], ), ("conflicts.resolve", true, false, &["namespace", "org"], &[]), + ( + "conflicts.bulk_accept", + true, + false, + &["namespace", "org"], + &[], + ), ( "conflicts.allowlist_list", true, @@ -17351,6 +17358,106 @@ impl ConflictsAllowlistRemoveInput { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum ConflictBulkResultStatus { + #[serde(rename = "resolved")] + Resolved, + #[serde(rename = "stale")] + Stale, + #[serde(rename = "failed")] + Failed, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ConflictBulkResult { + pub memory_id: String, + pub peer_id: String, + pub status: ConflictBulkResultStatus, + #[serde(default = "default_conflict_bulk_result_reason")] + pub reason: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ConflictsBulkAcceptOutput { + pub results: Vec, + pub requested: Integer, + pub resolved: Integer, + pub stale: Integer, + pub failed: Integer, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ConflictsResolverAcceptItem { + pub memory_id: String, + pub peer_id: String, + pub memory_sha256: String, + pub peer_sha256: String, + pub suggestion_hash: String, +} +impl ConflictsResolverAcceptItem { + pub fn new( + memory_id: impl Into, + peer_id: impl Into, + memory_sha256: impl Into, + peer_sha256: impl Into, + suggestion_hash: impl Into, + ) -> Self { + Self { + memory_id: memory_id.into(), + peer_id: peer_id.into(), + memory_sha256: memory_sha256.into(), + peer_sha256: peer_sha256.into(), + suggestion_hash: suggestion_hash.into(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ConflictsBulkAcceptInput { + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub org: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub namespace: Option, + pub items: Vec, +} +impl ConflictsBulkAcceptInput { + pub fn new(items: Vec) -> Self { + Self { + org: None, + namespace: None, + items, + } + } + pub fn org(mut self, org: impl Into) -> Self { + self.org = Some(org.into()); + self + } + pub fn namespace(mut self, namespace: impl Into) -> Self { + self.namespace = Some(namespace.into()); + self + } + pub async fn send( + self, + client: &crate::Client, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + client.call("conflicts.bulk_accept", &self, options).await + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ConflictRow { @@ -17414,6 +17521,34 @@ pub struct ConflictRow { deserialize_with = "present_value" )] pub sensitivity: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub capture_origin: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ConflictSourceCounts { + #[serde(default = "default_conflict_source_counts_plugin_captured")] + pub plugin_captured: Integer, + #[serde(default = "default_conflict_source_counts_caller_written")] + pub caller_written: Integer, + #[serde(default = "default_conflict_source_counts_unknown")] + pub unknown: Integer, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ConflictBacklog { + #[serde(default = "default_conflict_backlog_pending_judgement")] + pub pending_judgement: ConflictSourceCounts, + #[serde(default = "default_conflict_backlog_resolver_judged")] + pub resolver_judged: ConflictSourceCounts, + #[serde(default = "default_conflict_backlog_cosine_only")] + pub cosine_only: ConflictSourceCounts, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -17426,6 +17561,8 @@ pub struct ConflictsListOutput { pub total: Option, #[serde(default = "default_conflicts_list_output_proposals")] pub proposals: Option, + #[serde(default = "default_conflicts_list_output_backlog")] + pub backlog: Option, #[serde(default = "default_conflicts_list_output_keys")] pub keys: Option>, } @@ -35554,6 +35691,12 @@ pub struct MemoryAutoRetirement { pub judge_model: String, #[serde(default = "default_memory_auto_retirement_judge_prompt_version")] pub judge_prompt_version: String, + #[serde(default = "default_memory_auto_retirement_applied_policy")] + pub applied_policy: String, + #[serde(default = "default_memory_auto_retirement_winner_capture_origin")] + pub winner_capture_origin: String, + #[serde(default = "default_memory_auto_retirement_retired_capture_origin")] + pub retired_capture_origin: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -49574,6 +49717,9 @@ pub struct MentorBriefOutput { pub usage: std::collections::HashMap, #[serde(default = "default_mentor_brief_output_planes")] pub planes: Vec, + #[serde(default = "default_mentor_brief_output_conflict_backlog")] + pub conflict_backlog: + std::collections::HashMap>, #[serde(default = "default_mentor_brief_output_hints")] pub hints: Vec, #[serde(default = "default_mentor_brief_output_adoption")] @@ -50236,6 +50382,10 @@ pub struct NamespaceGetOutput { pub classify_endpoint: Option, #[serde(default = "default_namespace_get_output_default_conflict_policy")] pub default_conflict_policy: Option, + #[serde(default = "default_namespace_get_output_captured_conflict_policy")] + pub captured_conflict_policy: String, + #[serde(default = "default_namespace_get_output_captured_conflict_confidence")] + pub captured_conflict_confidence: f64, #[serde(default = "default_namespace_get_output_proposal_policy")] pub proposal_policy: Option, #[serde(default = "default_namespace_get_output_code_change_policy")] @@ -51774,6 +51924,15 @@ pub enum NamespaceRegisterInputDefaultConflictPolicy { AppendOnly, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum NamespaceRegisterInputCapturedConflictPolicy { + #[serde(rename = "manual_review")] + ManualReview, + #[serde(rename = "resolver_update")] + ResolverUpdate, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[non_exhaustive] pub enum NamespaceRegisterInputProposalPolicyMode { @@ -52036,6 +52195,18 @@ pub struct NamespaceRegisterInput { skip_serializing_if = "Option::is_none", deserialize_with = "present_nullable" )] + pub captured_conflict_policy: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] + pub captured_conflict_confidence: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] pub proposal_policy: Option>, #[serde( default, @@ -52081,6 +52252,8 @@ impl NamespaceRegisterInput { classify_prompt_template: None, tag_registry: None, default_conflict_policy: None, + captured_conflict_policy: None, + captured_conflict_confidence: None, proposal_policy: None, code_change_policy: None, curator_mode: None, @@ -52289,6 +52462,25 @@ impl NamespaceRegisterInput { self.default_conflict_policy = Some(None); self } + pub fn captured_conflict_policy( + mut self, + captured_conflict_policy: NamespaceRegisterInputCapturedConflictPolicy, + ) -> Self { + self.captured_conflict_policy = Some(Some(captured_conflict_policy)); + self + } + pub fn captured_conflict_policy_null(mut self) -> Self { + self.captured_conflict_policy = Some(None); + self + } + pub fn captured_conflict_confidence(mut self, captured_conflict_confidence: f64) -> Self { + self.captured_conflict_confidence = Some(Some(captured_conflict_confidence)); + self + } + pub fn captured_conflict_confidence_null(mut self) -> Self { + self.captured_conflict_confidence = Some(None); + self + } pub fn proposal_policy( mut self, proposal_policy: NamespaceRegisterInputProposalPolicy, @@ -52865,6 +53057,12 @@ pub struct SnapshotMemoryRow { skip_serializing_if = "Option::is_none", deserialize_with = "present_value" )] + pub capture_origin: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] pub files: Option>, #[serde( default, @@ -52933,6 +53131,7 @@ impl SnapshotMemoryRow { locked_at: None, on_expire: None, expire_reason: None, + capture_origin: None, files: None, concepts: None, } @@ -53194,6 +53393,10 @@ impl SnapshotMemoryRow { self.expire_reason = Some(expire_reason.into()); self } + pub fn capture_origin(mut self, capture_origin: impl Into) -> Self { + self.capture_origin = Some(capture_origin.into()); + self + } pub fn files(mut self, files: impl IntoIterator>) -> Self { self.files = Some(files.into_iter().map(Into::into).collect()); self @@ -53698,6 +53901,8 @@ pub struct NamespaceSnapshotOutputSnapshotMemoryRow { pub on_expire: String, #[serde(default = "default_namespace_snapshot_output_snapshot_memory_row_expire_reason")] pub expire_reason: String, + #[serde(default = "default_namespace_snapshot_output_snapshot_memory_row_capture_origin")] + pub capture_origin: String, #[serde(default = "default_namespace_snapshot_output_snapshot_memory_row_files")] pub files: Vec, #[serde(default = "default_namespace_snapshot_output_snapshot_memory_row_concepts")] @@ -70582,6 +70787,9 @@ fn default_collection_entry_document_count() -> Option { fn default_collection_list_output_next_cursor() -> Option { serde_json::from_str("null").expect("schema default") } +fn default_conflict_bulk_result_reason() -> String { + serde_json::from_str("\"\"").expect("schema default") +} fn default_conflicts_list_output_next_before_version() -> Option { serde_json::from_str("null").expect("schema default") } @@ -70591,6 +70799,30 @@ fn default_conflicts_list_output_total() -> Option { fn default_conflicts_list_output_proposals() -> Option { serde_json::from_str("null").expect("schema default") } +fn default_conflict_source_counts_plugin_captured() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_conflict_source_counts_caller_written() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_conflict_source_counts_unknown() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_conflict_backlog_pending_judgement() -> ConflictSourceCounts { + serde_json::from_str("{\"plugin_captured\":0,\"caller_written\":0,\"unknown\":0}") + .expect("schema default") +} +fn default_conflict_backlog_resolver_judged() -> ConflictSourceCounts { + serde_json::from_str("{\"plugin_captured\":0,\"caller_written\":0,\"unknown\":0}") + .expect("schema default") +} +fn default_conflict_backlog_cosine_only() -> ConflictSourceCounts { + serde_json::from_str("{\"plugin_captured\":0,\"caller_written\":0,\"unknown\":0}") + .expect("schema default") +} +fn default_conflicts_list_output_backlog() -> Option { + serde_json::from_str("null").expect("schema default") +} fn default_conflicts_list_output_keys() -> Option> { serde_json::from_str("null").expect("schema default") } @@ -72776,6 +73008,15 @@ fn default_memory_auto_retirement_judge_model() -> String { fn default_memory_auto_retirement_judge_prompt_version() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_memory_auto_retirement_applied_policy() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_memory_auto_retirement_winner_capture_origin() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_memory_auto_retirement_retired_capture_origin() -> String { + serde_json::from_str("\"\"").expect("schema default") +} fn default_memory_auto_retirements_output_rows() -> Vec { serde_json::from_str("[]").expect("schema default") } @@ -74466,6 +74707,10 @@ fn default_mentor_plane_mentored() -> bool { fn default_mentor_brief_output_planes() -> Vec { serde_json::from_str("[]").expect("schema default") } +fn default_mentor_brief_output_conflict_backlog( +) -> std::collections::HashMap> { + serde_json::from_str("{}").expect("schema default") +} fn default_mentor_hint_ops() -> Vec { serde_json::from_str("[]").expect("schema default") } @@ -74687,6 +74932,12 @@ fn default_namespace_get_output_classify_endpoint() -> Option { fn default_namespace_get_output_default_conflict_policy() -> Option { serde_json::from_str("null").expect("schema default") } +fn default_namespace_get_output_captured_conflict_policy() -> String { + serde_json::from_str("\"manual_review\"").expect("schema default") +} +fn default_namespace_get_output_captured_conflict_confidence() -> f64 { + serde_json::from_str("0.98").expect("schema default") +} fn default_namespace_get_output_proposal_policy() -> Option { serde_json::from_str("null").expect("schema default") } @@ -75005,6 +75256,9 @@ fn default_namespace_snapshot_output_snapshot_memory_row_on_expire() -> String { fn default_namespace_snapshot_output_snapshot_memory_row_expire_reason() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_namespace_snapshot_output_snapshot_memory_row_capture_origin() -> String { + serde_json::from_str("\"\"").expect("schema default") +} fn default_namespace_snapshot_output_snapshot_memory_row_files() -> Vec { serde_json::from_str("[]").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index dde0467b80f..1f84812c7dc 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -6026,6 +6026,11 @@ fn conflicts_list() { serde_json::from_str::("null").unwrap(), "conflicts.list:proposals" ); + assert_eq!( + encoded["backlog"], + serde_json::from_str::("null").unwrap(), + "conflicts.list:backlog" + ); assert_eq!( encoded["keys"], serde_json::from_str::("null").unwrap(), @@ -6083,6 +6088,19 @@ fn conflicts_resolve() { ); } #[test] +fn conflicts_bulk_accept() { + let value: clickhouse_loom::ConflictsBulkAcceptInput = + serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\",\"items\":[]}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::ConflictsBulkAcceptOutput = serde_json::from_str( + "{\"results\":[],\"requested\":1,\"resolved\":1,\"stale\":1,\"failed\":1}", + ) + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); +} +#[test] fn conflicts_allowlist_list() { let value: clickhouse_loom::ConflictsAllowlistListInput = serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\"}").unwrap(); @@ -6741,6 +6759,16 @@ fn namespace_get() { serde_json::from_str::("null").unwrap(), "namespace.get:default_conflict_policy" ); + assert_eq!( + encoded["captured_conflict_policy"], + serde_json::from_str::("\"manual_review\"").unwrap(), + "namespace.get:captured_conflict_policy" + ); + assert_eq!( + encoded["captured_conflict_confidence"], + serde_json::from_str::("0.98").unwrap(), + "namespace.get:captured_conflict_confidence" + ); assert_eq!( encoded["proposal_policy"], serde_json::from_str::("null").unwrap(), @@ -7254,6 +7282,11 @@ fn mentor_brief() { serde_json::from_str::("[]").unwrap(), "mentor.brief:planes" ); + assert_eq!( + encoded["conflict_backlog"], + serde_json::from_str::("{}").unwrap(), + "mentor.brief:conflict_backlog" + ); assert_eq!( encoded["hints"], serde_json::from_str::("[]").unwrap(), diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 836c63ef3e4..50bf8211211 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -2214,6 +2214,35 @@ export interface ConflictsAllowlistRemoveOutput { removed: boolean; } +export interface ConflictsResolverAcceptItem { + memory_id: string; + peer_id: string; + memory_sha256: string; + peer_sha256: string; + suggestion_hash: string; +} + +export interface ConflictsBulkAcceptInput { + org: string; + namespace: string; + items: ConflictsResolverAcceptItem[]; +} + +export interface ConflictBulkResult { + memory_id: string; + peer_id: string; + status: "resolved" | "stale" | "failed"; + reason?: string; +} + +export interface ConflictsBulkAcceptOutput { + results: ConflictBulkResult[]; + requested: number; + resolved: number; + stale: number; + failed: number; +} + export interface ConflictsListInput { org: string; namespace: string; @@ -2236,6 +2265,19 @@ export interface ConflictRow { conflict_with: string[]; content_sha256?: string; sensitivity?: string; + capture_origin?: string; +} + +export interface ConflictBacklog { + pending_judgement?: ConflictSourceCounts; + resolver_judged?: ConflictSourceCounts; + cosine_only?: ConflictSourceCounts; +} + +export interface ConflictSourceCounts { + plugin_captured?: number; + caller_written?: number; + unknown?: number; } export interface ConflictsListOutput { @@ -2243,6 +2285,7 @@ export interface ConflictsListOutput { next_before_version?: number | null; total?: number | null; proposals?: number | null; + backlog?: ConflictBacklog | null; keys?: string[] | null; } @@ -6418,6 +6461,9 @@ export interface MemoryAutoRetirement { judge_confidence?: number | null; judge_model?: string; judge_prompt_version?: string; + applied_policy?: string; + winner_capture_origin?: string; + retired_capture_origin?: string; } export interface MemoryAutoRetirementsOutput { @@ -9143,6 +9189,7 @@ export interface MentorBriefOutput { sessions: number; usage?: Record; planes?: MentorPlane[]; + conflict_backlog?: Record>; hints?: MentorHint[]; adoption?: MentorAdoption[]; usage_evidence?: UsageRung[]; @@ -9311,6 +9358,8 @@ export interface NamespaceGetOutput { rerank_endpoint?: string | null; classify_endpoint?: string | null; default_conflict_policy?: string | null; + captured_conflict_policy?: string; + captured_conflict_confidence?: number; proposal_policy?: ProposalPolicy | null; code_change_policy?: "retire_removed" | "flag" | "revise" | null; curator_mode?: string | null; @@ -9611,6 +9660,8 @@ export interface NamespaceRegisterInput { classify_prompt_template?: string | null; tag_registry?: NamespaceTypeConfig[]; default_conflict_policy?: "auto_reinforce" | "manual_review" | "newest_wins" | "append_only" | null; + captured_conflict_policy?: "manual_review" | "resolver_update" | null; + captured_conflict_confidence?: number | null; proposal_policy?: ProposalPolicy | null; code_change_policy?: "retire_removed" | "flag" | "revise" | null; /** `off`, `findings` or `assist`, which calls a model: In this mode the curator sends content of this namespace to the deployment's model provider: the namespace's */ @@ -9730,6 +9781,7 @@ export interface SnapshotMemoryRow { locked_at?: string | null; on_expire?: string; expire_reason?: string; + capture_origin?: string; files?: string[]; concepts?: string[]; } @@ -12469,6 +12521,7 @@ export type OpName = | "collection.move" | "conflicts.allowlist_list" | "conflicts.allowlist_remove" + | "conflicts.bulk_accept" | "conflicts.list" | "conflicts.propose_revision" | "conflicts.resolve" @@ -12898,6 +12951,7 @@ export interface OpMap { "collection.move": { input: CollectionMoveInput; output: CollectionMoveOutput }; "conflicts.allowlist_list": { input: ConflictsAllowlistListInput; output: ConflictsAllowlistListOutput }; "conflicts.allowlist_remove": { input: ConflictsAllowlistRemoveInput; output: ConflictsAllowlistRemoveOutput }; + "conflicts.bulk_accept": { input: ConflictsBulkAcceptInput; output: ConflictsBulkAcceptOutput }; "conflicts.list": { input: ConflictsListInput; output: ConflictsListOutput }; "conflicts.propose_revision": { input: ConflictsProposeRevisionInput; output: ConflictsProposeRevisionOutput }; "conflicts.resolve": { input: ConflictsResolveInput; output: ConflictsResolveOutput }; @@ -13327,6 +13381,7 @@ export const OPS: readonly OpSpec[] = [ { name: "collection.move", group: "collection", method: "move", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 80, audit: true, readOnly: false }, { name: "conflicts.allowlist_list", group: "conflicts", method: "allowlistList", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 80, audit: false, readOnly: true }, { name: "conflicts.allowlist_remove", group: "conflicts", method: "allowlistRemove", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 80, audit: true, readOnly: false }, + { name: "conflicts.bulk_accept", group: "conflicts", method: "bulkAccept", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 5000, audit: true, readOnly: false }, { name: "conflicts.list", group: "conflicts", method: "list", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 80, audit: false, readOnly: true }, { name: "conflicts.propose_revision", group: "conflicts", method: "proposeRevision", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 120, audit: false, readOnly: true }, { name: "conflicts.resolve", group: "conflicts", method: "resolve", idempotent: true, role: "admin", maturity: "stable", budgetP99Ms: 500, audit: true, readOnly: false }, @@ -13689,4 +13744,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 426; +export const GENERATED_OP_COUNT = 427; diff --git a/server/auth/delegation.py b/server/auth/delegation.py index d6e07003b2e..71c260742dc 100644 --- a/server/auth/delegation.py +++ b/server/auth/delegation.py @@ -75,6 +75,7 @@ def mint( *, jti: str | None = None, consumer: str | None = None, + capture_origin: str | None = None, reads_as_creator: bool = False, session_protection: bool = False, answer_mirrors: bool = False, @@ -91,6 +92,7 @@ def mint( read_scope=self.read_scope or None, read_user_id=self.read_user_id or None, consumer=consumer, + capture_origin=capture_origin, jti=jti, parents=self.parents, parent_subjects=self.parent_subjects, diff --git a/server/auth/jwt.py b/server/auth/jwt.py index aac4397106c..03fdab8f2ea 100644 --- a/server/auth/jwt.py +++ b/server/auth/jwt.py @@ -176,6 +176,9 @@ class AuthorizationClaims: # first); rows it stamps read `consumer_source = claimed`. '' = the # request's field, else the subject class, and the row reads self-reported. consumer: str = "" + # A server-issued, signed integration capture capability. It is deliberately + # absent from request models and delegated tokens. + capture_origin: str = "" # `traffic_class` claim: the operator's override of the # class every request under this token runs as — production | # interactive | bench. '' = the namespace row (then the request's hint, @@ -303,6 +306,7 @@ def mint_token( read_user_id: str | None = None, traffic_class: str | None = None, consumer: str | None = None, + capture_origin: str | None = None, jti: str | None = None, session_id: str | None = None, first_party: bool = False, @@ -347,6 +351,8 @@ def mint_token( if is_reserved_subject(subject): # Only an end-user issuer's tokens carry these. raise ValueError(f"{RESERVED_SUBJECT}: {subject!r}") + if capture_origin and not is_service_account: + raise TokenError("capture_origin is only valid on an approved service-account credential") now = int(time.time()) if issued_at is None else issued_at payload: dict[str, Any] = { "sub": subject, @@ -387,6 +393,7 @@ def mint_token( if not c: raise TokenError(f"consumer must be a printable name, got {consumer!r}") payload["consumer"] = c + _add_capture_origin_claim(payload, capture_origin) if parents: payload["parents"] = list(parents) if parent_subjects: @@ -480,23 +487,9 @@ def verify_token(token: str, *, secret: str | None = None) -> AuthInfo: _check_not_revoked(decoded) - roles: list[Role] = [] - for name in _str_list(decoded, "roles"): - try: - roles.append(Role[name.upper()]) - except KeyError as e: - raise TokenError(f"unknown role in token: {name!r}") from e + roles = _roles_claim(decoded) - ns_roles_claim = decoded.get("ns_roles") or {} - if not isinstance(ns_roles_claim, dict): - raise TokenError("claim 'ns_roles' must be an object") - org = decoded.get("org", "") - if not isinstance(org, str): - raise TokenError("claim 'org' must be a string") - if "\x00" in str(decoded["sub"]): - raise TokenError("claim 'sub' may not contain a NUL character") - if is_reserved_subject(str(decoded["sub"])): - raise TokenError(f"claim 'sub': {RESERVED_SUBJECT}") + ns_roles_claim, org = _identity_claims(decoded) exp = decoded.get("exp") return AuthInfo( @@ -512,6 +505,7 @@ def verify_token(token: str, *, secret: str | None = None) -> AuthInfo: token_id=token_id_of(token, decoded.get("jti")), traffic_class=_traffic_class_claim(decoded.get("traffic_class")), consumer=_consumer_claim(decoded.get("consumer")), + capture_origin=_capture_origin_claim(decoded.get("capture_origin")), parents=tuple(_str_list(decoded, "parents")), parent_subjects=tuple(_str_list(decoded, "parent_subjects")), parent_iats=tuple(_parent_iats(decoded)), @@ -576,6 +570,7 @@ def _end_user_key(token: str) -> tuple[str, EndUserIssuer, Any] | None: "creator", "saves_to", "parents", + "capture_origin", ) @@ -666,6 +661,7 @@ def _verify_end_user(token: str, issuer: str, spec: EndUserIssuer, public_key: A agent_principal=agent, token_id=token_id_of(token, decoded.get("jti")), consumer=_consumer_claim(decoded.get("consumer")), + capture_origin=_capture_origin_claim(decoded.get("capture_origin")), issued_at=iat, expires_at=int(exp), ) @@ -771,6 +767,31 @@ def _str_list(decoded: dict[str, Any], claim: str) -> list[str]: return value +def _roles_claim(decoded: dict[str, Any]) -> list[Role]: + roles: list[Role] = [] + for name in _str_list(decoded, "roles"): + try: + roles.append(Role[name.upper()]) + except KeyError as e: + raise TokenError(f"unknown role in token: {name!r}") from e + return roles + + +def _identity_claims(decoded: dict[str, Any]) -> tuple[dict[str, Any], str]: + ns_roles_claim = decoded.get("ns_roles") or {} + if not isinstance(ns_roles_claim, dict): + raise TokenError("claim 'ns_roles' must be an object") + org = decoded.get("org", "") + if not isinstance(org, str): + raise TokenError("claim 'org' must be a string") + subject = str(decoded["sub"]) + if "\x00" in subject: + raise TokenError("claim 'sub' may not contain a NUL character") + if is_reserved_subject(subject): + raise TokenError(f"claim 'sub': {RESERVED_SUBJECT}") + return ns_roles_claim, org + + def _parent_iats(decoded: dict[str, Any]) -> list[int]: """The `parent_iats` claim, one int per `parent_subjects` entry. A missing or misaligned list is refused: without it an ancestor's cutoff would be @@ -820,6 +841,20 @@ def _consumer_claim(raw: Any) -> str: return claim_consumer(raw) +def _capture_origin_claim(raw: Any) -> str: + """Only recognized signed claims establish captured plugin provenance.""" + return raw if isinstance(raw, str) and raw in {"claude-code", "codex"} else "" + + +def _add_capture_origin_claim(payload: dict[str, Any], raw: str | None) -> None: + if not raw: + return + origin = str(raw).strip() + if origin not in {"claude-code", "codex"}: + raise TokenError("capture_origin must be claude-code or codex") + payload["capture_origin"] = origin + + def _traffic_class_claim(raw: Any) -> str: """The `traffic_class` claim normalised; an unknown value is ignored ('' — the namespace decides) rather than refused, so a token minted by diff --git a/server/core/instances.py b/server/core/instances.py index 136370d4067..7183a474ebb 100644 --- a/server/core/instances.py +++ b/server/core/instances.py @@ -52,6 +52,7 @@ TABLE = "loom.instances" CELL_TABLE = "loom.cell_heartbeats" QUERY_TAG = "instances.heartbeat" +CAPTURED_CONFLICT_PROVENANCE_MARKER = "ccp1-" # A row is live while its last beat is younger than this many intervals. _LIVE_INTERVALS = 3 @@ -93,7 +94,8 @@ def _this_process() -> tuple[int, str, datetime]: def instance_id() -> str: - return _this_process()[1] + # KeeperMap cannot gain a column during rollout; an opaque ID prefix advertises support. + return f"{CAPTURED_CONFLICT_PROVENANCE_MARKER}{_this_process()[1]}" def _host() -> str: diff --git a/server/identity/api/models.py b/server/identity/api/models.py index e1f328e3b51..9f6df9a5209 100644 --- a/server/identity/api/models.py +++ b/server/identity/api/models.py @@ -191,6 +191,18 @@ class NamespaceRegisterInput(BaseModel): # Empty ⇒ namespace-level defaults apply uniformly. tag_registry: list[NamespaceTypeConfig] = Field(default_factory=list) default_conflict_policy: ConflictPolicyStr | None = None # fresh: auto_reinforce + # Captured integration conflicts stay human-reviewable unless the owner opts in. + captured_conflict_policy: Literal["manual_review", "resolver_update"] | None = None + # Minimum resolver confidence for an opted-in captured-to-captured update. + captured_conflict_confidence: float | None = Field(default=None, ge=0.5, le=1.0) + + @field_validator("captured_conflict_policy", "captured_conflict_confidence", mode="before") + @classmethod + def captured_conflict_settings_are_not_null(cls, value: Any) -> Any: + if value is None: + raise ValueError("captured conflict settings may be omitted but cannot be null") + return value + # The owner's rule for proposals (facts written with memory.set # proposed=true): under mode `auto`, `run.grade` rejects one once its failed # graded runs reach `reject_after_fails` (0 = never), and no policy accepts @@ -327,6 +339,9 @@ class NamespaceGetOutput(BaseModel): # How close writes are settled: `auto_reinforce` (the default when unset), # `manual_review`, `newest_wins` or `append_only`. default_conflict_policy: str | None = None + captured_conflict_policy: str = "manual_review" + captured_conflict_confidence: float = 0.98 + # How proposals (`memory.set proposed=true`) are decided; the manual default when unset. # The owner's rule for proposals (`memory.set proposed=true`): under mode `auto`, # `run.grade` rejects one once its failed graded runs reach `reject_after_fails` # (0 = never), and no policy accepts one; the manual default when unset. @@ -610,6 +625,7 @@ class _SnapshotMemoryRow(BaseModel): locked_at: datetime | None = None on_expire: str = "" expire_reason: str = "" + capture_origin: str = "" files: list[str] = Field(default_factory=list) concepts: list[str] = Field(default_factory=list) diff --git a/server/identity/app/me_service_accounts.py b/server/identity/app/me_service_accounts.py index 0ce8cddaed7..d507c978fc0 100644 --- a/server/identity/app/me_service_accounts.py +++ b/server/identity/app/me_service_accounts.py @@ -11,7 +11,8 @@ import json import secrets import time -from collections.abc import Mapping +from collections.abc import AsyncIterator, Mapping +from contextlib import asynccontextmanager from datetime import datetime from fastapi import APIRouter, HTTPException, Request @@ -140,6 +141,11 @@ async def _bound_trackers(org: str, subject: str, parent: AuthInfo, repos: list[ return out +@asynccontextmanager +async def _no_async_claim() -> AsyncIterator[None]: + yield + + async def _name_holder(org: str, name: str) -> str | None: """Who made the token, not yet revoked or expired, that holds `name` in `org`; None when it is free. A new row would replace its row, leaving it @@ -203,6 +209,7 @@ async def save_token( created_by: str, now: datetime, personal: bool = False, + client: str = "", ) -> None: """List the token in its owner's token list (`loom.service_accounts`). Called under the name's claim.""" @@ -239,7 +246,7 @@ async def save_token( "revoked_by": "", "version": version, "kind": "personal_agent" if personal else "service_account", - "client": "", + "client": client, # The gate and the namespace listings read this flag: a token # reads through its creator's live grants (server/auth/service_accounts.py). "inherit_creator_grants": True, @@ -353,6 +360,7 @@ async def _create_token( # otherwise); null: the parent token's when it may # write there, else the first such entry. Not with "*". ttl_days: int|null # default and null: 90 days; 0: never expires + capture_origin?: "claude-code" | "codex" # namespace-admin-issued capture credential Each namespace's role is delegated from the caller's token (`server.auth.delegation.delegate`): at most the caller's live grant on @@ -378,6 +386,31 @@ async def _create_token( name = token_name(payload.get("name"), default=generated_name(naive_utc_now_seconds())) requested_role = _requested_roles(payload) + capture_origin = str(payload.get("capture_origin") or "").strip() + if capture_origin: + from server.memory.app.provenance import require_capture_resolver_support + + if capture_origin not in {"claude-code", "codex"}: + raise _invalid("capture_origin must be claude-code or codex") + explicit_names = [ns for ns in requested_role if ns != "*"] + if ( + personal + or not settings.auth_actually_required() + or "*" in requested_role + or len(explicit_names) != 1 + or requested_role.get(explicit_names[0]) != "writer" + ): + raise _invalid( + "captured credentials require auth, one named namespace and the writer role" + ) + if not await me_callers.caller_admin_of(org, explicit_names[0], subject): + raise HTTPException( + status_code=403, + detail={ + "code": "AUTH_INSUFFICIENT", + "message": "only a namespace admin may issue a captured credential", + }, + ) ttl_seconds = parse_ttl_days(payload.get("ttl_days")) everything = "*" in requested_role asked = asked_saves_to(payload.get("saves_to"), everything=everything) @@ -390,9 +423,29 @@ async def _create_token( for tracker in await _bound_trackers(org, subject, parent, named): requested_role.setdefault(tracker, None if everything else "viewer") - from server.auth.grant_claims import service_account_change + from server.auth.grant_claims import account_change, service_account_change - async with service_account_change(org, name): + namespace_claim = ( + account_change(org, explicit_names[0]) if capture_origin else _no_async_claim() + ) + async with namespace_claim, service_account_change(org, name): + if capture_origin: + from server.core.ch import get_client + from server.memory.app.provenance import require_capture_resolver_support + from server.memory.store import conflicts as conflicts_repo + + await require_capture_resolver_support() + ns_settings = await conflicts_repo.namespace_write_row( + org, explicit_names[0], ch=get_client() + ) + if ( + str(ns_settings.get("default_conflict_policy") or "auto_reinforce") + != "manual_review" + ): + raise _invalid( + "captured credentials require default_conflict_policy=manual_review so " + "builds cannot automatically retire captured conflicts" + ) await refuse_taken_name(org, name, subject) delegated = await delegate( parent, @@ -411,11 +464,21 @@ async def _create_token( ) is_code = await token_grants.code_namespace_predicate(org, list(restricted_roles)) sa_subject = new_token_subject(org, name, subject) - minted = delegated.mint(sa_subject, reads_as_creator=personal) + minted = delegated.mint( + sa_subject, + reads_as_creator=personal, + capture_origin=capture_origin or None, + ) now = naive_utc_now_seconds() # after the mint: the row is never older than the token's iat expires_at = delegated.expires_at(now) await save_token( - name, sa_subject, delegated, created_by=subject, now=now, personal=personal + name, + sa_subject, + delegated, + created_by=subject, + now=now, + personal=personal, + client=capture_origin, ) # A restricted namespace named here is read only when the token's own subject holds a # direct grant: write it now, capped, revoked with the token; a name in the claim alone @@ -459,6 +522,7 @@ async def _create_token( "created_at": now.isoformat(), "expires_at": expires_at.isoformat() if expires_at else None, "restricted_namespaces": restricted_granted, + "capture_origin": capture_origin or None, "mcp_url": mcp_url, "clients": client_configs(mcp_url, minted), } diff --git a/server/identity/app/namespace.py b/server/identity/app/namespace.py index 91e23fbcdb0..830996fd70b 100644 --- a/server/identity/app/namespace.py +++ b/server/identity/app/namespace.py @@ -246,6 +246,12 @@ def registry_row( "default_conflict_policy": _set_or_stored( input.default_conflict_policy, existing, "default_conflict_policy", "auto_reinforce" ), + "captured_conflict_policy": _form_value_or_stored( + input, existing, "captured_conflict_policy", "manual_review" + ), + "captured_conflict_confidence": _form_value_or_stored( + input, existing, "captured_conflict_confidence", 0.98 + ), "auto_promote_gate": str((existing or {}).get("auto_promote_gate") or "k_supporters"), "evidence_threshold": int((existing or {}).get("evidence_threshold") or 5), # Preserved unless the form set it. @@ -289,6 +295,17 @@ def _sent_or_stored( return (existing or {}).get(field) +def _form_value_or_stored( + input: NamespaceRegisterInput, existing: dict[str, Any] | None, field: str, fresh: Any +) -> Any: + """An omitted settings field keeps the row read under account_change; an explicit + field value is the administrator's edit. Fresh rows use the field's default.""" + if field in input.model_fields_set: + return getattr(input, field) + stored = (existing or {}).get(field) + return fresh if stored is None else stored + + def _serialize_proposal_policy(policy: Any) -> str: from server.memory.domain.proposal_policy import serialize_policy @@ -444,6 +461,13 @@ async def handle_namespace_register( ) now = naive_utc_now_seconds() row = registry_row(input, existing, now) + if row["default_conflict_policy"] != "manual_review": + from server.memory.store import conflicts as conflicts_repo + + if await conflicts_repo.has_live_captured_rows(input.org, input.namespace, ch=ch): + raise ValidationError( + "default_conflict_policy must remain manual_review while captured rows are live" + ) refuse_curator_mode(row) with identity_write(): await ch.insert("loom.namespaces", [row]) @@ -596,6 +620,8 @@ async def handle_namespace_get(input: NamespaceGetInput) -> NamespaceGetOutput: ifNull(rerank_endpoint, '') AS rerank_endpoint, ifNull(classify_endpoint, '') AS classify_endpoint, ifNull(default_conflict_policy, '') AS default_conflict_policy, + ifNull(captured_conflict_policy, 'manual_review') AS captured_conflict_policy, + ifNull(captured_conflict_confidence, 0.98) AS captured_conflict_confidence, proposal_policy, code_change_policy, curator_mode, @@ -661,6 +687,8 @@ async def handle_namespace_get(input: NamespaceGetInput) -> NamespaceGetOutput: rerank_endpoint=row.get("rerank_endpoint") or "", classify_endpoint=row.get("classify_endpoint") or "", default_conflict_policy=row.get("default_conflict_policy") or "auto_reinforce", + captured_conflict_policy=row.get("captured_conflict_policy") or "manual_review", + captured_conflict_confidence=float(row.get("captured_conflict_confidence") or 0.98), proposal_policy=_parse_proposal_policy(row.get("proposal_policy")), code_change_policy=code_change.policy_of(str(row.get("code_change_policy") or "")), curator_mode=curator.stored_mode(row.get("curator_mode")), diff --git a/server/identity/app/namespace_snapshot.py b/server/identity/app/namespace_snapshot.py index 4abbebb0cef..1bb28826c99 100644 --- a/server/identity/app/namespace_snapshot.py +++ b/server/identity/app/namespace_snapshot.py @@ -29,7 +29,7 @@ from server.identity.store import namespaces as namespaces_repo from server.memory.app import blacklist_guard from server.memory.app import snapshot_rows as memory_snapshot -from server.memory.app.provenance import writer_actor +from server.memory.app.provenance import require_capture_resolver_support, writer_actor from server.observability import audit @@ -55,6 +55,22 @@ async def handle_namespace_snapshot( # Memories — active, non-tombstoned. memory_rows = await memory_snapshot.read_namespace(ch, org=input.org, namespace=input.namespace) memories = [snapshot_memory_row(r) for r in memory_rows] + from server.core.hashing import sha256_value + + captured_origins = { + str(m.memory_id): { + "origin": str(m.capture_origin), + "row_hash": sha256_value( + { + "content_sha256": str(m.content_sha256 or ""), + "value": str(m.value or ""), + "value_json": str(m.value_json or "{}"), + } + ), + } + for m in memories + if m.capture_origin in {"claude-code", "codex"} + } # Per-type configs. type_dicts = await list_type_configs(input.org, input.namespace) types = [_SnapshotTypeRow(**t) for t in type_dicts] @@ -124,6 +140,7 @@ async def handle_namespace_snapshot( "type_count": len(types), "grant_count": len(grants), "audit_tail_count": len(audit_tail), + "captured_origin_map": json.dumps(captured_origins, separators=(",", ":")), } ], settings={"async_insert": 0, "wait_for_async_insert": 1}, @@ -164,9 +181,31 @@ async def _restore_payload( input: NamespaceRestoreInput, version_base: int ) -> tuple[list[dict[str, Any]], int]: """Validate all restored values before the namespace or its grants change.""" + ch = get_client() + trusted = await ch.query_one( + """ + SELECT captured_origin_map + FROM loom.namespace_snapshots + WHERE org = {org:String} AND snapshot_id = {sid:UUID} + AND source_namespace = {source_ns:String} + ORDER BY created_at DESC + LIMIT 1 + """, + params={ + "org": input.org, + "sid": input.payload.snapshot_id, + "source_ns": input.payload.source_namespace, + }, + ) + origins = json.loads(str(trusted.get("captured_origin_map") or "{}")) if trusted else {} + if not isinstance(origins, dict): + origins = {} + memories = memory_snapshot.authenticated_capture_origins(input.payload.memories, origins) memories, erased = await memory_snapshot.without_erased( - input.org, input.target_namespace, input.payload.memories + input.org, input.target_namespace, memories ) + if any(memory.capture_origin for memory in memories): + await require_capture_resolver_support() rows = memory_snapshot.checked_rows( memory_snapshot.restore_rows( memories, diff --git a/server/insights/api/models_mentor.py b/server/insights/api/models_mentor.py index c398ac05030..d34dcd35fd2 100644 --- a/server/insights/api/models_mentor.py +++ b/server/insights/api/models_mentor.py @@ -110,6 +110,9 @@ class MentorBriefOutput(BaseModel): # Every plane the mentor knows, with this agent's calls to it (the sum of its ops' `usage` # counts) and whether it is available. planes: list[MentorPlane] = Field(default_factory=list) + # Conflicted memory rows in this namespace, grouped by resolver state and + # trustworthy provenance. These are rows, not distinct conflict pairs. + conflict_backlog: dict[str, dict[str, int]] = Field(default_factory=dict) # The rules that fired for this agent, each with the counts that fired it; empty when none. hints: list[MentorHint] = Field(default_factory=list) # Per hint code, sessions it was shown in and followed in, most shown first; empty when diff --git a/server/insights/app/mentor.py b/server/insights/app/mentor.py index 10045c19324..32e81700523 100644 --- a/server/insights/app/mentor.py +++ b/server/insights/app/mentor.py @@ -269,6 +269,7 @@ async def namespace_ledger(self) -> None: async def namespace_rows(self) -> None: self.facts.update(await self.store.namespace_rows()) + self.facts["conflict_backlog"] = await self.store.conflict_backlog() async def documents(self) -> None: self.facts["documents"] = await self.store.live_documents() diff --git a/server/insights/app/mentor_brief.py b/server/insights/app/mentor_brief.py index 5c518bca0b6..b8b1498d346 100644 --- a/server/insights/app/mentor_brief.py +++ b/server/insights/app/mentor_brief.py @@ -318,6 +318,7 @@ async def handle_mentor_brief(inp: MentorBriefInput) -> MentorBriefOutput: sessions=profile.sessions, usage=dict(sorted(profile.usage.items(), key=lambda kv: (-kv[1], kv[0]))), planes=_planes(profile), + conflict_backlog=dict(profile.facts.get("conflict_backlog") or {}), hints=hints, adoption=await _adoption(profile), usage_evidence=ladder.rungs, diff --git a/server/insights/app/mentor_rules.py b/server/insights/app/mentor_rules.py index a8d725e2d99..3d691247b6a 100644 --- a/server/insights/app/mentor_rules.py +++ b/server/insights/app/mentor_rules.py @@ -660,17 +660,6 @@ def _rules_shapes(c: _Ctx) -> None: duplicate_sets=dup, sets=sets, ) - conflicted = c.fact("conflicted_rows") - if conflicted > 0 and c.fact("ns_conflict_ops") == 0: - c.add( - "conflicts_pending", - "info", - f"{conflicted} facts in this namespace disagree with another and nobody has looked: " - f"conflicts.list shows the pairs, conflicts.resolve settles one; " - "search penalises them until then.", - ("conflicts.list", "conflicts.resolve"), - conflicted_rows=conflicted, - ) def _coordination_sentence(c: _Ctx, hot_set: bool, hot_get: bool) -> tuple[str, str]: diff --git a/server/insights/store/mentor.py b/server/insights/store/mentor.py index 1ed30108220..4441ae46f42 100644 --- a/server/insights/store/mentor.py +++ b/server/insights/store/mentor.py @@ -326,6 +326,65 @@ async def namespace_rows(self) -> dict[str, int]: for k in ("live_rows", "entity_rows", "conflicted_rows", "coord_keys") } + async def conflict_backlog(self) -> dict[str, dict[str, int]]: + """Namespace-scoped conflicted rows by resolver state and trusted source. + + Capture provenance is unknown unless a server-authenticated source exists; + operation traces identify a code path, not the client that invoked it. + """ + rows = await self.ch.query_all( + """ + SELECT judgement, provenance, count() AS n + FROM ( + SELECT + multiIf( + e.embedding_model = '', 'cosine_only', + e.conflict_checked_at < toDateTime(2, 'UTC') + AND (toUnixTimestamp(e.conflict_checked_at) = 1 + OR (toUnixTimestamp(e.conflict_checked_at) = 0 + AND m.created_at < now() - INTERVAL 60 SECOND)), + 'pending_judgement', + toUnixTimestamp(e.conflict_checked_at) = 2, 'resolver_judged', + 'cosine_only' + ) AS judgement, + multiIf( + m.capture_origin IN ('claude-code', 'codex'), 'plugin_captured', + m.source_class = 'asserted' AND startsWith(m.actor, 'human:'), + 'caller_written', + 'unknown' + ) AS provenance + FROM ( + SELECT org, namespace, agent, user_id, session_id, memory_key, version, + created_at, source_class, actor, capture_origin + FROM loom.memory FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND status = 'conflicted' AND tombstoned_at IS NULL + ) AS m + LEFT JOIN ( + SELECT org, namespace, agent, user_id, session_id, memory_key, version, + max(conflict_checked_at) AS conflict_checked_at, + any(embedding_model) AS embedding_model + FROM loom.memory_embeddings FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND scope = 'private' AND status = 'conflicted' + GROUP BY org, namespace, agent, user_id, session_id, memory_key, version + ) AS e + USING (org, namespace, agent, user_id, session_id, memory_key, version) + ) + GROUP BY judgement, provenance + """, + params={"org": self.params["org"], "ns": self.params["ns"]}, + ) + result = { + state: {source: 0 for source in ("plugin_captured", "caller_written", "unknown")} + for state in ("pending_judgement", "resolver_judged", "cosine_only") + } + for row in rows: + state, source = str(row.get("judgement") or ""), str(row.get("provenance") or "") + if state in result and source in result[state]: + result[state][source] = int(row.get("n") or 0) + return result + async def live_documents(self) -> int: r = await self._one( f"SELECT count() AS n FROM loom.documents WHERE {_SCOPE} AND superseded_at IS NULL" diff --git a/server/memory/api/models_conflicts.py b/server/memory/api/models_conflicts.py index d6ed65eb73a..9c22b4e8098 100644 --- a/server/memory/api/models_conflicts.py +++ b/server/memory/api/models_conflicts.py @@ -55,6 +55,24 @@ class _ConflictRow(ProjectedRow): content_sha256: str = "" # "" for a high row # Sensitivity tier ('' | low | medium | high); a high row comes without its value. sensitivity: str = "" + # Server-stamped capture provenance; blank means caller-written or legacy/unknown. + capture_origin: str = "" + + +class ConflictSourceCounts(BaseModel): + """Conflicted row counts for one resolver state, not pair counts.""" + + plugin_captured: int = 0 + caller_written: int = 0 + unknown: int = 0 + + +class ConflictBacklog(BaseModel): + """Conflicted rows split by resolver state and conservative provenance.""" + + pending_judgement: ConflictSourceCounts = Field(default_factory=ConflictSourceCounts) + resolver_judged: ConflictSourceCounts = Field(default_factory=ConflictSourceCounts) + cosine_only: ConflictSourceCounts = Field(default_factory=ConflictSourceCounts) class ConflictsListOutput(BaseModel): @@ -67,6 +85,8 @@ class ConflictsListOutput(BaseModel): total: int | None = None # The pending proposals in the same scope, from the same read; set on a count_only call. proposals: int | None = None + # Row-based backlog split, present on `count_only`; reciprocal links are not pairs. + backlog: ConflictBacklog | None = None # The conflicted memory keys of the namespace; set on a keys_only call. keys: list[str] | None = None @@ -107,6 +127,39 @@ class ConflictsResolveOutput(BaseModel): total: int | None = None +class ConflictsResolverAcceptItem(BaseModel): + # The row the resolver judged (the suggested winner) and its current peer. + memory_id: str + peer_id: str + # Current revisions observed with the resolver suggestion. + memory_sha256: str = Field(min_length=64, max_length=64) + peer_sha256: str = Field(min_length=64, max_length=64) + # The hash of the resolver audit row that supplied the suggestion. + suggestion_hash: str = Field(min_length=64, max_length=64) + + +class ConflictsBulkAcceptInput(BaseModel): + org: str + namespace: str + # Bounded so a request cannot monopolize the resolver or audit store. + items: list[ConflictsResolverAcceptItem] = Field(min_length=1, max_length=100) + + +class _ConflictBulkResult(BaseModel): + memory_id: str + peer_id: str + status: Literal["resolved", "stale", "failed"] + reason: str = "" + + +class ConflictsBulkAcceptOutput(BaseModel): + results: list[_ConflictBulkResult] + requested: int + resolved: int + stale: int + failed: int + + class ConflictsProposeRevisionInput(BaseModel): org: str namespace: str diff --git a/server/memory/api/models_crud.py b/server/memory/api/models_crud.py index 20f81d0ccce..125377f76d2 100644 --- a/server/memory/api/models_crud.py +++ b/server/memory/api/models_crud.py @@ -679,6 +679,10 @@ class MemoryAutoRetirement(BaseModel): judge_confidence: float | None = None judge_model: str = "" judge_prompt_version: str = "" + # Captured-memory settlement metadata; empty on other automatic paths. + applied_policy: str = "" + winner_capture_origin: str = "" + retired_capture_origin: str = "" class MemoryAutoRetirementsOutput(BaseModel): diff --git a/server/memory/api/ops_conflicts.py b/server/memory/api/ops_conflicts.py index 15d33fc7cd8..e199d01b1c7 100644 --- a/server/memory/api/ops_conflicts.py +++ b/server/memory/api/ops_conflicts.py @@ -7,6 +7,8 @@ ConflictsAllowlistListOutput, ConflictsAllowlistRemoveInput, ConflictsAllowlistRemoveOutput, + ConflictsBulkAcceptInput, + ConflictsBulkAcceptOutput, ConflictsListInput, ConflictsListOutput, ConflictsProposeRevisionInput, @@ -17,6 +19,7 @@ from server.memory.app.conflicts_ops import ( handle_conflicts_allowlist_list, handle_conflicts_allowlist_remove, + handle_conflicts_bulk_accept, handle_conflicts_list, handle_conflicts_propose_revision, handle_conflicts_resolve, @@ -43,6 +46,17 @@ audit=True, ) +conflicts_bulk_accept = Operation( + name="conflicts.bulk_accept", + maturity="experimental", + input_model=ConflictsBulkAcceptInput, + output_model=ConflictsBulkAcceptOutput, + handler=handle_conflicts_bulk_accept, + idempotent=True, + required_role=Role.ADMIN, + audit=True, +) + conflicts_propose_revision = Operation( name="conflicts.propose_revision", @@ -83,6 +97,7 @@ conflicts_list, conflicts_propose_revision, conflicts_resolve, + conflicts_bulk_accept, conflicts_allowlist_list, conflicts_allowlist_remove, ] diff --git a/server/memory/app/auto_resolution.py b/server/memory/app/auto_resolution.py index 0d6fa7d25d4..8b547310b86 100644 --- a/server/memory/app/auto_resolution.py +++ b/server/memory/app/auto_resolution.py @@ -65,6 +65,9 @@ "judge_confidence", "judge_model", "judge_prompt_version", + "applied_policy", + "winner_capture_origin", + "retired_capture_origin", ) diff --git a/server/memory/app/bulk_rows.py b/server/memory/app/bulk_rows.py index f53128b95ac..da97b2c2fe5 100644 --- a/server/memory/app/bulk_rows.py +++ b/server/memory/app/bulk_rows.py @@ -30,7 +30,11 @@ from server.memory.app.projections import ( resolved_entity_list, ) -from server.memory.app.provenance import writer_actor +from server.memory.app.provenance import ( + capture_origin_for_write, + revision_capture_origin, + writer_actor, +) from server.memory.app.sensitivity_level import decoded_text, resolve_level from server.memory.app.set_commit import count_attribute_tags, set_next from server.memory.domain import lock as _lock @@ -287,7 +291,7 @@ def _bulk_carried(state: _BulkWriteState, memory_key: str) -> dict[str, Any]: def _full_version_row( - state: _BulkWriteState, memory_row: dict[str, Any], now: datetime + state: _BulkWriteState, memory_row: dict[str, Any], now: datetime, capture_origin: str ) -> dict[str, Any]: """Every row carries every column (one insert, one column list): a revision carries the live row forward (`build_revision_row`), a first write takes the @@ -296,8 +300,16 @@ def _full_version_row( live = state.existing_rows.get(str(memory_row["memory_key"])) if live is not None: - return memory_repo.build_revision_row(live, memory_row) - return memory_repo.build_first_version_row(memory_row, now=now) + return memory_repo.build_revision_row( + live, + memory_row, + capture_origin=revision_capture_origin( + str(live.content_sha256 or ""), + str(memory_row.get("content_sha256") or ""), + origin=capture_origin, + ), + ) + return memory_repo.build_first_version_row(memory_row, now=now, capture_origin=capture_origin) def _bulk_locked(state: _BulkWriteState, memory_key: str, action: _lock.LockAction) -> bool: @@ -746,6 +758,7 @@ async def _bulk_build_rows( item per kept entry to `state`.""" now_utc = state.now_utc + capture_origin = await capture_origin_for_write() read = 0 # characters the sensitivity detector read for the entries before this one for entry in input.entries: if entry.memory_key in state.unchecked_keys: @@ -890,7 +903,9 @@ async def _bulk_build_rows( "on_expire": entry_on_expire, "updated_at": now_utc.replace(tzinfo=None), } - memory_row = _full_version_row(state, memory_row, now_utc.replace(tzinfo=None)) + memory_row = _full_version_row( + state, memory_row, now_utc.replace(tzinfo=None), capture_origin + ) # created vs updated, decided per row rather than labelling the whole batch # "created". Only byte-identical restatements are diverted by the skip-gate above; an # entry whose key already exists with DIFFERENT content is inserted as a new version, diff --git a/server/memory/app/conflict_resolver.py b/server/memory/app/conflict_resolver.py index 5b81f810acd..8eb28c8a42d 100644 --- a/server/memory/app/conflict_resolver.py +++ b/server/memory/app/conflict_resolver.py @@ -474,10 +474,26 @@ async def _settle_pair( """Act on one pair after re-reading both rows; what was done ({"action": ...}, for the audit row) when something changed, else None. A key another write holds past the lock's wait raises PreconditionFailedError.""" - async with _pair_locks(org, namespace, row, peer): - taken, retired = await _settle_locked_pair( - org, namespace, row, peer, action, counts, why=why - ) + from server.auth.grant_claims import account_change + from server.core.ch import get_client + from server.memory.store import conflicts as conflicts_repo + + # Namespace settings and the final row retirement share the registry claim. + # A settings edit that lands during the judge call therefore wins this fence. + async with account_change(org, namespace): + current = await conflicts_repo.namespace_write_row(org, namespace, ch=get_client()) + settled_why = dict(why) | { + "captured_conflict_policy": str( + current.get("captured_conflict_policy") or "manual_review" + ), + "captured_conflict_confidence": str( + current.get("captured_conflict_confidence") or 0.98 + ), + } + async with _pair_locks(org, namespace, row, peer): + taken, retired = await _settle_locked_pair( + org, namespace, row, peer, action, counts, why=settled_why + ) if retired is not None: await _after_retire(org, namespace, retired) return taken @@ -522,6 +538,38 @@ async def _settle_locked_pair( str(head.memory_id) in row.conflict_with or str(row.memory_id) in head.conflict_with ): return None, None # nothing flagged between them: nothing to clear + captured_update = bool( + action in (cr.FLAG, cr.RETIRE) + and cr.captured_update_eligible( + policy=why.get("captured_conflict_policy", ""), + verdict=why.get("judge_verdict", ""), + confidence=float(why.get("judge_confidence", "0")), + threshold=float(why.get("captured_conflict_confidence", "1")), + same_entity=why.get("judge_same_entity") == "true", + same_attribute=why.get("judge_same_attribute") == "true", + winner_origin=str(getattr(row, "capture_origin", "")), + retired_origin=str(getattr(head, "capture_origin", "")), + winner_agent=str(row.agent), + retired_agent=str(head.agent), + winner_user_id=str(row.user_id), + retired_user_id=str(head.user_id), + cross_session=_cross_session( + row, + {"agent": str(head.agent), "session_id": str(head.session_id)}, + ), + ) + ) + if captured_update: + action = cr.RETIRE + why = dict(why) | { + "applied_policy": "captured_resolver_update", + "winner_capture_origin": str(getattr(row, "capture_origin", "")), + "retired_capture_origin": str(getattr(head, "capture_origin", "")), + } + elif action == cr.RETIRE and (_capture_origin(row) or _capture_origin(head)): + # A captured row never auto-settles against a human or unknown row, and + # the owner’s manual-review setting overrides the general namespace policy. + action = cr.FLAG if action in (cr.RETIRE, cr.FLAG): # Read under the locks: a valid_at corrected during the call moves the order. # If this read fails the row stays unstamped and the next pass judges it again @@ -558,6 +606,9 @@ async def _settle_locked_pair( else: counts.cleared += 1 taken: dict[str, Any] = {"action": action} + if captured_update and action == cr.RETIRE: + taken["applied_policy"] = "captured_resolver_update" + taken["retired_capture_origin"] = str(getattr(head, "capture_origin", "")) if outranked: taken["reason"] = await _record_outranked(org, namespace, row, head) if action == cr.RETIRE and str(head.memory_id) in row.conflict_with: @@ -567,6 +618,10 @@ async def _settle_locked_pair( return taken, retired +def _capture_origin(row: Any) -> str: + return str(getattr(row, "capture_origin", "") or "") + + async def _outranked(org: str, namespace: str, row: Any, peer: Any) -> bool: """Whether `peer`'s standing is above the judged row's, which would retire it (`server.memory.domain.standing`).""" @@ -654,6 +709,8 @@ async def resolve_row( policy: str, counts: Counts, shown: frozenset[str] = frozenset(), + captured_policy: str = "manual_review", + captured_confidence: float = 0.98, ) -> frozenset[str] | None: """Judge one queue row, act on its pairs and stamp it judged; a provider failure raises and the row stays owed. Returns None once stamped (or skipped), else the ids @@ -699,7 +756,16 @@ async def resolve_row( if peers: row, peers = await _still_unprotected(org, row, peers) if row is not None and peers: - unanswered = await _judge_and_act(org, namespace, row, peers, policy=policy, counts=counts) + unanswered = await _judge_and_act( + org, + namespace, + row, + peers, + policy=policy, + counts=counts, + captured_policy=captured_policy, + captured_confidence=captured_confidence, + ) judged_ids = frozenset(str(p["memory_id"]) for p in peers) if unanswered & {str(x) for x in row.conflict_with} or cluster.flags_left: # A flagged peer the answer left out, or one past the cluster's places: stamped, @@ -817,6 +883,8 @@ async def _judge_and_act( *, policy: str, counts: Counts, + captured_policy: str = "manual_review", + captured_confidence: float = 0.98, ) -> set[str]: """Judge the row and act on the answer; the ids of the peers it gave no verdict.""" found = await _assertion_order(org, namespace, [row, *peers]) @@ -837,7 +905,20 @@ async def _judge_and_act( verdicts, model = await judge(new, notes) counts.judged += 1 acting = asyncio.ensure_future( - _act_on_verdicts(org, namespace, row, peers, verdicts, policy, counts, model, new, notes) + _act_on_verdicts( + org, + namespace, + row, + peers, + verdicts, + policy, + counts, + model, + new, + notes, + captured_policy=captured_policy, + captured_confidence=captured_confidence, + ) ) try: await asyncio.shield(acting) @@ -868,6 +949,9 @@ async def _act_on_verdicts( model: str, new: cr.Note, notes: list[cr.Note], + *, + captured_policy: str = "manual_review", + captured_confidence: float = 0.98, ) -> None: """Settle each pair the answer acts on, then one audit row for the row, written even when a later pair fails, for the pairs done. `new` and `notes`: the row and its @@ -885,6 +969,19 @@ async def _act_on_verdicts( if v is None else _action(v, policy, cross_session=cross, same_written=same) ) + if ( + v is not None + and captured_policy == "resolver_update" + and v.verdict == cr.UPDATE + and v.same_entity + and v.same_attribute + and v.confidence >= captured_confidence + and action == cr.NOTHING + and not cross + ): + # The owner lowered the floor; the locked re-read must still + # prove that both rows carry trusted capture provenance. + action = cr.FLAG if v is None or action == cr.NOTHING: # Unsure, self-contradicting, or a peer the answer left out: the pair # stays as it is. @@ -893,14 +990,26 @@ async def _act_on_verdicts( why = { "judge_verdict": v.verdict, "judge_confidence": str(v.confidence), + "judge_same_entity": str(v.same_entity).lower(), + "judge_same_attribute": str(v.same_attribute).lower(), "judge_model": model, "judge_prompt_version": cr.PROMPT_VERSION, + "captured_conflict_policy": captured_policy, + "captured_conflict_confidence": str(captured_confidence), + "captured_origin": str(getattr(row, "capture_origin", "") or ""), } taken = await _settle_pair(org, namespace, row, peer, action, counts, why=why) if taken is not None: acted.append( {"peer_id": str(peer["memory_id"]), **taken} - | {"verdict": v.verdict, "confidence": v.confidence} + | { + "verdict": v.verdict, + "confidence": v.confidence, + "same_entity": v.same_entity, + "same_attribute": v.same_attribute, + "memory_sha256": str(row.content_sha256 or ""), + "peer_sha256": str(peer.get("content_sha256") or ""), + } ) except BaseException: # The pairs done still get their audit row, and the error raised is the one that diff --git a/server/memory/app/conflicts.py b/server/memory/app/conflicts.py index 0e498e9a264..74fabb70580 100644 --- a/server/memory/app/conflicts.py +++ b/server/memory/app/conflicts.py @@ -357,7 +357,7 @@ async def _peer_rows_joined( """ SELECT m.memory_id, m.memory_key, m.value, m.pinned, - m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, + m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, m.capture_origin, """ + "cosineDistance(e.embedding, {emb:Array(Float32)})" + """ AS dist @@ -469,6 +469,7 @@ def _peer_of(r: dict[str, Any]) -> ConflictPeer: value=str(r.get("value") or ""), run_id=str(r.get("run_id") or "-"), valid_at=_as_datetime(r.get("valid_at")), + capture_origin=str(r.get("capture_origin") or ""), ) @@ -505,6 +506,10 @@ async def _substitution_verdict( policy = "" if policy != "newest_wins": return None + from server.memory.app.provenance import capture_origin + + if capture_origin() or any(peer.capture_origin for peer in subst): + return ConflictResult(verdict="conflict", peers=peers, review=True) return substitution_result(subst, peers, new_valid_at=new_valid_at) diff --git a/server/memory/app/conflicts_ops.py b/server/memory/app/conflicts_ops.py index 91d4a060185..e221f916f91 100644 --- a/server/memory/app/conflicts_ops.py +++ b/server/memory/app/conflicts_ops.py @@ -2,12 +2,14 @@ from __future__ import annotations +import asyncio import itertools import logging import time -from contextlib import nullcontext +from collections.abc import Mapping +from contextlib import AsyncExitStack, nullcontext from datetime import datetime -from typing import Any +from typing import Any, Literal from server.core.ch import sequential_reads from server.core.datetimes import naive_utc_now @@ -15,10 +17,13 @@ from server.identity.app.request_scope import request_scope from server.identity.domain.read_scope import WHOLE_NAMESPACE, ReadFilters, scope_and from server.memory.api.models_conflicts import ( + ConflictBacklog, ConflictsAllowlistListInput, ConflictsAllowlistListOutput, ConflictsAllowlistRemoveInput, ConflictsAllowlistRemoveOutput, + ConflictsBulkAcceptInput, + ConflictsBulkAcceptOutput, ConflictsListInput, ConflictsListOutput, ConflictsProposeRevisionInput, @@ -26,6 +31,7 @@ ConflictsResolveInput, ConflictsResolveOutput, _AllowlistRow, + _ConflictBulkResult, _ConflictCandidateMemory, _ConflictRevisionSuggestion, _ConflictRow, @@ -39,7 +45,9 @@ # Each count read takes the next ticket when it starts; a cached entry keeps its read's ticket. _count_tickets = itertools.count(1) -_count_cache: dict[tuple[str, str, ReadFilters], tuple[float, int, tuple[int, int]]] = {} +_count_cache: dict[ + tuple[str, str, ReadFilters], tuple[float, int, tuple[int, int, dict[str, dict[str, int]]]] +] = {} # A read whose ticket is at or below its namespace's drop, or the last full reset, caches nothing. _counts_dropped_at: dict[tuple[str, str], int] = {} _counts_reset_at = 0 @@ -65,10 +73,8 @@ def forget_review_counts(org: str, namespace: str) -> None: async def _review_counts_cached( repo: Any, org: str, namespace: str, scope: ReadFilters, *, fresh: bool = False -) -> tuple[int, int]: - """The conflicted and pending counts, from this replica's cache unless `fresh`. A fresh - count reads with sequential consistency, so a replica that has yet to apply a decision - cannot serve it, and refreshes the cache.""" +) -> tuple[int, int, dict[str, dict[str, int]]]: + """Review counts and the row backlog split, cached together per read scope.""" key = (org, namespace, scope) hit = _count_cache.get(key) now = time.monotonic() @@ -77,7 +83,8 @@ async def _review_counts_cached( ticket = next(_count_tickets) with sequential_reads() if fresh else nullcontext(): conflicted, proposed = await repo.count_review(org, namespace, scope=scope) - counts = (int(conflicted), int(proposed)) + backlog = await repo.count_conflict_backlog(org, namespace, scope=scope) + counts = (int(conflicted), int(proposed), backlog) hit = _count_cache.get(key) dropped = max(_counts_reset_at, _counts_dropped_at.get((org, namespace), 0)) if ticket <= dropped or (hit is not None and hit[1] > ticket): @@ -104,10 +111,15 @@ async def handle_conflicts_list( # (org, namespace) per `memory_conflicts_count_ttl_s` serves them all, and the count # reads no value column — reading the rows costs ~33 MB per tick on a large namespace. # The same read counts the pending proposals, so the Review queue badge is one request. - total, proposals = await _review_counts_cached( + total, proposals, backlog = await _review_counts_cached( conflicts_repo, input.org, input.namespace, scope, fresh=input.fresh ) - return ConflictsListOutput(rows=[], total=total, proposals=proposals) + return ConflictsListOutput( + rows=[], + total=total, + proposals=proposals, + backlog=ConflictBacklog.model_validate(backlog), + ) rows = await conflicts_repo.list_conflicted( input.org, input.namespace, @@ -130,6 +142,7 @@ async def handle_conflicts_list( conflict_with=[str(p) for p in r["conflict_with"]], content_sha256=_sha256(r["value"]) if r["value"] else "", sensitivity=r["sensitivity"], + capture_origin=str(r.get("capture_origin") or ""), ) for r in rows ] @@ -293,6 +306,9 @@ async def live(memory_id: str) -> bool: async def handle_conflicts_resolve( input: ConflictsResolveInput, + *, + expected_sha256: dict[str, str] | None = None, + write_fence_locked: set[str] | None = None, ) -> ConflictsResolveOutput: """Three decision paths: @@ -323,6 +339,8 @@ async def handle_conflicts_resolve( peers = await _live_peers(input, [input.peer_id] if input.peer_id else all_peers) if peers is None: return unresolved + if expected_sha256 is not None and not set(expected_sha256).issubset({input.memory_id, *peers}): + return unresolved affected: list[str] = [] # The tombstones are announced as soon as they are in, before the kept side's status @@ -330,9 +348,25 @@ async def handle_conflicts_resolve( # resolve keeps live change only their status, as on memory.verify: no event. ns = input.namespace if input.decision == "revise": + + def skip_locked(row: Any) -> bool: + locked = expected_sha256 is not None and _bulk_loser_is_locked(row, input.memory_id) + if locked and write_fence_locked is not None: + write_fence_locked.add(str(row.memory_id)) + return locked + tombstoned = await conflicts_repo.tombstone_ids( - input.org, peers, audit_note, now, namespace=ns + input.org, + peers, + audit_note, + now, + namespace=ns, + expected_sha256=expected_sha256, + skip=skip_locked if expected_sha256 is not None else None, ) + expected_peers = set(expected_sha256 or {}) & set(peers) + if expected_sha256 is not None and len(tombstoned) != len(expected_peers): + return unresolved await webhooks.announce([("memory.tombstoned", row) for row in tombstoned]) affected.extend(peers) await conflicts_repo.mark_active_by_ids(input.org, [input.memory_id], namespace=ns) @@ -361,7 +395,7 @@ async def handle_conflicts_resolve( total: int | None = None try: # fresh reads with sequential consistency, so the count sees the writes above - total, _ = await _review_counts_cached( + total, _, _ = await _review_counts_cached( conflicts_repo, input.org, input.namespace, request_scope(), fresh=True ) except Exception as e: # noqa: BLE001 — the count never fails an applied resolve @@ -376,6 +410,263 @@ async def handle_conflicts_resolve( ) +async def handle_conflicts_bulk_accept( + input: ConflictsBulkAcceptInput, +) -> ConflictsBulkAcceptOutput: + """Accept current hash-only resolver update suggestions independently. + + The transport requires ADMIN and authorizes the named namespace. Each item is + checked against the latest pair judgement, current row hashes, flags, pins and Undo + records before delegating the actual state change to the existing resolve handler. + """ + results: list[_ConflictBulkResult] = [] + grouped: dict[tuple[str, str], list[Any]] = {} + for item in input.items: + pair = ( + (item.memory_id, item.peer_id) + if item.memory_id < item.peer_id + else (item.peer_id, item.memory_id) + ) + grouped.setdefault(pair, []).append(item) + selected: dict[tuple[str, str], Any] = {} + from server.memory.store import conflicts as conflicts_repo + + for pair, items in grouped.items(): + event = await conflicts_repo.latest_resolver_pair_audit( + input.org, input.namespace, pair[0], pair[1] + ) + direction = "" + if event is not None: + import json + + direction = str(json.loads(str(event.get("subject") or "{}")).get("memory_id") or "") + selected[pair] = next((item for item in items if item.memory_id == direction), items[0]) + seen: set[tuple[str, str]] = set() + for item in input.items: + pair = ( + (item.memory_id, item.peer_id) + if item.memory_id < item.peer_id + else (item.peer_id, item.memory_id) + ) + if not _bulk_item_selected(pair, item, selected, seen): + results.append(_bulk_accept_result(item, "failed", "Duplicate item")) + continue + try: + results.append(await _accept_bulk_item(input, item)) + except Exception as e: # noqa: BLE001 — one item failure must not stop independent selections + from server.memory.store.pg_memory import AdmissionContendedError + + if isinstance(e, AdmissionContendedError): + results.append( + _bulk_accept_result(item, "stale", "A memory changed during acceptance") + ) + continue + log.warning("conflicts.bulk_accept: item failed for %s: %s", item.memory_id, e) + results.append(_bulk_accept_result(item, "failed", "Item could not be resolved")) + return ConflictsBulkAcceptOutput( + results=results, + requested=len(results), + resolved=sum(r.status == "resolved" for r in results), + stale=sum(r.status == "stale" for r in results), + failed=sum(r.status == "failed" for r in results), + ) + + +def _bulk_accept_result( + item: Any, status: Literal["resolved", "stale", "failed"], reason: str = "" +) -> _ConflictBulkResult: + return _ConflictBulkResult( + memory_id=item.memory_id, peer_id=item.peer_id, status=status, reason=reason + ) + + +async def _accept_bulk_item(input: ConflictsBulkAcceptInput, item: Any) -> _ConflictBulkResult: + from server.memory.app.provenance import writer_actor + from server.observability import audit + + stale_reason = await _bulk_suggestion_stale_reason(input, item) + if stale_reason: + return _bulk_accept_result(item, "stale", stale_reason) + applied = await _resolve_current_bulk_pair(input, item) + if isinstance(applied, _ConflictBulkResult): + return applied + if not applied.resolved: + return _bulk_accept_result(item, "stale", "Conflict is no longer open") + await audit.emit( + "memory.conflict_suggestion_accepted", + org=input.org, + namespace=input.namespace, + actor=writer_actor("process:loom"), + subject={ + "memory_id": item.memory_id, + "peer_id": item.peer_id, + "memory_sha256": item.memory_sha256, + "peer_sha256": item.peer_sha256, + "suggestion_hash": item.suggestion_hash, + "decision": "revise", + }, + ) + return _bulk_accept_result(item, "resolved") + + +async def _bulk_suggestion_stale_reason(input: ConflictsBulkAcceptInput, item: Any) -> str | None: + import json + + from server.memory.store import conflicts as conflicts_repo + from server.observability import audit + + event = await conflicts_repo.latest_resolver_pair_audit( + input.org, input.namespace, item.memory_id, item.peer_id + ) + stored_hash = event.get("row_hash", "") if event else "" + if isinstance(stored_hash, bytes): + stored_hash = stored_hash.decode("utf-8") + if event is None or str(stored_hash).rstrip("\x00") != item.suggestion_hash: + return "Resolver suggestion changed" + if not audit.row_matches_hash(event): + return "Resolver audit record failed verification" + subject = json.loads(str(event["subject"])) + pair_record = ( + next( + (p for p in subject.get("pairs", []) if str(p.get("peer_id")) == item.peer_id), + None, + ) + if str(subject.get("memory_id")) == item.memory_id + else None + ) + eligible = bool( + pair_record + and pair_record.get("action") == "flag" + and pair_record.get("verdict") == "update" + and pair_record.get("same_entity") is True + and pair_record.get("same_attribute") is True + and str(subject.get("content_sha256") or "") == item.memory_sha256 + and str(pair_record.get("memory_sha256") or "") == item.memory_sha256 + and str(pair_record.get("peer_sha256") or "") == item.peer_sha256 + ) + return None if eligible else "Suggestion is not an eligible update" + + +async def _resolve_current_bulk_pair( + input: ConflictsBulkAcceptInput, item: Any +) -> ConflictsResolveOutput | _ConflictBulkResult: + import server.memory.store as memory_repo + from server.memory.app import conflict_resolver as resolver + from server.memory.app.provenance import writer_actor + from server.memory.store import conflict_resolver as resolver_queue + from server.memory.store.key_write_lock import key_write_locks, lock_name + + rows = await _bulk_memory_pair(memory_repo, input, item) + winner, loser = rows + if winner is None or loser is None or winner.tombstoned_at or loser.tombstoned_at: + return _bulk_accept_result(item, "stale", "A memory is no longer live") + names = sorted( + {resolver_queue.key_identity(winner), resolver_queue.key_identity(loser)}, + key=lambda key: lock_name(input.org, input.namespace, *key), + ) + async with AsyncExitStack() as stack: + for identity in names: + await stack.enter_async_context( + key_write_locks.hold(input.org, input.namespace, *identity) + ) + winner, loser = await _bulk_memory_pair(memory_repo, input, item) + if not _bulk_pair_is_current(winner, loser, item): + return _bulk_accept_result(item, "stale", "Memory revision or conflict changed") + if _bulk_pair_is_protected(winner, loser): + return _bulk_accept_result(item, "failed", "A memory is protected from bulk acceptance") + order = await resolver._assertion_order(input.org, input.namespace, [winner, loser]) + if resolver._undone(winner, loser, order.when, order.undos): + return _bulk_accept_result(item, "failed", "An Undo or erasure protects this pair") + if await resolver_queue.under_erasure(input.org): + return _bulk_accept_result(item, "failed", "An Undo or erasure protects this pair") + write_fence_locked: set[str] = set() + resolved = await handle_conflicts_resolve( + ConflictsResolveInput( + org=input.org, + namespace=input.namespace, + memory_id=item.memory_id, + peer_id=item.peer_id, + decision="revise", + reason="resolver suggestion accepted", + resolved_by=writer_actor(), + ), + expected_sha256={ + item.memory_id: item.memory_sha256, + item.peer_id: item.peer_sha256, + }, + write_fence_locked=write_fence_locked, + ) + if write_fence_locked: + return _bulk_accept_result( + item, + "failed", + "A memory lock protects this pair from bulk acceptance", + ) + return resolved + + +async def _bulk_memory_pair( + repo: Any, input: ConflictsBulkAcceptInput, item: Any +) -> tuple[Any, Any]: + return await asyncio.gather( + repo.get_by_id( + item.memory_id, + org=input.org, + namespace=input.namespace, + scope=WHOLE_NAMESPACE, + fresh=True, + strong=True, + ), + repo.get_by_id( + item.peer_id, + org=input.org, + namespace=input.namespace, + scope=WHOLE_NAMESPACE, + fresh=True, + strong=True, + ), + ) + + +def _bulk_pair_is_current(winner: Any, loser: Any, item: Any) -> bool: + return ( + winner is not None + and loser is not None + and str(winner.content_sha256 or "") == item.memory_sha256 + and str(loser.content_sha256 or "") == item.peer_sha256 + and str(winner.status) == "conflicted" + and str(loser.status) == "conflicted" + and item.peer_id in {str(peer) for peer in winner.conflict_with} + and item.memory_id in {str(peer) for peer in loser.conflict_with} + ) + + +def _bulk_pair_is_protected(winner: Any, loser: Any) -> bool: + return any(row.pinned or str(row.sensitivity or "") == "high" for row in (winner, loser)) + + +def _bulk_item_selected( + pair: tuple[str, str], + item: Any, + selected: Mapping[tuple[str, str], Any], + seen: set[tuple[str, str]], +) -> bool: + """Consume a pair only when its latest resolver direction is selected.""" + if pair in seen or selected[pair] is not item: + return False + seen.add(pair) + return True + + +def _bulk_loser_is_locked(row: Any, winner_id: str) -> bool: + """Recheck the losing head's deletion lock at the tombstone write fence.""" + if str(row.memory_id) == winner_id: + return False + from server.memory.domain.lock import refuses_retirement + + return refuses_retirement(row) + + async def _allow_pairs( input: ConflictsResolveInput, peers: list[str], *, now: datetime, by: str, reason: str ) -> None: diff --git a/server/memory/app/observe.py b/server/memory/app/observe.py index dc7d76da2e9..61ca74cfd12 100644 --- a/server/memory/app/observe.py +++ b/server/memory/app/observe.py @@ -34,7 +34,7 @@ ObserveRecordInput, ObserveRecordOutput, ) -from server.memory.app.provenance import writer_actor +from server.memory.app.provenance import capture_origin_for_write, writer_actor from server.memory.domain.observation_tags import ( BLACKLISTED_REASON, BLACKLISTED_TAG, @@ -358,6 +358,7 @@ async def handle_observe_record(input: ObserveRecordInput) -> ObserveRecordOutpu "content_sha256": content_sha, }, now=now_naive, + capture_origin=await capture_origin_for_write(), ) await insert_memory_versions([row], ch=ch) diff --git a/server/memory/app/provenance.py b/server/memory/app/provenance.py index 6ca8f0644b0..f01e78df3fb 100644 --- a/server/memory/app/provenance.py +++ b/server/memory/app/provenance.py @@ -5,9 +5,13 @@ from __future__ import annotations +import logging + from server.memory.domain import trust from server.memory.domain.provenance import pipeline_actor_var +log = logging.getLogger(__name__) + def writer_actor(fallback: str = "") -> str: """The writing principal as `kind:subject`, kind from the token; then the @@ -25,6 +29,63 @@ def writer_actor(fallback: str = "") -> str: return trust.actor_for(subject, is_service_account=bool(auth.is_service_account)) +def capture_origin() -> str: + """The integration origin bound to the verified token; request fields never set it.""" + from server.auth.context import current_auth + + auth = current_auth() + origin = str(getattr(auth, "capture_origin", "") or "") if auth is not None else "" + return origin if origin in {"claude-code", "codex"} else "" + + +async def require_capture_resolver_support() -> None: + """Refuse captured memory writes until every live resolver reports support.""" + from server.core import instances + from server.core.ch import get_client + from server.core.errors import BackendUnavailableError + from server.settings import settings + + if settings.deployment: + try: + live = await instances.read_live(get_client()) + except Exception as e: # unknown ClickHouse state must refuse captured writes + log.warning("captured memory provenance disabled: replica versions unavailable: %s", e) + raise BackendUnavailableError( + "captured memory writes are paused until resolver support is known; retry", + retry_after_s=5, + ) from e + if not live or any( + not str(row.get("instance_id") or "").startswith( + instances.CAPTURED_CONFLICT_PROVENANCE_MARKER + ) + for row in live + ): + raise BackendUnavailableError( + "captured memory writes are paused while an unsupported resolver is live; retry", + retry_after_s=5, + ) + + +async def capture_origin_for_write() -> str: + """Return signed provenance only when each live replica's resolver reports support.""" + origin = capture_origin() + if origin: + await require_capture_resolver_support() + return origin + + +def revision_capture_origin( + existing_sha256: str, new_sha256: str, *, origin: str | None = None +) -> str | None: + """Use the verified writer origin for changed content; maintenance-only copies keep + the row's stored origin through the version builder.""" + return ( + (origin if origin is not None else capture_origin()) + if existing_sha256 != new_sha256 + else None + ) + + def label_actor() -> str: """The principal an agent's usage label (`used`, `evidence`, `harm`) is stamped with: the token's actor, '-' with no auth. Never '', which marks the server's own diff --git a/server/memory/app/set_commit.py b/server/memory/app/set_commit.py index 7b53b9be76f..15c8307d34e 100644 --- a/server/memory/app/set_commit.py +++ b/server/memory/app/set_commit.py @@ -261,6 +261,7 @@ class _SetWrite: writer_actor: str = "" source_class: str = "" memory_row: dict[str, Any] = field(default_factory=dict) + capture_origin: str = "" embedder: Any = None excerpt: str = "" embedding: list[float] = field(default_factory=list) diff --git a/server/memory/app/snapshot_rows.py b/server/memory/app/snapshot_rows.py index 472ead24ed1..7a4719affda 100644 --- a/server/memory/app/snapshot_rows.py +++ b/server/memory/app/snapshot_rows.py @@ -60,6 +60,7 @@ def persisted_columns() -> tuple[str, ...]: "version", "tombstoned_at", "content_sha256", + "capture_origin", } ) @@ -127,6 +128,33 @@ def snapshot_fields(r: Mapping[str, Any], keep: Container[str]) -> dict[str, Any return data +def authenticated_capture_origins(memories: Sequence[Any], origins: Mapping[str, Any]) -> list[Any]: + """Apply only server-recorded capture provenance; restore payload values are untrusted.""" + from server.core.hashing import sha256_value + + def authenticated(memory: Any) -> str: + record = origins.get(str(memory.memory_id)) + if not isinstance(record, Mapping): + return "" + origin = record.get("origin") + digest = sha256_value( + { + "content_sha256": str(memory.content_sha256 or ""), + "value": str(memory.value or ""), + "value_json": str(memory.value_json or "{}"), + } + ) + return ( + str(origin) + if origin in {"claude-code", "codex"} and digest == record.get("row_hash") + else "" + ) + + return [ + memory.model_copy(update={"capture_origin": authenticated(memory)}) for memory in memories + ] + + def restore_rows( memories: Sequence[Any], *, diff --git a/server/memory/app/update.py b/server/memory/app/update.py index 6629aa40c23..5e48c19a39f 100644 --- a/server/memory/app/update.py +++ b/server/memory/app/update.py @@ -1080,6 +1080,17 @@ async def _write_revision( tombstoned_at=None, char_limit=input.char_limit, content_sha256=new_sha, + **( + { + "capture_origin": app_provenance.revision_capture_origin( + str(existing.content_sha256 or ""), + new_sha, + origin=await app_provenance.capture_origin_for_write(), + ) + } + if existing.content_sha256 != new_sha + else {} + ), tags=new_tags, concepts=new_concepts, sensitivity=sensitivity, diff --git a/server/memory/app/write.py b/server/memory/app/write.py index c196414e7bd..79fad6574f5 100644 --- a/server/memory/app/write.py +++ b/server/memory/app/write.py @@ -618,11 +618,21 @@ def _set_build_memory_row(w: _SetWrite) -> None: # from the live row; the builder resets the ones about the old value. import server.memory.store as memory_repo - memory_row = memory_repo.build_revision_row(existing, memory_row) + memory_row = memory_repo.build_revision_row( + existing, + memory_row, + capture_origin=app_provenance.revision_capture_origin( + str(existing.content_sha256 or ""), + str(memory_row.get("content_sha256") or ""), + origin=w.capture_origin, + ), + ) else: import server.memory.store as memory_repo - memory_row = memory_repo.build_first_version_row(memory_row, now=now_naive) + memory_row = memory_repo.build_first_version_row( + memory_row, now=now_naive, capture_origin=w.capture_origin + ) w.memory_id = memory_id w.had_existing_row = had_existing_row w.writer_actor = writer_actor @@ -736,6 +746,7 @@ async def _memory_set_once(input: MemorySetInput, *, embedder: Any = None) -> Me # under Postgres the commit keeps the newer head, a delete's tombstone too. if head is not None: w.version = version_over(head, w.version) + w.capture_origin = await app_provenance.capture_origin_for_write() _set_build_memory_row(w) # Non-searchable type, or a 'high' sensitivity row: single insert is the @@ -784,6 +795,7 @@ async def _memory_set_once(input: MemorySetInput, *, embedder: Any = None) -> Me raise AdmissionContendedError( f"commits to {input.namespace!r} kept changing this write's verdict" ) from None + w.capture_origin = await app_provenance.capture_origin_for_write() _set_build_memory_row(w) # the next verdict stamps a fresh row if conflict_result.verdict == "clear": peers_out = [] # a conflict the mark found no live peer for: none to resolve diff --git a/server/memory/domain/conflict_resolution.py b/server/memory/domain/conflict_resolution.py index e1f143b5432..318d048dd3f 100644 --- a/server/memory/domain/conflict_resolution.py +++ b/server/memory/domain/conflict_resolution.py @@ -321,6 +321,41 @@ def action_for( return CLEAR +def captured_update_eligible( + *, + policy: str, + verdict: str, + confidence: float, + threshold: float, + same_entity: bool, + same_attribute: bool, + winner_origin: str, + retired_origin: str, + winner_agent: str, + retired_agent: str, + winner_user_id: str, + retired_user_id: str, + cross_session: bool, +) -> bool: + """Whether an owner-approved resolver update may settle captured rows. + + All provenance arguments come from the signed capture claim persisted on each + row; caller supplied actor, source_class and source_trace are not evidence. + """ + return ( + policy == "resolver_update" + and verdict == UPDATE + and same_entity + and same_attribute + and confidence >= threshold + and winner_origin in {"claude-code", "codex"} + and retired_origin in {"claude-code", "codex"} + and winner_agent == retired_agent + and winner_user_id == retired_user_id + and not cross_session + ) + + def later_close_siblings(vectors: list[list[float]], types: list[str], floor: float) -> set[int]: """The indexes of a batch's rows that have an EARLIER row of the same type at cosine >= `floor`. The verdicts compare each row with the store only, so an diff --git a/server/memory/domain/conflicts.py b/server/memory/domain/conflicts.py index 2c53ebf043a..ca69de90f49 100644 --- a/server/memory/domain/conflicts.py +++ b/server/memory/domain/conflicts.py @@ -33,6 +33,7 @@ class ConflictPeer: # retires the peer only if this is not later than the new row's own valid_at — # arrival order is the clock only when the calendar cannot tell. valid_at: datetime | None = None + capture_origin: str = "" @dataclass(frozen=True) diff --git a/server/memory/store/conflict_candidates.py b/server/memory/store/conflict_candidates.py index c1eec3ec225..4654bcecad2 100644 --- a/server/memory/store/conflict_candidates.py +++ b/server/memory/store/conflict_candidates.py @@ -50,7 +50,7 @@ def candidate_sql_many(n: int, in_scope: str = "") -> str: SELECT hit.1 - 1 AS qidx, m.memory_id, m.memory_key, m.value, m.pinned, - m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, + m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, m.capture_origin, hit.2 AS dist{_CANDIDATE_JOIN} ARRAY JOIN arrayFilter( x -> x.2 <= {{max_dists:Array(Float32)}}[x.1] @@ -100,7 +100,7 @@ def _peer_candidates_sql(in_scope: str = "") -> str: # Stage B: the candidates' rows, by sort key, with the row filters. _PEER_ROWS_SQL = """ SELECT memory_id, memory_key, value, pinned, - agent, user_id, session_id, run_id, valid_at + agent, user_id, session_id, run_id, valid_at, capture_origin FROM loom.memory FINAL PREWHERE org = {org:String} AND namespace = {ns:String} @@ -134,7 +134,7 @@ def _pinned_row_filter(type_filter: str) -> str: PINNED_PEERS_SQL = f""" SELECT m.memory_id, m.memory_key, m.value, m.pinned, - m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, + m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, m.capture_origin, e.dist AS dist FROM loom.memory m FINAL JOIN ( @@ -176,7 +176,7 @@ def pinned_sql_many(n: int) -> str: SELECT hit.1 - 1 AS qidx, m.memory_id, m.memory_key, m.value, m.pinned, - m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, + m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, m.capture_origin, hit.2 AS dist FROM loom.memory m FINAL JOIN ( diff --git a/server/memory/store/conflicts.py b/server/memory/store/conflicts.py index 80c7da5092c..beb7bb0a2a3 100644 --- a/server/memory/store/conflicts.py +++ b/server/memory/store/conflicts.py @@ -64,7 +64,7 @@ async def list_conflicted( located = await ch.query_all( f""" SELECT memory_id, memory_key, memory_type, version, - pinned, created_at, conflict_with, sensitivity + pinned, created_at, conflict_with, sensitivity, capture_origin FROM loom.memory FINAL WHERE {" AND ".join(where)} ORDER BY version DESC @@ -109,11 +109,42 @@ async def list_conflicted( return out +async def latest_resolver_pair_audit( + org: str, namespace: str, memory_id: str, peer_id: str, *, ch: _CHClient | None = None +) -> dict[str, Any] | None: + """Latest resolver audit row that judged this exact pair in either direction.""" + ch = ch or _default_client() + rows = await ch.query_all( + """ + SELECT ts, event_type, org, namespace, actor, subject, request_id, row_hash + FROM loom.audit_log + WHERE org = {org:String} + AND namespace = {ns:String} + AND event_type = 'memory.conflict_resolver' + AND ( + (JSONExtractString(subject, 'memory_id') = {mid:String} + AND arrayExists(p -> JSONExtractString(p, 'peer_id') = {peer:String}, + JSONExtractArrayRaw(subject, 'pairs'))) + OR + (JSONExtractString(subject, 'memory_id') = {peer:String} + AND arrayExists(p -> JSONExtractString(p, 'peer_id') = {mid:String}, + JSONExtractArrayRaw(subject, 'pairs'))) + ) + ORDER BY ts DESC, row_hash DESC + LIMIT 1 + """, + params={"org": org, "ns": namespace, "mid": memory_id, "peer": peer_id}, + ) + return dict(rows[0]) if rows else None + + async def ids_in_scope( ch: _CHClient, org: str, namespace: str, memory_ids: list[str], scope: ReadFilters ) -> set[str]: """The ids among `memory_ids` whose rows lie inside `scope`. A row's `conflict_with` has no cap, so the ids are bound a slice at a time; no id, no statement.""" + if not memory_ids: + return set() params: dict[str, Any] = {"org": org, "ns": namespace, "ids": sorted(set(memory_ids))} sql = f""" SELECT DISTINCT toString(memory_id) AS mid @@ -153,6 +184,77 @@ async def count_review( return int(row.get("conflicted") or 0), int(row.get("proposed") or 0) +async def count_conflict_backlog( + org: str, + namespace: str, + *, + scope: ReadFilters, + ch: _CHClient | None = None, +) -> dict[str, dict[str, int]]: + """Count conflicted rows by resolver mark and conservative source evidence. + + Counts are rows, not independent pairs: links can be reciprocal and a cluster can + connect more than two rows. Unknown provenance stays visible as its own bucket. + """ + ch = ch or _default_client() + params: dict[str, Any] = {"org": org, "ns": namespace} + scope_filters = "".join(f" AND {part}" for part in scope_where(scope, params)) + rows = await ch.query_all( + f""" + SELECT judgement, provenance, count() AS n + FROM ( + SELECT + multiIf( + e.embedding_model = '', 'cosine_only', + e.conflict_checked_at < toDateTime(2, 'UTC') + AND (toUnixTimestamp(e.conflict_checked_at) = 1 + OR (toUnixTimestamp(e.conflict_checked_at) = 0 + AND m.created_at < now() - INTERVAL 60 SECOND)), + 'pending_judgement', + toUnixTimestamp(e.conflict_checked_at) = 2, 'resolver_judged', + 'cosine_only' + ) AS judgement, + multiIf( + m.capture_origin IN ('claude-code', 'codex'), 'plugin_captured', + m.source_class = 'asserted' AND startsWith(m.actor, 'human:'), + 'caller_written', + 'unknown' + ) AS provenance + FROM ( + SELECT org, namespace, agent, user_id, session_id, memory_key, version, + created_at, source_class, actor, capture_origin + FROM loom.memory FINAL + WHERE org = {{org:String}} AND namespace = {{ns:String}} + AND status = 'conflicted' AND tombstoned_at IS NULL + {scope_filters} + ) AS m + LEFT JOIN ( + SELECT org, namespace, agent, user_id, session_id, memory_key, version, + max(conflict_checked_at) AS conflict_checked_at, + any(embedding_model) AS embedding_model + FROM loom.memory_embeddings FINAL + WHERE org = {{org:String}} AND namespace = {{ns:String}} + AND scope = 'private' AND status = 'conflicted' + GROUP BY org, namespace, agent, user_id, session_id, memory_key, version + ) AS e + USING (org, namespace, agent, user_id, session_id, memory_key, version) + ) + GROUP BY judgement, provenance + """, + params=params, + ) + result = { + judgement: {source: 0 for source in ("plugin_captured", "caller_written", "unknown")} + for judgement in ("pending_judgement", "resolver_judged", "cosine_only") + } + for row in rows: + judgement = str(row.get("judgement") or "") + provenance = str(row.get("provenance") or "") + if judgement in result and provenance in result[judgement]: + result[judgement][provenance] = int(row.get("n") or 0) + return result + + async def conflicted_keys( org: str, namespace: str, @@ -231,6 +333,8 @@ async def tombstone_ids( when: datetime, *, namespace: str, + expected_sha256: dict[str, str] | None = None, + skip: Any = None, ch: _CHClient | None = None, ) -> list[dict[str, Any]]: """Tombstone N rows of `namespace` by memory_id. `audit_note` is appended to @@ -247,6 +351,10 @@ def _note(row: memory_repo.MemoryRow) -> dict[str, Any]: trace = carried_trace(row.source_trace) # the delete_version marker is not carried return {"source_trace": f"{trace} | {audit_note}" if trace else audit_note} + def _unchanged(row: memory_repo.MemoryRow) -> bool: + expected = (expected_sha256 or {}).get(str(row.memory_id)) + return expected is not None and str(row.content_sha256 or "") != expected + # The tombstone must reach memory_embeddings too, or the losing side of a # conflict keeps surfacing in search. return await memory_repo.tombstone_cascade_by_ids( @@ -254,6 +362,16 @@ def _note(row: memory_repo.MemoryRow) -> dict[str, Any]: memory_ids, when=when, update=_note, + skip=( + (lambda row: _unchanged(row) or skip(row)) + if expected_sha256 is not None and skip is not None + else _unchanged + if expected_sha256 is not None + else skip + ), + strong=expected_sha256 is not None, + exact=expected_sha256 is not None, + guard_sha256=expected_sha256, ch=ch, namespace=namespace, ) @@ -407,7 +525,8 @@ async def namespace_write_row( namespace has no row).""" ch = ch or _default_client() row = await ch.query_one( - "SELECT conflict_threshold, duplicate_threshold, default_conflict_policy " + "SELECT conflict_threshold, duplicate_threshold, default_conflict_policy, " + "captured_conflict_policy, captured_conflict_confidence " "FROM loom.namespaces FINAL " "WHERE org = {org:String} AND namespace = {ns:String} LIMIT 1", params={"org": org, "ns": namespace}, @@ -415,6 +534,23 @@ async def namespace_write_row( return dict(row or {}) +async def has_live_captured_rows(org: str, namespace: str, *, ch: _CHClient | None = None) -> bool: + """Whether a namespace holds captured memory that a rollback resolver cannot read.""" + ch = ch or _default_client() + row = await ch.query_one( + """ + SELECT count() AS n + FROM loom.memory FINAL + WHERE org = {org:String} + AND namespace = {ns:String} + AND capture_origin IN ('claude-code', 'codex') + AND tombstoned_at IS NULL + """, + params={"org": org, "ns": namespace}, + ) + return bool(row and int(row.get("n") or 0)) + + async def allowlisted_peers( org: str, namespace: str, memory_key: str, *, ch: _CHClient | None = None ) -> set[str]: diff --git a/server/memory/store/inserts.py b/server/memory/store/inserts.py index bd4ec0d679a..02e81f7ed71 100644 --- a/server/memory/store/inserts.py +++ b/server/memory/store/inserts.py @@ -39,6 +39,7 @@ async def insert_memory_versions( publish_now: bool = True, policy: Mapping[tuple[str, str], int] | None = None, expected_heads: Mapping[IdentityKey, MemoryRow | None] | None = None, + guard_heads: Mapping[IdentityKey, MemoryRow | None] | None = None, on_send: Callable[[], None] | None = None, on_inserted: Callable[[], None] | None = None, refuse_values: bool = False, @@ -61,6 +62,9 @@ async def insert_memory_versions( if pg.enabled() and not published: from server.memory.store import pg_memory, pg_publish + if guard_heads: + raise RuntimeError("guard heads require insert_versions_over_heads") + admission = pg_memory.Admission(generations=dict(policy)) if policy else None try: if publish_now: @@ -80,10 +84,17 @@ async def insert_memory_versions( from server.memory.store import refusals from server.memory.store.write_fence import checked_write + checked_heads = dict(expected_heads or {}) + checked_heads.update(guard_heads or {}) guard = ( refusals.publication(ch, rows, committed=True) if pg.enabled() - else checked_write(rows, expected_heads=expected_heads, ch=ch, refuse_values=refuse_values) + else checked_write( + rows, + expected_heads=checked_heads if expected_heads is not None or guard_heads else None, + ch=ch, + refuse_values=refuse_values, + ) ) async with guard: if on_send is not None: diff --git a/server/memory/store/lifecycle.py b/server/memory/store/lifecycle.py index 0ec2355b051..808af27e709 100644 --- a/server/memory/store/lifecycle.py +++ b/server/memory/store/lifecycle.py @@ -76,13 +76,17 @@ async def write_versions_by_ids( on_unconfirmed: Callable[[list[dict[str, Any]]], Awaitable[None]] | None = None, judged: bool = False, strict: bool = False, + exact: bool = False, + guard_sha256: Mapping[str, str] | None = None, ) -> int: """Write a new version of each live row in `memory_ids`: `update(existing)`'s overrides on every persisted column carried forward, a fresh `version` unless it sets one; an `update` that raises writes nothing, since every row is built before any is written; `skip` and `update` run once every row is read. `namespace`: the rows of that namespace (`reads.get_by_id`). `skip` leaves a row as it is; `strong` - reads read-your-writes, the status mirror's vector rows included. + reads read-your-writes, the status mirror's vector rows included. `guard_sha256` + keeps additional heads at their reviewed hashes through the write fence, without + changing those rows. `on_written` / `on_unconfirmed` hear what the re-read confirmed or could not (see Lifecycle in memory-architecture.md). `judged`: the rows land a verdict reached after the write (the conflict resolver's) on the write it judged @@ -94,10 +98,19 @@ async def write_versions_by_ids( if not memory_ids: return 0 ch = ch or _default_client() - found = await _heads_by_ids(org, namespace, memory_ids, ch=ch, strong=strong) + all_ids = list(dict.fromkeys([*map(str, memory_ids), *(guard_sha256 or {}).keys()])) + found = await _heads_by_ids(org, namespace, all_ids, ch=ch, strong=strong) + by_id = {str(r.memory_id): r for r in found if r is not None} + guard_heads: dict[IdentityKey, MemoryRow] = {} + for memory_id, expected in (guard_sha256 or {}).items(): + head = by_id.get(str(memory_id)) + if head is None or str(head.content_sha256 or "") != expected: + raise pg_memory.AdmissionContendedError("the memory changed while it was read") + guard_heads[identity_key(head)] = head rows: list[dict[str, Any]] = [] sources: list[MemoryRow] = [] - for existing in found: + for memory_id in dict.fromkeys(map(str, memory_ids)): + existing = by_id.get(memory_id) if existing is None or (skip is not None and skip(existing)): continue overrides = dict(update(existing)) @@ -108,7 +121,7 @@ async def write_versions_by_ids( if not rows: return 0 - await insert_versions_over_heads(rows, sources, ch=ch) + await insert_versions_over_heads(rows, sources, ch=ch, exact=exact, guard_heads=guard_heads) confirmed = rows if on_written is not None: # Under Postgres the commit is over each head read (`heads_unchanged(exact=True)`) @@ -317,6 +330,7 @@ async def _insert_clickhouse_copies( on_commit: Callable[[], None] | None, exact: bool, refuse_values: bool, + guard_heads: Mapping[IdentityKey, MemoryRow | None] | None, ) -> int: inserted = not rows count = 0 @@ -335,12 +349,15 @@ async def follow() -> int: try: if rows: expected = ( - {identity_key(r): h for r, h in zip(rows, read, strict=True)} if exact else None + {identity_key(r): h for r, h in zip(rows, read, strict=True)} + if exact or guard_heads + else None ) await insert_memory_versions( rows, ch=ch, expected_heads=expected, + guard_heads=guard_heads, on_inserted=mark_inserted, refuse_values=refuse_values, ) @@ -366,13 +383,15 @@ async def insert_versions_over_heads( on_commit: Callable[[], None] | None = None, exact: bool = False, refuse_values: bool = False, + guard_heads: Mapping[IdentityKey, MemoryRow | None] | None = None, ) -> int: """Write `rows`, each a copy of the authority's head beside it in `read`, drawn above it (`rows.version_over`) or, to yield to a write since, before the read: a copy below the head is overtaken by it. Under Postgres only over that very version, else 503 (`heads_unchanged(exact=True)`): a copy never overwrites a write, a relabel or a redaction it did not see; a key with no head read (None) is held to having no live - head. On ClickHouse, `exact` checks the rows under the same Keeper fences every + head. Guard heads are checked under the same fences or commit locks without being + rewritten. On ClickHouse, `exact` checks the rows under the same Keeper fences every memory insert takes, refusing a moved head with 503 `ADMISSION_CONTENDED`; without it, only the insert is fenced and the source may have moved before the fence. @@ -397,12 +416,15 @@ async def insert_versions_over_heads( on_commit=on_commit, exact=exact, refuse_values=refuse_values, + guard_heads=guard_heads, ) check_memory_rows(rows) heads = {identity_key(r): e for r, e in zip(rows, read, strict=True)} + heads.update(guard_heads or {}) admission = pg_memory.Admission( generations=dict(policy or {}), recheck=pg_memory.heads_unchanged(heads, exact=True), + head_keys=tuple(heads), sources=sources, live_sources=live_sources, ) @@ -1245,6 +1267,8 @@ async def tombstone_cascade_by_ids( namespace: str, skip: Callable[[MemoryRow], bool] | None = None, strong: bool = False, + exact: bool = False, + guard_sha256: Mapping[str, str] | None = None, ) -> list[dict[str, Any]]: """Tombstone rows by memory_id AND mirror the tombstone onto every tier search reads (`strong`: the rows read current, for a `skip` that must see a write @@ -1298,7 +1322,15 @@ def _tombstone(existing: MemoryRow) -> dict[str, Any]: # `write_versions_by_ids` mirrors the tombstone onto memory_embeddings at its version. await write_versions_by_ids( - org, memory_ids, _tombstone, ch=ch, namespace=namespace, skip=skip, strong=strong + org, + memory_ids, + _tombstone, + ch=ch, + namespace=namespace, + skip=skip, + strong=strong, + exact=exact, + guard_sha256=guard_sha256, ) # A decision's record goes with its writer's row, as on memory.delete; under Postgres # the tombstone's publication retires it (`pg_publish.retire_decision_records`). diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index d34cab74458..31e8a40d6ea 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -268,11 +268,13 @@ class Admission: """What a semantic write checked against, rechecked inside its commit. `generations`: each scope's generation the verdict was reached at. `recheck` - is called with each written key and its current head (a decoded row, or None) + is called with each written or guard key and its current head (a decoded row, or None) under the head's row lock, and raises to refuse or restart the write.""" generations: dict[tuple[str, str], int] = field(default_factory=dict) recheck: Callable[[IdentityKey, dict[str, Any] | None], None] | None = None + # Heads read only to authorize another row's write, checked under the same row locks. + head_keys: Sequence[IdentityKey] = () # Called inside the commit, under the namespace's generation lock, with the rows # committed after the captured generation: True when none can change the # verdict, so the commit goes ahead at the new generation. It does no I/O. @@ -725,6 +727,7 @@ async def commit_versions( for t, r in zip(per_row, stored, strict=True) ] per_scope, scopes, heads, keys = _batch_indexes(stored) + check_keys = sorted(set(keys) | set(admission.head_keys if admission is not None else ())) async with pg.transaction() as conn: await _bound_lock_waits(conn) from server.memory.store import refusals @@ -754,14 +757,14 @@ async def commit_versions( # Each written key's head, locked: checked against what the write read, and a row # not embedded over one that was owes its vectors' retirement (`_replaces_vectors`). recheck = admission.recheck if admission is not None else None - locked = await conn.fetch(_LOCK_HEADS, *_key_arrays(keys)) + locked = await conn.fetch(_LOCK_HEADS, *_key_arrays(check_keys)) current = {identity_key(h): decode_row(h["row"]) for h in locked} enforce_review(stored, current) - for k in keys: + for k in check_keys: head = current.get(k) if recheck is not None: recheck(k, head) - if _replaces_vectors(stored[heads[k]], head): + if k in heads and _replaces_vectors(stored[heads[k]], head): per_row[heads[k]] |= OLD_VECTORS if refuse_values: await refusals.record_postgres(conn, stored) diff --git a/server/memory/store/rows.py b/server/memory/store/rows.py index e248f69a74a..e08389686c1 100644 --- a/server/memory/store/rows.py +++ b/server/memory/store/rows.py @@ -165,6 +165,7 @@ class MemoryRow(BaseModel): # observed | derived | imported | external). actor: str = "" source_class: str = "" + capture_origin: str = "" # Write-time lock. '' = unlocked; a past lock_until means # the lock lapsed. Read through # server/memory/domain/lock.effective_mode, never the raw column. @@ -315,6 +316,7 @@ def memory_head_state(row: MemoryRow | None) -> dict[str, Any] | None: "locked_at", "on_expire", "expire_reason", + "capture_origin", ) @@ -340,6 +342,7 @@ def memory_head_state(row: MemoryRow | None) -> dict[str, Any] | None: "locked_by", "on_expire", "expire_reason", + "capture_origin", } ) @@ -481,7 +484,9 @@ def build_memory_version_row( } -def build_revision_row(existing: MemoryRow, new: Mapping[str, Any]) -> dict[str, Any]: +def build_revision_row( + existing: MemoryRow, new: Mapping[str, Any], *, capture_origin: str | None = None +) -> dict[str, Any]: """The version row of a revision: `new` (the columns the write sets) over the live row `existing`, through `build_memory_version_row`, with REVISION_RESETS applied to every column `new` does not set. The @@ -494,6 +499,8 @@ def build_revision_row(existing: MemoryRow, new: Mapping[str, Any]) -> dict[str, if c not in new } overrides.update(new) + if capture_origin is not None: + overrides["capture_origin"] = capture_origin return build_memory_version_row(existing, **overrides) @@ -538,7 +545,9 @@ def build_revision_row(existing: MemoryRow, new: Mapping[str, Any]) -> dict[str, } -def build_first_version_row(new: Mapping[str, Any], *, now: datetime) -> dict[str, Any]: +def build_first_version_row( + new: Mapping[str, Any], *, now: datetime, capture_origin: str = "" +) -> dict[str, Any]: """`new` completed to every persisted column with the DDL defaults of the ones it does not set (FIRST_VERSION_DEFAULTS; `updated_at` and `last_reinforced_at` = `now`).""" @@ -551,6 +560,9 @@ def build_first_version_row(new: Mapping[str, Any], *, now: datetime) -> dict[st row.setdefault("last_reinforced_at", now) row.setdefault("created_at", now) row.update(new) + # The application layer passes this only from the verified token claim. Existing row + # updates use build_memory_version_row, which carries the stored value. + row["capture_origin"] = capture_origin row["requires_review"] = int( bool(row.get("requires_review")) or row.get("status") in {"proposed"} ) @@ -914,6 +926,7 @@ def _hydrate(row: dict[str, Any]) -> MemoryRow: grounding=row.get("grounding", "") or "", actor=row.get("actor", "") or "", source_class=row.get("source_class", "") or "", + capture_origin=row.get("capture_origin", "") or "", evidence=row.get("evidence", "") or "", sensitivity=str(row.get("sensitivity", "") or ""), lock_mode=row.get("lock_mode", "") or "", diff --git a/server/memory/store/sql.py b/server/memory/store/sql.py index 0f2e8aab0eb..912a14b1427 100644 --- a/server/memory/store/sql.py +++ b/server/memory/store/sql.py @@ -49,7 +49,7 @@ sensitivity, actor, source_class, grounding, evidence, lock_mode, lock_reason, lock_until, locked_by, locked_at, - on_expire, expire_reason + on_expire, expire_reason, capture_origin FROM loom.memory FINAL""" diff --git a/server/memory/store/write_fence.py b/server/memory/store/write_fence.py index ced15c7ba25..eef438ff9b1 100644 --- a/server/memory/store/write_fence.py +++ b/server/memory/store/write_fence.py @@ -42,22 +42,25 @@ async def checked_write( A failed send retains its Keeper holders until all admitted inserts expire; an old process cannot send an insert after another holder starts its check. + Extra expected heads are read-only guards fenced and checked with the inserted keys. """ keys = {identity_key(r) for r in rows} - if expected_heads is not None and set(expected_heads) != keys: - raise ValueError("expected heads must name exactly the inserted keys") + if expected_heads is not None and not keys.issubset(expected_heads): + raise ValueError("expected heads must include every inserted key") + fenced_keys = set(expected_heads) if expected_heads is not None else keys from server.memory.store import refusals names = sorted( set( - [lease_name(key) for key in keys] + refusals.fence_names(rows, forgetting=refuse_values) + [lease_name(key) for key in fenced_keys] + + refusals.fence_names(rows, forgetting=refuse_values) ) ) async with lease_writes.fenced_many( names, ch=_lease_client(ch), wait_s=_admission_wait_s() ) as mark: current = await memory_rows_by_identity_keys( - list(keys), ch=ch, sequential=True, include_tombstoned=True + list(fenced_keys), ch=ch, sequential=True, include_tombstoned=True ) enforce_review(rows, current) if expected_heads is not None: diff --git a/server/memory/workers/conflict_resolver.py b/server/memory/workers/conflict_resolver.py index ce1dc14c4c0..5218d9cebda 100644 --- a/server/memory/workers/conflict_resolver.py +++ b/server/memory/workers/conflict_resolver.py @@ -143,7 +143,13 @@ async def _queued(p: _Pass) -> tuple[dict[tuple[str, str], list[dict[str, Any]]] return groups, full -async def _resolve_one(p: _Pass, r: dict[str, Any], policy: str) -> None: +async def _resolve_one( + p: _Pass, + r: dict[str, Any], + policy: str, + captured_policy: str = "manual_review", + captured_confidence: float = 0.98, +) -> None: from server.observability import cost_accumulator from server.observability.budget import namespace_over_cap from server.observability.events import get_emitter @@ -165,7 +171,9 @@ async def _resolve_one(p: _Pass, r: dict[str, Any], policy: str) -> None: if await namespace_over_cap(org, namespace, **_cap_share()): counts.skipped_budget += 1 return - await _judge_row(p, r, org, namespace, policy, counts) + await _judge_row( + p, r, org, namespace, policy, counts, captured_policy, captured_confidence + ) except customer.GROUP_HOLDS as e: _HELD.hold([_identity(r)], hold_seconds(e)) except resolver.PeerBehind: @@ -212,11 +220,20 @@ async def _judge_row( namespace: str, policy: str, counts: resolver.Counts, + captured_policy: str = "manual_review", + captured_confidence: float = 0.98, ) -> None: """Judge one row; a row it leaves owed after a call counts an attempt.""" key = _attempt_key(r) shown = _state.attempts.get(key, (0, frozenset()))[1] - judged = await resolver.resolve_row(r, policy=policy, counts=counts, shown=shown) + judged = await resolver.resolve_row( + r, + policy=policy, + counts=counts, + shown=shown, + captured_policy=captured_policy, + captured_confidence=captured_confidence, + ) _after_row(p, org, namespace, key, counts, judged) if judged is not None and await _out_of_attempts(r, judged): counts.errored += 1 @@ -318,12 +335,15 @@ async def _stamp_refused(p: _Pass) -> None: async def _resolve_all(p: _Pass, groups: dict[tuple[str, str], list[dict[str, Any]]]) -> None: """Every row of the pass, `memory_conflict_resolver_concurrency` at a time.""" from server.core.ch import get_client - from server.memory.app.conflicts import namespace_conflict_policy + from server.memory.store import conflicts as conflicts_repo jobs = [] for (org, namespace), rows in groups.items(): - policy = await namespace_conflict_policy(org, namespace, ch=get_client()) - jobs += [_resolve_one(p, r, policy) for r in rows] + ns = await conflicts_repo.namespace_write_row(org, namespace, ch=get_client()) + policy = str(ns.get("default_conflict_policy") or "auto_reinforce") + captured_policy = str(ns.get("captured_conflict_policy") or "manual_review") + captured_confidence = float(ns.get("captured_conflict_confidence") or 0.98) + jobs += [_resolve_one(p, r, policy, captured_policy, captured_confidence) for r in rows] # A task group: whatever escapes a row cancels the others and waits for them, so # the pass never ends while a row still writes. async with asyncio.TaskGroup() as group: diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index c4b5d478c3c..ed1ca4a9ae2 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -216,8 +216,13 @@ "sdk_method", "dashboard", ), + "conflicts.bulk_accept": ( + "sdk_method", + "dashboard", + ), "conflicts.list": ( "sdk_method", + "plugin_hook", "dashboard", ), "conflicts.propose_revision": ( diff --git a/server/operations/toolsets.py b/server/operations/toolsets.py index f28555960a2..726d84d5922 100644 --- a/server/operations/toolsets.py +++ b/server/operations/toolsets.py @@ -41,6 +41,8 @@ "memory.dedup_collapse", "memory.outcome", "memory.touch", + # Bulk conflict decisions are an administrator UI workflow and stay HTTP-only. + "conflicts.bulk_accept", # Admin-only lifecycle ops: loosening a lock and forcing an expiry # pass are operator actions, not agent ones. "memory.unlock", diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 34860ebcd1a..9a5b83c9c06 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -6587,6 +6587,8 @@ class TrackerSettings(BaseModel): "conflicts.propose_revision": 120, # Fans ALTER UPDATE across all peers. "conflicts.resolve": 500, + # Per-item current-revision and audit checks, bounded to 100 suggestions. + "conflicts.bulk_accept": 5000, "consolidations.list": 200, "context.fetch": 150, "context.offload": 300, diff --git a/tests/integration/test_conflict_resolver_ch.py b/tests/integration/test_conflict_resolver_ch.py index 5d81235b56d..d01c6237348 100644 --- a/tests/integration/test_conflict_resolver_ch.py +++ b/tests/integration/test_conflict_resolver_ch.py @@ -207,11 +207,19 @@ async def _drop_vectors(ch: Any, org: str, namespace: str, key_prefix: str) -> N def _policy(monkeypatch: pytest.MonkeyPatch, name: str) -> None: from server.memory.app import conflicts + from server.memory.store import conflicts as conflicts_repo async def policy(org: str, namespace: str, ch: Any = None) -> str: return name + namespace_row = conflicts_repo.namespace_write_row + + async def write_row(org: str, namespace: str, *, ch: Any = None) -> dict[str, Any]: + row = await namespace_row(org, namespace, ch=ch) + return {**row, "default_conflict_policy": name} + monkeypatch.setattr(conflicts, "namespace_conflict_policy", policy) + monkeypatch.setattr(conflicts_repo, "namespace_write_row", write_row) async def _later() -> None: @@ -603,6 +611,434 @@ async def clear(**kw: Any) -> ConflictResult: await _place(ch, org, "s2", new, _vec((axis, 0.8), (axis + 1, 0.6)), owed=True) +async def test_bulk_accept_uses_current_resolver_audit_and_is_retry_safe(ch: Any) -> None: + import server.memory.store as memory_repo + from server.identity.domain.read_scope import WHOLE_NAMESPACE + from server.memory.api.models_conflicts import ( + ConflictsBulkAcceptInput, + ConflictsResolverAcceptItem, + ) + from server.memory.app import conflicts as conflict_app + from server.memory.app.conflicts_ops import handle_conflicts_bulk_accept + from server.observability import audit + + org = unique_org("resolver-bulk-accept") + await _pair(ch, org, "city_old", "city_new", 150, gap=False) + rows = await _rows(ch, org) + old, new = rows["city_old"], rows["city_new"] + old_row, new_row = await asyncio.gather( + memory_repo.get_by_id( + old["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ), + memory_repo.get_by_id( + new["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ), + ) + assert old_row is not None and new_row is not None + assert ( + await conflict_app.mark_peers_conflicted( + org=org, + namespace=NS, + new_memory_id=new["id"], + peer_ids=[old["id"]], + expected_sha256=str(new_row.content_sha256), + peer_sha256={old["id"]: str(old_row.content_sha256)}, + ) + == "conflict" + ) + suggestion_hash = await audit.emit( + "memory.conflict_resolver", + org=org, + namespace=NS, + actor="process:loom", + subject={ + "memory_id": new["id"], + "content_sha256": str(new_row.content_sha256), + "model": "scripted", + "prompt_version": PROMPT_VERSION, + "pairs": [ + { + "peer_id": old["id"], + "action": "flag", + "verdict": "update", + "confidence": 0.99, + "same_entity": True, + "same_attribute": True, + "memory_sha256": str(new_row.content_sha256), + "peer_sha256": str(old_row.content_sha256), + } + ], + }, + ) + request = ConflictsBulkAcceptInput( + org=org, + namespace=NS, + items=[ + ConflictsResolverAcceptItem( + memory_id=new["id"], + peer_id=old["id"], + memory_sha256=str(new_row.content_sha256), + peer_sha256=str(old_row.content_sha256), + suggestion_hash=suggestion_hash, + ), + ConflictsResolverAcceptItem( + memory_id=old["id"], + peer_id=new["id"], + memory_sha256=str(old_row.content_sha256), + peer_sha256=str(new_row.content_sha256), + suggestion_hash=suggestion_hash, + ), + ], + ) + + accepted = await handle_conflicts_bulk_accept(request) + retry = await handle_conflicts_bulk_accept(request) + after = await _rows(ch, org) + tombstone = await ch.query_all( + "SELECT status, tombstoned_at FROM loom.memory FINAL WHERE org = {org:String}" + " AND namespace = {ns:String} AND memory_id = {id:UUID}" + " SETTINGS select_sequential_consistency = 1", + params={"org": org, "ns": NS, "id": old["id"]}, + ) + + assert (accepted.resolved, accepted.stale, accepted.failed) == (1, 0, 1) + assert accepted.results[1].reason == "Duplicate item" + assert retry.results[0].status == "stale" + assert tombstone and tombstone[0]["status"] == "tombstoned" + assert tombstone[0]["tombstoned_at"] is not None + assert after["city_new"]["status"] == "active" + audit_rows = await ch.query_all( + "SELECT count() AS n FROM loom.audit_log WHERE org = {org:String} " + "AND namespace = {ns:String} AND event_type = 'memory.conflict_suggestion_accepted'", + params={"org": org, "ns": NS}, + ) + assert int(audit_rows[0]["n"]) == 1 + + +@pytest.mark.parametrize( + ("instance_ids", "expected_origin"), + [(["legacy"], ""), (["ccp1-current"], "claude-code"), (["ccp1-current", "legacy"], "")], +) +async def test_signed_capture_origin_reaches_conflicts_list_and_backlog( + ch: Any, + monkeypatch: pytest.MonkeyPatch, + instance_ids: list[str], + expected_origin: str, +) -> None: + import server.memory.store as memory_repo + from server.auth import revocation + from server.auth.context import set_current_auth + from server.auth.jwt import mint_token, verify_token + from server.core import instances + from server.core.errors import BackendUnavailableError + from server.identity.domain.read_scope import WHOLE_NAMESPACE + from server.insights.store.mentor import ProfileReads + from server.memory.api.models_conflicts import ConflictsListInput + from server.memory.app.conflicts import mark_peers_conflicted + from server.memory.app.conflicts_ops import handle_conflicts_list + from server.memory.app.provenance import capture_origin_for_write + from server.memory.store.conflicts import count_conflict_backlog + from server.settings import settings + + async def current_replicas(_ch: Any) -> list[dict[str, Any]]: + return [{"schema_version": 128, "instance_id": instance_id} for instance_id in instance_ids] + + monkeypatch.setattr(instances, "read_live", current_replicas) + monkeypatch.setattr(settings, "deployment", "resolver-rollout-test") + + org = unique_org("resolver-capture-origin") + token = mint_token( + "sa:capture-test", + org, + [NS], + ["writer"], + capture_origin="claude-code", + secret=settings.jwt_secret, + ) + await revocation.refresh() + set_current_auth(verify_token(token, secret=settings.jwt_secret)) + try: + if not expected_origin: + with pytest.raises(BackendUnavailableError): + await capture_origin_for_write() + assert await _rows(ch, org) == {} + return + await _pair(ch, org, "captured_old", "captured_new", 152, gap=False) + rows = await _rows(ch, org) + old, new = rows["captured_old"], rows["captured_new"] + old_row, new_row = await asyncio.gather( + memory_repo.get_by_id( + old["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ), + memory_repo.get_by_id( + new["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ), + ) + assert old_row is not None and new_row is not None + await mark_peers_conflicted( + org=org, + namespace=NS, + new_memory_id=new["id"], + peer_ids=[old["id"]], + expected_sha256=str(new_row.content_sha256), + peer_sha256={old["id"]: str(old_row.content_sha256)}, + ) + listed = await handle_conflicts_list(ConflictsListInput(org=org, namespace=NS)) + assert listed.rows and all(row.capture_origin == expected_origin for row in listed.rows) + backlog = await count_conflict_backlog(org, NS, scope=WHOLE_NAMESPACE, ch=ch) + expected_captured = 2 if expected_origin else 0 + assert sum(group["plugin_captured"] for group in backlog.values()) == expected_captured + mentor_backlog = await ProfileReads( + org, + NS, + "capture-test", + 3600, + ops={"sets": (), "gets": (), "searches": (), "packs": ()}, + limits={ + "ttl": 60, + "large": 1, + "huge": 2, + "advisory": 3, + "clip": 4, + "episodic_chars": 5, + }, + ch=ch, + ).conflict_backlog() + assert ( + sum(group["plugin_captured"] for group in mentor_backlog.values()) == expected_captured + ) + finally: + set_current_auth(None) + + +async def test_captured_conflict_confidence_round_trips_at_threshold(ch: Any) -> None: + org = unique_org("resolver-confidence-roundtrip") + await ch.insert( + "loom.namespaces", + [{"org": org, "namespace": NS, "captured_conflict_confidence": 0.98}], + ) + row = await ch.query_one( + "SELECT captured_conflict_confidence FROM loom.namespaces " + "WHERE org = {org:String} AND namespace = {ns:String} " + "ORDER BY updated_at DESC LIMIT 1", + params={"org": org, "ns": NS}, + ) + assert row is not None + assert float(row["captured_conflict_confidence"]) == 0.98 + assert 0.98 >= float(row["captured_conflict_confidence"]) + + +@pytest.mark.parametrize("lock_mode", ["no_delete", "read_only"]) +async def test_bulk_accept_respects_loser_delete_lock_at_write_fence( + ch: Any, lock_mode: str +) -> None: + import server.memory.store as memory_repo + from server.identity.domain.read_scope import WHOLE_NAMESPACE + from server.memory.api.models_conflicts import ( + ConflictsBulkAcceptInput, + ConflictsResolverAcceptItem, + ) + from server.memory.app.conflicts import mark_peers_conflicted + from server.memory.app.conflicts_ops import handle_conflicts_bulk_accept + from server.observability import audit + + org = unique_org("resolver-bulk-lock") + await _pair(ch, org, "locked_old", "locked_new", 157, gap=False) + rows = await _rows(ch, org) + old, new = rows["locked_old"], rows["locked_new"] + old_row, new_row = await asyncio.gather( + memory_repo.get_by_id( + old["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ), + memory_repo.get_by_id( + new["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ), + ) + assert old_row is not None and new_row is not None + await mark_peers_conflicted( + org=org, + namespace=NS, + new_memory_id=new["id"], + peer_ids=[old["id"]], + expected_sha256=str(new_row.content_sha256), + peer_sha256={old["id"]: str(old_row.content_sha256)}, + ) + suggestion_hash = await audit.emit( + "memory.conflict_resolver", + org=org, + namespace=NS, + actor="process:loom", + subject={ + "memory_id": new["id"], + "content_sha256": str(new_row.content_sha256), + "model": "scripted", + "prompt_version": PROMPT_VERSION, + "pairs": [ + { + "peer_id": old["id"], + "action": "flag", + "verdict": "update", + "confidence": 0.99, + "same_entity": True, + "same_attribute": True, + "memory_sha256": str(new_row.content_sha256), + "peer_sha256": str(old_row.content_sha256), + } + ], + }, + ) + await memory_repo.write_versions_by_ids( + org, + [old["id"]], + lambda _row: {"lock_mode": lock_mode, "lock_reason": "review guard"}, + namespace=NS, + strong=True, + ) + accepted = await handle_conflicts_bulk_accept( + ConflictsBulkAcceptInput( + org=org, + namespace=NS, + items=[ + ConflictsResolverAcceptItem( + memory_id=new["id"], + peer_id=old["id"], + memory_sha256=str(new_row.content_sha256), + peer_sha256=str(old_row.content_sha256), + suggestion_hash=suggestion_hash, + ) + ], + ) + ) + loser = await memory_repo.get_by_id( + old["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ) + assert accepted.results[0].status == "failed" + assert accepted.results[0].reason == "A memory lock protects this pair from bulk acceptance" + assert loser is not None and loser.tombstoned_at is None + assert loser.lock_mode == lock_mode + + +@pytest.mark.parametrize("replace_winner", [False, True]) +async def test_bulk_accept_does_not_retire_a_replaced_pair_member_after_validation( + ch: Any, monkeypatch: pytest.MonkeyPatch, replace_winner: bool +) -> None: + import server.memory.store as memory_repo + from server.identity.domain.read_scope import WHOLE_NAMESPACE + from server.memory.api.models_conflicts import ( + ConflictsBulkAcceptInput, + ConflictsResolverAcceptItem, + ) + from server.memory.app import conflicts, conflicts_ops + from server.observability import audit + + org = unique_org("resolver-bulk-cas") + await _pair(ch, org, "city_old", "city_new", 151, gap=False) + rows = await _rows(ch, org) + old, new = rows["city_old"], rows["city_new"] + old_row, new_row = await asyncio.gather( + memory_repo.get_by_id( + old["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ), + memory_repo.get_by_id( + new["id"], org=org, namespace=NS, scope=WHOLE_NAMESPACE, fresh=True, strong=True + ), + ) + assert old_row is not None and new_row is not None + await conflicts.mark_peers_conflicted( + org=org, + namespace=NS, + new_memory_id=new["id"], + peer_ids=[old["id"]], + expected_sha256=str(new_row.content_sha256), + peer_sha256={old["id"]: str(old_row.content_sha256)}, + ) + suggestion_hash = await audit.emit( + "memory.conflict_resolver", + org=org, + namespace=NS, + actor="process:loom", + subject={ + "memory_id": new["id"], + "content_sha256": str(new_row.content_sha256), + "model": "scripted", + "prompt_version": PROMPT_VERSION, + "pairs": [ + { + "peer_id": old["id"], + "action": "flag", + "verdict": "update", + "confidence": 0.99, + "same_entity": True, + "same_attribute": True, + "memory_sha256": str(new_row.content_sha256), + "peer_sha256": str(old_row.content_sha256), + } + ], + }, + ) + request = ConflictsBulkAcceptInput( + org=org, + namespace=NS, + items=[ + ConflictsResolverAcceptItem( + memory_id=new["id"], + peer_id=old["id"], + memory_sha256=str(new_row.content_sha256), + peer_sha256=str(old_row.content_sha256), + suggestion_hash=suggestion_hash, + ) + ], + ) + original_resolve = conflicts_ops.handle_conflicts_resolve + replaced = new if replace_winner else old + replaced_key = "city_new" if replace_winner else "city_old" + replaced_session = "s2" if replace_winner else "s1" + + if replace_winner: + original_insert = lifecycle.insert_versions_over_heads + replacing = False + + async def replace_winner_after_read(rows: Any, read: Any, **kwargs: Any) -> Any: + nonlocal replacing + if kwargs.get("guard_heads") and not replacing: + replacing = True + replacement_id = await _set( + org, replaced_session, replaced_key, "The office is in London" + ) + assert replacement_id == replaced["id"] + return await original_insert(rows, read, **kwargs) + + monkeypatch.setattr(lifecycle, "insert_versions_over_heads", replace_winner_after_read) + else: + + async def replace_peer_then_resolve(resolve_input: Any, **kwargs: Any) -> Any: + replacement_id = await _set( + org, replaced_session, replaced_key, "The office is in London" + ) + assert replacement_id == replaced["id"] + return await original_resolve(resolve_input, **kwargs) + + monkeypatch.setattr(conflicts_ops, "handle_conflicts_resolve", replace_peer_then_resolve) + accepted = await conflicts_ops.handle_conflicts_bulk_accept(request) + current = await ch.query_all( + "SELECT content_sha256, status, tombstoned_at FROM loom.memory FINAL " + "WHERE org = {org:String} AND namespace = {ns:String} AND memory_id = {id:UUID} " + "SETTINGS select_sequential_consistency = 1", + params={"org": org, "ns": NS, "id": replaced["id"]}, + ) + + assert accepted.results[0].status == "stale" + prior_hash = new_row.content_sha256 if replace_winner else old_row.content_sha256 + assert current and current[0]["content_sha256"] != str(prior_hash) + assert current[0]["tombstoned_at"] is None + accepted_events = await ch.query_all( + "SELECT count() AS n FROM loom.audit_log WHERE org = {org:String} " + "AND namespace = {ns:String} AND event_type = 'memory.conflict_suggestion_accepted'", + params={"org": org, "ns": NS}, + ) + assert int(accepted_events[0]["n"]) == 0 + + async def test_a_row_the_provider_refuses_does_not_stop_another_orgs_update( ch, wired, monkeypatch ) -> None: diff --git a/tests/integration/test_materialized_view_replace_atomic_ch.py b/tests/integration/test_materialized_view_replace_atomic_ch.py new file mode 100644 index 00000000000..1a382ac5f04 --- /dev/null +++ b/tests/integration/test_materialized_view_replace_atomic_ch.py @@ -0,0 +1,53 @@ +"""Modifying an explicit-TO materialized view must not leave an insert gap.""" + +from __future__ import annotations + +import asyncio +import uuid + +import pytest + + +@pytest.mark.asyncio +async def test_modify_materialized_view_query_is_safe_with_concurrent_inserts() -> None: + from server.core.ch import get_client, set_query_tag + + ch = get_client() + await ch.connect() + suffix = uuid.uuid4().hex + source = f"test_mv_replace_source_{suffix}" + target = f"test_mv_replace_target_{suffix}" + view = f"test_mv_replace_view_{suffix}" + set_query_tag("test.materialized_view.replace_atomic") + try: + await ch.execute(f"CREATE TABLE loom.{source} (x UInt64) ENGINE = MergeTree ORDER BY x") + await ch.execute( + f"CREATE TABLE loom.{target} (value UInt64) ENGINE = MergeTree ORDER BY value" + ) + await ch.execute( + f"CREATE MATERIALIZED VIEW loom.{view} TO loom.{target} AS " + f"SELECT x AS value FROM loom.{source}" + ) + await ch.execute(f"INSERT INTO loom.{source} VALUES (0)") + + async def insert_rows() -> None: + for i in range(1, 101): + await ch.execute(f"INSERT INTO loom.{source} VALUES ({i})") + + async def alter_view() -> None: + for _ in range(20): + await ch.execute( + f"ALTER TABLE loom.{view} MODIFY QUERY SELECT x AS value FROM loom.{source}" + ) + + await asyncio.gather(insert_rows(), alter_view()) + rows = await ch.query_all( + f"SELECT count() AS total, uniqExact(value) AS distinct_values FROM loom.{target}" + ) + assert int(rows[0]["total"]) == 101 + assert int(rows[0]["distinct_values"]) == 101 + finally: + await ch.execute(f"DROP VIEW IF EXISTS loom.{view}") + await ch.execute(f"DROP TABLE IF EXISTS loom.{target}") + await ch.execute(f"DROP TABLE IF EXISTS loom.{source}") + await ch.disconnect() diff --git a/tests/unit/test_badge_reads.py b/tests/unit/test_badge_reads.py index 709206a785a..2429aa56d97 100644 --- a/tests/unit/test_badge_reads.py +++ b/tests/unit/test_badge_reads.py @@ -20,12 +20,23 @@ class _FakeConflictsRepo: def __init__(self) -> None: self.counts = 0 + self.backlog_reads = 0 self.lists = 0 async def count_review(self, org: str, namespace: str, scope: Any = None) -> tuple[int, int]: self.counts += 1 return 4, 2 + async def count_conflict_backlog( + self, org: str, namespace: str, scope: Any = None + ) -> dict[str, dict[str, int]]: + self.backlog_reads += 1 + return { + "pending_judgement": {"plugin_captured": 1, "caller_written": 0, "unknown": 0}, + "resolver_judged": {"plugin_captured": 0, "caller_written": 1, "unknown": 0}, + "cosine_only": {"plugin_captured": 0, "caller_written": 0, "unknown": 1}, + } + async def list_conflicted(self, org: str, namespace: str, **_: Any) -> list[dict[str, Any]]: self.lists += 1 return [] @@ -49,6 +60,7 @@ async def test_count_only_answers_the_number_from_one_cached_count( fake = _FakeConflictsRepo() monkeypatch.setattr(conflicts_repo, "count_review", fake.count_review) + monkeypatch.setattr(conflicts_repo, "count_conflict_backlog", fake.count_conflict_backlog) monkeypatch.setattr(conflicts_repo, "list_conflicted", fake.list_conflicted) out1 = await conflicts_mod.handle_conflicts_list( @@ -58,8 +70,12 @@ async def test_count_only_answers_the_number_from_one_cached_count( ConflictsListInput(org="acme", namespace="team", count_only=True) ) assert (out1.total, out1.proposals) == (out2.total, out2.proposals) == (4, 2) + assert out1.backlog.pending_judgement.plugin_captured == 1 + assert out1.backlog.resolver_judged.caller_written == 1 + assert out1.backlog.cosine_only.unknown == 1 assert out1.rows == [] and out1.next_before_version is None assert fake.counts == 1, "one count per namespace per minute serves every badge tick" + assert fake.backlog_reads == 1 assert fake.lists == 0, "no row (and no value column) is read for a number" # another namespace is its own count; a decision drops the cached one @@ -83,12 +99,14 @@ async def test_a_fresh_count_skips_the_cache_and_refills_it( fake = _FakeConflictsRepo() monkeypatch.setattr(conflicts_repo, "count_review", fake.count_review) + monkeypatch.setattr(conflicts_repo, "count_conflict_backlog", fake.count_conflict_backlog) cached = ConflictsListInput(org="acme", namespace="team", count_only=True) fresh = ConflictsListInput(org="acme", namespace="team", count_only=True, fresh=True) await conflicts_mod.handle_conflicts_list(cached) # The review queue asks fresh: another replica's resolve may have made the cache stale. await conflicts_mod.handle_conflicts_list(fresh) assert fake.counts == 2 + assert fake.backlog_reads == 2 # The badge's next tick takes the count the fresh read stored. await conflicts_mod.handle_conflicts_list(cached) assert fake.counts == 2 @@ -116,6 +134,13 @@ async def count_review(org: str, namespace: str, scope: Any = None) -> tuple[int return 0, seen monkeypatch.setattr(conflicts_repo, "count_review", count_review) + + async def count_conflict_backlog( + org: str, namespace: str, scope: Any = None + ) -> dict[str, dict[str, int]]: + return {} + + monkeypatch.setattr(conflicts_repo, "count_conflict_backlog", count_conflict_backlog) badge = ConflictsListInput(org="acme", namespace="team", count_only=True) held = asyncio.create_task(conflicts_mod.handle_conflicts_list(badge)) await held_read.wait() @@ -151,6 +176,13 @@ async def count_review(org: str, namespace: str, scope: Any = None) -> tuple[int return 0, seen monkeypatch.setattr(conflicts_repo, "count_review", count_review) + + async def count_conflict_backlog( + org: str, namespace: str, scope: Any = None + ) -> dict[str, dict[str, int]]: + return {} + + monkeypatch.setattr(conflicts_repo, "count_conflict_backlog", count_conflict_backlog) badge = ConflictsListInput(org="acme", namespace="b", count_only=True) assert (await conflicts_mod.handle_conflicts_list(badge)).proposals == 1 pending = 0 # another replica rejects the proposal @@ -186,6 +218,11 @@ async def count_review(org: str, namespace: str, scope: Any = None) -> tuple[int return 0, 0 monkeypatch.setattr(conflicts_repo, "count_review", count_review) + + async def count_conflict_backlog(*_: Any, **__: Any) -> dict[str, dict[str, int]]: + return {} + + monkeypatch.setattr(conflicts_repo, "count_conflict_backlog", count_conflict_backlog) badge = ConflictsListInput(org="acme", namespace="team", count_only=True) # A replica that has yet to apply a decision must not serve the count the queue asks for. await conflicts_mod.handle_conflicts_list(badge.model_copy(update={"fresh": True})) @@ -203,6 +240,7 @@ async def test_the_listing_path_is_unchanged_without_count_only( fake = _FakeConflictsRepo() monkeypatch.setattr(conflicts_repo, "count_review", fake.count_review) + monkeypatch.setattr(conflicts_repo, "count_conflict_backlog", fake.count_conflict_backlog) monkeypatch.setattr(conflicts_repo, "list_conflicted", fake.list_conflicted) out = await conflicts_mod.handle_conflicts_list( ConflictsListInput(org="acme", namespace="team") @@ -223,6 +261,7 @@ async def test_a_proposal_decision_drops_the_namespaces_cached_counts( fake = _FakeConflictsRepo() monkeypatch.setattr(conflicts_repo, "count_review", fake.count_review) + monkeypatch.setattr(conflicts_repo, "count_conflict_backlog", fake.count_conflict_backlog) async def _decide(*_: Any, **__: Any) -> list[Any]: return [] diff --git a/tests/unit/test_captured_conflict_simulation.py b/tests/unit/test_captured_conflict_simulation.py new file mode 100644 index 00000000000..5b0234d0dd9 --- /dev/null +++ b/tests/unit/test_captured_conflict_simulation.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from scripts.ops.simulate_captured_conflicts import run + + +def test_seven_day_simulation_is_reproducible_and_checks_policy_invariants() -> None: + first = run(seed=2077, review_capacity_per_sitting=2000) + second = run(seed=2077, review_capacity_per_sitting=2000) + + assert first == second + assert first["days"] == 7 + assert all(first["checks"].values()) + defaults = first["default_policy"] + opted_in = first["opt_in_capture_policy"] + assert len(defaults) == len(opted_in) == 3 + for baseline, enabled in zip(defaults, opted_in, strict=True): + assert enabled["policy_automatically_settled"] > 0 + assert enabled["human_reviewable_pairs"] < baseline["human_reviewable_pairs"] + assert enabled["genuine_contradictions_settled"] == 0 + assert enabled["backlog_growth"] == 0 diff --git a/tests/unit/test_cell.py b/tests/unit/test_cell.py index 8cf86f17a11..29dcde969ea 100644 --- a/tests/unit/test_cell.py +++ b/tests/unit/test_cell.py @@ -338,6 +338,7 @@ def test_the_heartbeat_reports_the_cell_and_a_gated_process_is_not_serving( _cell_settings(monkeypatch) _view(monkeypatch) assert instances.row()["serving"] == 0 + assert instances.row()["instance_id"].startswith(instances.CAPTURED_CONFLICT_PROVENANCE_MARKER) _serving_view(monkeypatch) assert instances.row()["serving"] == 1 reported = instances.cell_row() diff --git a/tests/unit/test_conflict_check.py b/tests/unit/test_conflict_check.py index 1bd4e02880f..0936240269b 100644 --- a/tests/unit/test_conflict_check.py +++ b/tests/unit/test_conflict_check.py @@ -136,6 +136,33 @@ async def default(*a: Any, **k: Any) -> str: assert (await _check(new, memory_key="user_basketball_origin")).verdict == "conflict" +@pytest.mark.asyncio +async def test_captured_update_against_templated_peer_stays_for_review( + env: NS, monkeypatch: pytest.MonkeyPatch +) -> None: + env.rows[:] = [ + _row( + _P1, + "basketball_creat_in", + "User read that basketball was created in the country of United States of America.", + 0.03, + ) + | {"capture_origin": "codex"} + ] + + async def newest(*a: Any, **k: Any) -> str: + return "newest_wins" + + monkeypatch.setattr(cf, "namespace_conflict_policy", newest) + monkeypatch.setattr("server.memory.app.provenance.capture_origin", lambda: "claude-code") + result = await _check( + "User read that basketball was created in the country of Soviet Union.", + memory_key="user_basketball_origin", + ) + assert result.verdict == "conflict" + assert result.refined_peers == [] + + def test_templated_substitution_shape() -> None: from server.memory.domain.conflicts import templated_substitution as ts diff --git a/tests/unit/test_conflict_resolver.py b/tests/unit/test_conflict_resolver.py index ae01a4aef2e..37be0db08a9 100644 --- a/tests/unit/test_conflict_resolver.py +++ b/tests/unit/test_conflict_resolver.py @@ -469,6 +469,10 @@ def row_env(monkeypatch: pytest.MonkeyPatch) -> NS: acted=[], audits=[], llm_calls=0, + captured_settings={ + "captured_conflict_policy": "manual_review", + "captured_conflict_confidence": 0.98, + }, ) # The peer was stated a day before the judged row. day_before = datetime(2026, 1, 1) @@ -537,6 +541,18 @@ async def audit(org: str, namespace: str, row: Any, acted: list[Any], model: str e.audit_model = model monkeypatch.setattr(resolver, "_current", current) + + from contextlib import asynccontextmanager + + @asynccontextmanager + async def account_change(*args: Any, **kwargs: Any): + yield + + async def namespace_write_row(*args: Any, **kwargs: Any) -> dict[str, Any]: + return e.captured_settings + + monkeypatch.setattr("server.auth.grant_claims.account_change", account_change) + monkeypatch.setattr("server.memory.store.conflicts.namespace_write_row", namespace_write_row) monkeypatch.setattr(queue, "cluster_peers", cluster) monkeypatch.setattr(resolver, "judge", judge) monkeypatch.setattr(queue, "stamp_judged", stamp) @@ -580,9 +596,20 @@ async def after_retire(org: str, namespace: str, done: Any) -> None: return e -async def _resolve(policy: str = "newest_wins") -> resolver.Counts: +async def _resolve( + policy: str = "newest_wins", + *, + captured_policy: str = "manual_review", + captured_confidence: float = 0.98, +) -> resolver.Counts: counts = resolver.Counts() - await resolver.resolve_row(_q(), policy=policy, counts=counts) + await resolver.resolve_row( + _q(), + policy=policy, + counts=counts, + captured_policy=captured_policy, + captured_confidence=captured_confidence, + ) return counts @@ -595,6 +622,58 @@ async def test_a_confident_update_under_newest_wins_retires_and_stamps(row_env: assert row_env.audit_model == "gpt-6.1-sol-2026-09-01" +async def test_setting_changed_during_judge_is_rechecked_before_retirement( + row_env: NS, monkeypatch: pytest.MonkeyPatch +) -> None: + row_env.mem.capture_origin = "codex" + row_env.heads["m2"].capture_origin = "claude-code" + row_env.mem.session_id = row_env.heads["m2"].session_id = "s1" + row_env.peers[0]["session_id"] = "s1" + row_env.captured_settings = { + "captured_conflict_policy": "resolver_update", + "captured_conflict_confidence": 0.9, + } + original_judge = resolver.judge + + async def judge_then_owner_changes_settings(new: Any, notes: list[Any]) -> Any: + result = await original_judge(new, notes) + row_env.captured_settings = { + "captured_conflict_policy": "manual_review", + "captured_conflict_confidence": 0.98, + } + return result + + monkeypatch.setattr(resolver, "judge", judge_then_owner_changes_settings) + await _resolve(captured_policy="resolver_update", captured_confidence=0.9) + assert row_env.acted == [(cr.FLAG, "m1", "m2")] + + +async def test_higher_confidence_floor_during_judge_blocks_retirement( + row_env: NS, monkeypatch: pytest.MonkeyPatch +) -> None: + row_env.mem.capture_origin = "codex" + row_env.heads["m2"].capture_origin = "claude-code" + row_env.mem.session_id = row_env.heads["m2"].session_id = "s1" + row_env.peers[0]["session_id"] = "s1" + row_env.captured_settings = { + "captured_conflict_policy": "resolver_update", + "captured_conflict_confidence": 0.99, + } + original_judge = resolver.judge + + async def judge_then_owner_raises_floor(new: Any, notes: list[Any]) -> Any: + result = await original_judge(new, notes) + row_env.captured_settings = { + "captured_conflict_policy": "resolver_update", + "captured_conflict_confidence": 1.0, + } + return result + + monkeypatch.setattr(resolver, "judge", judge_then_owner_raises_floor) + await _resolve(captured_policy="resolver_update", captured_confidence=0.9) + assert row_env.acted == [(cr.FLAG, "m1", "m2")] + + async def test_the_record_and_follow_run_after_the_keys_locks_are_released( row_env: NS, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -1483,7 +1562,17 @@ def pass_env(monkeypatch: pytest.MonkeyPatch) -> NS: from server.memory.workers import conflict_resolver as worker from server.observability import budget - e = NS(owed=[], recheck=[], resolved=[], over=set(), raise_for={}, slow=0.0, stamped=[]) + e = NS( + owed=[], + recheck=[], + resolved=[], + over=set(), + raise_for={}, + slow=0.0, + stamped=[], + policy_rows={}, + captured_options=[], + ) e.left_owed = set() monkeypatch.setattr(worker, "_state", worker._State()) e.in_flight = e.most_in_flight = 0 @@ -1521,7 +1610,15 @@ async def over(org, namespace, **kw): e.cap_reads.append(kw) return (org, namespace) in e.over - async def resolve(q, *, policy, counts, shown=frozenset()): + async def resolve( + q, + *, + policy, + counts, + shown=frozenset(), + captured_policy="manual_review", + captured_confidence=0.98, + ): e.in_flight += 1 e.most_in_flight = max(e.most_in_flight, e.in_flight) await asyncio.sleep(e.slow) @@ -1529,6 +1626,7 @@ async def resolve(q, *, policy, counts, shown=frozenset()): if q["memory_key"] in e.raise_for: raise e.raise_for[q["memory_key"]] e.resolved.append((q["org"], q["namespace"], q["memory_key"], policy)) + e.captured_options.append((captured_policy, captured_confidence)) counts.judged += 1 return frozenset({"m2"}) if q["memory_key"] in e.left_owed else None @@ -1538,6 +1636,14 @@ async def stamp(q, **kw): async def policy(org, namespace, ch=None): return "newest_wins" + async def namespace_row(org, namespace, *, ch=None): + return { + "default_conflict_policy": "newest_wins", + "captured_conflict_policy": "manual_review", + "captured_conflict_confidence": 0.98, + **e.policy_rows.get((org, namespace), {}), + } + monkeypatch.setattr(queue, "owed_rows", owed) monkeypatch.setattr(queue, "unjudged_conflicted_rows", recheck) monkeypatch.setattr(queue, "queued_namespaces", namespaces) @@ -1546,11 +1652,26 @@ async def policy(org, namespace, ch=None): monkeypatch.setattr(budget, "namespace_over_cap", over) monkeypatch.setattr(resolver, "resolve_row", resolve) monkeypatch.setattr("server.memory.app.conflicts.namespace_conflict_policy", policy) + monkeypatch.setattr("server.memory.store.conflicts.namespace_write_row", namespace_row) monkeypatch.setattr("server.core.ch.get_client", lambda: object()) e.run = worker.run_pass return e +async def test_a_pass_reads_the_captured_conflict_policy_for_each_namespace( + pass_env: NS, +) -> None: + pass_env.owed = [_q(memory_key="captured")] + pass_env.policy_rows[("o", "ns")] = { + "captured_conflict_policy": "resolver_update", + "captured_conflict_confidence": 0.93, + } + + await pass_env.run() + + assert pass_env.captured_options == [("resolver_update", 0.93)] + + async def test_a_pass_handles_each_tenant_on_its_own_and_each_row_once(pass_env: NS) -> None: pass_env.owed = [ _q(org="o1", namespace="a", memory_key="k1"), @@ -1611,7 +1732,9 @@ async def test_an_answer_whose_action_failed_breaks_a_refusal_streak( monkeypatch.setattr(settings, "memory_conflict_resolver_concurrency", 1) - async def resolve(q: Any, *, policy: str, counts: Any, shown: Any = frozenset()) -> None: + async def resolve( + q: Any, *, policy: str, counts: Any, shown: Any = frozenset(), **_capture: Any + ) -> None: if q["memory_key"] == "answered": counts.judged += 1 raise resolver.JudgedThenFailed("RuntimeError: insert failed") @@ -1633,7 +1756,9 @@ async def test_another_namespaces_answer_breaks_no_refusal_streak( whose rows stay owed instead of being stamped.""" order = {k: asyncio.Event() for k in ("answered", "quiet")} - async def resolve(q: Any, *, policy: str, counts: Any, shown: Any = frozenset()) -> None: + async def resolve( + q: Any, *, policy: str, counts: Any, shown: Any = frozenset(), **_capture: Any + ) -> None: key = q["memory_key"] if key == "b-answered": counts.judged += 1 @@ -1829,7 +1954,7 @@ async def test_a_failure_that_escapes_a_row_ends_the_pass_with_no_row_running( running: set[str] = set() - async def resolve(q, *, policy, counts, shown=frozenset()): + async def resolve(q, *, policy, counts, shown=frozenset(), **_capture): running.add(q["memory_key"]) try: await asyncio.sleep(0 if q["memory_key"] == "k1" else 0.2) diff --git a/tests/unit/test_conflicts_bulk_accept.py b/tests/unit/test_conflicts_bulk_accept.py new file mode 100644 index 00000000000..e5f332965bc --- /dev/null +++ b/tests/unit/test_conflicts_bulk_accept.py @@ -0,0 +1,258 @@ +"""Current resolver suggestions can be accepted in a bounded, partial batch.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime +from types import SimpleNamespace + +import pytest +from pydantic import ValidationError + +from server.memory.api.models_conflicts import ( + ConflictsBulkAcceptInput, + ConflictsResolveOutput, +) + + +def _audit_record(memory_id: str, peer_id: str, sha_a: str, sha_b: str) -> dict[str, object]: + from server.observability.audit import audit_row + + subject = { + "memory_id": memory_id, + "content_sha256": sha_a, + "model": "fixed-test-judge", + "prompt_version": "v3", + "pairs": [ + { + "peer_id": peer_id, + "action": "flag", + "verdict": "update", + "confidence": 0.99, + "same_entity": True, + "same_attribute": True, + "memory_sha256": sha_a, + "peer_sha256": sha_b, + } + ], + } + return audit_row( + "memory.conflict_resolver", + "org", + "ns", + "process:loom", + subject, + ts=datetime(2026, 1, 1, tzinfo=UTC), + ) + + +def _item( + record: dict[str, object], memory_id: str, peer_id: str, sha_a: str, sha_b: str +) -> dict[str, str]: + return { + "memory_id": memory_id, + "peer_id": peer_id, + "memory_sha256": sha_a, + "peer_sha256": sha_b, + "suggestion_hash": str(record["row_hash"]), + } + + +def test_bulk_accept_input_is_bounded() -> None: + with pytest.raises(ValidationError): + ConflictsBulkAcceptInput( + org="o", + namespace="n", + items=[ + { + "memory_id": str(i), + "peer_id": "peer", + "memory_sha256": "a" * 64, + "peer_sha256": "b" * 64, + "suggestion_hash": "c" * 64, + } + for i in range(101) + ], + ) + + +def test_bulk_accept_is_admin_only_and_hidden_from_mcp() -> None: + from server.memory.api.ops_conflicts import conflicts_bulk_accept + from server.operations.base import Role + from server.operations.reach import mcp_reach + + assert conflicts_bulk_accept.required_role == Role.ADMIN + assert not mcp_reach("conflicts.bulk_accept") + + +@pytest.mark.parametrize("stale_first", [False, True]) +def test_bulk_duplicate_pair_selects_current_direction_in_either_order(stale_first: bool) -> None: + from server.memory.app.conflicts_ops import _bulk_item_selected + + current, stale = object(), object() + selected = {("a", "z"): current} + seen: set[tuple[str, str]] = set() + ordered = [stale, current] if stale_first else [current, stale] + assert [_bulk_item_selected(("a", "z"), item, selected, seen) for item in ordered] == ( + [False, True] if stale_first else [True, False] + ) + + +@pytest.mark.parametrize("mode", ["no_delete", "read_only"]) +def test_bulk_accept_rechecks_loser_deletion_lock_at_write_fence(mode: str) -> None: + from server.memory.app.conflicts_ops import _bulk_loser_is_locked + + loser = SimpleNamespace(memory_id="loser", lock_mode=mode, lock_until=None) + assert _bulk_loser_is_locked(loser, "winner") + + +@pytest.mark.asyncio +async def test_bulk_accept_resolves_current_item_and_returns_stale_for_changed_suggestion( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import server.memory.store as memory_repo + from server.memory.api.models_conflicts import ConflictsResolveInput + from server.memory.app import conflict_resolver as resolver + from server.memory.app import conflicts_ops + from server.memory.store import conflicts as conflicts_repo + from server.memory.store import key_write_lock + from server.observability import audit + + sha_a, sha_b = "a" * 64, "b" * 64 + record = _audit_record("winner", "loser", sha_a, sha_b) + loser_record = _audit_record("other", "peer", "d" * 64, "e" * 64) + changed_record = _audit_record("changed-winner", "changed-loser", "d" * 64, "e" * 64) + records = { + ("winner", "loser"): record, + ("other", "peer"): loser_record, + ("changed-winner", "changed-loser"): changed_record, + } + monkeypatch.setattr( + conflicts_repo, + "latest_resolver_pair_audit", + lambda org, ns, mid, peer: _async_value(records.get((mid, peer))), + ) + rows = { + "winner": SimpleNamespace( + memory_id="winner", + namespace="ns", + agent="a", + user_id="u", + session_id="s", + memory_key="k1", + content_sha256=sha_a, + status="conflicted", + conflict_with=["loser"], + pinned=False, + sensitivity="", + tombstoned_at=None, + version=1, + valid_at=None, + ), + "loser": SimpleNamespace( + memory_id="loser", + namespace="ns", + agent="a", + user_id="u", + session_id="s", + memory_key="k2", + content_sha256=sha_b, + status="conflicted", + conflict_with=["winner"], + pinned=False, + sensitivity="", + tombstoned_at=None, + version=1, + valid_at=None, + ), + "changed-winner": SimpleNamespace( + memory_id="changed-winner", + namespace="ns", + agent="a", + user_id="u", + session_id="s", + memory_key="k3", + content_sha256="f" * 64, + status="conflicted", + conflict_with=["changed-loser"], + pinned=False, + sensitivity="", + tombstoned_at=None, + version=2, + valid_at=None, + ), + "changed-loser": SimpleNamespace( + memory_id="changed-loser", + namespace="ns", + agent="a", + user_id="u", + session_id="s", + memory_key="k4", + content_sha256="e" * 64, + status="conflicted", + conflict_with=["changed-winner"], + pinned=False, + sensitivity="", + tombstoned_at=None, + version=1, + valid_at=None, + ), + } + monkeypatch.setattr( + memory_repo, "get_by_id", lambda memory_id, **kwargs: _async_value(rows.get(memory_id)) + ) + + async def assertion_order(org: str, ns: str, pair_rows: list[object]): + return resolver.AssertionOrder({str(r.memory_id): (1, 1) for r in pair_rows}, []) + + monkeypatch.setattr(resolver, "_assertion_order", assertion_order) + monkeypatch.setattr(resolver, "_undone", lambda *args: False) + monkeypatch.setattr(resolver.queue, "under_erasure", lambda org: _async_value(False)) + + @asynccontextmanager + async def no_lease(*_key: str) -> AsyncIterator[None]: + yield + + monkeypatch.setattr(key_write_lock.key_write_locks, "hold", no_lease) + called: list[tuple[ConflictsResolveInput, dict[str, str] | None]] = [] + + async def resolve( + inp: ConflictsResolveInput, + *, + expected_sha256: dict[str, str] | None = None, + write_fence_locked: set[str] | None = None, + ) -> ConflictsResolveOutput: + assert write_fence_locked == set() + called.append((inp, expected_sha256)) + return ConflictsResolveOutput( + resolved=True, decision="revise", affected_memory_ids=[inp.peer_id or ""] + ) + + monkeypatch.setattr(conflicts_ops, "handle_conflicts_resolve", resolve) + monkeypatch.setattr(audit, "emit", _audit_emit) + out = await conflicts_ops.handle_conflicts_bulk_accept( + ConflictsBulkAcceptInput( + org="org", + namespace="ns", + items=[ + _item(record, "winner", "loser", sha_a, sha_b), + _item(loser_record, "other", "peer", "d" * 64, "e" * 64), + _item(changed_record, "changed-winner", "changed-loser", "d" * 64, "e" * 64), + ], + ) + ) + + assert [r.status for r in out.results] == ["resolved", "stale", "stale"] + assert (out.requested, out.resolved, out.stale, out.failed) == (3, 1, 2, 0) + assert len(called) == 1 + assert called[0][0].decision == "revise" and called[0][0].peer_id == "loser" + assert called[0][1] == {"winner": sha_a, "loser": sha_b} + + +async def _async_value(value): + return value + + +async def _audit_emit(*args, **kwargs): + return "hash" diff --git a/tests/unit/test_conflicts_list.py b/tests/unit/test_conflicts_list.py new file mode 100644 index 00000000000..41768ff8a34 --- /dev/null +++ b/tests/unit/test_conflicts_list.py @@ -0,0 +1,41 @@ +"""The conflicts API returns stored, signed capture provenance to reviewers.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import pytest + + +@pytest.mark.asyncio +async def test_conflicts_list_projects_persisted_capture_origin( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.identity.domain.read_scope import WHOLE_NAMESPACE + from server.memory.api.models_conflicts import ConflictsListInput + from server.memory.app import conflicts_ops + from server.memory.store import conflicts as conflicts_repo + + monkeypatch.setattr(conflicts_ops, "request_scope", lambda: WHOLE_NAMESPACE) + + async def list_conflicted(*_args: Any, **_kwargs: Any) -> list[dict[str, Any]]: + return [ + { + "memory_id": "m1", + "memory_key": "decision", + "memory_type": "fact", + "value": '"the build is green"', + "version": 7, + "pinned": False, + "created_at": datetime(2026, 1, 1), + "conflict_with": ["m2"], + "sensitivity": "", + "capture_origin": "claude-code", + } + ] + + monkeypatch.setattr(conflicts_repo, "list_conflicted", list_conflicted) + output = await conflicts_ops.handle_conflicts_list(ConflictsListInput(org="o", namespace="n")) + + assert output.rows[0].capture_origin == "claude-code" diff --git a/tests/unit/test_conflicts_repo.py b/tests/unit/test_conflicts_repo.py index 60889bd2799..cdf3ff669e4 100644 --- a/tests/unit/test_conflicts_repo.py +++ b/tests/unit/test_conflicts_repo.py @@ -15,7 +15,10 @@ allowlist_insert, allowlist_list, allowlist_remove, + count_conflict_backlog, + has_live_captured_rows, ids_in_scope, + latest_resolver_pair_audit, list_conflicted, lookup_keys_for_ids, lookup_target, @@ -24,6 +27,23 @@ ) +@pytest.mark.asyncio +async def test_latest_resolver_pair_audit_is_namespace_scoped_and_ordered() -> None: + ch = StubCH() + expected = {"row_hash": "h", "subject": "{}"} + ch.query_all_returns.append([expected]) + + row = await latest_resolver_pair_audit("o", "n", "new", "old", ch=ch) + + assert row == expected + sql, params = ch.query_all_calls[0] + assert "event_type = 'memory.conflict_resolver'" in sql + assert "ORDER BY ts DESC, row_hash DESC" in sql + assert "LIMIT 1" in sql + assert "arrayExists" in sql + assert params == {"org": "o", "ns": "n", "mid": "new", "peer": "old"} + + class StubCH: def __init__(self) -> None: self.query_one_calls: list[tuple[str, dict[str, Any]]] = [] @@ -48,6 +68,59 @@ async def insert(self, table, rows, settings=None): self.insert_calls.append((table, rows, settings or {})) +@pytest.mark.asyncio +async def test_live_captured_row_probe_is_namespace_scoped() -> None: + ch = StubCH() + ch.query_one_returns.append({"n": 1}) + + assert await has_live_captured_rows("o", "n", ch=ch) + sql, params = ch.query_one_calls[0] + assert "capture_origin IN ('claude-code', 'codex')" in sql + assert "tombstoned_at IS NULL" in sql + assert params == {"org": "o", "ns": "n"} + + +@pytest.mark.asyncio +async def test_conflict_backlog_counts_rows_by_mark_and_provenance() -> None: + ch = StubCH() + ch.query_all_returns.append( + [ + {"judgement": "pending_judgement", "provenance": "plugin_captured", "n": 2}, + {"judgement": "resolver_judged", "provenance": "caller_written", "n": 1}, + {"judgement": "cosine_only", "provenance": "unknown", "n": 3}, + ] + ) + + out = await count_conflict_backlog("o", "n", scope=WHOLE_NAMESPACE, ch=ch) + + assert out["pending_judgement"] == {"plugin_captured": 2, "caller_written": 0, "unknown": 0} + assert out["resolver_judged"] == {"plugin_captured": 0, "caller_written": 1, "unknown": 0} + assert out["cosine_only"] == {"plugin_captured": 0, "caller_written": 0, "unknown": 3} + sql, params = ch.query_all_calls[0] + assert "FROM loom.memory FINAL" in sql + assert "FROM loom.memory_embeddings FINAL" in sql + assert "GROUP BY judgement, provenance" in sql + assert "toUnixTimestamp(e.conflict_checked_at) = 2" in sql + assert "source_trace" not in sql + assert "m.capture_origin IN ('claude-code', 'codex')" in sql + assert "AS provenance" in sql + assert "m.source_class = 'asserted' AND startsWith(m.actor, 'human:')" in sql + assert params == {"org": "o", "ns": "n"} + + +@pytest.mark.asyncio +async def test_conflict_backlog_applies_narrow_read_scope() -> None: + from server.identity.domain.read_scope import ReadFilters + + ch = StubCH() + await count_conflict_backlog( + "o", "n", scope=ReadFilters(scope="own_session", user_id="u1", session_id="s1"), ch=ch + ) + sql, params = ch.query_all_calls[0] + assert "user_id = {scope_uid:String} AND session_id = {scope_sid:String}" in sql + assert params == {"org": "o", "ns": "n", "scope_uid": "u1", "scope_sid": "s1"} + + @pytest.mark.asyncio async def test_list_conflicted_filters_and_paginates() -> None: ch = StubCH() @@ -160,7 +233,16 @@ async def fake_get_by_id(mid, *, org=None, namespace=None, ch=None, scope=None): monkeypatch.setattr(lifecycle, "get_by_id", fake_get_by_id) async def fake_write_versions_by_ids( - org, memory_ids, update, *, ch=None, namespace=None, skip=None, strong=False + org, + memory_ids, + update, + *, + ch=None, + namespace=None, + skip=None, + strong=False, + exact=False, + guard_sha256=None, ): row = memory_repo.MemoryRow( memory_id="11111111-2222-3333-4444-555555555555", diff --git a/tests/unit/test_delegation.py b/tests/unit/test_delegation.py index df923b0d84b..4ac4dea322e 100644 --- a/tests/unit/test_delegation.py +++ b/tests/unit/test_delegation.py @@ -138,6 +138,13 @@ async def _child(parent: AuthInfo, requested: dict[str, str | None], **kw: Any) return verify_token(d.mint(kw.pop("subject", "sa:bot"))) +@pytest.mark.asyncio +async def test_a_child_token_does_not_inherit_capture_origin(world) -> None: + parent = _login(capture_origin="claude-code") + child = await _child(parent, {"a": "writer"}) + assert child.capture_origin == "" + + async def _reaches(token: AuthInfo, ns: str, role: Role = Role.VIEWER, org: str = ORG) -> bool: try: await authz.check_authorized(token, role, org, ns) diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index f5134883813..f888b6b1654 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -511,6 +511,20 @@ def test_an_end_user_token_revokes_nothing_here(_world, monkeypatch) -> None: assert r.status_code == 200 and _world["revoked"] == [] +def test_an_end_user_issuer_cannot_claim_a_captured_plugin_origin(monkeypatch) -> None: + from server.auth.jwt import TokenError, verify_token + from server.settings import settings + from tests import end_user_issuer + + private, public = end_user_issuer.new_key() + monkeypatch.setattr( + settings, "jwt_end_user_issuers_json", end_user_issuer.issuers_setting(public) + ) + token = end_user_issuer.mint("acme", "u-1", private_pem=private, capture_origin="claude-code") + with pytest.raises(TokenError, match="capture_origin"): + verify_token(token) + + def test_revoking_garbage_is_a_quiet_200(_world) -> None: r = _client().post("/oauth/revoke", data={"token": "nonsense", "client_id": "loom-cli"}) assert r.status_code == 200 and _world["revoked"] == [] diff --git a/tests/unit/test_lineage_and_snapshot_fidelity.py b/tests/unit/test_lineage_and_snapshot_fidelity.py index a7d400c9ab8..5bf5ee1816b 100644 --- a/tests/unit/test_lineage_and_snapshot_fidelity.py +++ b/tests/unit/test_lineage_and_snapshot_fidelity.py @@ -23,6 +23,7 @@ "evidence", "tags", "valid_at", + "capture_origin", } @@ -80,6 +81,7 @@ def test_snapshot_query_and_restore_row_agree_with_the_model() -> None: valid_at=None, content_sha256="ab" * 32, tags=["t"], + capture_origin="claude-code", ) (out,) = restore_rows( [row], @@ -90,11 +92,47 @@ def test_snapshot_query_and_restore_row_agree_with_the_model() -> None: actor="process:restore", ) assert set(out) == set(MEMORY_PERSISTED_COLS) - for col in ("verified_by", "verified_sha256", "grounding", "evidence", "valid_at"): + for col in ( + "verified_by", + "verified_sha256", + "grounding", + "evidence", + "valid_at", + "capture_origin", + ): assert out[col] == getattr(row, col), col assert out["content_sha256"] == "ab" * 32 and out["tags"] == ["t"] and out["version"] == 7 +def test_restore_replaces_payload_capture_origin_with_snapshot_record() -> None: + from server.core.hashing import sha256_value + from server.memory.app.snapshot_rows import authenticated_capture_origins + + row = _SnapshotMemoryRow( + memory_id="55555555-5555-5555-5555-555555555555", + agent="a", + user_id="-", + session_id="-", + run_id="-", + memory_key="k", + memory_type="semantic", + value='"v"', + confidence=1.0, + source_trace="", + pinned=False, + capture_origin="codex", + ) + source = {"content_sha256": "", "value": row.value, "value_json": row.value_json} + record = {"origin": "claude-code", "row_hash": sha256_value(source)} + assert authenticated_capture_origins([row], {})[0].capture_origin == "" + assert ( + authenticated_capture_origins([row], {row.memory_id: record})[0].capture_origin + == "claude-code" + ) + changed = row.model_copy(update={"value": '"caller changed this"'}) + assert authenticated_capture_origins([changed], {row.memory_id: record})[0].capture_origin == "" + + def test_a_restored_row_drops_a_copy_rules_marker() -> None: """Fails when a snapshot payload writes the trace only a copy rule's run stamps, so a restored proposal names a rule that proposed nothing. A caller's trace and the row's diff --git a/tests/unit/test_mentor.py b/tests/unit/test_mentor.py index 2f501030741..63caa7a36a9 100644 --- a/tests/unit/test_mentor.py +++ b/tests/unit/test_mentor.py @@ -82,6 +82,7 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None): M_PREFIX = "AS top_prefix_sets" M_NSLEDGER = "AS conflict_ops" M_NSROWS = "AS coord_keys" +M_CONFLICT_BACKLOG = "GROUP BY judgement, provenance" M_DOCS = "FROM loom.documents" M_RECS = "FROM loom.memory_records" # The agent-scoped shape read: documents and checkpoints this agent wrote. @@ -121,6 +122,7 @@ def _store(usage: list[dict[str, Any]], sessions: int, **facts: Any) -> dict[str "live_rows": 100, "entity_rows": 0, "conflicted_rows": 0, + "conflict_backlog": [], "coord_keys": 0, "documents": 0, "records": 0, @@ -170,6 +172,7 @@ def _store(usage: list[dict[str, Any]], sessions: int, **facts: Any) -> dict[str M_NSROWS: [ {k: f[k] for k in ("live_rows", "entity_rows", "conflicted_rows", "coord_keys")} ], + M_CONFLICT_BACKLOG: f["conflict_backlog"], M_DOCS: [{"n": f["documents"]}], M_RECS: [{"n": f["records"]}], M_SHAPES: [ @@ -390,14 +393,13 @@ def test_every_other_rule_fires_on_its_fact_and_the_profile_keeps_eight( "checkpoints_as_memory", "documents_as_memories", "records_for_identities", - "conflicts_pending", "facts_graph_unused", "bisect_available", "runs_unused", "no_session_pack", } - # Nine rules fire (the blame calls are code.* calls, so the code index is not - # "unused"); the profile keeps the eight that matter most, warnings first. + # The namespace conflict count is observability, not agent guidance; the + # remaining rules fit in the profile limit. assert len(p.hints) == mentor_rules.PROFILE_MAX_HINTS assert codes <= expected assert {h.code for h in p.hints if h.severity == "warning"} == { @@ -1104,6 +1106,11 @@ def test_mentor_brief_returns_the_profile_planes_and_adoption( "records": 0, "entity_rows": 3, "conflicted_rows": 0, + "conflict_backlog": { + "pending_judgement": {"plugin_captured": 0, "caller_written": 1, "unknown": 2}, + "resolver_judged": {"plugin_captured": 0, "caller_written": 0, "unknown": 3}, + "cosine_only": {"plugin_captured": 0, "caller_written": 0, "unknown": 4}, + }, }, ) @@ -1141,6 +1148,9 @@ async def _p(*a: Any, **k: Any) -> Any: assert planes["claims"].calls == 12 and planes["code index"].available is True assert planes["documents"].available is False and planes["tracker"].available is None assert planes["erasure"].mentored is False and planes["code index"].mentored is True + assert out.conflict_backlog["pending_judgement"]["unknown"] == 2 + assert out.conflict_backlog["resolver_judged"]["unknown"] == 3 + assert out.conflict_backlog["cosine_only"]["unknown"] == 4 # A named agent is used as given; the writers list rode along (empty here). assert out.agent == "a" and out.agent_defaulted is False adoption = {a.code: (a.shown_sessions, a.followed_sessions) for a in out.adoption} @@ -2207,6 +2217,39 @@ def test_every_profile_ledger_read_leaves_the_inspectors_out() -> None: assert params["inspectors"] == ["loom-ui", "loom-assistant", "loom-cli-inspect"] +def test_mentor_conflict_backlog_is_namespace_scoped_and_labels_rows() -> None: + from server.insights.store.mentor import ProfileReads + + ch = _CH( + { + M_CONFLICT_BACKLOG: [ + {"judgement": "pending_judgement", "provenance": "unknown", "n": 5}, + {"judgement": "resolver_judged", "provenance": "caller_written", "n": 2}, + {"judgement": "cosine_only", "provenance": "plugin_captured", "n": 3}, + ] + } + ) + reads = ProfileReads( + "org-x", + "ns-y", + "agent", + 3600, + ops={"sets": m.SETS, "gets": m.GETS, "searches": m.SEARCHES, "packs": m.PACKS}, + limits={"ttl": 60, "large": 1, "huge": 2, "advisory": 3, "clip": 4, "episodic_chars": 5}, + ch=ch, + ) + out = asyncio.run(reads.conflict_backlog()) + assert out["pending_judgement"]["unknown"] == 5 + assert out["resolver_judged"]["caller_written"] == 2 + assert out["cosine_only"]["plugin_captured"] == 3 + sql, params = ch.sqls[0], ch.params[0] + assert "FROM loom.memory FINAL" in sql and "FROM loom.memory_embeddings FINAL" in sql + assert "status = 'conflicted'" in sql and "GROUP BY judgement, provenance" in sql + assert "m.capture_origin IN ('claude-code', 'codex')" in sql + assert "created_at, source_class, actor, capture_origin" in sql + assert params == {"org": "org-x", "ns": "ns-y"} + + def test_a_profile_whose_repository_fact_failed_is_remembered_briefly( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/tests/unit/test_namespace_register_preserve.py b/tests/unit/test_namespace_register_preserve.py index 1494c4a14c5..0ee792a9292 100644 --- a/tests/unit/test_namespace_register_preserve.py +++ b/tests/unit/test_namespace_register_preserve.py @@ -32,6 +32,8 @@ "classify_endpoint": "https://classify.example/v1", "classify_prompt_template": "classify {text}", "default_conflict_policy": "manual_review", + "captured_conflict_policy": "resolver_update", + "captured_conflict_confidence": 0.99, } FRESH: dict[str, Any] = { "description": "", @@ -50,6 +52,8 @@ "classify_endpoint": "", "classify_prompt_template": "", "default_conflict_policy": "auto_reinforce", + "captured_conflict_policy": "manual_review", + "captured_conflict_confidence": 0.98, } NOW = datetime(2026, 9, 28, 12, 0, 0) @@ -73,6 +77,12 @@ def test_a_fresh_row_takes_the_default(field: str) -> None: assert _row(None)[field] == FRESH[field] +@pytest.mark.parametrize("field", ["captured_conflict_policy", "captured_conflict_confidence"]) +def test_explicit_null_is_rejected_for_non_nullable_captured_settings(field: str) -> None: + with pytest.raises(ValueError, match="cannot be null"): + NamespaceRegisterInput(org="o", namespace="n", owner_email="o@x", **{field: None}) + + @pytest.mark.parametrize("field", sorted(FRESH)) def test_an_explicit_value_wins_over_the_stored_one(field: str) -> None: assert _row(_existing(), **{field: FRESH[field]})[field] == FRESH[field] @@ -93,6 +103,34 @@ def test_tags_are_replaced_whole() -> None: assert _row(_existing(), tags=["x"])["tags"] == ["x"] +def test_description_save_keeps_a_policy_changed_by_another_admin() -> None: + original = _existing( + captured_conflict_policy="resolver_update", captured_conflict_confidence=0.99 + ) + changed_by_admin_b = h.registry_row( + NamespaceRegisterInput( + org="o", + namespace="n", + owner_email="o@x", + captured_conflict_policy="manual_review", + captured_conflict_confidence=0.82, + ), + original, + NOW, + ) + saved_by_admin_a = h.registry_row( + NamespaceRegisterInput( + org="o", namespace="n", owner_email="o@x", description="updated description" + ), + changed_by_admin_b, + NOW, + ) + + assert saved_by_admin_a["description"] == "updated description" + assert saved_by_admin_a["captured_conflict_policy"] == "manual_review" + assert saved_by_admin_a["captured_conflict_confidence"] == 0.82 + + def test_a_restricted_row_stays_private() -> None: row = _row(_existing(classification="restricted"), visibility="public") assert row["visibility"] == "private" diff --git a/tests/unit/test_namespace_restore_existing_target.py b/tests/unit/test_namespace_restore_existing_target.py index 01a0e464162..eacdfd25663 100644 --- a/tests/unit/test_namespace_restore_existing_target.py +++ b/tests/unit/test_namespace_restore_existing_target.py @@ -550,3 +550,73 @@ async def _record(*_a: Any, subject: dict[str, Any], **_k: Any) -> str: assert out.restored is True and out.publication_pending is True counts = {"memories": 1, "types": 0, "grants": 0, "erased_skipped": 0} assert order == ["memories:1", f"audit:{counts}"] + + +@pytest.mark.asyncio +async def test_restore_of_authenticated_capture_waits_for_every_resolver(wire, monkeypatch) -> None: + """A restore must not introduce a captured row while a legacy resolver is live.""" + from server.core import ch as core_ch + from server.core import instances + from server.core.errors import BackendUnavailableError + from server.core.hashing import sha256_value + from server.identity.api.models import _SnapshotMemoryRow + from server.settings import settings + + install, grants = wire + grants[(ORG, NS, "owner@x")] = Role.ADMIN + ch = install(_deleted_row(active=True), "owner@x", Role.ADMIN) + monkeypatch.setattr(settings, "deployment", "rolling-test") + monkeypatch.setattr(core_ch, "get_client", lambda: ch) + + async def live_rows(_ch: Any) -> list[dict[str, Any]]: + return [{"instance_id": "legacy-resolver", "schema_version": 128}] + + monkeypatch.setattr(instances, "read_live", live_rows) + memory_id = "33333333-3333-3333-3333-333333333333" + value = '"captured"' + value_json = "{}" + content_sha256 = "ab" * 32 + origin_record = { + memory_id: { + "origin": "codex", + "row_hash": sha256_value( + { + "content_sha256": content_sha256, + "value": value, + "value_json": value_json, + } + ), + } + } + query_one = ch.query_one + + async def snapshot_lookup(sql: str, params: Any = None, **kwargs: Any) -> Any: + if "FROM loom.namespace_snapshots" in sql: + return {"captured_origin_map": json.dumps(origin_record)} + return await query_one(sql, params, **kwargs) + + ch.query_one = snapshot_lookup # type: ignore[method-assign] + inp = _restore_input() + memory = _SnapshotMemoryRow( + memory_id=memory_id, + agent="agent", + user_id="-", + session_id="-", + run_id="-", + memory_key="captured", + memory_type="semantic", + value=value, + value_json=value_json, + content_sha256=content_sha256, + confidence=1.0, + source_trace="", + pinned=False, + ) + payload = inp.payload.model_copy(update={"memories": [memory], "memory_count": 1}) + + with pytest.raises(BackendUnavailableError, match="unsupported resolver"): + await namespace_snapshot.handle_namespace_restore( + inp.model_copy(update={"payload": payload}) + ) + + assert ch.inserts == [] diff --git a/tests/unit/test_provenance.py b/tests/unit/test_provenance.py index 0831abacc21..bd8bc2fc02c 100644 --- a/tests/unit/test_provenance.py +++ b/tests/unit/test_provenance.py @@ -22,6 +22,222 @@ def test_writer_actor_kind_comes_from_the_token() -> None: assert writer_actor(fallback="process:consolidation") == "process:consolidation" +def test_capture_origin_is_signed_and_first_write_ignores_body_value( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from datetime import UTC, datetime + + from server.auth.jwt import TokenError, mint_token, verify_token + from server.core import instances + from server.memory.app.provenance import capture_origin + from server.memory.store.rows import build_first_version_row + + token = mint_token( + "sa:claude", "o", ["n"], ["writer"], capture_origin="claude-code", secret="s3" * 16 + ) + auth = verify_token(token, secret="s3" * 16) + assert auth.capture_origin == "claude-code" + with pytest.raises(TokenError): + mint_token("sa:claude", "o", ["n"], ["writer"], capture_origin="fake", secret="s3" * 16) + with pytest.raises(TokenError, match="service-account"): + mint_token( + "alice", + "o", + ["n"], + ["writer"], + is_service_account=False, + capture_origin="claude-code", + secret="s3" * 16, + ) + + set_current_auth(auth) + monkeypatch.setattr(instances, "every_live_replica_at", lambda migration: True) + assert capture_origin() == "claude-code" + at = datetime(2026, 1, 1, tzinfo=UTC) + row = build_first_version_row( + { + "org": "o", + "namespace": "n", + "agent": "agent", + "user_id": "-", + "session_id": "-", + "memory_key": "fact", + "memory_type": "semantic", + "value": "{}", + "version": 1, + "content_sha256": "a" * 64, + "actor": "process:claude", + "source_class": "observed", + "capture_origin": "codex", + }, + now=at, + capture_origin="claude-code", + ) + assert row["capture_origin"] == "claude-code" + set_current_auth(None) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("instance_ids", "blocked"), + [(["legacy"], True), (["ccp1-current"], False), (["ccp1-current", "legacy"], True)], +) +async def test_capture_origin_waits_until_every_live_replica_reports_support( + monkeypatch: pytest.MonkeyPatch, instance_ids: list[str], blocked: bool +) -> None: + from server.core import instances + from server.core.errors import BackendUnavailableError + from server.memory.app.provenance import capture_origin_for_write + from server.settings import settings + + set_current_auth(SimpleNamespace(subject="test", org="o", capture_origin="claude-code")) + monkeypatch.setattr(settings, "deployment", "rolling-test") + + async def live_rows(_ch): + return [{"instance_id": instance_id, "schema_version": 128} for instance_id in instance_ids] + + monkeypatch.setattr(instances, "read_live", live_rows) + try: + if blocked: + with pytest.raises(BackendUnavailableError) as exc: + await capture_origin_for_write() + assert exc.value.status_code == 503 + assert exc.value.extra["retry_after_s"] == 5 + else: + assert await capture_origin_for_write() == "claude-code" + finally: + set_current_auth(None) + + +def test_instance_id_advertises_capture_provenance_capability() -> None: + from server.core.instances import CAPTURED_CONFLICT_PROVENANCE_MARKER, instance_id + + assert instance_id().startswith(CAPTURED_CONFLICT_PROVENANCE_MARKER) + + +def test_memory_version_builder_carries_capture_origin() -> None: + from datetime import datetime + + from server.memory.store.rows import MemoryRow, build_memory_version_row + + row = MemoryRow( + memory_id="id", + org="o", + namespace="n", + agent="agent", + user_id="-", + session_id="-", + memory_key="fact", + memory_type="semantic", + value="value", + confidence=1.0, + version=1, + pinned=False, + created_at=datetime(2026, 1, 1), + expires_at=None, + capture_origin="codex", + ) + assert build_memory_version_row(row, version=2)["capture_origin"] == "codex" + + +def test_content_changes_take_the_verified_writer_origin_and_copies_keep_the_old_one() -> None: + from datetime import datetime + + from server.auth.jwt import mint_token, verify_token + from server.memory.app.provenance import revision_capture_origin + from server.memory.store.rows import MemoryRow, build_revision_row + + token = mint_token( + "sa:claude", "o", ["n"], ["writer"], capture_origin="claude-code", secret="s3" * 16 + ) + set_current_auth(verify_token(token, secret="s3" * 16)) + try: + row = MemoryRow( + memory_id="m1", + org="o", + namespace="n", + agent="agent", + user_id="-", + session_id="-", + memory_key="fact", + memory_type="semantic", + value="old", + confidence=1.0, + version=1, + pinned=False, + created_at=datetime(2026, 1, 1), + expires_at=None, + content_sha256="a" * 64, + capture_origin="codex", + ) + assert revision_capture_origin("a" * 64, "a" * 64) is None + origin = revision_capture_origin("a" * 64, "b" * 64) + assert origin == "claude-code" + assert build_revision_row(row, {"value": "copy"})["capture_origin"] == "codex" + assert ( + build_revision_row(row, {"value": "replacement"}, capture_origin=origin)[ + "capture_origin" + ] + == "claude-code" + ) + finally: + set_current_auth(None) + + +@pytest.mark.parametrize( + ("winner_origin", "retired_origin", "winner_user", "threshold", "expected"), + [ + ("claude-code", "codex", "u1", 0.70, True), + ("", "codex", "u1", 0.70, False), + ("claude-code", "", "u1", 0.70, False), + ("claude-code", "codex", "u1", 0.90, False), + ("claude-code", "codex", "u2", 0.70, False), + ], +) +def test_captured_settlement_requires_owner_policy_trusted_same_subject_update( + winner_origin: str, + retired_origin: str, + winner_user: str, + threshold: float, + expected: bool, +) -> None: + from server.memory.domain.conflict_resolution import captured_update_eligible + + assert ( + captured_update_eligible( + policy="resolver_update", + verdict="update", + confidence=0.80, + threshold=threshold, + same_entity=True, + same_attribute=True, + winner_origin=winner_origin, + retired_origin=retired_origin, + winner_agent="agent", + retired_agent="agent", + winner_user_id=winner_user, + retired_user_id="u1", + cross_session=False, + ) + is expected + ) + assert not captured_update_eligible( + policy="resolver_update", + verdict="contradiction", + confidence=0.99, + threshold=0.50, + same_entity=True, + same_attribute=True, + winner_origin="claude-code", + retired_origin="codex", + winner_agent="agent", + retired_agent="agent", + winner_user_id="u1", + retired_user_id="u1", + cross_session=False, + ) + + def test_trace_conventions_imply_a_class() -> None: assert prov.class_from_trace("pipeline:set_from_messages|prompt=x") == "extracted" assert prov.class_from_trace("conversation:abc") == "extracted" diff --git a/tests/unit/test_read_scope_admission.py b/tests/unit/test_read_scope_admission.py index 16e3dddc5df..58ce548d779 100644 --- a/tests/unit/test_read_scope_admission.py +++ b/tests/unit/test_read_scope_admission.py @@ -624,9 +624,14 @@ async def count_review(org: str, namespace: str, *, scope: ReadFilters) -> tuple seen.append(scope) return (7, 2) if scope is WHOLE_NAMESPACE else (1, 0) - repo = SimpleNamespace(count_review=count_review) - assert await conflicts_ops._review_counts_cached(repo, "o", "n", WHOLE_NAMESPACE) == (7, 2) - assert await conflicts_ops._review_counts_cached(repo, "o", "n", U1) == (1, 0) + async def count_conflict_backlog( + org: str, namespace: str, *, scope: ReadFilters + ) -> dict[str, dict[str, int]]: + return {} + + repo = SimpleNamespace(count_review=count_review, count_conflict_backlog=count_conflict_backlog) + assert await conflicts_ops._review_counts_cached(repo, "o", "n", WHOLE_NAMESPACE) == (7, 2, {}) + assert await conflicts_ops._review_counts_cached(repo, "o", "n", U1) == (1, 0, {}) assert seen == [WHOLE_NAMESPACE, U1] conflicts_ops.reset_conflicts_count_cache() diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py index 72a4fe33648..5db6292c566 100644 --- a/tests/unit/test_schema_baseline.py +++ b/tests/unit/test_schema_baseline.py @@ -180,6 +180,7 @@ def test_the_journal_files() -> None: "122_read_receipts.sql", "123_namespace_curator_mode.sql", "124_knowledge_source_worker_subject.sql", + "125_captured_conflict_provenance.sql", "128_skills.sql", "130_knowledge_suites.sql", "132_stewardship_events.sql",