Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: log operator actions to a machine-local user_action_events ledger (#5594)
[._.]/ Adam Eivy67216d40c88f
diff --git a/docs/API.md b/docs/API.mdindex ce7fe40e07..707a250646 100644--- a/docs/API.md+++ b/docs/API.md@@ -632,6 +632,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/feeds` | RSS/content feeds || `/api/catalog` | Creative ingredients catalog || `/api/tribe` | Tribe relationship graph |+| `/api/user-actions` | Operator-action ledger — read-only log of what the user did (machine-local) || `/api/notes` | Notes || `/api/calendar` | Calendar integration || `/api/messages` | Messages (email) integration |diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 06026cdd31..566bc1d434 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -32,6 +32,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store).- `memories` / `memory_links` — long-term memory + pgvector similarity.- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).+- `user_action_events` — the operator-action ledger (#5594): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings). `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and PII must not ride the federation layer (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.diff --git a/scripts/migrations/328-user-action-events-table.js b/scripts/migrations/328-user-action-events-table.jsnew file mode 100644index 0000000000..1615484e05--- /dev/null+++ b/scripts/migrations/328-user-action-events-table.js@@ -0,0 +1,27 @@+/**+ * Registration stub for the user_action_events table (issue #5594, epic #5593).+ *+ * The actual DDL — `CREATE TABLE IF NOT EXISTS user_action_events` plus its+ * `idx_user_action_dedupe` unique index and the `idx_user_action_happened` /+ * `idx_user_action_type_time` / `idx_user_action_actor_time` indexes — is+ * idempotent and lives in `ensureSchema()` (`server/lib/db/schema/userActions.js`,+ * composed by `server/lib/db.js`) and the fresh-install seed+ * (`server/scripts/init-db.sql`), both of which run at server boot AFTER the DB+ * pool is up. The `scripts/migrations/` runner executes BEFORE the pool is+ * initialized, so a DB-table create cannot live here — the same reason+ * migrations 048–052, 108, and 161 are boot-time + stub-registered.+ *+ * This stub exists so the new-table change is *registered the standard way*: it+ * lands in `data/migrations.applied.json` so the migration ledger and `git log`+ * show when the operator-action ledger was introduced. The table is additive (a+ * brand-new, machine-local db-primary store), so there is no data backfill —+ * `server/services/userActions.js` populates it as the user acts.+ *+ * No-op + idempotent: nothing to do here.+ */++export default {+ async up() {+ console.log('🧾 user_action_events: table created idempotently by ensureSchema at boot; nothing to do in the file runner');+ },+};diff --git a/server/index.js b/server/index.jsindex 875fd33ac2..58ec6ffb7b 100644--- a/server/index.js+++ b/server/index.js@@ -52,6 +52,7 @@ import gsdRoutes from './routes/gsd.js';import catalogRoutes from './routes/catalog.js';import memoryRoutes from './routes/memory.js';import tribeRoutes from './routes/tribe.js';+import userActionsRoutes from './routes/userActions.js';import timelineRoutes from './routes/timeline.js';import imessageRoutes from './routes/imessage.js';import contactsRoutes from './routes/contacts.js';@@ -321,6 +322,7 @@ app.use('/api/feeds', feedsRoutes);app.use('/api/catalog', catalogRoutes);app.use('/api/memory', memoryRoutes);app.use('/api/tribe', tribeRoutes);+app.use('/api/user-actions', userActionsRoutes);app.use('/api/timeline', timelineRoutes);app.use('/api/imessage', imessageRoutes);app.use('/api/contacts', contactsRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex 7983d2318c..1d310a8156 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -467,6 +467,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `repoIntakeActions.js` | `REPO_INTAKE_KEYS` + `normalizeRepoIntake(input)` — the opt-in post-clone agent actions a Brain capture can request for a GitHub repo URL (`malwareScan` → `/do:scan`, `learn` → a `repo-study` review). Pure half of `services/repoIntake.js` (which pulls the CoS task graph), so the link write path and the Zod schemas can import it freely. Normalizes to null when nothing was ticked, so "no intake" is never persisted onto a link. || `tombstones.js` | Generic timestamped tombstones (`{ <keyField>, deletedAt }`) that let an otherwise add-only peer merge represent a DELETE, so a record removed on one machine is not resurrected by a peer that still has it (#3530). `normalizeTombstones` / `recordTombstone` / `clearTombstone` / `tombstoneTimestamp` maintain the list; `mergeTombstones` unions it in both directions (newest deletion per key wins) so a delete propagates rather than only defending locally; `isTombstoned(list, key, createdAt)` suppresses a record unless its own creation stamp is strictly NEWER than the deletion; `pruneTombstones(list, records)` drops tombstones a re-created record has superseded (otherwise a stale peer copy keeps reaping it); `supersedingTimestamp(deletedAt)` stamps a re-create that lands in the same millisecond (or behind a skewed peer clock). Comparison goes through `lwwTimestamp.js`, so polarity matches every other sync merge. Key on a field that means the same thing on every machine — locally-minted ids usually do not. `DEFAULT_TOMBSTONE_LIMIT` (200) caps growth. || `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. |+| `userActionTypes.js` | Closed vocabulary for the operator-action ledger (`user_action_events`, #5594): `USER_ACTION_TYPES` (the phase-1 action list), `USER_ACTION_ACTORS` (`user` / `mind` / `schedule` / `system`), and the `isUserActionType` / `isUserActionActor` predicates. `recordUserAction` (`services/userActions.js`) throws on a type absent from the list, so a typo fails a test instead of writing a row nothing can filter on. || `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. || `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. || `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex d1dc8cbc23..ef15e95d66 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -138,6 +138,7 @@"/api/update","/api/uploads","/api/usage",+ "/api/user-actions","/api/video-gen","/api/video-timeline","/api/voice",@@ -5183,7 +5184,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 480+ "line": 561}]},@@ -6239,7 +6240,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 100+ "line": 139}]},@@ -6250,7 +6251,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 364+ "line": 405}]},@@ -6261,7 +6262,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 422+ "line": 478}]},@@ -6272,7 +6273,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 380+ "line": 422}]},@@ -6283,7 +6284,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 434+ "line": 505}]},@@ -6294,7 +6295,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 447+ "line": 528}]},@@ -6305,7 +6306,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 464+ "line": 545}]},@@ -6316,7 +6317,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 486+ "line": 567}]},@@ -6327,7 +6328,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 154+ "line": 193}]},@@ -6338,7 +6339,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 130+ "line": 169}]},@@ -6349,7 +6350,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 330+ "line": 370}]},@@ -6360,7 +6361,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 136+ "line": 175}]},@@ -6371,7 +6372,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 142+ "line": 181}]},@@ -6382,7 +6383,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 173+ "line": 212}]},@@ -6393,7 +6394,7 @@"sources": [{"source": "server/routes/cosTaskRoutes.js",- "line": 124+ "line": 163}]},@@ -22243,6 +22244,28 @@}]},+ {+ "method": "GET",+ "path": "/api/user-actions",+ "mountPath": "/api/user-actions",+ "sources": [+ {+ "source": "server/routes/userActions.js",+ "line": 32+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/user-actions/types",+ "mountPath": "/api/user-actions",+ "sources": [+ {+ "source": "server/routes/userActions.js",+ "line": 22+ }+ ]+ },{"method": "POST","path": "/api/video-gen",@@ -23807,9 +23830,9 @@}],"stats": {- "mounts": 146,- "operations": 2148,- "declarations": 2151,- "sourceFiles": 227+ "mounts": 147,+ "operations": 2150,+ "declarations": 2153,+ "sourceFiles": 228}}diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 0224b1bf2d..3c8df2f059 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -94,9 +94,12 @@ function extractColumnNames(body) {.filter((p) => p && !/^(PRIMARY|FOREIGN|UNIQUE|CHECK|CONSTRAINT)$/i.test(p));}+// Matches both plain and UNIQUE index declarations: a dedupe index is usually+// the UNIQUE one (idx_user_action_dedupe), and a name captured on only one side+// of the parity check is exactly the drift this file exists to catch.function extractIndexNames(source, prefix = 'idx_catalog_') {const out = new Set();- const re = new RegExp(`CREATE INDEX IF NOT EXISTS\\s+(${prefix}\\w+)`, 'gi');+ const re = new RegExp(`CREATE (?:UNIQUE )?INDEX IF NOT EXISTS\\s+(${prefix}\\w+)`, 'gi');let m;while ((m = re.exec(source)) !== null) out.add(m[1]);return out;@@ -168,6 +171,32 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {expect(sqlIdx.size).toBeGreaterThan(0);});+ // The operator-action ledger (#5594) is a machine-local db-primary table that+ // ships in BOTH sources. `human_activity_events` has no dedicated assertion here+ // and that is a gap, not a precedent — a column or index added to one file only+ // would leave every EXISTING install without it (init-db.sql runs on fresh+ // provisioning alone), so pin columns and index names for this one explicitly.+ it('user_action_events has the same columns and indexes in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'user_action_events');+ const jsBody = extractCreateTable(DB_JS, 'user_action_events');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE user_action_events').toBeTruthy();+ expect(jsBody, 'db/schema/userActions.js missing CREATE TABLE user_action_events').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());++ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_user_action_');+ const jsIdx = extractIndexNames(DB_JS, 'idx_user_action_');+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());+ // The dedupe index is the idempotency contract (ON CONFLICT (type, dedupe_key)+ // DO NOTHING) — name it so dropping it can never read as a passing set match.+ expect([...sqlIdx].sort()).toEqual([+ 'idx_user_action_actor_time',+ 'idx_user_action_dedupe',+ 'idx_user_action_happened',+ 'idx_user_action_type_time',+ ]);+ });+it('every idx_catalog_* index name appears in both files', () => {const sqlIdx = extractIndexNames(INIT_SQL);const jsIdx = extractIndexNames(DB_JS);diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 8d54bfdfaa..2fd277ca2c 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -23,6 +23,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by| `humanActivity.js` | `humanActivityDdl` | Human-activity timeline event store (machine-local) || `post.js` | `postDdl` | MeatSpace POST normalized runs and attempts (machine-local) || `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) |+| `userActions.js` | `userActionsDdl` | Operator-action ledger — what the human did in the UI (machine-local) || `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types || `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets || `universes.js` | `universesDdl` | Universes, machine-local character voice profiles/renders, + universe run history |@@ -37,7 +38,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by### Composer (`index.js`)-- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions`).+- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions`).- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →`audit` DDL → audit triggers).diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.jsindex 13df998efe..04419ead62 100644--- a/server/lib/db/schema/index.js+++ b/server/lib/db/schema/index.js@@ -18,6 +18,7 @@ import { tribeDdl } from './tribe.js';import { humanActivityDdl } from './humanActivity.js';import { postDdl } from './post.js';import { commissionsDdl } from './commissions.js';+import { userActionsDdl } from './userActions.js';import { catalogDdl, catalogUserTypesDdl } from './catalog.js';import { mediaDdl } from './media.js';import { universesDdl } from './universes.js';@@ -36,6 +37,7 @@ export {humanActivityDdl,postDdl,commissionsDdl,+ userActionsDdl,catalogDdl,catalogUserTypesDdl,mediaDdl,@@ -53,8 +55,8 @@ export {};// Phase 1 — the `upgrades` list: memory-sync columns + migration tracker, then-// the machine-local Tribe / human-activity / POST / commission tables. Run first,-// before the catalog block.+// the machine-local Tribe / human-activity / POST / commission / user-action+// tables. Run first, before the catalog block.export function buildUpgradeDdl() {return [...coreDdl,@@ -62,6 +64,7 @@ export function buildUpgradeDdl() {...humanActivityDdl,...postDdl,...commissionsDdl,+ ...userActionsDdl,];}diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.jsindex 33e5bd7f82..4fb64592ed 100644--- a/server/lib/db/schema/schema.test.js+++ b/server/lib/db/schema/schema.test.js@@ -25,7 +25,7 @@ import {} from './index.js';const DOMAIN_ARRAYS = [- 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl',+ 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl','catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl','libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl','auditDdl',@@ -46,6 +46,7 @@ describe('db/schema barrel + composer (#2832)', () => {...schema.humanActivityDdl,...schema.postDdl,...schema.commissionsDdl,+ ...schema.userActionsDdl,];expect(buildUpgradeDdl()).toEqual(expected);});diff --git a/server/lib/db/schema/userActions.js b/server/lib/db/schema/userActions.jsnew file mode 100644index 0000000000..7d62a9de45--- /dev/null+++ b/server/lib/db/schema/userActions.js@@ -0,0 +1,31 @@+// Operator-action ledger DDL (#5594, epic #5593) — the durable, filterable+// record of what the human actually did in PortOS (queued a CoS task, rated an+// agent run, hit Run Now on a schedule, changed settings).+//+// Machine-local like `human_activity_events`: excluded from peer sync, guarded+// in sharing/peerSync.test.js. Idempotent via the unique (type, dedupe_key)+// index + ON CONFLICT DO NOTHING, so a retried request records once.+//+// Deliberately NOT in `auditedTables` (server/lib/db/schema/audit.js) — this is+// a personal operator log, same rationale as `post_runs`; auditing an audit log+// doubles every row for no recoverable value.+export const userActionsDdl = [+ `CREATE TABLE IF NOT EXISTS user_action_events (+ id TEXT PRIMARY KEY,+ type TEXT NOT NULL,+ actor TEXT NOT NULL,+ happened_at TIMESTAMPTZ NOT NULL,+ target TEXT,+ target_name TEXT,+ success BOOLEAN NOT NULL DEFAULT TRUE,+ summary TEXT NOT NULL,+ payload JSONB NOT NULL DEFAULT '{}'::jsonb,+ source JSONB NOT NULL DEFAULT '{}'::jsonb,+ dedupe_key TEXT NOT NULL,+ created_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_user_action_dedupe ON user_action_events (type, dedupe_key)`,+ `CREATE INDEX IF NOT EXISTS idx_user_action_happened ON user_action_events (happened_at DESC)`,+ `CREATE INDEX IF NOT EXISTS idx_user_action_type_time ON user_action_events (type, happened_at DESC)`,+ `CREATE INDEX IF NOT EXISTS idx_user_action_actor_time ON user_action_events (actor, happened_at DESC)`,+];diff --git a/server/lib/index.js b/server/lib/index.jsindex 8613df9f5d..b5128e27fd 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -444,6 +444,7 @@ export * from './sseUtils.js';export * from './repoIntakeActions.js';export * from './tombstones.js';export * from './uploadLimits.js';+export * from './userActionTypes.js';export * from './uuid.js';export * from './versionUtils.js';export * from './workTracker.js';diff --git a/server/lib/userActionTypes.js b/server/lib/userActionTypes.jsnew file mode 100644index 0000000000..83da3f0c8a--- /dev/null+++ b/server/lib/userActionTypes.js@@ -0,0 +1,45 @@+/**+ * Closed vocabulary for the operator-action ledger (#5594, epic #5593).+ *+ * `user_action_events` exists so a later phase can ask "what did the user+ * actually do?" without replaying every log PortOS keeps. That question is only+ * answerable if the type column is a small, stable, enumerable set — an+ * open-ended string would drift into a second, unqueryable `history.jsonl`.+ * `recordUserAction` therefore THROWS on a type absent from this list rather+ * than inventing one silently, so a typo fails a test instead of quietly+ * writing a row nothing will ever filter on.+ *+ * Adding a type is a deliberate act: append it here, hook the exact mutation+ * site that produces it, and give it a test. Phase 2/3 of the epic expand this+ * list (mind-queued tasks, creative generation, Brain captures); a value living+ * here does NOT imply anything writes it yet — `mind` is a reserved actor with+ * no phase-1 producer.+ */++/**+ * Who performed the action. `user` is a human acting through the UI/API;+ * `schedule` is a cron-style automation the user configured; `mind` is the+ * Persistent Mind acting on its own (reserved — phase 2); `system` is PortOS+ * itself (boot, restore, internal maintenance). The distinction is the whole+ * point of the ledger: a settings write from the settings page and one from a+ * backup restore must never read as the same event.+ */+export const USER_ACTION_ACTORS = Object.freeze(['user', 'mind', 'schedule', 'system']);++/** Phase-1 operator actions (issue #5594). */+export const USER_ACTION_TYPES = Object.freeze([+ 'cos.task.create',+ 'cos.task.update',+ 'cos.task.delete',+ 'cos.task.approve',+ 'cos.task.spawn',+ 'cos.agent.feedback',+ 'cos.schedule.trigger',+ 'settings.update',+]);++const TYPES = new Set(USER_ACTION_TYPES);+const ACTORS = new Set(USER_ACTION_ACTORS);++export const isUserActionType = (value) => typeof value === 'string' && TYPES.has(value);+export const isUserActionActor = (value) => typeof value === 'string' && ACTORS.has(value);diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 1b42c1be35..09de8871a5 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -20,6 +20,7 @@ import {isFederatedMediaAudioPrompt,} from './federatedMediaWire.js';import { isPlainObject } from './objects.js';+import { USER_ACTION_ACTORS, USER_ACTION_TYPES } from './userActionTypes.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total// pixels. Mirror the ceiling for every image-gen route. Local mflux can@@ -1629,6 +1630,33 @@ export const shellImageDropSchema = z.object({message: z.string().max(5000).optional()});+// =============================================================================+// USER ACTION LEDGER+// =============================================================================++// GET /api/user-actions — read the machine-local operator-action ledger (#5594).+// Every value arrives as a query string, so numbers are coerced and `success` is+// the string form of the boolean. Range checking is deliberately loose here and+// the CLAMP lives in `userActions.normalizeListOptions`: a caller asking for 5000+// rows wants "as many as you will give me", not a 400.+const isParseableDate = (value) => !Number.isNaN(new Date(value).getTime());+const userActionDateFilter = z.string().trim().min(1).max(64)+ .refine(isParseableDate, 'must be a parseable date');+const userActionType = z.enum([...USER_ACTION_TYPES]);++export const userActionsListQuerySchema = z.object({+ type: userActionType.optional(),+ // Repeated `?types=a&types=b` arrives as an array; a single one as a string.+ types: z.union([userActionType, z.array(userActionType)]).optional(),+ actor: z.enum([...USER_ACTION_ACTORS]).optional(),+ target: z.string().trim().min(1).max(200).optional(),+ success: z.enum(['true', 'false']).optional(),+ from: userActionDateFilter.optional(),+ to: userActionDateFilter.optional(),+ limit: z.coerce.number().int().optional(),+ offset: z.coerce.number().int().optional(),+});+// =============================================================================// CLIENT ERROR REPORT// =============================================================================diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex 21dff5728d..9585cbcbc9 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -1,7 +1,27 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import express from 'express';+import { rmSync } from 'node:fs';import { request } from '../lib/testHelper.js';import { ServerError } from '../lib/errorHandler.js';++// The CoS task routes write operator-action rows (#5594) through the ledger's+// file backend, which resolves under PATHS.data — re-root it so this suite can+// never write into the developer's live `data/` tree (#3683/#3687). Everything+// else in fileUtils stays real. `vi.hoisted` because the router below is a+// STATIC import, so the mock factory runs during module linking.+const ledgerRoot = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ return mkdtempSync(join(tmpdir(), 'portos-cos-routes-ledger-'));+});+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ const { makePathsProxy } = await import('../lib/mockPathsDataRoot.js');+ return makePathsProxy(actual, { dataRoot: ledgerRoot });+});+afterAll(() => rmSync(ledgerRoot, { recursive: true, force: true }));+import cosRoutes from './cos.js';// Mock the cos service@@ -19,6 +39,8 @@ vi.mock('../services/cos.js', () => ({reorderTasks: vi.fn(),addTask: vi.fn(),updateTask: vi.fn(),+ // Read by the DELETE route so the ledger row keeps the task's description.+ getTaskById: vi.fn(async () => null),deleteTask: vi.fn(),approveTask: vi.fn(),evaluateTasks: vi.fn(),diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex 1402729831..3fda3696a5 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -15,6 +15,7 @@ import { workTrackerLabel } from '../lib/workTracker.js';import { getSlashdoWorkflow, slashdoWorkflowAppliesTo, SLASHDO_COMMAND_NAMES } from '../lib/slashdoCatalog.js';import { NON_PM2_TYPES } from '../services/streamingDetect.js';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';+import { recordUserAction } from '../services/userActions.js';import {createCosTaskSchema,slashdoTaskSchema,@@ -31,6 +32,44 @@ const enhanceTaskSchema = z.object({context: z.string().optional(),});+// ── Operator-action ledger (#5594) ──────────────────────────────────────────+//+// Hooked at the THREE HTTP create routes below rather than at+// `cosTaskStore.addTask`, which is ALSO the generator / autopilot / mind dispatch+// path. Only a request arriving here is a human pressing a button, and the whole+// point of the ledger is to separate those from everything PortOS queues itself.+//+// Every write is awaited before the response (same posture as `history.logAction`),+// and every hook fires only AFTER the mutation succeeded — a 409/404 is not an+// operator action that happened.+const TASK_CREATE_PAYLOAD_FIELDS = [+ 'prompt', 'description', 'context', 'provider', 'model', 'effort', 'app',+ 'useWorktree', 'openPR', 'prCompletion', 'planOnly', 'reviewLoop', 'reviewers',+ 'approvalRequired',+ // The one create field with an open shape (`cosTaskDiagnosticsSchema` is a+ // passthrough), so it is both the most informative thing to keep and the reason+ // `recordUserAction` redacts credential-shaped keys at all.+ 'diagnostics',+];++const routeSource = (req) => ({ route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method });++const pickDefined = (source, fields) => Object.fromEntries(+ fields.filter((field) => source?.[field] !== undefined).map((field) => [field, source[field]]),+);++async function logTaskCreated(req, task, taskData) {+ await recordUserAction({+ type: 'cos.task.create',+ target: task.id,+ targetName: task.description,+ summary: `Queued CoS task: ${task.description}`,+ payload: { taskId: task.id, ...pickDefined(taskData, TASK_CREATE_PAYLOAD_FIELDS) },+ source: routeSource(req),+ dedupeKey: `cos.task.create:${task.id}`,+ });+}+// One-off "implement THIS JIRA ticket" task (the per-card play button on the// app overview's sprint board). `ticketKey` is a JIRA key like `PROJ-1234`.const jiraTicketTaskSchema = z.object({@@ -319,6 +358,7 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {throw new ServerError(`A task with this description is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });}+ await logTaskCreated(req, result, taskData);res.json(result);}));@@ -357,6 +397,7 @@ router.post('/tasks/jira-ticket', asyncHandler(async (req, res) => {throw new ServerError(`A task for ${key} is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });}+ await logTaskCreated(req, result, taskData);res.json(result);}));@@ -373,6 +414,7 @@ router.post('/tasks', asyncHandler(async (req, res) => {throw new ServerError(`A task with this description is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });}+ await logTaskCreated(req, result, preparedTask);res.json(result);}));@@ -415,6 +457,20 @@ router.put('/tasks/:id', asyncHandler(async (req, res) => {if (result?.error) {throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });}++ // An edit is not an idempotent retry — two saves of the same field are two+ // distinct operator actions — so the timestamp is part of the dedupe key.+ const happenedAt = new Date().toISOString();+ await recordUserAction({+ type: 'cos.task.update',+ target: id,+ targetName: result?.description,+ summary: `Edited CoS task ${id}: ${Object.keys(updates).join(', ') || 'no fields'}`,+ payload: { taskId: id, ...updates },+ source: routeSource(req),+ happenedAt,+ dedupeKey: `cos.task.update:${id}:${happenedAt}`,+ });res.json(result);}));@@ -423,10 +479,25 @@ router.delete('/tasks/:id', asyncHandler(async (req, res) => {const { id } = req.params;const { type = 'user' } = req.query;+ // Read the description BEFORE the delete: once the row is gone the ledger's+ // only handle on what was thrown away would be an opaque task id.+ // `.catch` because this read only supplies a LABEL — a task file that will not+ // parse must not turn a working delete into a 500.+ const doomed = await cos.getTaskById(id).catch(() => null);const result = await cos.deleteTask(id, type);if (result?.error) {throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });}++ await recordUserAction({+ type: 'cos.task.delete',+ target: id,+ targetName: doomed?.description,+ summary: `Deleted CoS task ${id}${doomed?.description ? `: ${doomed.description}` : ''}`,+ payload: { taskId: id, description: doomed?.description ?? null },+ source: routeSource(req),+ dedupeKey: `cos.task.delete:${id}`,+ });res.json(result);}));@@ -438,6 +509,16 @@ router.post('/tasks/:id/approve', asyncHandler(async (req, res) => {if (result?.error) {throw new ServerError(result.error, { status: 400, code: 'BAD_REQUEST' });}++ await recordUserAction({+ type: 'cos.task.approve',+ target: id,+ targetName: result?.description,+ summary: `Approved CoS task ${id}${result?.description ? `: ${result.description}` : ''}`,+ payload: { taskId: id },+ source: routeSource(req),+ dedupeKey: `cos.task.approve:${id}`,+ });res.json(result);}));@@ -501,6 +582,19 @@ router.post('/tasks/:id/spawn', asyncHandler(async (req, res) => {}throw new ServerError(result.error, { status, code });}++ // Force-spawn is repeatable (spawn, it fails, spawn again), so each press is+ // its own row — hence the timestamp in the dedupe key.+ const happenedAt = new Date().toISOString();+ await recordUserAction({+ type: 'cos.task.spawn',+ target: req.params.id,+ summary: `Force-spawned CoS task ${req.params.id}`,+ payload: { taskId: req.params.id },+ source: routeSource(req),+ happenedAt,+ dedupeKey: `cos.task.spawn:${req.params.id}:${happenedAt}`,+ });res.json(result);}));diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.jsindex 67ea396afb..e7915ad4b4 100644--- a/server/routes/cosTaskRoutes.test.js+++ b/server/routes/cosTaskRoutes.test.js@@ -4,13 +4,41 @@* be re-settable and CLEARABLE on update, and be refused when it names an* instance this install doesn't know — a pin nothing matches would leave the* task pending on every peer forever.+ *+ * Also the operator-action ledger hooks (#5594): these routes are the ONLY CoS+ * task writes that are a human pressing a button, so they are where the ledger+ * rows are produced. Those cases run against the real `services/userActions.js`+ * on its file backend (with `PATHS.data` re-rooted at a temp dir below) so they+ * assert a PERSISTED row rather than a mock call.*/-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import express from 'express';+import { rmSync } from 'node:fs';+import { join } from 'node:path';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';+// Re-root PATHS.data so the ledger writes land in a temp dir instead of the+// developer's live `data/` tree (#3683/#3687). Everything else in fileUtils+// stays real.+//+// `vi.hoisted` + an in-factory import, rather than the shorter+// `mockPathsDataRoot()` destructure: this file imports the router STATICALLY, so+// the mock factory runs during module linking — before any module-body const is+// initialized.+const tempRoot = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join: joinPath } = await import('node:path');+ return mkdtempSync(joinPath(tmpdir(), 'portos-cos-task-routes-'));+});+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ const { makePathsProxy } = await import('../lib/mockPathsDataRoot.js');+ return makePathsProxy(actual, { dataRoot: tempRoot });+});+vi.mock('../services/cos.js', () => ({addTask: vi.fn(),updateTask: vi.fn(),@@ -26,6 +54,7 @@ vi.mock('../services/cos.js', () => ({resolveTaskChallengeWithRecheck: vi.fn(),evaluateTasks: vi.fn(),reviveBlockedTask: vi.fn(),+ forceSpawnTask: vi.fn(),}));vi.mock('../services/taskWatcher.js', () => ({ refreshTasks: vi.fn() }));vi.mock('../services/taskEnhancer.js', () => ({ enhanceTaskPrompt: vi.fn() }));@@ -43,6 +72,7 @@ import { getAssignableInstances } from '../services/instances.js';import { getAppById, getAppWorkTracker } from '../services/apps.js';import { resolveManagedAppIssueTarget } from '../services/managedAppRepositories.js';import cosTaskRoutes from './cosTaskRoutes.js';+import { listUserActions } from '../services/userActions.js';const SELF = 'self-instance-id';const PEER = 'peer-instance-id';@@ -55,8 +85,11 @@ const buildApp = () => {return app;};+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));+beforeEach(() => {vi.clearAllMocks();+ rmSync(join(tempRoot, 'user-action-events.json'), { force: true });getAssignableInstances.mockResolvedValue([{ instanceId: SELF, name: 'workstation', isSelf: true },{ instanceId: PEER, name: 'render-box', isSelf: false },@@ -194,3 +227,103 @@ describe('PUT /api/cos/tasks/:id — targetInstanceId (#4520)', () => {expect(metadataOf()).toEqual({ targetInstanceId: PEER, blocker: 'waiting on hardware' });});});+++// ── Operator-action ledger (#5594) ──────────────────────────────────────────+describe('CoS task routes write operator-action rows (#5594)', () => {+ const onlyType = async (type) => (await listUserActions({ type }));++ it('records cos.task.create with the run settings, a truncated prompt, and no secret value', async () => {+ const prompt = `render the shot ${'x'.repeat(5000)}`;+ const res = await request(buildApp())+ .post('/api/cos/tasks')+ .send({+ description: 'Render the opening shot',+ prompt,+ provider: 'claude',+ model: 'opus',+ effort: 'high',+ app: 'portos-default',+ useWorktree: true,+ openPR: true,+ // `diagnostics` is the one create field with an open shape+ // (cosTaskDiagnosticsSchema passthrough), so a credential-shaped key+ // genuinely survives validation and reaches the recorder here.+ diagnostics: { category: 'render', apiKey: 'sk-EXAMPLE-not-a-real-key' },+ });++ expect(res.status).toBe(200);+ const [event] = await onlyType('cos.task.create');+ expect(event).toMatchObject({+ actor: 'user',+ target: 'task-1',+ success: true,+ dedupeKey: 'cos.task.create:task-1',+ source: { route: '/api/cos/tasks', method: 'POST' },+ });+ expect(event.payload).toMatchObject({+ taskId: 'task-1',+ provider: 'claude',+ model: 'opus',+ effort: 'high',+ app: 'portos-default',+ useWorktree: true,+ openPR: true,+ });+ expect(event.payload.prompt.length).toBeLessThan(prompt.length);+ expect(event.payload.truncated).toBe(true);+ expect(event.payload.redactedKeys).toEqual(['diagnostics.apiKey']);+ expect(JSON.stringify(event)).not.toContain('sk-EXAMPLE-not-a-real-key');+ });++ it('records nothing when the create is refused as a duplicate', async () => {+ cos.addTask.mockResolvedValueOnce({ id: 'task-1', duplicate: true, status: 'pending' });+ const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'Render the opening shot' });+ expect(res.status).toBe(409);+ expect(await listUserActions()).toEqual([]);+ });++ it('records cos.task.update with only the fields that changed', async () => {+ const res = await request(buildApp())+ .put('/api/cos/tasks/task-1')+ .send({ priority: 'HIGH', model: 'sonnet' });++ expect(res.status).toBe(200);+ const [event] = await onlyType('cos.task.update');+ expect(event).toMatchObject({ actor: 'user', target: 'task-1' });+ expect(event.payload).toEqual({ taskId: 'task-1', priority: 'HIGH', model: 'sonnet' });+ // Updates are not idempotent retries — the key carries the timestamp.+ expect(event.dedupeKey).toBe(`cos.task.update:task-1:${event.happenedAt}`);+ });++ it('records cos.task.delete with the description the task had before it was removed', async () => {+ cos.getTaskById.mockResolvedValue({ id: 'task-1', description: 'Render the opening shot' });+ cos.deleteTask.mockResolvedValue({ success: true, taskId: 'task-1' });++ const res = await request(buildApp()).delete('/api/cos/tasks/task-1');++ expect(res.status).toBe(200);+ const [event] = await onlyType('cos.task.delete');+ expect(event.payload).toEqual({ taskId: 'task-1', description: 'Render the opening shot' });+ expect(event.dedupeKey).toBe('cos.task.delete:task-1');+ });++ it('records cos.task.approve and cos.task.spawn', async () => {+ cos.approveTask.mockResolvedValue({ id: 'sys-1', description: 'Nightly sweep' });+ cos.forceSpawnTask.mockResolvedValue({ success: true });++ expect((await request(buildApp()).post('/api/cos/tasks/sys-1/approve')).status).toBe(200);+ expect((await request(buildApp()).post('/api/cos/tasks/sys-1/spawn')).status).toBe(200);++ const [approve] = await onlyType('cos.task.approve');+ expect(approve).toMatchObject({ target: 'sys-1', dedupeKey: 'cos.task.approve:sys-1' });+ const [spawn] = await onlyType('cos.task.spawn');+ expect(spawn.dedupeKey).toBe(`cos.task.spawn:sys-1:${spawn.happenedAt}`);+ });++ it('records nothing when the mutation itself failed', async () => {+ cos.updateTask.mockResolvedValueOnce({ error: 'Task not found' });+ expect((await request(buildApp()).put('/api/cos/tasks/ghost').send({ priority: 'HIGH' })).status).toBe(404);+ expect(await listUserActions()).toEqual([]);+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 3647d8051e..d0d163083b 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -397,13 +397,16 @@ router.put('/', asyncHandler(async (req, res) => {// slice merges per sub-key and persisted write-only tokens the incoming patch// omits get re-injected — both against the freshest snapshot inside the write// queue (see mergeFederationSlice / preserveExternallyOwnedKeys).+ // `actor: 'user'` is what separates a save made HERE — a human on the Settings+ // page — from every other `save()` caller (schedulers, sync hooks, feature+ // writes), which keep the `'system'` default in the operator-action ledger (#5594).let merged = await updateSettingsWith((current) =>preserveExternallyOwnedKeys(mergeFederationSlice({ ...current, ...settingsPatch }, current),current,- ));+ ), { actor: 'user' });if (subscriptionCostsPatch !== undefined) {- const costs = await saveSubscriptionCosts(subscriptionCostsPatch);+ const costs = await saveSubscriptionCosts(subscriptionCostsPatch, { actor: 'user' });merged = { ...merged, subscriptionCosts: costs };}// The queue caches codex.parallelLimit in-process; sync it from thediff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex 9aa92f9d65..f596ecd5a2 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -60,6 +60,7 @@ vi.mock('../services/eidoverseHost.js', () => ({}));import settingsRoutes from './settings.js';+import { updateSettingsWith } from '../services/settings.js';import { hasConfiguredInstances as hasConfiguredDatadogInstances } from '../services/datadog.js';import { hasConfiguredInstances as hasConfiguredJiraInstances } from '../services/jira.js';import { assertEidoverseInstalled, installEidoverse, setEidoverseWorldsOrigin } from '../services/eidoverse.js';@@ -72,6 +73,18 @@ const buildApp = () => {return app;};+// The operator-action ledger (#5594) distinguishes a human on the Settings page+// from every other settings writer purely by this argument, so the route has to+// keep passing it. The row it produces is asserted end-to-end in+// services/settings.userActions.test.js.+describe('Settings routes — operator-action actor (#5594)', () => {+ it('marks a settings PUT as a user action', async () => {+ const res = await request(buildApp()).put('/api/settings').send({ timezone: 'America/Los_Angeles' });+ expect(res.status).toBe(200);+ expect(updateSettingsWith).toHaveBeenCalledWith(expect.any(Function), { actor: 'user' });+ });+});+describe('Settings routes — apiAccess slice', () => {beforeEach(() => {store = {};diff --git a/server/routes/usage.js b/server/routes/usage.jsindex 1077690a88..fb71d32ae4 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -42,7 +42,7 @@ router.get('/', asyncHandler(async (req, res) => {// stored price; one sent as null (or 0) is cleared.router.put('/subscriptions', asyncHandler(async (req, res) => {const { costs } = validateRequest(subscriptionCostsSchema, req.body);- res.json({ costs: await saveSubscriptionCosts(costs) });+ res.json({ costs: await saveSubscriptionCosts(costs, { actor: 'user' }) });}));// GET /api/usage/providers - Subscription-quota status for every enableddiff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex 6b270ced12..a17282a351 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -143,7 +143,9 @@ describe('usage routes', () => {.put('/api/usage/subscriptions').send({ costs: { claude: 200, codex: null } });expect(res.status).toBe(200);- expect(saveSubscriptionCosts).toHaveBeenCalledWith({ claude: 200, codex: null });+ // The second argument marks the save as a human edit for the operator-action+ // ledger (#5594) — without it the row would read as actor 'system'.+ expect(saveSubscriptionCosts).toHaveBeenCalledWith({ claude: 200, codex: null }, { actor: 'user' });});it('PUT /api/usage/subscriptions rejects a non-numeric price', async () => {diff --git a/server/routes/userActions.js b/server/routes/userActions.jsnew file mode 100644index 0000000000..5559e31ef0--- /dev/null+++ b/server/routes/userActions.js@@ -0,0 +1,42 @@+/**+ * Operator-action ledger read API (#5594, epic #5593).+ *+ * Read-only on purpose: rows are written at the mutation sites that produce them+ * (CoS task routes, agent feedback, on-demand trigger, settings save), never by+ * a client POST — an operator log a client can forge is not evidence of anything.+ *+ * Auth: no entry in `ALWAYS_PUBLIC_API_PATHS` and no `API_REGISTRY` public+ * prefix, so `authGate` covers these under the normal `/api/*` gate.+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { userActionsListQuerySchema, validateRequest } from '../lib/validation.js';+import { USER_ACTION_ACTORS, USER_ACTION_TYPES } from '../lib/userActionTypes.js';+import { DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT, listUserActions } from '../services/userActions.js';++const router = Router();++// GET /api/user-actions/types — the closed vocabulary, for a filter UI that must+// not hardcode a mirror of the server list.+router.get('/types', asyncHandler(async (_req, res) => {+ res.json({+ types: [...USER_ACTION_TYPES],+ actors: [...USER_ACTION_ACTORS],+ defaultLimit: DEFAULT_LIST_LIMIT,+ maxLimit: MAX_LIST_LIMIT,+ });+}));++// GET /api/user-actions — newest-first slice of the ledger.+router.get('/', asyncHandler(async (req, res) => {+ const query = validateRequest(userActionsListQuerySchema, req.query);+ const events = await listUserActions({+ ...query,+ // Query strings carry no booleans; absent stays absent so it means "either".+ success: query.success === undefined ? undefined : query.success === 'true',+ });+ res.json({ events });+}));++export default router;diff --git a/server/routes/userActions.test.js b/server/routes/userActions.test.jsnew file mode 100644index 0000000000..4dd7e11bb9--- /dev/null+++ b/server/routes/userActions.test.js@@ -0,0 +1,128 @@+/**+ * GET /api/user-actions — the read API over the operator-action ledger (#5594).+ *+ * Runs against the real service on its file backend (PATHS.data re-rooted at a+ * temp dir) so the filters are proven end to end rather than against a stub. The+ * writes come from `recordUserAction` because the ledger has no write endpoint —+ * an operator log a client can POST into is not evidence of anything.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import express from 'express';+import { rmSync } from 'node:fs';+import { join } from 'node:path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const tempRoot = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join: joinPath } = await import('node:path');+ return mkdtempSync(joinPath(tmpdir(), 'portos-user-actions-routes-'));+});+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ const { makePathsProxy } = await import('../lib/mockPathsDataRoot.js');+ return makePathsProxy(actual, { dataRoot: tempRoot });+});++import userActionRoutes from './userActions.js';+import { USER_ACTION_TYPES } from '../lib/userActionTypes.js';+import { MAX_LIST_LIMIT, recordUserAction } from '../services/userActions.js';+import { apiAccessForPath } from '../lib/apiCatalog.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/user-actions', userActionRoutes);+ app.use(errorMiddleware);+ return app;+};++const daysAgo = (days) => new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();++beforeEach(async () => {+ rmSync(join(tempRoot, 'user-action-events.json'), { force: true });+ await recordUserAction({+ type: 'cos.task.create', actor: 'user', target: 'task-1',+ summary: 'Queued CoS task: example', dedupeKey: 'e1', happenedAt: daysAgo(9),+ });+ await recordUserAction({+ type: 'cos.schedule.trigger', actor: 'user', target: 'branch-reconcile',+ summary: 'Ran branch-reconcile', dedupeKey: 'e2', happenedAt: daysAgo(5),+ });+ await recordUserAction({+ type: 'settings.update', actor: 'system',+ summary: 'Updated settings: theme', dedupeKey: 'e3', happenedAt: daysAgo(1),+ });+});++afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++describe('GET /api/user-actions', () => {+ it('returns the ledger newest-first', async () => {+ const res = await request(buildApp()).get('/api/user-actions');+ expect(res.status).toBe(200);+ expect(res.body.events.map((e) => e.dedupeKey)).toEqual(['e3', 'e2', 'e1']);+ });++ it('filters by type, actor, and time window', async () => {+ const byType = await request(buildApp()).get('/api/user-actions?type=settings.update');+ expect(byType.body.events.map((e) => e.dedupeKey)).toEqual(['e3']);++ const byActor = await request(buildApp()).get('/api/user-actions?actor=system');+ expect(byActor.body.events.map((e) => e.dedupeKey)).toEqual(['e3']);++ const window = await request(buildApp())+ .get(`/api/user-actions?from=${encodeURIComponent(daysAgo(7))}&to=${encodeURIComponent(daysAgo(3))}`);+ expect(window.body.events.map((e) => e.dedupeKey)).toEqual(['e2']);+ });++ it('accepts a repeated types parameter', async () => {+ const res = await request(buildApp())+ .get('/api/user-actions?types=cos.task.create&types=settings.update');+ expect(res.body.events.map((e) => e.dedupeKey)).toEqual(['e3', 'e1']);+ });++ it('clamps an oversized limit instead of rejecting it', async () => {+ const res = await request(buildApp()).get(`/api/user-actions?limit=${MAX_LIST_LIMIT * 10}`);+ expect(res.status).toBe(200);+ expect(res.body.events).toHaveLength(3);+ });++ it('pages with limit + offset', async () => {+ const res = await request(buildApp()).get('/api/user-actions?limit=1&offset=1');+ expect(res.body.events.map((e) => e.dedupeKey)).toEqual(['e2']);+ });++ it('rejects a type outside the closed vocabulary and an unparseable date', async () => {+ expect((await request(buildApp()).get('/api/user-actions?type=cos.task.explode')).status).toBe(400);+ expect((await request(buildApp()).get('/api/user-actions?from=not-a-date')).status).toBe(400);+ // Bypass probe: the same shape with valid values is accepted, so the two+ // refusals above are about the values and not about the route being broken.+ expect((await request(buildApp()).get(`/api/user-actions?type=cos.task.create&from=${encodeURIComponent(daysAgo(30))}`)).status).toBe(200);+ });+});++describe('GET /api/user-actions/types', () => {+ it('serves the closed vocabulary so a filter UI need not mirror it', async () => {+ const res = await request(buildApp()).get('/api/user-actions/types');+ expect(res.status).toBe(200);+ expect(res.body.types).toEqual([...USER_ACTION_TYPES]);+ expect(res.body.actors).toEqual(['user', 'mind', 'schedule', 'system']);+ expect(res.body.maxLimit).toBe(MAX_LIST_LIMIT);+ });+});++describe('auth posture', () => {+ it('sits behind the normal /api/* gate', () => {+ // The ledger names what one operator did on one machine. It must never be+ // reachable without a session when the instance password is on, so it may+ // not appear in ALWAYS_PUBLIC_API_PATHS or an API_REGISTRY public prefix.+ expect(apiAccessForPath('/api/user-actions')).toBe('authenticated-ui');+ expect(apiAccessForPath('/api/user-actions/types')).toBe('authenticated-ui');+ // Bypass probe: the classifier does return something else for a genuinely+ // public path, so the two assertions above are not vacuously true.+ expect(apiAccessForPath('/api/system/health')).toBe('always-public');+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex f4b8c57d95..2f20824302 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -197,6 +197,31 @@ CREATE TABLE IF NOT EXISTS human_activity_events (CREATE UNIQUE INDEX IF NOT EXISTS idx_human_activity_dedupe ON human_activity_events (source, dedupe_key);CREATE INDEX IF NOT EXISTS idx_human_activity_happened ON human_activity_events (happened_at);+-- Operator-action ledger (#5594) — the durable, filterable record of what the+-- human actually did in PortOS. Machine-local like human_activity_events:+-- excluded from peer sync, guarded in sharing/peerSync.test.js. Idempotent via+-- the unique (type, dedupe_key) index + ON CONFLICT DO NOTHING. Deliberately+-- NOT audited (no trg_user_action_events_audit) — a personal operator log, same+-- rationale as post_runs.+CREATE TABLE IF NOT EXISTS user_action_events (+ id TEXT PRIMARY KEY,+ type TEXT NOT NULL,+ actor TEXT NOT NULL,+ happened_at TIMESTAMPTZ NOT NULL,+ target TEXT,+ target_name TEXT,+ success BOOLEAN NOT NULL DEFAULT TRUE,+ summary TEXT NOT NULL,+ payload JSONB NOT NULL DEFAULT '{}'::jsonb,+ source JSONB NOT NULL DEFAULT '{}'::jsonb,+ dedupe_key TEXT NOT NULL,+ created_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE UNIQUE INDEX IF NOT EXISTS idx_user_action_dedupe ON user_action_events (type, dedupe_key);+CREATE INDEX IF NOT EXISTS idx_user_action_happened ON user_action_events (happened_at DESC);+CREATE INDEX IF NOT EXISTS idx_user_action_type_time ON user_action_events (type, happened_at DESC);+CREATE INDEX IF NOT EXISTS idx_user_action_actor_time ON user_action_events (actor, happened_at DESC);+-- Auto-update updated_at and sync_sequence on content/metadata changes.-- Skips bump for access-stat-only updates (access_count, last_accessed)-- to avoid sync noise from read operations.diff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.jsindex e5cef95144..3b4fe110ee 100644--- a/server/services/cosAgentFeedback.js+++ b/server/services/cosAgentFeedback.js@@ -15,6 +15,7 @@ import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { loadAgentIndex, getAgentDir } from './cosAgentIndex.js';import { ServerError } from '../lib/errorHandler.js';+import { recordUserAction } from './userActions.js';const isSystemAgent = (agent) =>agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');@@ -74,9 +75,15 @@ export async function getPendingAgentFeedbackCount() {.length;}-// Submit feedback for a completed agent+// Submit feedback for a completed agent.+//+// The operator-action ledger write (#5594) happens AFTER the state lock releases,+// not inside it: a rating is a human verdict every caller should record, so it+// belongs at this one boundary rather than in the HTTP route — but nesting a DB+// write inside the CoS state lock would hold the lock across an I/O round trip+// for a log line. The lock's own failures still reject before anything is logged.export async function submitAgentFeedback(agentId, feedback) {- return withStateLock(async () => {+ const result = await withStateLock(async () => {const state = await loadState();const feedbackData = {rating: feedback.rating,@@ -110,7 +117,7 @@ export async function submitAgentFeedback(agentId, feedback) {emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });- return { success: true, agent: state.agents[agentId] };+ return { success: true, agent: state.agents[agentId], feedbackData };}// Agent not in state — look up from disk via index@@ -130,8 +137,27 @@ export async function submitAgentFeedback(agentId, feedback) {emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });- return { success: true, agent: { ...raw, id: agentId } };+ return { success: true, agent: { ...raw, id: agentId }, feedbackData };});++ const { feedbackData, ...response } = result;+ await recordUserAction({+ type: 'cos.agent.feedback',+ target: agentId,+ targetName: response.agent?.metadata?.taskDescription,+ summary: `Rated agent ${agentId} ${feedbackData.rating}`,+ payload: {+ agentId,+ taskId: response.agent?.taskId ?? null,+ rating: feedbackData.rating,+ comment: feedbackData.comment,+ taskType: extractTaskType(response.agent?.metadata?.taskDescription),+ },+ source: { service: 'cosAgentFeedback', fn: 'submitAgentFeedback' },+ happenedAt: feedbackData.submittedAt,+ dedupeKey: `cos.agent.feedback:${agentId}:${feedbackData.submittedAt}`,+ });+ return response;}// Get aggregated feedback statisticsdiff --git a/server/services/cosAgentFeedback.test.js b/server/services/cosAgentFeedback.test.jsindex ed8a9f7208..fd3981085f 100644--- a/server/services/cosAgentFeedback.test.js+++ b/server/services/cosAgentFeedback.test.js@@ -24,7 +24,23 @@ vi.mock('./cosAgentIndex.js', () => ({getAgentDir: (agentId, dateBucket) => join(mockCosState.agentsDir, dateBucket || '', agentId)}));-import { getFeedbackStats, getPendingAgentFeedbackCount } from './cosAgentFeedback.js';+// The operator-action ledger's file backend writes under PATHS.data — re-root it+// at a temp dir so this suite never touches the developer's live `data/` tree+// (#3683/#3687). Everything else in fileUtils stays real (agent metadata I/O).+const ledgerRoot = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join: joinPath } = await import('node:path');+ return mkdtempSync(joinPath(tmpdir(), 'portos-agent-feedback-ledger-'));+});+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ const { makePathsProxy } = await import('../lib/mockPathsDataRoot.js');+ return makePathsProxy(actual, { dataRoot: ledgerRoot });+});++import { getFeedbackStats, getPendingAgentFeedbackCount, submitAgentFeedback } from './cosAgentFeedback.js';+import { listUserActions } from './userActions.js';describe('getPendingAgentFeedbackCount', () => {beforeEach(() => {@@ -125,3 +141,60 @@ describe('getPendingAgentFeedbackCount', () => {});});});++// ── Operator-action ledger (#5594) ──────────────────────────────────────────+//+// The hook lives in `submitAgentFeedback` rather than the HTTP route so every+// caller records the rating, and it runs AFTER the CoS state lock releases so a+// ledger write never holds that lock across I/O.+describe('submitAgentFeedback records the rating (#5594)', () => {+ beforeEach(async () => {+ mockCosState.state = {+ agents: {+ 'agent-1': {+ id: 'agent-1',+ taskId: 'task-42',+ status: 'completed',+ completedAt: '2026-08-01T10:00:00.000Z',+ metadata: { taskType: 'user', taskDescription: 'Fix the failing render test' },+ },+ },+ };+ mockAgentIndex.entries = new Map();+ await rm(join(ledgerRoot, 'user-action-events.json'), { force: true });+ });++ afterAll(async () => {+ await rm(ledgerRoot, { recursive: true, force: true });+ });++ it('writes a cos.agent.feedback row with the rating, comment, and derived task type', async () => {+ const result = await submitAgentFeedback('agent-1', { rating: 'negative', comment: 'Missed the root cause' });+ expect(result).toMatchObject({ success: true });+ // The internal feedbackData carrier must not leak into the caller's response.+ expect(result).not.toHaveProperty('feedbackData');++ const [event] = await listUserActions({ type: 'cos.agent.feedback' });+ expect(event).toMatchObject({+ actor: 'user',+ target: 'agent-1',+ targetName: 'Fix the failing render test',+ source: { service: 'cosAgentFeedback', fn: 'submitAgentFeedback' },+ });+ expect(event.payload).toMatchObject({+ agentId: 'agent-1',+ taskId: 'task-42',+ rating: 'negative',+ comment: 'Missed the root cause',+ // extractTaskType maps the description to a bucket the learning view uses.+ taskType: 'bug-fix',+ });+ expect(event.dedupeKey).toBe(`cos.agent.feedback:agent-1:${event.happenedAt}`);+ });++ it('records nothing when the agent is not in a ratable state', async () => {+ mockCosState.state.agents['agent-1'].status = 'running';+ await expect(submitAgentFeedback('agent-1', { rating: 'positive' })).rejects.toThrow(/completed agents/);+ expect(await listUserActions({ type: 'cos.agent.feedback' })).toEqual([]);+ });+});diff --git a/server/services/settings.js b/server/services/settings.jsindex a1fee60d4d..6e66f883ac 100644--- a/server/services/settings.js+++ b/server/services/settings.js@@ -2,7 +2,8 @@ import { join } from 'path';import { EventEmitter } from 'events';import { safeJSONParse, PATHS, atomicWrite, tryReadFile, tryReadFileStrict } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';-import { isPlainObject, POLLUTING_KEYS } from '../lib/objects.js';+import { canonicalStringify, isPlainObject, POLLUTING_KEYS } from '../lib/objects.js';+import { recordUserAction } from './userActions.js';// POLLUTING_KEYS (`__proto__`/`constructor`/`prototype`) is the project-wide// prototype-pollution denylist (defined in server/lib/objects.js). Without it,@@ -178,7 +179,60 @@ export const reloadSettings = async () => {// stay off the queue — atomicWrite's temp-file+rename keeps every read whole.const queueWrite = createFileWriteQueue();-const save = async (settings) => {+// Longest scalar the ledger keeps verbatim. A settings value longer than this+// is a blob (a prompt template, a key list), and the useful fact for "what did I+// change?" is THAT it changed, not its full text.+const LEDGER_SCALAR_MAX_CHARS = 120;++// `undefined` counts: it is how "the key was not set before" arrives, and a+// first-time set is exactly the case where a before/after pair is most useful.+// It is normalized to null in the recorded value.+const isShortScalar = (value) => (+ value === null+ || value === undefined+ || typeof value === 'boolean'+ || typeof value === 'number'+ || (typeof value === 'string' && value.length <= LEDGER_SCALAR_MAX_CHARS)+);++// Shallow top-level diff of the settings object. Top-level is the right grain:+// the settings file is a map of feature slices, and "the `federation` slice+// changed" is the answerable question — a deep diff would produce a per-leaf+// path list nobody reads and would carry slice internals into the log.+//+// Values are only kept for SHORT SCALARS; everything else records the fact of the+// change alone. Secret-shaped keys are NOT filtered here — `recordUserAction`+// redacts by key name and lists the paths under `payload.redactedKeys`, so the+// denylist has exactly one home.+//+// Equality goes through `canonicalStringify` (key-order independent) so a slice+// that was merely REBUILT — same values, different insertion order — is not+// reported as an edit the user did not make.+const diffSettings = (prev, next) => {+ const keys = [...new Set([...Object.keys(prev), ...Object.keys(next)])].sort();+ const keysChanged = [];+ const changes = {};+ for (const key of keys) {+ const before = prev[key];+ const after = next[key];+ if (canonicalStringify(before) === canonicalStringify(after)) continue;+ keysChanged.push(key);+ changes[key] = isShortScalar(before) && isShortScalar(after)+ ? { from: before ?? null, to: after ?? null }+ : { changed: true };+ }+ return { keysChanged, changes };+};++/**+ * Persist settings.+ *+ * `actor` (#5594) names WHO is saving, and defaults to `'system'` — the honest+ * default, because most callers here are schedulers, sync hooks, and internal+ * feature writes. Only `PUT /api/settings` passes `'user'`. `reloadSettings` does+ * not call this at all, so a backup restore is excluded by construction.+ */+const save = async (settings, { actor = 'system' } = {}) => {const cleaned = stripStoreKeys(settings);// Stamp `timezoneUpdatedAt` whenever the effective `timezone` actually// changes, so timezone-dependent schedulers can gate catch-up/re-evaluation@@ -189,11 +243,12 @@ const save = async (settings) => {// comparison is against the freshest persisted snapshot, and any prior// `timezoneUpdatedAt` on an unchanged-timezone save rides through untouched// via the merged object.- if (isPlainObject(cleaned)) {- const prev = stripStoreKeys(await loadRaw());- if (isPlainObject(prev) && cleaned.timezone !== prev.timezone) {- cleaned.timezoneUpdatedAt = Date.now();- }+ const prev = isPlainObject(cleaned) ? stripStoreKeys(await loadRaw()) : null;+ // Diff BEFORE the timezoneUpdatedAt stamp below, so a timezone change reports+ // `keysChanged: ['timezone']` rather than dragging in the derived stamp.+ const change = isPlainObject(prev) ? diffSettings(prev, cleaned) : null;+ if (isPlainObject(prev) && cleaned.timezone !== prev.timezone) {+ cleaned.timezoneUpdatedAt = Date.now();}// atomicWrite (temp-file + rename) so a mid-write crash never truncates// settings.json. Pass a pre-stringified string to preserve the trailing@@ -208,6 +263,27 @@ const save = async (settings) => {}}settingsEvents.emit('settings:updated', cleaned);+ // A no-op save writes no ledger row: the settings page PUTs the whole object+ // on every visit, and a log full of "changed nothing" rows would bury the+ // changes that matter.+ if (change && change.keysChanged.length > 0) {+ const happenedAt = new Date().toISOString();+ const changedKeys = change.keysChanged.join(',');+ await recordUserAction({+ type: 'settings.update',+ actor,+ summary: `Updated settings: ${change.keysChanged.join(', ')}`,+ payload: { keysChanged: change.keysChanged, changes: change.changes },+ source: { service: 'settings', fn: 'save' },+ happenedAt,+ // Timestamp because a save is not an idempotent retry, PLUS the changed+ // keys because `toISOString()` only resolves to the millisecond — two+ // distinct saves landing in the same one would otherwise silently collapse+ // to a single row. Deterministic (not random) so a genuine duplicate still+ // dedupes.+ dedupeKey: `settings.update:${happenedAt}:${changedKeys.slice(0, 200)}`,+ });+ }return cleaned;};@@ -251,18 +327,18 @@ export const getSettingsWithStatus = async () => {};export const getSettings = async () => (await getSettingsWithStatus()).settings;-export const saveSettings = (settings) => queueWrite(() => save(settings));+export const saveSettings = (settings, options) => queueWrite(() => save(settings, options));// Merge against the unstripped on-disk snapshot so save() sees every// MortalLoom store key in one place — guaranteeing exactly one warning// per updateSettings call, only when the write succeeds. The whole// read-merge-write runs inside one queued turn so it merges against the// freshest persisted snapshot, not a stale pre-image.-export const updateSettings = (patch) => queueWrite(async () => {+export const updateSettings = (patch, options) => queueWrite(async () => {const raw = await loadRaw();const incoming = isPlainObject(patch) ? patch : {};const merged = { ...raw, ...incoming };- return save(merged);+ return save(merged, options);});// Read-modify-write INSIDE the write queue. For callers whose merge semantics@@ -276,7 +352,7 @@ export const updateSettings = (patch) => queueWrite(async () => {// between the external read and the queued write was clobbered by the caller's// stale pre-image. Here the read and the write share one queued turn, so the// mutator always sees the latest persisted snapshot.-export const updateSettingsWith = (mutate) => queueWrite(async () => {+export const updateSettingsWith = (mutate, options) => queueWrite(async () => {const current = stripStoreKeys(await loadRaw());const next = await mutate(current);// Guard the mutator's return BEFORE persisting: unlike the old@@ -286,5 +362,5 @@ export const updateSettingsWith = (mutate) => queueWrite(async () => {if (!isPlainObject(next)) {throw new TypeError('updateSettingsWith: mutate() must return a plain settings object');}- return save(next);+ return save(next, options);});diff --git a/server/services/settings.test.js b/server/services/settings.test.jsindex 50b4118310..10d2a8b5c9 100644--- a/server/services/settings.test.js+++ b/server/services/settings.test.js@@ -21,6 +21,11 @@ vi.mock('../lib/fileUtils.js', async (importActual) => {};});+// The operator-action ledger (#5594) writes through the SAME mocked atomicWrite+// this suite asserts on, so leave it stubbed here — the real settings→ledger+// round trip is covered end-to-end in settings.userActions.test.js.+vi.mock('./userActions.js', () => ({ recordUserAction: vi.fn() }));+import { mkdtempSync, rmSync } from 'fs';import { join as joinPath } from 'path';import { tmpdir } from 'os';diff --git a/server/services/settings.userActions.test.js b/server/services/settings.userActions.test.jsnew file mode 100644index 0000000000..030b65ac25--- /dev/null+++ b/server/services/settings.userActions.test.js@@ -0,0 +1,122 @@+/**+ * settings.js → operator-action ledger (#5594), end to end.+ *+ * Separate from `settings.test.js` because that suite stubs `atomicWrite` and+ * asserts on it; here BOTH writes are real (settings.json and the ledger's file+ * backend), with `PATHS.data` re-rooted at a temp dir, so what is pinned is the+ * actual persisted row rather than a call to a mock.+ *+ * What matters here is the `actor` split — `PUT /api/settings` is the only+ * caller that says `user`; a scheduler or sync hook writing the same file must+ * not look like the human did it — plus the diff itself: which keys changed,+ * before/after for short scalars, secret values withheld, and nothing written at+ * all for a no-op save.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { rmSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';+import { join } from 'node:path';++const tempRoot = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join: joinPath } = await import('node:path');+ return mkdtempSync(joinPath(tmpdir(), 'portos-settings-actions-'));+});+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ const { makePathsProxy } = await import('../lib/mockPathsDataRoot.js');+ return makePathsProxy(actual, { dataRoot: tempRoot });+});++const { saveSettings, updateSettings, updateSettingsWith, reloadSettings, __resetSettingsCache } =+ await import('./settings.js');+const { listUserActions } = await import('./userActions.js');++const SETTINGS_FILE = join(tempRoot, 'settings.json');+const seed = (settings) => writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2));++beforeEach(() => {+ rmSync(tempRoot, { recursive: true, force: true });+ mkdirSync(tempRoot, { recursive: true });+ seed({ timezone: 'UTC' });+ __resetSettingsCache();+});++afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++describe('settings save → user_action_events (#5594)', () => {+ it('records the changed keys with before/after and the caller-supplied actor', async () => {+ await updateSettingsWith((current) => ({ ...current, timezone: 'America/Los_Angeles' }), { actor: 'user' });++ const [event] = await listUserActions({ type: 'settings.update' });+ expect(event).toMatchObject({ type: 'settings.update', actor: 'user', success: true });+ expect(event.payload.keysChanged).toEqual(['timezone']);+ expect(event.payload.changes.timezone).toEqual({ from: 'UTC', to: 'America/Los_Angeles' });+ // The derived `timezoneUpdatedAt` stamp is not an operator edit.+ expect(event.payload.keysChanged).not.toContain('timezoneUpdatedAt');+ // ...but it still reached disk — the diff runs before the stamp, not instead of it.+ expect(JSON.parse(readFileSync(SETTINGS_FILE, 'utf8')).timezoneUpdatedAt).toEqual(expect.any(Number));+ });++ it('defaults to actor "system" for every non-route caller', async () => {+ await updateSettings({ theme: 'dark' });+ const [event] = await listUserActions({ type: 'settings.update' });+ expect(event.actor).toBe('system');+ expect(event.payload.keysChanged).toEqual(['theme']);+ });++ it('threads the actor through saveSettings and updateSettings too', async () => {+ await saveSettings({ timezone: 'UTC', theme: 'dark' }, { actor: 'user' });+ await updateSettings({ theme: 'light' }, { actor: 'user' });+ const events = await listUserActions({ type: 'settings.update' });+ expect(events).toHaveLength(2);+ expect(events.every((e) => e.actor === 'user')).toBe(true);+ });++ it('lists a secret-shaped key as changed but withholds its value', async () => {+ await updateSettings({ civitaiApiKey: 'EXAMPLE-not-a-real-key' }, { actor: 'user' });++ const [event] = await listUserActions({ type: 'settings.update' });+ expect(event.payload.keysChanged).toEqual(['civitaiApiKey']);+ expect(event.payload.redactedKeys).toEqual(['changes.civitaiApiKey']);+ expect(event.payload.changes).not.toHaveProperty('civitaiApiKey');+ expect(JSON.stringify(event)).not.toContain('EXAMPLE-not-a-real-key');+ });++ it('records the fact of a change for a non-scalar slice without copying it in', async () => {+ await updateSettings({ backup: { enabled: true, destination: '/example/backups' } }, { actor: 'user' });++ const [event] = await listUserActions({ type: 'settings.update' });+ expect(event.payload.changes.backup).toEqual({ changed: true });+ });++ it('writes nothing for a no-op save', async () => {+ await updateSettings({ timezone: 'UTC' }, { actor: 'user' });+ expect(await listUserActions({ type: 'settings.update' })).toEqual([]);++ // Bypass probe: the same call with a real change DOES record, so the+ // assertion above is about the no-op, not about the hook being dead.+ await updateSettings({ timezone: 'Europe/Berlin' }, { actor: 'user' });+ expect(await listUserActions({ type: 'settings.update' })).toHaveLength(1);+ });++ it('keeps two same-millisecond saves apart in the dedupe key', async () => {+ // `toISOString()` resolves only to the millisecond, so the changed-key list+ // is part of the key — without it a second distinct save landing in the same+ // millisecond would be swallowed by ON CONFLICT DO NOTHING.+ await updateSettings({ theme: 'dark' }, { actor: 'user' });+ await updateSettings({ locale: 'en-GB' }, { actor: 'user' });++ const events = await listUserActions({ type: 'settings.update' });+ expect(events).toHaveLength(2);+ expect(new Set(events.map((e) => e.dedupeKey)).size).toBe(2);+ expect(events.every((e) => e.dedupeKey.startsWith('settings.update:'))).toBe(true);+ });++ it('records nothing for reloadSettings — a restore is not an operator edit', async () => {+ seed({ timezone: 'Asia/Tokyo', theme: 'dark' });+ await reloadSettings();+ expect(await listUserActions({ type: 'settings.update' })).toEqual([]);+ });+});diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex eba9c2012b..c1474de674 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -3928,7 +3928,7 @@ describe('peerSync', () => {}});- it('keeps the Tribe graph + universe render-runs + activity timeline intentionally OUT of the sync graph (#1724, #2150)', () => {+ it('keeps the Tribe graph + universe render-runs + activity timeline + operator-action ledger intentionally OUT of the sync graph (#1724, #2150, #5594)', () => {// ADR 2026-06-26: tribe_* and universe_runs are deliberately machine-local.// - Tribe is relationship-graph data (mirrors the deliberate "memory_links// are instance-local" policy in memorySync.js) and is coupled to@@ -3939,14 +3939,19 @@ describe('peerSync', () => {// - human_activity_events (#2150) is coupled to per-machine accounts and OS// databases; only DERIVED summaries (Brain journals, digital-twin) federate,// never the raw events. Same machine-local boundary per the ADR.+ // - user_action_events (#5594) is the operator-action ledger: what ONE human+ // did on ONE machine, with task prompts and settings diffs attached. PII+ // must not ride the federation layer at all (ADR+ // 2026-08-08-privacy-records-machine-local), and a peer has no use for a+ // record of a button someone pressed on another install.// This guard pins that decision: federating any of them later is a conscious// act — wire the kind AND update this assertion + the ADR together.- const localOnlyKinds = ['tribe', 'tribePerson', 'tribeTouchpoint', 'tribeMemoryLink', 'universeRun', 'humanActivityEvent'];+ const localOnlyKinds = ['tribe', 'tribePerson', 'tribeTouchpoint', 'tribeMemoryLink', 'universeRun', 'humanActivityEvent', 'userActionEvent'];for (const kind of localOnlyKinds) {expect(PEER_SUBSCRIBABLE_KINDS).not.toContain(kind);expect(RECORD_KIND_SCHEMA_CATEGORIES[kind]).toBeUndefined();}- const localOnlyCategories = ['tribe', 'tribePeople', 'tribeTouchpoints', 'tribeMemoryLinks', 'universeRuns', 'humanActivityEvents'];+ const localOnlyCategories = ['tribe', 'tribePeople', 'tribeTouchpoints', 'tribeMemoryLinks', 'universeRuns', 'humanActivityEvents', 'userActionEvents'];for (const category of localOnlyCategories) {expect(PORTOS_SCHEMA_VERSIONS[category]).toBeUndefined();expect(NON_RECORD_SCHEMA_CATEGORIES.has(category)).toBe(false);diff --git a/server/services/subscriptionCosts.js b/server/services/subscriptionCosts.jsindex 6b9ee58002..0bf0314e2f 100644--- a/server/services/subscriptionCosts.js+++ b/server/services/subscriptionCosts.js@@ -71,7 +71,10 @@ export async function getSubscriptionCosts() {* is deleted. Without that split, an editor that only submits changed rows* could never remove a plan the user cancelled.*/-export async function saveSubscriptionCosts(patch) {+// `options` is forwarded to `updateSettingsWith` so the operator-action actor+// (#5594) survives: both callers — the Settings PUT and the usage page's price+// editor — are a human, and would otherwise be logged as `system`.+export async function saveSubscriptionCosts(patch, options) {const incoming = isPlainObject(patch) ? patch : {};const next = await updateSettingsWith((current) => {const merged = { ...normalizeSubscriptionCosts(current?.[SETTINGS_KEY]) };@@ -81,7 +84,7 @@ export async function saveSubscriptionCosts(patch) {else merged[family] = cost;}return { ...current, [SETTINGS_KEY]: merged };- });+ }, options);return normalizeSubscriptionCosts(next?.[SETTINGS_KEY]);}diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 8c2df8a822..aead9468d1 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -47,6 +47,7 @@ import {} from './taskScheduleRegistry.js';import { loadSchedule, updateSchedule } from './taskScheduleStore.js';import { isInstanceFeatureEnabled } from './instanceFeatures.js';+import { recordUserAction } from './userActions.js';import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';import {clearFailureLedgerFields,@@ -1166,6 +1167,23 @@ export async function triggerOnDemandTask(taskType, appId = null, { emit = true,if (request.error) return request;+ // Operator-action ledger (#5594): ONLY a human pressing Run Now. The perpetual+ // drain re-issues itself through this same lane with `origin: REFILL` — logging+ // that would fill the ledger with events the user never performed and make+ // "what did I trigger?" unanswerable.+ if (origin === ON_DEMAND_ORIGINS.USER) {+ await recordUserAction({+ type: 'cos.schedule.trigger',+ target: taskType,+ targetName: appId,+ summary: `Ran scheduled task '${taskType}' on demand${appId ? ` for ${appId}` : ''}`,+ payload: { taskType, appId: appId ?? null, requestId: request.id },+ source: { service: 'taskSchedule', fn: 'triggerOnDemandTask' },+ happenedAt: request.requestedAt,+ dedupeKey: `cos.schedule.trigger:${request.id}`,+ });+ }+emitLog('info', `On-demand task requested: ${taskType}`, { appId }, '📅 TaskSchedule');// The event's only consumer is a `dequeueNextTask()` trigger (cos.js). Callers// that already own their own dequeue (the perpetual drain-on-completion refill,diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 1026e28061..3ee0bb90b0 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -30,6 +30,11 @@ tryReadFile: vi.fn().mockResolvedValue(null),// slashdoLoader mock: taskPromptService.js reads the bundled command body// through loadSlashdoFile — stub it the same way the prior fileUtils mock did,// now that the slashdo loaders live in their own module (#3110's home moved).+// Operator-action ledger (#5594). Stubbed so the origin gate in+// triggerOnDemandTask can be asserted directly (recorded vs not recorded)+// without this suite's minimal fileUtils stub having to grow a data root.+vi.mock('./userActions.js', () => ({ recordUserAction: vi.fn() }));+vi.mock('../lib/slashdoLoader.js', () => ({loadSlashdoFile: vi.fn().mockResolvedValue(''),}))@@ -153,6 +158,7 @@ import {boundParkedUntil} from './taskSchedule.js'import { cosEvents } from './cosEvents.js'+import { recordUserAction } from './userActions.js'// Prompt getters moved to taskPromptService.js (issue #744 split, #1083 cycle// break). taskSchedule.js re-exports the version constants but not the getters.@@ -1933,6 +1939,36 @@ describe('taskSchedule', () => {expect(refill.origin).toBe(ON_DEMAND_ORIGINS.REFILL)})+ // Operator-action ledger (#5594). Only a human pressing Run Now is an+ // operator action; the perpetual drain re-issues itself through this same+ // lane, and logging that would fill the ledger with events nobody performed.+ it('records a cos.schedule.trigger row for a human Run Now, and none for a refill', async () => {+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })+ const request = await triggerOnDemandTask('branch-reconcile', 'app-1')++ expect(recordUserAction).toHaveBeenCalledTimes(1)+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({+ type: 'cos.schedule.trigger',+ target: 'branch-reconcile',+ targetName: 'app-1',+ dedupeKey: `cos.schedule.trigger:${request.id}`,+ payload: { taskType: 'branch-reconcile', appId: 'app-1', requestId: request.id },+ }))+ // actor defaults to 'user' in the recorder; the hook must not override it.+ expect(recordUserAction.mock.calls[0][0].actor).toBeUndefined()++ recordUserAction.mockClear()+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })+ await triggerOnDemandTask('branch-reconcile', 'app-1', { emit: false, origin: ON_DEMAND_ORIGINS.REFILL })+ expect(recordUserAction).not.toHaveBeenCalled()+ })++ it('records nothing when the trigger is refused', async () => {+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: false } } })+ expect((await triggerOnDemandTask('branch-reconcile', 'app-1')).error).toMatch(/disabled/i)+ expect(recordUserAction).not.toHaveBeenCalled()+ })+// The policy that used to be open-coded in each spawn engine — which is how the// loop got in. One home, so the three queue consumers can't drift on it.describe('applyOnDemandRunResets', () => {diff --git a/server/services/userActions.db.test.js b/server/services/userActions.db.test.jsnew file mode 100644index 0000000000..274ca82bb2--- /dev/null+++ b/server/services/userActions.db.test.js@@ -0,0 +1,155 @@+/**+ * Postgres-backed tests for the operator-action ledger (#5594):+ * - insertUserActionEvent() — idempotent insert via ON CONFLICT (type, dedupe_key)+ * - listUserActionEvents() — type / actor / success / time-window filters + paging+ * - pruneUserActionEvents() — the row cap AND the age cap+ *+ * These drive `userActionsDb.js` directly rather than `userActions.js`: the store+ * facade selects the FILE backend under NODE_ENV=test (which this config sets),+ * so the SQL is only reachable through the leaf module. Same split as+ * `postRunDb.db.test.js`.+ *+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`, never+ * the real `portos` DB (the db.js runner guard + the suite skip below enforce+ * this). The DB is shared across worktrees, so every row created here uses a+ * per-run nonce and is torn down in afterAll.+ */+import { describe, it, expect, afterAll, beforeAll } from 'vitest';+import * as db from '../lib/db.js';+import { checkHealth, ensureSchema, close, query } from '../lib/db.js';+import {+ insertUserActionEvent,+ listUserActionEvents,+ pruneUserActionEvents,+} from './userActionsDb.js';+import { normalizeListOptions, normalizeUserAction } from './userActions.js';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ dbReady = true;+ }+}+if (!dbReady) console.log(`⏭️ userActions.db.test: skipping suite — ${skipReason || 'no database'}`);++const nonce = `ua${Date.now()}`;+const key = (suffix) => `${nonce}:${suffix}`;++// Start from an empty table: the row-cap assertion below is arithmetic over the+// GLOBAL row count, so a row stranded by a crashed earlier run would silently+// become the one the cap evicts. Safe here and nowhere else — this suite only+// ever runs against `portos_test`.+beforeAll(async () => {+ if (dbReady) await query('DELETE FROM user_action_events');+});++afterAll(async () => {+ if (dbReady) {+ await query('DELETE FROM user_action_events WHERE dedupe_key LIKE $1', [`${nonce}:%`]).catch(() => {});+ await close();+ }+});++const daysAgo = (days) => new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();++const event = (over = {}) => normalizeUserAction({+ type: 'cos.task.create',+ summary: 'Queued CoS task: example',+ dedupeKey: key(Math.random().toString(36).slice(2)),+ ...over,+});++// Scope every read to this run's rows — the table is shared with whatever the+// developer's own install wrote.+const listMine = async (options = {}) => {+ const rows = await listUserActionEvents(db, normalizeListOptions({ limit: 500, ...options }));+ return rows.filter((row) => row.dedupeKey.startsWith(`${nonce}:`));+};++describe.skipIf(!dbReady)('user_action_events store (#5594)', () => {+ it('inserts and round-trips the full row shape', async () => {+ const row = event({+ dedupeKey: key('shape'),+ target: 'task-1',+ targetName: 'render the shot',+ payload: { taskId: 'task-1', provider: 'claude', apiKey: 'sk-EXAMPLE-not-real' },+ source: { route: '/api/cos/tasks', method: 'POST' },+ happenedAt: daysAgo(1),+ });+ expect(await insertUserActionEvent(db, row)).toBe(true);++ const [stored] = await listMine({ target: 'task-1' });+ expect(stored).toMatchObject({+ type: 'cos.task.create',+ actor: 'user',+ target: 'task-1',+ targetName: 'render the shot',+ success: true,+ dedupeKey: key('shape'),+ source: { route: '/api/cos/tasks', method: 'POST' },+ });+ // JSONB survives the round trip, and the recorder's redaction rode into it.+ expect(stored.payload).toMatchObject({ taskId: 'task-1', provider: 'claude' });+ expect(stored.payload.redactedKeys).toEqual(['apiKey']);+ expect(stored.payload).not.toHaveProperty('apiKey');+ });++ it('is idempotent on (type, dedupe_key) and scopes the key to the type', async () => {+ expect(await insertUserActionEvent(db, event({ dedupeKey: key('dup') }))).toBe(true);+ expect(await insertUserActionEvent(db, event({ dedupeKey: key('dup') }))).toBe(false);+ expect(await insertUserActionEvent(db, event({ type: 'cos.task.delete', dedupeKey: key('dup') }))).toBe(true);+ });++ it('filters by type, actor, success, and time window', async () => {+ await insertUserActionEvent(db, event({+ type: 'cos.schedule.trigger', dedupeKey: key('f1'), actor: 'user', happenedAt: daysAgo(9),+ }));+ await insertUserActionEvent(db, event({+ type: 'settings.update', dedupeKey: key('f2'), actor: 'system', success: false, happenedAt: daysAgo(5),+ }));++ expect((await listMine({ type: 'settings.update' })).map((r) => r.dedupeKey)).toEqual([key('f2')]);+ expect((await listMine({ actor: 'system' })).map((r) => r.dedupeKey)).toEqual([key('f2')]);+ expect((await listMine({ success: false })).map((r) => r.dedupeKey)).toEqual([key('f2')]);+ expect((await listMine({ types: ['cos.schedule.trigger', 'settings.update'] })).map((r) => r.dedupeKey))+ .toEqual([key('f2'), key('f1')]);+ expect((await listMine({ from: daysAgo(7), to: daysAgo(3) })).map((r) => r.dedupeKey)).toEqual([key('f2')]);+ });++ it('prunes past the age cap without touching fresher rows', async () => {+ await insertUserActionEvent(db, event({ dedupeKey: key('stale'), happenedAt: daysAgo(120) }));+ await insertUserActionEvent(db, event({ dedupeKey: key('recent'), happenedAt: daysAgo(1) }));++ await pruneUserActionEvents(db, {+ maxRows: 1_000_000,+ cutoffIso: daysAgo(90),+ });++ const keys = (await listMine()).map((r) => r.dedupeKey);+ expect(keys).not.toContain(key('stale'));+ expect(keys).toContain(key('recent'));+ });++ it('prunes past the row cap, keeping the newest', async () => {+ // The cap is global, so measure it against the live table: keep every row+ // that exists plus two of this run's three, and assert the OLDEST of the+ // three is the one that goes.+ for (const index of [0, 1, 2]) {+ await insertUserActionEvent(db, event({ dedupeKey: key(`cap${index}`), happenedAt: daysAgo(30 - index) }));+ }+ const total = Number((await query('SELECT COUNT(*)::int AS n FROM user_action_events')).rows[0].n);++ // Keep everything but one row; `cap0` is the oldest thing in the table.+ await pruneUserActionEvents(db, { maxRows: total - 1, cutoffIso: daysAgo(365) });++ const keys = (await listMine()).map((r) => r.dedupeKey);+ expect(keys).toContain(key('cap2'));+ expect(keys).toContain(key('cap1'));+ expect(keys).not.toContain(key('cap0'));+ });+});diff --git a/server/services/userActions.js b/server/services/userActions.jsnew file mode 100644index 0000000000..4f5f772113--- /dev/null+++ b/server/services/userActions.js@@ -0,0 +1,368 @@+/**+ * Operator-action ledger (#5594, epic #5593) — the durable, filterable record of+ * what the HUMAN did in PortOS.+ *+ * PortOS already logs a great deal, and none of it answers that question:+ * `history.jsonl` is PM2 lifecycle, `human_activity_events` is ingested external+ * activity (messages, calendar, media), the CoS JSONL ledgers are per-agent+ * transcripts, and `record_audit` is row-level before/after diffs. This store is+ * the one place that says "the user queued THIS task with THIS provider", "the+ * user rated THAT run negative", "the user changed these settings keys".+ *+ * Contract:+ * - **Closed vocabulary.** `type` must be in `USER_ACTION_TYPES`+ * (`lib/userActionTypes.js`); an unknown type THROWS. A ledger whose type+ * column is free text is a second `history.jsonl`, not a queryable log.+ * - **Idempotent.** Every event carries a stable `dedupeKey`; the unique+ * `(type, dedupe_key)` index + `ON CONFLICT DO NOTHING` make a retried request+ * a no-op. Same contract as `human_activity_events` / `tribe_touchpoints`.+ * - **Redacted.** Payload keys that look like a credential are dropped (value+ * and all) and their paths listed under `payload.redactedKeys`, and long+ * strings are truncated. A prompt or a settings patch can carry a token; the+ * ledger must not become the place it leaks from.+ * - **Machine-local.** Never federated (PII must not ride the federation layer —+ * ADR docs/decisions/2026-08-08-privacy-records-machine-local.md); guarded in+ * sharing/peerSync.test.js. This log names what one operator did on one+ * machine, which is exactly the kind of record that must not cross the wire.+ * - **Bounded.** Retention is enforced inline after an insert (row cap AND age+ * cap) rather than by a new cron — one more scheduled job for a table that+ * only grows when the user acts is not worth the moving part.+ *+ * PostgreSQL is authoritative. The file backend exists ONLY for the dev/test+ * escape hatch (`NODE_ENV=test` / `MEMORY_BACKEND=file`, see AGENTS.md's Storage+ * backend policy), which is what lets route suites assert a persisted row+ * without a database. It is deliberately built on `createPgFileFacade` rather+ * than copying `humanActivity.js`'s DB-only `ensureReady()` shape, which would+ * force every instrumented route's tests onto Postgres.+ *+ * Writes are AWAITED by their callers (same posture as `history.logAction`), so+ * a route's response implies the row landed and a test can assert it. No+ * fire-and-forget layer.+ */++import { join } from 'path';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { isPlainObject } from '../lib/objects.js';+import { createPgFileFacade, resolvePgBackend } from '../lib/pgFileFacade.js';+import { isTestRunner } from '../lib/db.js';+import { isUserActionActor, isUserActionType } from '../lib/userActionTypes.js';+import { insertUserActionEvent, listUserActionEvents, pruneUserActionEvents } from './userActionsDb.js';++// Resolved per call, not at module load: PATHS.data is re-rooted by the shared+// test proxy (lib/mockPathsDataRoot.js), and a load-time join would both bind the+// pre-mock value and crash any suite whose fileUtils stub omits PATHS.data.+const eventsFile = () => join(PATHS.data, 'user-action-events.json');++/** LLM-readable one-liner cap — the ledger is read by a model, not paged through. */+export const SUMMARY_MAX_CHARS = 240;+/** Per-string payload cap; the containing object gets `truncated: true`. */+export const PAYLOAD_STRING_MAX_CHARS = 4096;+/** Retention bounds. BOTH hold: no more rows than this, nothing older than this. */+export const DEFAULT_MAX_ROWS = 20_000;+export const DEFAULT_MAX_AGE_DAYS = 90;++/** List clamps — an unbounded read of an operator log is never what a caller wants. */+export const MAX_LIST_LIMIT = 500;+export const DEFAULT_LIST_LIMIT = 100;++let retention = { maxRows: DEFAULT_MAX_ROWS, maxAgeDays: DEFAULT_MAX_AGE_DAYS };++/**+ * Test seam — lower the retention bounds so a suite can prove pruning with a+ * handful of rows instead of 20,000. Production code never calls this; pass no+ * argument to restore the defaults.+ */+export function __setUserActionRetention({ maxRows, maxAgeDays } = {}) {+ retention = {+ maxRows: Number.isFinite(maxRows) && maxRows > 0 ? Math.floor(maxRows) : DEFAULT_MAX_ROWS,+ maxAgeDays: Number.isFinite(maxAgeDays) && maxAgeDays > 0 ? maxAgeDays : DEFAULT_MAX_AGE_DAYS,+ };+}++// ---------------------------------------------------------------------------+// Pure helpers (exported for focused tests — no I/O, no side effects).+// ---------------------------------------------------------------------------++// Credential-shaped key names, matched against the key with separators and case+// removed (`api_key`, `apiKey`, `API-KEY` all normalize to `apikey`). Substring+// matching is deliberate over-redaction: dropping `tokenCount` costs one boring+// number, while missing `refreshToken` writes a live credential to disk.+const SECRET_KEY_FRAGMENTS = [+ 'password', 'passwd', 'passphrase', 'secret', 'token', 'apikey', 'authorization',+ 'credential', 'privatekey', 'ciphertext', 'cookie', 'accesskey',+];+// Names too short to substring-match safely (a bare `key` fragment would eat+// `keysChanged`, `env` would eat `envelope`), so they redact only as a WHOLE key.+const SECRET_KEY_EXACT = new Set(['key', 'keys', 'auth', 'env', 'dotenv', 'vault', 'pat', 'pw']);++const normalizeKey = (key) => String(key).toLowerCase().replace(/[^a-z0-9]/g, '');++/** True when a payload key name looks like it holds a credential. */+export function isSecretKey(key) {+ const normalized = normalizeKey(key);+ if (!normalized) return false;+ if (SECRET_KEY_EXACT.has(normalized)) return true;+ // A trailing `Key`/`Keys` is how every provider-specific credential is named+ // (`openaiKey`, `sshKey`, `signingKey`, `deployKeys`), and none of them contain+ // the literal `apikey`. Anchoring at the END keeps `keysChanged` out.+ if (normalized.endsWith('key') || normalized.endsWith('keys')) return true;+ return SECRET_KEY_FRAGMENTS.some((fragment) => normalized.includes(fragment));+}++/** Collapse whitespace and clamp to one LLM-readable line. */+export function clampSummary(text, max = SUMMARY_MAX_CHARS) {+ const line = String(text ?? '').replace(/\s+/g, ' ').trim();+ if (line.length <= max) return line;+ return `${line.slice(0, max - 1).trimEnd()}…`;+}++// Recursive redact+truncate. Returns `{ value, truncated }` where `truncated`+// reports a truncation the CALLER must flag — an object flags its own children,+// so it always reports false upward; an array can't carry a flag, so it hands+// the responsibility to the nearest enclosing object.+function redactNode(value, path, redactedKeys) {+ if (typeof value === 'string') {+ return value.length > PAYLOAD_STRING_MAX_CHARS+ ? { value: `${value.slice(0, PAYLOAD_STRING_MAX_CHARS)}…`, truncated: true }+ : { value, truncated: false };+ }+ if (Array.isArray(value)) {+ let truncated = false;+ const out = value.map((item, index) => {+ const child = redactNode(item, path ? `${path}.${index}` : String(index), redactedKeys);+ truncated = truncated || child.truncated;+ return child.value;+ });+ return { value: out, truncated };+ }+ if (isPlainObject(value)) {+ const out = {};+ let truncated = false;+ for (const [key, child] of Object.entries(value)) {+ const childPath = path ? `${path}.${key}` : key;+ if (isSecretKey(key)) {+ redactedKeys.push(childPath);+ continue;+ }+ const result = redactNode(child, childPath, redactedKeys);+ if (result.truncated) truncated = true;+ out[key] = result.value;+ }+ if (truncated) out.truncated = true;+ return { value: out, truncated: false };+ }+ return { value, truncated: false };+}++/**+ * Drop credential-shaped keys and truncate long strings.+ * @returns {{ payload: object, redactedKeys: string[] }} dotted paths of what was dropped.+ */+export function redactPayload(payload) {+ const redactedKeys = [];+ const { value } = redactNode(isPlainObject(payload) ? payload : {}, '', redactedKeys);+ return { payload: value, redactedKeys };+}++/**+ * Validate + normalize one action into the stored row shape. Throws on an+ * unknown type/actor or a missing dedupe key — all three are programmer errors+ * at a fixed hook site, and a silently-dropped row is worse than a red test.+ */+export function normalizeUserAction(input = {}) {+ const { type, actor = 'user', dedupeKey, summary } = input;+ if (!isUserActionType(type)) {+ throw new Error(`Unknown user action type '${String(type)}' — add it to USER_ACTION_TYPES first`);+ }+ if (!isUserActionActor(actor)) {+ throw new Error(`Unknown user action actor '${String(actor)}' for ${type}`);+ }+ const key = String(dedupeKey ?? '').trim();+ if (!key) throw new Error(`User action ${type} is missing a dedupeKey`);++ const when = input.happenedAt ? new Date(input.happenedAt) : new Date();+ if (Number.isNaN(when.getTime())) throw new Error(`User action ${type} has an invalid happenedAt`);++ // `redactedKeys` is written by the recorder alone — producers hand over raw+ // values and this is the single denylist that decides what is withheld.+ const { payload, redactedKeys } = redactPayload(input.payload);+ if (redactedKeys.length > 0) payload.redactedKeys = [...redactedKeys].sort();++ return {+ id: input.id || uuidv4(),+ type,+ actor,+ happenedAt: when.toISOString(),+ target: input.target ?? null,+ targetName: input.targetName ? clampSummary(input.targetName, SUMMARY_MAX_CHARS) : null,+ success: input.success !== false,+ summary: clampSummary(summary || type),+ payload,+ source: isPlainObject(input.source) ? input.source : {},+ dedupeKey: key,+ };+}++/** Clamp list options to the documented bounds. Exported for the route test. */+export function normalizeListOptions(options = {}) {+ const rawTypes = [+ ...(options.type ? [options.type] : []),+ ...(Array.isArray(options.types) ? options.types : []),+ ].filter((value) => typeof value === 'string' && value);+ const limit = Number.isFinite(Number(options.limit))+ ? Math.min(MAX_LIST_LIMIT, Math.max(1, Math.floor(Number(options.limit))))+ : DEFAULT_LIST_LIMIT;+ const offset = Number.isFinite(Number(options.offset))+ ? Math.max(0, Math.floor(Number(options.offset)))+ : 0;+ return {+ types: [...new Set(rawTypes)],+ actor: options.actor || null,+ target: options.target || null,+ // Absent (undefined/null) means "either"; only an explicit boolean filters.+ success: typeof options.success === 'boolean' ? options.success : null,+ from: options.from ? new Date(options.from).toISOString() : null,+ to: options.to ? new Date(options.to).toISOString() : null,+ limit,+ offset,+ };+}++// Id breaks the tie so the file backend orders identically to the PG backend's+// `ORDER BY happened_at DESC, id DESC` — otherwise two events stamped in the same+// millisecond would page differently depending on which backend answered.+const newestFirst = (a, b) => (+ String(b.happenedAt).localeCompare(String(a.happenedAt))+ || String(b.id).localeCompare(String(a.id))+);++// Shared by both backends so "what retention keeps" has ONE definition.+function retentionCutoff(now = Date.now()) {+ return new Date(now - retention.maxAgeDays * 24 * 60 * 60 * 1000).toISOString();+}++// ---------------------------------------------------------------------------+// File backend — dev/test escape hatch only.+// ---------------------------------------------------------------------------++// Every file write goes through one tail: the read-modify-write below would+// otherwise let two concurrent records clobber each other's row.+const queueWrite = createFileWriteQueue();++async function loadFileEvents() {+ const raw = await readJSONFile(eventsFile(), { events: [] }, { allowArray: false });+ return Array.isArray(raw?.events) ? raw.events : [];+}++function pruneEvents(events) {+ const cutoff = retentionCutoff();+ return events+ .filter((event) => String(event.happenedAt) >= cutoff)+ .sort(newestFirst)+ .slice(0, retention.maxRows);+}++function matchesFilters(event, filters) {+ if (filters.types.length > 0 && !filters.types.includes(event.type)) return false;+ if (filters.actor && event.actor !== filters.actor) return false;+ if (filters.target && event.target !== filters.target) return false;+ if (filters.success !== null && event.success !== filters.success) return false;+ if (filters.from && String(event.happenedAt) < filters.from) return false;+ if (filters.to && String(event.happenedAt) > filters.to) return false;+ return true;+}++function makeFileBackend() {+ return {+ name: 'file',+ record: (event) => queueWrite(async () => {+ const events = await loadFileEvents();+ if (events.some((row) => row.type === event.type && row.dedupeKey === event.dedupeKey)) return null;+ await ensureDir(PATHS.data);+ await atomicWrite(eventsFile(), { events: pruneEvents([...events, event]) });+ return event;+ }),+ list: async (filters) => {+ const events = await loadFileEvents();+ return events+ .filter((event) => matchesFilters(event, filters))+ .sort(newestFirst)+ .slice(filters.offset, filters.offset + filters.limit);+ },+ };+}++// ---------------------------------------------------------------------------+// PostgreSQL backend — authoritative. The SQL itself lives in userActionsDb.js+// (taking `db` as an argument) so `npm run test:db` can exercise it: this facade+// selects the FILE backend under NODE_ENV=test, which every DB-backed suite runs+// under. Same split as postRunStore.js / postRunDb.js.+// ---------------------------------------------------------------------------++function makePgBackend(db) {+ return {+ name: 'postgres',+ record: async (event) => {+ const inserted = await insertUserActionEvent(db, event);+ if (!inserted) return null;+ // Retention runs only after a row actually landed — a deduped retry must+ // not pay for two DELETE scans.+ await pruneUserActionEvents(db, { maxRows: retention.maxRows, cutoffIso: retentionCutoff() });+ return event;+ },+ list: (filters) => listUserActionEvents(db, filters),+ };+}++const facade = createPgFileFacade({+ // Vitest's VITEST marker is the resilient test signal when a wrapper drops+ // NODE_ENV; never let a focused route suite fall through to the live Postgres.+ isFile: () => process.env.MEMORY_BACKEND === 'file' || isTestRunner(),+ makeFile: makeFileBackend,+ makePg: () => resolvePgBackend({+ requirement: 'The operator-action ledger requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file)',+ loadDb: () => import('../lib/db.js'),+ makePg: makePgBackend,+ }),+});++// ---------------------------------------------------------------------------+// Public surface.+// ---------------------------------------------------------------------------++/**+ * Persist one operator action. Returns the stored event, or `null` when an event+ * with the same `(type, dedupeKey)` already exists (a retried request).+ *+ * @param {object} action+ * @param {string} action.type One of USER_ACTION_TYPES; unknown values throw.+ * @param {string} [action.actor] 'user' (default) | 'mind' | 'schedule' | 'system'.+ * @param {string} [action.target] Stable id of what was acted on (task id, agent id).+ * @param {string} [action.targetName] Human label for that target.+ * @param {boolean} [action.success] Defaults true; pass false only when the handler+ * already holds a structured failure result.+ * @param {string} action.summary One LLM-readable line, clamped to 240 chars.+ * @param {object} [action.payload] Structured detail; redacted + truncated here.+ * @param {object} [action.source] `{ route, method }` or `{ service, fn }`.+ * @param {string} action.dedupeKey Stable idempotency key; required.+ * @param {string|Date} [action.happenedAt] Defaults to now.+ */+export async function recordUserAction(action) {+ const event = normalizeUserAction(action);+ const backend = await facade.getBackend();+ return backend.record(event);+}++/** Read the ledger newest-first. See `normalizeListOptions` for the clamps. */+export async function listUserActions(options = {}) {+ const filters = normalizeListOptions(options);+ const backend = await facade.getBackend();+ return backend.list(filters);+}++/** Test seam — drop the memoized backend selection so a suite can re-select. */+export function _resetUserActionsBackend() {+ facade.reset();+}diff --git a/server/services/userActions.test.js b/server/services/userActions.test.jsnew file mode 100644index 0000000000..0dab923a7e--- /dev/null+++ b/server/services/userActions.test.js@@ -0,0 +1,211 @@+/**+ * Operator-action ledger store (#5594) — recorder contract + read filters.+ *+ * Runs on the FILE backend (NODE_ENV=test), which is exactly the escape hatch+ * that lets the instrumented route suites assert a persisted row without a+ * database. The Postgres round-trip is covered by `userActions.db.test.js`+ * (`npm run test:db`).+ *+ * What is pinned here is the stuff a higher-level test cannot pin cheaply: the+ * redaction/truncation guarantee (a security boundary), the closed-vocabulary+ * refusal, idempotency, and the two retention bounds — all with the caps lowered+ * so the test proves the behavior instead of the constant.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { rmSync } from 'node:fs';+import { join } from 'node:path';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-user-actions-' });+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++const {+ DEFAULT_LIST_LIMIT,+ MAX_LIST_LIMIT,+ PAYLOAD_STRING_MAX_CHARS,+ SUMMARY_MAX_CHARS,+ __setUserActionRetention,+ clampSummary,+ listUserActions,+ normalizeListOptions,+ recordUserAction,+ redactPayload,+} = await import('./userActions.js');++const EVENTS_FILE = join(tempRoot, 'user-action-events.json');++// Fixture timestamps are RELATIVE: the 90-day age cap is real, so a hardcoded+// calendar date silently ages out of the ledger and the suite goes green-empty.+const daysAgo = (days) => new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();++const action = (over = {}) => ({+ type: 'cos.task.create',+ summary: 'Queued CoS task: render the shot',+ dedupeKey: `k-${Math.random().toString(36).slice(2)}`,+ ...over,+});++beforeEach(() => {+ rmSync(EVENTS_FILE, { force: true });+ __setUserActionRetention();+});++afterAll(cleanup);++describe('recordUserAction', () => {+ it('persists an action and reads it back newest-first', async () => {+ await recordUserAction(action({ dedupeKey: 'a', happenedAt: daysAgo(2) }));+ await recordUserAction(action({ dedupeKey: 'b', happenedAt: daysAgo(1), summary: 'second' }));++ const events = await listUserActions();+ expect(events.map((e) => e.dedupeKey)).toEqual(['b', 'a']);+ expect(events[0]).toMatchObject({ type: 'cos.task.create', actor: 'user', success: true });+ });++ it('is idempotent on (type, dedupeKey)', async () => {+ expect(await recordUserAction(action({ dedupeKey: 'same' }))).not.toBeNull();+ expect(await recordUserAction(action({ dedupeKey: 'same', summary: 'retry' }))).toBeNull();+ expect(await listUserActions()).toHaveLength(1);++ // The key is scoped to the TYPE, so the same dedupe key under a different+ // action is a different event, not a swallowed duplicate.+ await recordUserAction(action({ type: 'cos.task.delete', dedupeKey: 'same' }));+ expect(await listUserActions()).toHaveLength(2);+ });++ it('refuses an unknown type or actor, and accepts a known one', async () => {+ // Bypass probe: the same call with a vocabulary member must succeed, or this+ // guard would pass for reasons unrelated to the vocabulary check.+ await expect(recordUserAction(action({ type: 'cos.task.explode' }))).rejects.toThrow(/Unknown user action type/);+ await expect(recordUserAction(action({ actor: 'robot' }))).rejects.toThrow(/Unknown user action actor/);+ await expect(recordUserAction(action({ actor: 'schedule' }))).resolves.not.toBeNull();+ });++ it('refuses an action with no dedupe key', async () => {+ await expect(recordUserAction(action({ dedupeKey: ' ' }))).rejects.toThrow(/missing a dedupeKey/);+ });++ it('drops credential-shaped payload keys and lists their paths', async () => {+ await recordUserAction(action({+ dedupeKey: 'secretive',+ payload: {+ taskId: 'task-1',+ provider: 'claude',+ apiKey: 'sk-EXAMPLE-not-a-real-key',+ nested: { refreshToken: 'EXAMPLE-token', model: 'opus' },+ },+ }));++ const [event] = await listUserActions();+ expect(event.payload.redactedKeys).toEqual(['apiKey', 'nested.refreshToken']);+ expect(event.payload).not.toHaveProperty('apiKey');+ expect(event.payload.nested).toEqual({ model: 'opus' });+ // The non-secret siblings survive — redaction must not be a payload wipe.+ expect(event.payload).toMatchObject({ taskId: 'task-1', provider: 'claude' });+ expect(JSON.stringify(event)).not.toContain('sk-EXAMPLE-not-a-real-key');+ expect(JSON.stringify(event)).not.toContain('EXAMPLE-token');+ });++ it('truncates a long payload string and flags the containing object', async () => {+ const prompt = 'x'.repeat(PAYLOAD_STRING_MAX_CHARS + 500);+ await recordUserAction(action({ dedupeKey: 'long', payload: { taskId: 't', prompt } }));++ const [event] = await listUserActions();+ expect(event.payload.prompt.length).toBe(PAYLOAD_STRING_MAX_CHARS + 1); // + the ellipsis+ expect(event.payload.truncated).toBe(true);+ });++ it('clamps the summary to one readable line', async () => {+ const long = `start ${'word '.repeat(200)}end`;+ await recordUserAction(action({ dedupeKey: 'wordy', summary: long }));++ const [event] = await listUserActions();+ expect(event.summary.length).toBeLessThanOrEqual(SUMMARY_MAX_CHARS);+ expect(event.summary.startsWith('start ')).toBe(true);+ expect(clampSummary(' a\n b ')).toBe('a b');+ });+});++describe('redactPayload', () => {+ it('redacts provider-specific *Key names without eating keysChanged', () => {+ const { payload, redactedKeys } = redactPayload({+ openaiKey: 'EXAMPLE-1',+ sshKey: 'EXAMPLE-2',+ deployKeys: ['EXAMPLE-3'],+ // The recorder's own bookkeeping field and a plain list of names must+ // survive — an over-broad `key` rule would swallow both.+ keysChanged: ['timezone'],+ monkeyCount: 3,+ });+ // redactPayload reports in walk order; normalizeUserAction is what sorts.+ expect([...redactedKeys].sort()).toEqual(['deployKeys', 'openaiKey', 'sshKey']);+ expect(payload).toEqual({ keysChanged: ['timezone'], monkeyCount: 3 });+ });++ it('reports paths through arrays and tolerates a non-object payload', () => {+ const { payload, redactedKeys } = redactPayload({ items: [{ password: 'p' }, { ok: 1 }] });+ expect(redactedKeys).toEqual(['items.0.password']);+ expect(payload.items).toEqual([{}, { ok: 1 }]);+ expect(redactPayload(undefined)).toEqual({ payload: {}, redactedKeys: [] });+ });+});++describe('listUserActions', () => {+ beforeEach(async () => {+ await recordUserAction(action({+ type: 'cos.task.create', dedupeKey: 'l1', actor: 'user',+ happenedAt: daysAgo(9), target: 'task-1',+ }));+ await recordUserAction(action({+ type: 'cos.schedule.trigger', dedupeKey: 'l2', actor: 'user',+ happenedAt: daysAgo(5), target: 'branch-reconcile',+ }));+ await recordUserAction(action({+ type: 'settings.update', dedupeKey: 'l3', actor: 'system',+ happenedAt: daysAgo(1), success: false,+ }));+ });++ it('filters by type, actor, target, success, and time window', async () => {+ expect((await listUserActions({ type: 'settings.update' })).map((e) => e.dedupeKey)).toEqual(['l3']);+ expect((await listUserActions({ types: ['cos.task.create', 'settings.update'] })).map((e) => e.dedupeKey))+ .toEqual(['l3', 'l1']);+ expect((await listUserActions({ actor: 'system' })).map((e) => e.dedupeKey)).toEqual(['l3']);+ expect((await listUserActions({ target: 'branch-reconcile' })).map((e) => e.dedupeKey)).toEqual(['l2']);+ expect((await listUserActions({ success: false })).map((e) => e.dedupeKey)).toEqual(['l3']);+ expect((await listUserActions({+ from: daysAgo(7), to: daysAgo(3),+ })).map((e) => e.dedupeKey)).toEqual(['l2']);+ });++ it('pages with offset and clamps the limit', async () => {+ expect((await listUserActions({ limit: 1, offset: 1 })).map((e) => e.dedupeKey)).toEqual(['l2']);+ expect(normalizeListOptions({}).limit).toBe(DEFAULT_LIST_LIMIT);+ expect(normalizeListOptions({ limit: 5000 }).limit).toBe(MAX_LIST_LIMIT);+ expect(normalizeListOptions({ limit: 0 }).limit).toBe(1);+ expect(normalizeListOptions({ limit: -3 }).limit).toBe(1);+ expect(normalizeListOptions({ offset: -3 }).offset).toBe(0);+ });+});++describe('retention', () => {+ it('drops the oldest rows past the row cap', async () => {+ __setUserActionRetention({ maxRows: 2 });+ for (const index of [0, 1, 2]) {+ await recordUserAction(action({ dedupeKey: `r${index}`, happenedAt: daysAgo(3 - index) }));+ }+ expect((await listUserActions()).map((e) => e.dedupeKey)).toEqual(['r2', 'r1']);+ });++ it('drops rows past the age cap on the next write', async () => {+ __setUserActionRetention({ maxAgeDays: 1 });+ const old = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString();+ await recordUserAction(action({ dedupeKey: 'stale', happenedAt: old }));+ await recordUserAction(action({ dedupeKey: 'fresh' }));+ expect((await listUserActions()).map((e) => e.dedupeKey)).toEqual(['fresh']);+ });+});diff --git a/server/services/userActionsDb.js b/server/services/userActionsDb.jsnew file mode 100644index 0000000000..163dc661ed--- /dev/null+++ b/server/services/userActionsDb.js@@ -0,0 +1,89 @@+/**+ * PostgreSQL leaf I/O for the operator-action ledger (#5594).+ *+ * Split out of `userActions.js` the same way `postRunDb.js` is split out of+ * `postRunStore.js`: the store owns backend selection (and therefore selects the+ * FILE backend under `NODE_ENV=test`), so the SQL would otherwise be unreachable+ * from a test. Every function here takes the `db` module as its first argument —+ * no module-level database import — which is what lets `userActions.db.test.js`+ * drive it against `portos_test` under `npm run test:db`.+ */++const iso = (value) => (value instanceof Date ? value.toISOString() : value);++/** Map a `user_action_events` row to the camelCase event shape the API returns. */+export function rowToUserActionEvent(row) {+ return {+ id: row.id,+ type: row.type,+ actor: row.actor,+ happenedAt: iso(row.happened_at),+ target: row.target,+ targetName: row.target_name,+ success: row.success,+ summary: row.summary,+ payload: row.payload || {},+ source: row.source || {},+ dedupeKey: row.dedupe_key,+ createdAt: iso(row.created_at),+ };+}++/**+ * Insert one event, idempotent on `(type, dedupe_key)`.+ * @returns {Promise<boolean>} true when a row landed, false when it was a duplicate.+ */+export async function insertUserActionEvent(db, event) {+ const result = await db.query(+ `INSERT INTO user_action_events+ (id, type, actor, happened_at, target, target_name, success, summary, payload, source, dedupe_key)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10::jsonb, $11)+ ON CONFLICT (type, dedupe_key) DO NOTHING+ RETURNING id`,+ [+ event.id, event.type, event.actor, event.happenedAt, event.target, event.targetName,+ event.success, event.summary, JSON.stringify(event.payload),+ JSON.stringify(event.source), event.dedupeKey,+ ],+ );+ return (result.rowCount || 0) > 0;+}++/**+ * Enforce BOTH retention bounds: nothing older than `cutoffIso`, and no more than+ * `maxRows` rows. Called inline after a successful insert rather than from a cron+ * — the table only grows when the user acts, so a scheduled job for it would be a+ * moving part that earns nothing.+ * @returns {Promise<number>} rows deleted.+ */+export async function pruneUserActionEvents(db, { maxRows, cutoffIso }) {+ const aged = await db.query('DELETE FROM user_action_events WHERE happened_at < $1', [cutoffIso]);+ const overflow = await db.query(+ `DELETE FROM user_action_events WHERE id IN (+ SELECT id FROM user_action_events ORDER BY happened_at DESC, id DESC OFFSET $1+ )`,+ [maxRows],+ );+ return (aged.rowCount || 0) + (overflow.rowCount || 0);+}++/** Newest-first slice of the ledger. `filters` comes from `normalizeListOptions`. */+export async function listUserActionEvents(db, filters) {+ const where = [];+ const params = [];+ const bind = (value) => { params.push(value); return `$${params.length}`; };+ if (filters.types.length > 0) where.push(`type = ANY(${bind(filters.types)})`);+ if (filters.actor) where.push(`actor = ${bind(filters.actor)}`);+ if (filters.target) where.push(`target = ${bind(filters.target)}`);+ if (filters.success !== null) where.push(`success = ${bind(filters.success)}`);+ if (filters.from) where.push(`happened_at >= ${bind(filters.from)}`);+ if (filters.to) where.push(`happened_at <= ${bind(filters.to)}`);+ const result = await db.query(+ `SELECT * FROM user_action_events+ ${where.length ? `WHERE ${where.join(' AND ')}` : ''}+ ORDER BY happened_at DESC, id DESC+ LIMIT ${bind(filters.limit)} OFFSET ${bind(filters.offset)}`,+ params,+ );+ return result.rows.map(rowToUserActionEvent);+}diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 2adc513a1b..22889f67bf 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -20,6 +20,7 @@ export const DB_TEST_INCLUDE = ['services/catalogDB.facets.db.test.js','services/humanActivity.db.test.js','services/postRunDb.db.test.js',+ 'services/userActions.db.test.js','services/memoryDB.db.test.js','services/privacySubjects.db.test.js','services/privacyVault.db.test.js',