Skip to content

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

feat: let Persistent Mind observe operator actions and propose automations (#5595)

[._.]/ Adam Eivy4ce85e7631b6
diff --git a/server/lib/README.md b/server/lib/README.md
index 73bf015b73..5979a65f30 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -217,6 +217,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |
| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
+| `secretText.js` | `scrubSecretTokens(text)` — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with `[REDACTED]` in free text bound for an LLM provider or a world-readable artifact; `scrubSecretTokensDeep(value)` walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based `redactPayload` and `commandSecurity.js#redactOutput`'s JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive. |
| `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). |
| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore`. |
| `mimeTypes.js` | MIME tables and extension allowlists, image format detection, and filename sanitization. |
diff --git a/server/lib/index.js b/server/lib/index.js
index efb3ac94e3..48c5444a6c 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -215,6 +215,7 @@ export * from './uploads.js';
export * from './icloudFile.js';
export * from './spawnCwd.js';
export * from './schemaVersions.js';
+export * from './secretText.js';
export * from './imageClean.js';
export * from './imageFrameStats.js';
export * from './imageRgba.js';
diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.js
index 9fb477b9c1..cc33180a50 100644
--- a/server/lib/persistentMindCapabilities.js
+++ b/server/lib/persistentMindCapabilities.js
@@ -73,13 +73,14 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze([
id: 'portos.read',
capability: 'readPortos',
name: 'Read PortOS context',
- description: 'Use the bounded semantic catalog to inspect selected Brain, goals, journal, calendar, health, feed, catalog, and runtime context.',
+ description: 'Use the bounded semantic catalog to inspect selected Brain, goals, journal, calendar, health, feed, catalog, runtime context, and the recent operator-action ledger (what you did in PortOS — including the prompts and settings changes those actions recorded).',
kind: 'semantic-tools',
defaultEnabled: false,
guardrails: [
'Read-only adapters only',
'No arbitrary URL, route, SQL, shell, or filesystem access',
'Tool inputs and results are schema-validated and size-bounded',
+ 'Operator-action ledger reads are machine-local, capped at 100 events per call, and credential-redacted at record time plus value-scrubbed on output',
],
}),
Object.freeze({
diff --git a/server/lib/secretText.js b/server/lib/secretText.js
new file mode 100644
index 0000000000..d3707c41cb
--- /dev/null
+++ b/server/lib/secretText.js
@@ -0,0 +1,50 @@
+/**
+ * Scrub credential-SHAPED token values out of free text bound for an LLM
+ * provider or a world-readable artifact.
+ *
+ * The operator-action ledger already drops credential-shaped KEYS at record
+ * time (`services/userActions.js#redactPayload`), but free-text fields —
+ * summaries, target names — can carry a pasted token by VALUE, where no key
+ * name exists to match. This is the value-side counterpart: conservative,
+ * well-known token shapes only, so ordinary prose, git SHAs (40 hex), and
+ * short ids survive untouched. Complements `commandSecurity.js#redactOutput`
+ * (JSON key/value patterns) rather than replacing it.
+ */
+
+const SECRET_TOKEN_PATTERNS = [
+ // OpenAI/Anthropic/Stripe-style prefixed keys (sk-…, sk-ant-…, pk_live_…).
+ /\b[sprx]k[-_](?:[A-Za-z0-9]+[-_])*[A-Za-z0-9]{16,}\b/g,
+ // GitHub tokens (ghp_/gho_/ghu_/ghs_/ghr_ + the fine-grained github_pat_).
+ /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,
+ /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
+ // Slack tokens.
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
+ // JWTs (three dot-joined base64url segments starting with the {"alg" header).
+ /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}\b/g,
+ // AWS access key ids.
+ /\bAKIA[0-9A-Z]{16}\b/g,
+ // Bearer/token headers pasted whole.
+ /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/gi,
+ // Very long unbroken hex (48+ — deliberately above a 40-char git SHA).
+ /\b[A-Fa-f0-9]{48,}\b/g,
+];
+
+/** Replace credential-shaped substrings with `[REDACTED]`. Non-strings pass through. */
+export function scrubSecretTokens(text) {
+ if (typeof text !== 'string' || text.length === 0) return text;
+ return SECRET_TOKEN_PATTERNS.reduce((out, pattern) => out.replace(pattern, '[REDACTED]'), text);
+}
+
+/**
+ * Apply `scrubSecretTokens` to every string in a JSON-shaped value — arrays and
+ * plain objects are walked (values only; key names are handled by the key-based
+ * redaction at record time), everything else passes through untouched.
+ */
+export function scrubSecretTokensDeep(value) {
+ if (typeof value === 'string') return scrubSecretTokens(value);
+ if (Array.isArray(value)) return value.map(scrubSecretTokensDeep);
+ if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, scrubSecretTokensDeep(child)]));
+ }
+ return value;
+}
diff --git a/server/lib/secretText.test.js b/server/lib/secretText.test.js
new file mode 100644
index 0000000000..9e8ff23ffd
--- /dev/null
+++ b/server/lib/secretText.test.js
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+import { scrubSecretTokens, scrubSecretTokensDeep } from './secretText.js';
+
+describe('scrubSecretTokens', () => {
+ it('redacts well-known credential shapes by value', () => {
+ const cases = [
+ 'queued with sk-abcdefghijklmnopqrstuvwx set',
+ 'sk-ant-api03-abcdefghijklmnop1234 pasted',
+ 'push with ghp_abcdefghijklmnopqrstuv please',
+ 'github_pat_11ABCDEFGHIJKLMNOPQRST_more',
+ 'slack xoxb-1234567890-abcdefghij done',
+ 'jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.abcdef123456 here',
+ 'aws AKIAIOSFODNN7EXAMPLE key',
+ 'header Authorization: Bearer abcdef1234567890abcdef',
+ `hex ${'a1'.repeat(30)} blob`,
+ ];
+ for (const text of cases) {
+ expect(scrubSecretTokens(text), text).toContain('[REDACTED]');
+ }
+ });
+
+ it('leaves prose, git SHAs, and short ids untouched', () => {
+ const sha = 'a'.repeat(40);
+ const cases = [
+ 'Ran scheduled task branch-reconcile on demand',
+ `merged commit ${sha} to main`,
+ 'task-mtiw9qyv finished with rating 4',
+ 'set threshold to 12345678',
+ ];
+ for (const text of cases) {
+ expect(scrubSecretTokens(text), text).toBe(text);
+ }
+ });
+
+ it('passes non-strings and empty strings through', () => {
+ expect(scrubSecretTokens(null)).toBeNull();
+ expect(scrubSecretTokens(42)).toBe(42);
+ expect(scrubSecretTokens('')).toBe('');
+ });
+});
+
+describe('scrubSecretTokensDeep', () => {
+ it('scrubs string values through nested objects and arrays', () => {
+ expect(scrubSecretTokensDeep({
+ prompt: 'deploy with sk-abcdefghijklmnopqrstuvwx now',
+ nested: { notes: ['fine', 'token ghp_abcdefghijklmnopqrstuv here'] },
+ count: 3,
+ flag: true,
+ })).toEqual({
+ prompt: 'deploy with [REDACTED] now',
+ nested: { notes: ['fine', 'token [REDACTED] here'] },
+ count: 3,
+ flag: true,
+ });
+ });
+
+ it('leaves non-plain objects and primitives alone', () => {
+ const when = new Date(0);
+ expect(scrubSecretTokensDeep(when)).toBe(when);
+ expect(scrubSecretTokensDeep(null)).toBeNull();
+ expect(scrubSecretTokensDeep(7)).toBe(7);
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index a75de3760e..ad7c04a24f 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1874,6 +1874,35 @@ export async function generateSelfImprovementTaskForType(taskType, state) {
// exists for — so the pre-step runs here, not only in the per-app lane. It
// returns `skip` when the sweep left nothing for an agent to do, which is the
// common case on an already-clean machine and costs no provider call.
+ // Programmatic pre-agent input hook (taskTypeHooks.js) — the install-wide
+ // lane mirrors the per-app one so a hook-gated type (user-action-review's
+ // empty-ledger check) can skip here too, without burning an agent. Gated to
+ // INSTALL-WIDE types: the per-app hooks (issue-watcher, layered-intelligence)
+ // guard on `!app`, and the synthetic `{ id: null }` row below is truthy — an
+ // ungated call would march issue-watcher into resolving the PortOS repo as
+ // its app via getOriginInfo's cwd default. The synthetic row only labels the
+ // skip log / execution record; provider pins from a hook are a per-app
+ // concept and are not applied in this lane.
+ if (taskSchedule.INSTALL_WIDE_TASK_TYPES.has(taskType)) {
+ const inputHook = await resolveTaskInputHook({ id: null, name: 'PortOS' }, taskType, taskSchedule);
+ if (inputHook.skip) return null;
+ if (inputHook.hookPrompt) description = inputHook.hookPrompt;
+ }
+
+ // user-action-review delivers filed issues / queued tasks, never a commit.
+ // Stamp the action-output posture the way the audit file-issues path does —
+ // `noCodeOutput` is dispatch-stamped, not user-settable, so it cannot arrive
+ // from DEFAULT_TASK_INTERVALS through sanitizeTaskMetadata. Without it the
+ // completion contract tells a live-checkout agent to commit and `/do:push`.
+ if (taskType === 'user-action-review') {
+ metadata.noCodeOutput = true;
+ metadata.worktreeChangesExpected = false;
+ }
+
+ // user-action-review: render the delivery posture the operator chose
+ // (fileIssues on = tracker issues, off = queued CoS tasks).
+ description = applyUserActionDeliveryMode(description, taskType, metadata);
+
const repoSync = await resolveRepoSyncBlock(null, taskType, metadata);
if (repoSync.skip) return null;
if (repoSync.block) {
@@ -2874,6 +2903,35 @@ async function resolvePrWatcherBlock(app, taskType, metadata, taskSchedule) {
return { skip: false, block, repoFullName: check.repoFullName, defaultBranch: check.defaultBranch };
}
+/**
+ * user-action-review's `{userActionDelivery}` block: the operator's
+ * `fileIssues` choice decides HOW proposals leave the run — filed tracker
+ * issues (default) or queued CoS tasks. Resolved at dispatch, like the audit
+ * mode contract, so a customized stored prompt still honors the toggle. The
+ * type is not in the audit catalog (its "do work" alternative is queueing
+ * tasks, not editing code), so the audit mode wrapper does not apply to it.
+ */
+export function resolveUserActionDeliveryBlock(taskType, metadata) {
+ if (taskType !== 'user-action-review') return '';
+ return metadata?.fileIssues === false || metadata?.fileIssues === 'false'
+ ? 'Deliver each accepted proposal as a QUEUED CoS TASK (`POST /api/cos/tasks`, one bounded task per proposal, priority LOW unless the evidence is severe) — the operator turned off file-issues mode for this schedule. Do not file tracker issues.'
+ : 'Deliver each accepted proposal as a FILED TRACKER ISSUE in the PortOS repository (`gh issue create` with the `plan` label; create the label first if missing). This is file-issues mode, the default. Do not queue CoS tasks.';
+}
+
+/**
+ * Render the delivery posture into a user-action-review prompt. Mirrors
+ * `applyAuditModeWrapper`: a customized stored prompt that dropped the
+ * `{userActionDelivery}` token still gets the operator's choice PREPENDED —
+ * otherwise flipping fileIssues would be a silent no-op on that install.
+ */
+export function applyUserActionDeliveryMode(promptTemplate, taskType, metadata) {
+ const prompt = typeof promptTemplate === 'string' ? promptTemplate : '';
+ const block = resolveUserActionDeliveryBlock(taskType, metadata);
+ if (!block) return prompt;
+ if (prompt.includes('{userActionDelivery}')) return prompt.replace(/\{userActionDelivery\}/g, () => block);
+ return `## Delivery mode\n\n${block}\n\n---\n\n${prompt}`;
+}
+
/**
* Prompt resolution: resolve the `{reviewers}` / `{issueAuthorFilter}` /
* `{swarm}` directives from task metadata + the user's Code Review Defaults,
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 45ef3736ff..c6c48a2dd0 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -77,6 +77,8 @@ import {
buildClaimOverrideContextBlock,
buildLocalReviewerInstructions,
resolveTaskInputHook,
+ resolveUserActionDeliveryBlock,
+ applyUserActionDeliveryMode,
resolveReconcileDrainGate,
applyPerpetualDrainCap
} from './cosTaskGenerator.js';
@@ -271,7 +273,7 @@ describe('isConfiguredApprovalRequired', () => {
it('both generators stamp approvalReason onto metadata so the hint survives COS-TASKS.md', () => {
const selfStart = GEN_SRC.indexOf('export async function generateSelfImprovementTaskForType');
const appStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');
- expect(GEN_SRC.slice(selfStart, selfStart + 2500)).toContain('stampApprovalReason(metadata, approval)');
+ expect(GEN_SRC.slice(selfStart, selfStart + 4500)).toContain('stampApprovalReason(metadata, approval)');
expect(GEN_SRC.slice(appStart, appStart + 11000)).toContain('stampApprovalReason(metadata, approval)');
});
@@ -1383,6 +1385,50 @@ describe('buildImprovementDedupSets (#2614 — failure-blocked tasks occupy thei
});
});
+describe('resolveUserActionDeliveryBlock (#5595)', () => {
+ it('renders the tracker-issue posture by default and the CoS-task posture when fileIssues is off', () => {
+ expect(resolveUserActionDeliveryBlock('user-action-review', { fileIssues: true })).toContain('FILED TRACKER ISSUE');
+ expect(resolveUserActionDeliveryBlock('user-action-review', {})).toContain('FILED TRACKER ISSUE');
+ expect(resolveUserActionDeliveryBlock('user-action-review', { fileIssues: false })).toContain('QUEUED CoS TASK');
+ // Metadata round-trips through COS-TASKS.md as text — string 'false' counts.
+ expect(resolveUserActionDeliveryBlock('user-action-review', { fileIssues: 'false' })).toContain('QUEUED CoS TASK');
+ expect(resolveUserActionDeliveryBlock('security', { fileIssues: false })).toBe('');
+ });
+
+ it('applyUserActionDeliveryMode substitutes the token, or PREPENDS on a customized prompt that dropped it', () => {
+ const withToken = applyUserActionDeliveryMode('Intro\n\n{userActionDelivery}\n\nOutro', 'user-action-review', {});
+ expect(withToken).toContain('FILED TRACKER ISSUE');
+ expect(withToken).not.toContain('{userActionDelivery}');
+ // A customized stored prompt without the token must still receive the
+ // operator's fileIssues choice — otherwise the toggle is a silent no-op.
+ const custom = applyUserActionDeliveryMode('My custom review prompt', 'user-action-review', { fileIssues: false });
+ expect(custom).toMatch(/^## Delivery mode\n\n.*QUEUED CoS TASK/s);
+ expect(custom).toContain('My custom review prompt');
+ // Every other task type passes through untouched.
+ expect(applyUserActionDeliveryMode('Prompt', 'security', {})).toBe('Prompt');
+ });
+
+ it('the install-wide lane consumes the input hook and renders the delivery block', () => {
+ // Source-pinned like the approval-stamp guard above: the empty-ledger skip
+ // and the delivery posture must reach the "Run Now with no app" lane, which
+ // is the only lane an install-wide type dispatches from.
+ const selfStart = GEN_SRC.indexOf('export async function generateSelfImprovementTaskForType');
+ const selfBody = GEN_SRC.slice(selfStart, selfStart + 9000);
+ // Gated to install-wide types: the per-app hooks (issue-watcher,
+ // layered-intelligence) guard on `!app`, and the truthy synthetic
+ // `{ id: null }` row would defeat that guard.
+ expect(selfBody).toContain('if (taskSchedule.INSTALL_WIDE_TASK_TYPES.has(taskType)) {');
+ expect(selfBody).toContain("resolveTaskInputHook({ id: null, name: 'PortOS' }, taskType, taskSchedule)");
+ expect(selfBody).toContain('applyUserActionDeliveryMode(description, taskType, metadata)');
+ // The action-output posture must be dispatch-stamped: noCodeOutput is not a
+ // sanitizer-allowed key, so it cannot ride in from DEFAULT_TASK_INTERVALS —
+ // without the stamp the completion contract tells a live-checkout agent to
+ // commit and /do:push.
+ expect(selfBody).toContain('metadata.noCodeOutput = true');
+ expect(selfBody).toContain('metadata.worktreeChangesExpected = false');
+ });
+});
+
/**
* `hookMetadata` is the channel a buildTaskInput hook uses to defer a side
* effect until the task is CERTAIN to exist (#3179). quota-burn rides its
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index 6235452015..bb7b508c08 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -22,6 +22,7 @@ import {
eidoverseWorldAugmentSchema,
eidoverseWorldSaySchema,
} from '../lib/validation.js';
+import { USER_ACTION_ACTORS, USER_ACTION_TYPES } from '../lib/userActionTypes.js';
import { dispatchTool, getToolSpecs, getToolSpecsForIntent } from './voice/tools.js';
import { executePersistentMindTaskRequests } from './persistentMindTaskCapability.js';
import { cleanupPersistentMind } from './persistentMindMaintenance.js';
@@ -139,6 +140,39 @@ const mindCleanupTool = Object.freeze({
adapter: { kind: 'persistent-mind-maintenance' },
});
+// One mind turn must not be able to dump the whole ledger into context — the
+// store's own list cap (500) is sized for the HTTP API, not a prompt.
+export const USER_ACTIONS_QUERY_MAX_RESULTS = 100;
+
+const userActionsQuerySchema = z.object({
+ from: z.string().trim().min(1).optional(),
+ to: z.string().trim().min(1).optional(),
+ type: z.enum([...USER_ACTION_TYPES]).optional(),
+ types: z.array(z.enum([...USER_ACTION_TYPES])).max(USER_ACTION_TYPES.length).optional(),
+ actor: z.enum([...USER_ACTION_ACTORS]).optional(),
+ limit: z.number().int().min(1).optional(),
+}).strict();
+
+const userActionsQueryTool = Object.freeze({
+ type: 'portos_tool',
+ name: 'user-actions.query',
+ version: COS_TOOL_SCHEMA_VERSION,
+ providerName: 'user_actions_query',
+ aliases: ['user_actions_query'],
+ description: 'Query the machine-local operator-action ledger — what the user, a schedule, or PortOS itself recently did in the app — filtered by time range, event type, and actor.',
+ input_schema: zodToOpenApiSchema(userActionsQuerySchema),
+ output_schema: objectOutputSchema,
+ policy: {
+ scopes: ['agent', 'mind', 'ui'],
+ requiredCapabilities: ['readPortos'],
+ sideEffect: 'read',
+ idempotent: true,
+ async: false,
+ confirmation: 'none',
+ },
+ adapter: { kind: 'user-actions' },
+});
+
const eidoverseStatusTool = Object.freeze({
type: 'portos_tool',
name: 'eidoverse.status',
@@ -220,7 +254,7 @@ const eidoverseSayTool = Object.freeze({
});
const eidoverseTools = [eidoverseStatusTool, eidoverseProjectTool, eidoverseAugmentTool, eidoverseSayTool];
-const toolCatalog = (intent) => [taskTool, mindCleanupTool, ...eidoverseTools, ...voiceTools(intent)];
+const toolCatalog = (intent) => [taskTool, mindCleanupTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];
const toolCalls = new Map();
const toolCallFingerprints = new Map();
@@ -356,6 +390,44 @@ const executeAdapter = async (tool, args, context) => {
preserveMessageId: context.wake?.kind === 'message' ? context.wake.message?.id || null : null,
});
}
+ if (tool.adapter.kind === 'user-actions') {
+ const [{ listUserActions }, { scrubSecretTokens, scrubSecretTokensDeep }] = await Promise.all([
+ import('./userActions.js'),
+ import('../lib/secretText.js'),
+ ]);
+ // Refinements do not survive the input schema's JSON-Schema round trip, so
+ // date parseability is enforced here — with field attribution, since the
+ // failure surfaces to the model as this error string.
+ for (const field of ['from', 'to']) {
+ if (args[field] !== undefined && Number.isNaN(new Date(args[field]).getTime())) {
+ throw new ServerError(`Invalid '${field}' for '${tool.name}': must be a parseable date/timestamp`, { status: 400, code: 'TOOL_VALIDATION_ERROR' });
+ }
+ }
+ const limit = Math.min(args.limit ?? USER_ACTIONS_QUERY_MAX_RESULTS, USER_ACTIONS_QUERY_MAX_RESULTS);
+ // Fetch one extra row so a full page can honestly report `truncated`.
+ const rows = await listUserActions({ ...args, limit: limit + 1 });
+ return {
+ events: rows.slice(0, limit).map((event) => ({
+ happenedAt: event.happenedAt,
+ type: event.type,
+ actor: event.actor,
+ // Every text projection gets the value-side token scrub — the ledger's
+ // record-time redaction is key-based and cannot catch a credential
+ // pasted into a task description or a settings value.
+ summary: scrubSecretTokens(event.summary),
+ target: event.target ?? null,
+ targetName: event.targetName != null ? scrubSecretTokens(event.targetName) : null,
+ payload: scrubSecretTokensDeep(event.payload ?? {}),
+ // Only the route identity crosses into a prompt — a `{ service, fn }`
+ // source or any filesystem path stays behind.
+ source: {
+ ...(event.source?.route ? { route: event.source.route } : {}),
+ ...(event.source?.method ? { method: event.source.method } : {}),
+ },
+ })),
+ truncated: rows.length > limit,
+ };
+ }
if (tool.adapter.kind === 'eidoverse-world') {
const world = await import('./eidoverseWorld.js');
if (tool.adapter.operation === 'status') return world.getEidoverseWorldStatus();
diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.js
index 2bd3cab195..5e315e2a99 100644
--- a/server/services/cosToolRegistry.test.js
+++ b/server/services/cosToolRegistry.test.js
@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({
worldProject: vi.fn(),
worldAugment: vi.fn(),
worldSay: vi.fn(),
+ listUserActions: vi.fn(),
}));
const specs = [
@@ -54,6 +55,9 @@ vi.mock('./eidoverseWorld.js', () => ({
augmentEidoverseWorld: (...args) => mocks.worldAugment(...args),
sayInEidoverseWorld: (...args) => mocks.worldSay(...args),
}));
+vi.mock('./userActions.js', () => ({
+ listUserActions: (...args) => mocks.listUserActions(...args),
+}));
import {
__testing,
@@ -82,6 +86,7 @@ describe('cosToolRegistry', () => {
expect(catalog.tools.map((tool) => tool.name)).toEqual([
'cos.create-task',
'mind.cleanup',
+ 'user-actions.query',
'eidoverse.status',
'eidoverse.project',
'eidoverse.augment',
@@ -93,6 +98,7 @@ describe('cosToolRegistry', () => {
expect(catalog.tools.find((tool) => tool.name === 'brain.capture').granted).toBe(false);
const openai = formatCosToolCatalog(catalog, 'openai');
expect(openai.tools).toEqual([
+ expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'user_actions_query' }) }),
expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'eidoverse_status' }) }),
expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'brain_search' }) }),
]);
@@ -106,6 +112,90 @@ describe('cosToolRegistry', () => {
expect(prompt).not.toContain('brain.capture');
});
+ it('exposes the operator-action ledger to mind and agent scopes only behind readPortos', async () => {
+ const agentCatalog = getCosToolCatalog({ scope: 'agent', capabilities: { readPortos: true } });
+ expect(agentCatalog.tools.find((tool) => tool.providerName === 'user_actions_query').granted).toBe(true);
+ // scope 'agent' + granted is exactly what agentContextMcp's
+ // semanticToolsForConfig re-exports over the loopback MCP surface.
+ expect(formatCosToolCatalog(agentCatalog, 'mcp').tools.map((tool) => tool.name)).toContain('user_actions_query');
+ const denied = getCosToolCatalog({ scope: 'agent', capabilities: { writePortos: true } });
+ expect(denied.tools.find((tool) => tool.providerName === 'user_actions_query').granted).toBe(false);
+ await expect(executeCosToolCall({
+ call: { requestId: 'ua-denied', name: 'user-actions.query', arguments: {} },
+ authority: { scope: 'mind', capabilities: { createTasks: true } },
+ })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
+ expect(mocks.listUserActions).not.toHaveBeenCalled();
+ });
+
+ it('returns bounded ledger events with source reduced to route identity', async () => {
+ mocks.listUserActions.mockResolvedValue([
+ {
+ id: 'evt-1', happenedAt: '2026-09-01T00:00:02.000Z', type: 'cos.schedule.trigger', actor: 'user',
+ summary: "Ran scheduled task 'branch-reconcile' on demand", target: 'branch-reconcile', targetName: null,
+ payload: { taskType: 'branch-reconcile', prompt: 'use sk-abcdefghijklmnopqrstuvwx for deploy' },
+ source: { route: '/api/cos/schedule/trigger', method: 'POST', service: 'taskSchedule', file: '/home/alice/portos/server.js' },
+ },
+ {
+ id: 'evt-2', happenedAt: '2026-09-01T00:00:01.000Z', type: 'settings.update', actor: 'user',
+ summary: 'Updated settings with token ghp_abcdefghijklmnopqrstuv inside',
+ targetName: 'uses sk-abcdefghijklmnopqrstuvwx here',
+ payload: {}, source: { service: 'settings', fn: 'save' },
+ },
+ {
+ id: 'evt-3', happenedAt: '2026-09-01T00:00:00.000Z', type: 'cos.task.create', actor: 'user',
+ summary: 'Queued task', payload: {}, source: {},
+ },
+ ]);
+ const result = await executeCosToolCall({
+ call: { requestId: 'ua-read', name: 'user-actions.query', arguments: { actor: 'user', limit: 2 } },
+ authority: { scope: 'mind', capabilities: { readPortos: true } },
+ });
+ // Fetches one extra row so a full page reports truncation honestly.
+ expect(mocks.listUserActions).toHaveBeenCalledWith({ actor: 'user', limit: 3 });
+ expect(result.state).toBe('completed');
+ expect(result.result.truncated).toBe(true);
+ expect(result.result.events).toHaveLength(2);
+ expect(result.result.events[0]).toMatchObject({
+ type: 'cos.schedule.trigger',
+ target: 'branch-reconcile',
+ source: { route: '/api/cos/schedule/trigger', method: 'POST' },
+ });
+ // A `{ service, fn }` source (and any filesystem path) never crosses out.
+ expect(result.result.events[1].source).toEqual({});
+ expect(JSON.stringify(result.result)).not.toContain('/home/alice');
+ // Free-text projections get the value-side credential scrub — payload
+ // string values included (record-time redaction is key-based only).
+ expect(result.result.events[1].summary).toBe('Updated settings with token [REDACTED] inside');
+ expect(result.result.events[1].targetName).toBe('uses [REDACTED] here');
+ expect(result.result.events[0].payload.prompt).toBe('use [REDACTED] for deploy');
+ });
+
+ it('rejects an unparseable date filter with field attribution', async () => {
+ mocks.listUserActions.mockResolvedValue([]);
+ const result = await executeCosToolCall({
+ call: { requestId: 'ua-bad-date', name: 'user-actions.query', arguments: { from: 'last tuesday-ish' } },
+ authority: { scope: 'mind', capabilities: { readPortos: true } },
+ });
+ expect(result.state).toBe('failed');
+ expect(result.error).toContain("Invalid 'from'");
+ expect(mocks.listUserActions).not.toHaveBeenCalled();
+ });
+
+ it('clamps the ledger query limit to 100 and rejects unknown filters', async () => {
+ mocks.listUserActions.mockResolvedValue([]);
+ const result = await executeCosToolCall({
+ call: { requestId: 'ua-clamp', name: 'user-actions.query', arguments: { limit: 500 } },
+ authority: { scope: 'mind', capabilities: { readPortos: true } },
+ });
+ expect(result.state).toBe('completed');
+ expect(result.result).toEqual({ events: [], truncated: false });
+ expect(mocks.listUserActions).toHaveBeenCalledWith({ limit: 101 });
+ await expect(executeCosToolCall({
+ call: { requestId: 'ua-bad', name: 'user-actions.query', arguments: { sql: 'DROP TABLE' } },
+ authority: { scope: 'mind', capabilities: { readPortos: true } },
+ })).rejects.toMatchObject({ code: 'TOOL_VALIDATION_ERROR' });
+ });
+
it('validates arguments and executes an allowed read', async () => {
const signal = new AbortController().signal;
const result = await executeCosToolCall({
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index 2186552432..0ab486eaa5 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -41,6 +41,7 @@ import {
buildPersistentMindVisibilityPrompt,
readPersistentMindVisibility,
} from './persistentMindVisibility.js';
+import { readPersistentMindUserActionsPrompt } from './persistentMindUserActions.js';
import {
buildPersistentMindToolPrompt,
executeCosToolCall,
@@ -221,11 +222,11 @@ const currentWakeText = (wake) => {
return `This is a self-directed wake. Continue one worthwhile thread from the trajectory.\nreason=${wake?.reason || 'scheduled reflection'}`;
};
-export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, toolCapabilityPrompt = '# PortOS semantic tools\nSemantic tool access is OFF.', visibilityPrompt = '# Persistent Mind environment visibility\nWorkspace and runtime visibility is unknown.', callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: false }) }) {
+export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, toolCapabilityPrompt = '# PortOS semantic tools\nSemantic tool access is OFF.', visibilityPrompt = '# Persistent Mind environment visibility\nWorkspace and runtime visibility is unknown.', userActionsPrompt = '', callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: false }) }) {
return `${context.text}
${visibilityPrompt}
-
+${userActionsPrompt ? `\n${userActionsPrompt}\n` : ''}
# Current wake
${currentWakeText(wake)}
@@ -350,6 +351,10 @@ export function createPersistentMindTurnAdapter() {
catalog: taskCatalog,
});
const visibilityPrompt = buildPersistentMindVisibilityPrompt(visibility);
+ // Deterministic and always included (epic #5593 decision 14): bounded,
+ // already redacted, no grant required. Deeper lookbacks use the
+ // readPortos-gated user-actions.query tool.
+ const userActionsPrompt = await readPersistentMindUserActionsPrompt();
const toolCapabilityPrompt = buildPersistentMindToolPrompt(taskAccess);
const callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: taskAccess.callUser });
const screenshots = (Array.isArray(wake?.message?.images) ? wake.message.images : []).map((image) => {
@@ -363,6 +368,7 @@ export function createPersistentMindTurnAdapter() {
taskCapabilityPrompt,
toolCapabilityPrompt,
visibilityPrompt,
+ userActionsPrompt,
callCapabilityPrompt,
});
let providerPrompt = basePrompt;
diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.js
index b0d6f565b9..6ddb9eee5a 100644
--- a/server/services/persistentMindAdapter.test.js
+++ b/server/services/persistentMindAdapter.test.js
@@ -41,6 +41,9 @@ vi.mock('./persistentMindVisibility.js', () => ({
readPersistentMindVisibility: (...args) => mock.readVisibility(...args),
buildPersistentMindVisibilityPrompt: () => 'Environment visibility: READY',
}));
+vi.mock('./persistentMindUserActions.js', () => ({
+ readPersistentMindUserActionsPrompt: vi.fn(async () => '# Recent user actions (last 24h)\n- 2× cos.schedule.trigger (branch-reconcile) actor=user'),
+}));
vi.mock('./persistentMindCallCapability.js', () => ({
buildPersistentMindCallCapabilityPrompt: ({ enabled }) => `Call access: ${enabled ? 'ON' : 'OFF'}`,
executePersistentMindCallRequest: (...args) => mock.executeCallRequest(...args),
@@ -112,6 +115,7 @@ describe('persistent mind adapter', () => {
});
expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Task access: ON');
expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Environment visibility: READY');
+ expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('# Recent user actions (last 24h)');
expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('PortOS tools: read=false write=false');
});
diff --git a/server/services/persistentMindUserActions.js b/server/services/persistentMindUserActions.js
new file mode 100644
index 0000000000..f551fa9a72
--- /dev/null
+++ b/server/services/persistentMindUserActions.js
@@ -0,0 +1,103 @@
+/**
+ * Deterministic "recent user actions" section for the Persistent Mind turn
+ * prompt (#5595, epic #5593).
+ *
+ * The mind's wake context is identity + trajectory + visibility; none of it says
+ * what the OPERATOR just did in the app. This module reads the last 24 hours of
+ * the machine-local operator-action ledger (services/userActions.js) and renders
+ * it as a compact, bounded section — counts by type first, then the newest
+ * summaries — so the mind can notice repetition worth automating without any
+ * tool call. Deeper lookbacks go through the `user-actions.query` tool, which is
+ * gated on the `readPortos` grant; this snippet is always included because it is
+ * bounded and built only from fields the recorder already redacted and clamped
+ * (type / actor / target / summary — never payload values).
+ *
+ * No LLM call, no new grant: an empty ledger renders NOTHING (the section is
+ * omitted entirely rather than adding "none" noise to every wake).
+ */
+
+import { scrubSecretTokens } from '../lib/secretText.js';
+import { listUserActions } from './userActions.js';
+
+export const USER_ACTIONS_SNIPPET_WINDOW_MS = 24 * 60 * 60 * 1000;
+export const USER_ACTIONS_SNIPPET_MAX_CHARS = 1500;
+export const USER_ACTIONS_SNIPPET_MAX_SUMMARIES = 20;
+// Enough for accurate counts on a busy day without paging the whole table.
+const SNIPPET_FETCH_LIMIT = 200;
+// Types whose `target` names a CLASS of action (a scheduled task type) rather
+// than one record's id — the only targets worth a per-target count line.
+const CLASS_TARGET_TYPES = new Set(['cos.schedule.trigger']);
+
+// Every string this module renders passes through here: one line, clamped, and
+// scrubbed of credential-shaped VALUES — the ledger's record-time redaction is
+// key-based, so a token pasted into a task description survives it by value.
+const oneLine = (value, max) => {
+ const text = scrubSecretTokens(String(value ?? '')).replace(/\s+/g, ' ').trim();
+ return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
+};
+
+/**
+ * Render the section from already-fetched ledger events (newest first). Pure —
+ * exported for focused tests. Returns '' when there is nothing to show.
+ *
+ * Deliberately reads ONLY type/actor/target/summary: payload values (even
+ * post-redaction) never reach the wake prompt from here.
+ */
+export function buildPersistentMindUserActionsPrompt(events) {
+ const rows = (Array.isArray(events) ? events : [])
+ .filter((event) => event && typeof event === 'object' && event.type);
+ if (rows.length === 0) return '';
+
+ const counts = new Map();
+ for (const event of rows) {
+ // Group by target only where the target is a CLASS (the task type of a
+ // schedule trigger). Everywhere else it is a record id — grouping on those
+ // yields one `1×` line per event, which floods the char budget with
+ // signal-free ids and evicts the summaries that carry the actual pattern.
+ const target = CLASS_TARGET_TYPES.has(event.type) && event.target ? ` (${oneLine(event.target, 60)})` : '';
+ const label = `${oneLine(event.type, 60)}${target} actor=${oneLine(event.actor || 'user', 20)}`;
+ counts.set(label, (counts.get(label) || 0) + 1);
+ }
+ const countLines = [...counts.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([label, count]) => `- ${count}× ${label}`);
+
+ const summaryLines = rows
+ .slice(0, USER_ACTIONS_SNIPPET_MAX_SUMMARIES)
+ .map((event) => `- ${oneLine(event.summary || event.type, 240)}`);
+
+ const header = '# Recent user actions (last 24h)';
+ // Hold the ~1.5k budget by dropping trailing summary lines first, then count
+ // lines; the "Last N" header is composed after trimming so it never overstates.
+ const compose = () => [
+ header,
+ ...countLines,
+ ...(summaryLines.length > 0 ? [`Last ${summaryLines.length}, newest first:`, ...summaryLines] : []),
+ ].join('\n');
+ let out = compose();
+ while (out.length > USER_ACTIONS_SNIPPET_MAX_CHARS && summaryLines.length > 0) {
+ summaryLines.pop();
+ out = compose();
+ }
+ while (out.length > USER_ACTIONS_SNIPPET_MAX_CHARS && countLines.length > 1) {
+ countLines.pop();
+ out = compose();
+ }
+ return out;
+}
+
+/**
+ * Read the last 24h of the ledger and render the section. A ledger read failing
+ * must never sink a mind turn (this runs outside the Express request
+ * lifecycle), so a failure logs once and renders as "no section".
+ */
+export async function readPersistentMindUserActionsPrompt({ now = Date.now() } = {}) {
+ const events = await listUserActions({
+ from: new Date(now - USER_ACTIONS_SNIPPET_WINDOW_MS).toISOString(),
+ limit: SNIPPET_FETCH_LIMIT,
+ }).catch((error) => {
+ console.error(`❌ Persistent mind user-action snippet read failed: ${error.message}`);
+ return [];
+ });
+ return buildPersistentMindUserActionsPrompt(events);
+}
diff --git a/server/services/persistentMindUserActions.test.js b/server/services/persistentMindUserActions.test.js
new file mode 100644
index 0000000000..368359f464
--- /dev/null
+++ b/server/services/persistentMindUserActions.test.js
@@ -0,0 +1,105 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ listUserActions: vi.fn() }));
+vi.mock('./userActions.js', () => ({
+ listUserActions: (...args) => mocks.listUserActions(...args),
+}));
+
+import {
+ USER_ACTIONS_SNIPPET_MAX_CHARS,
+ USER_ACTIONS_SNIPPET_MAX_SUMMARIES,
+ USER_ACTIONS_SNIPPET_WINDOW_MS,
+ buildPersistentMindUserActionsPrompt,
+ readPersistentMindUserActionsPrompt,
+} from './persistentMindUserActions.js';
+
+const event = (overrides = {}) => ({
+ id: 'evt-1',
+ type: 'cos.schedule.trigger',
+ actor: 'user',
+ target: 'branch-reconcile',
+ summary: "Ran scheduled task 'branch-reconcile' on demand",
+ happenedAt: '2026-09-01T10:00:00.000Z',
+ payload: {},
+ ...overrides,
+});
+
+describe('buildPersistentMindUserActionsPrompt', () => {
+ it('renders counts by type+target first, then the newest summaries', () => {
+ const prompt = buildPersistentMindUserActionsPrompt([
+ event({ id: 'a' }),
+ event({ id: 'b' }),
+ event({ id: 'c', type: 'cos.task.create', target: 'task-1', summary: 'Queued CoS task "Fix flaky test"' }),
+ event({ id: 'd', type: 'cos.task.create', target: 'task-2', summary: 'Queued CoS task "Bump deps"' }),
+ ]);
+ expect(prompt).toMatch(/^# Recent user actions \(last 24h\)\n/);
+ // Schedule triggers count per task TYPE (the target is a class)…
+ expect(prompt).toContain('- 2× cos.schedule.trigger (branch-reconcile) actor=user');
+ // …while record-id targets fold into one line per event type, so a busy
+ // day of distinct task ids cannot flood the budget with 1× lines.
+ expect(prompt).toContain('- 2× cos.task.create actor=user');
+ expect(prompt).not.toContain('(task-1)');
+ expect(prompt).toContain('Last 4, newest first:');
+ expect(prompt).toContain("- Ran scheduled task 'branch-reconcile' on demand");
+ expect(prompt).toContain('- Queued CoS task "Fix flaky test"');
+ });
+
+ it('omits the section entirely when there are no events', () => {
+ expect(buildPersistentMindUserActionsPrompt([])).toBe('');
+ expect(buildPersistentMindUserActionsPrompt(null)).toBe('');
+ expect(buildPersistentMindUserActionsPrompt([null, 'garbage', {}])).toBe('');
+ });
+
+ it('never emits payload values — even a secret that slipped past redaction', () => {
+ const prompt = buildPersistentMindUserActionsPrompt([
+ event({ payload: { apiToken: 'sk-live-EXAMPLE-SECRET-VALUE', note: 'private-note-body' } }),
+ ]);
+ expect(prompt).not.toContain('sk-live-EXAMPLE-SECRET-VALUE');
+ expect(prompt).not.toContain('private-note-body');
+ });
+
+ it('scrubs a credential pasted into a summary by VALUE — key-based redaction cannot catch it', () => {
+ const prompt = buildPersistentMindUserActionsPrompt([
+ event({ summary: 'Queued CoS task: deploy with sk-abcdefghijklmnopqrstuvwx as the key' }),
+ ]);
+ expect(prompt).not.toContain('sk-abcdefghijklmnopqrstuvwx');
+ expect(prompt).toContain('[REDACTED]');
+ });
+
+ it('caps the section size and the summary count without evicting every summary', () => {
+ // Worst realistic shape: many events with DISTINCT record-id targets. The
+ // counts must fold per type so summaries — the lines carrying the actual
+ // pattern — survive the char budget.
+ const many = Array.from({ length: 80 }, (_, index) => event({
+ id: `evt-${index}`,
+ type: 'cos.task.create',
+ target: `task-${index}`,
+ summary: `Summary line ${index} ${'x'.repeat(60)}`,
+ }));
+ const prompt = buildPersistentMindUserActionsPrompt(many);
+ expect(prompt.length).toBeLessThanOrEqual(USER_ACTIONS_SNIPPET_MAX_CHARS);
+ expect(prompt).toContain('- 80× cos.task.create actor=user');
+ const summaryLines = prompt.split('\n').filter((line) => line.startsWith('- Summary line'));
+ expect(summaryLines.length).toBeLessThanOrEqual(USER_ACTIONS_SNIPPET_MAX_SUMMARIES);
+ // Non-vacuous: the cap trims summaries, it must not zero them.
+ expect(summaryLines.length).toBeGreaterThan(0);
+ });
+});
+
+describe('readPersistentMindUserActionsPrompt', () => {
+ it('queries the last 24 hours and renders the section', async () => {
+ const now = Date.parse('2026-09-01T12:00:00.000Z');
+ mocks.listUserActions.mockResolvedValueOnce([event()]);
+ const prompt = await readPersistentMindUserActionsPrompt({ now });
+ expect(mocks.listUserActions).toHaveBeenCalledWith({
+ from: new Date(now - USER_ACTIONS_SNIPPET_WINDOW_MS).toISOString(),
+ limit: 200,
+ });
+ expect(prompt).toContain('# Recent user actions (last 24h)');
+ });
+
+ it('renders nothing instead of sinking the mind turn when the ledger read fails', async () => {
+ mocks.listUserActions.mockRejectedValueOnce(new Error('database offline'));
+ await expect(readPersistentMindUserActionsPrompt()).resolves.toBe('');
+ });
+});
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index c34d097551..37e253ff6d 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -31,6 +31,7 @@
"release-check": "644e5f2f6df1daf06f3792a81ba7a51a",
"stash-cleanup": "1c12bac5aac6bb27008c40981e7db08c",
"repo-sync": "0a648d35d43b023b758226b9c709c8ea",
+ "user-action-review": "945a716d446d26a03e2805d28bd1ae16",
"jira-sprint-manager": "3e63c8a3bdf0d5a05a30faaa2dc07980",
"do-replan": "35660eb7b43e4259a6a9253ed288a1db",
"jira-status-report": "9d374a9d8ccb92c5c8fd0aa9899e79a5",
@@ -59,6 +60,7 @@
"branch-reconcile": 3,
"issue-reconcile": 4,
"refresh-local-llm-catalog": 4,
+ "user-action-review": 1,
"plan-feature": 5,
"security": 2,
"code-quality": 3,
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index f412c44dd4..b8f1052f61 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -2014,6 +2014,50 @@ Once every escalation is handled, walk EVERY repository named above and confirm
Per repository: what you changed, what you deliberately left and why, and the five verification results above. End with a one-line verdict per repo — CLEAN, or what is still outstanding. If you left anything unresolved, say exactly what a human needs to decide.`,
+ 'user-action-review': `[Improvement] User Action Review — propose automations from the operator-action ledger
+
+PortOS keeps a machine-local ledger of what the operator actually did in the app (created CoS tasks, rated agent runs, pressed Run Now on scheduled tasks, changed settings). Your job is to read the last 7 days of that ledger, find the repetition a mind or a schedule should have handled, and PROPOSE concrete automations. You propose — you never enact.
+
+## Delivery mode
+
+{userActionDelivery}
+
+## Read the ledger
+
+Query the last 7 days of events, then group them by \`type\` + \`target\` (for schedule triggers the target is the task type; for tasks/agents it is the record id):
+
+- If you can call PortOS semantic tools, use \`user_actions_query\` (readPortos grant) with a \`from\` timestamp 7 days back. Results are capped at 100 events per call and carry no event ids; when a result says \`truncated: true\`, narrow the window (set \`to\` just BELOW the oldest \`happenedAt\` you already have — the bound is inclusive, so reusing it verbatim repeats that event — or filter by \`type\`) and query again.
+- Otherwise call the local PortOS HTTP API from this machine: \`GET ${PORTOS_API_URL}/api/user-actions?from=<ISO-7-days-ago>&limit=100\`. Filters: \`type\`/\`types\`, \`actor\`, \`from\`/\`to\`, \`limit\`, \`offset\`.
+
+**If the query returns no events, stop immediately**: report "nothing to review" in one line and make no further LLM tool calls, no proposals, and no filed items.
+
+## What counts as automatable tedium
+
+Look specifically for, in priority order:
+
+1. **Repeated manual schedule triggers** — multiple \`cos.schedule.trigger\` events with \`actor=user\` for the same task type (especially \`branch-reconcile\` / \`issue-reconcile\`) while that schedule presumably remains on-demand. The proposal is to enable a cadence (say which) or queue a reconcile run — proposed, never enacted.
+2. **Repeated similar CoS tasks** — several \`cos.task.create\` events whose prompts/settings look alike. Propose a scheduled task, a saved automation, or one recurring CoS task that replaces the hand-queued ones.
+3. **Negative feedback clusters** — \`cos.agent.feedback\` events with low ratings concentrated on one task type, provider, or model. Propose the configuration change worth trying (different model/effort, a prompt fix), as a proposal the operator applies.
+4. **Settings churn** — repeated \`settings.update\` events touching the same key paths. Propose whatever would remove the need to keep flipping them.
+
+## Propose (1–5 proposals, evidence-grounded)
+
+Deliver each surviving proposal through the delivery mode above. Every proposal must:
+
+- **Name its evidence**: event counts, types, date ranges, and — where the target is a task TYPE (schedule triggers) — the target itself (e.g. "5× cos.schedule.trigger branch-reconcile between <date> and <date>"). No evidence, no proposal.
+- **Describe the automation concretely**: which schedule/cadence/task/setting, and what the operator gains.
+- **Summarize, never paste**: a filed item is world-readable the moment it exists. CoS task prompts, target NAMES (task descriptions), and settings values in the ledger may contain private project names or personal context — describe them ("three near-identical tasks asking for dependency updates on the same app") and never quote prompt bodies, targetName values, or payload values. When a proposal must point at specific ledger rows, cite counts, event types, and time ranges — plus the opaque event \`id\`s when you read the ledger over the HTTP API (the semantic tool's projection carries no ids), nothing more.
+
+## Hard limits
+
+- NEVER change settings (\`PUT /api/settings\`), schedule types, cadences, or task metadata yourself — not even the automation you are proposing. The proposal IS the deliverable; enacting it is the operator's call.
+- Do not edit source, commit, open a PR, or create branches. The run must end with a clean \`git status\`.
+- Cap yourself at 5 proposals per run; fold duplicates of an already-filed proposal into a comment on the existing item instead of filing again.
+
+## Report
+
+End with a short summary: the event window you reviewed, total events by type, each proposal you delivered (with its issue/task reference), and anything you deliberately did not propose and why.`,
+
'jira-sprint-manager': `[Improvement: {appName}] JIRA Sprint Manager
Triage and implement JIRA tickets for {appName}:
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index bfbb963ff7..66524f4593 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -23,6 +23,7 @@ export const PROMPT_VERSIONS = {
'branch-reconcile': 3, // v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.
'issue-reconcile': 4, // v4: follow-up recipes apply independent slashdo dispatch hints and contributor labels (`good first issue`/`help wanted`, Jira hyphenated equivalents) instead of only `plan`. v3: adds a JIRA arm — status-based zombies (a ticket left In Review with remaining scope + no live claim; JIRA has no `in-progress` label) detected via the PortOS JIRA API and healed through ticket transitions + `POST tickets`, routed in via the app's resolved workTracker ('jira') rather than the git host. v2: forge-aware — the scan + coordinator now cover GitLab (`glab` issues + MRs) as well as GitHub, resolved from the app's origin host; every heal command is shown as gh/glab and the injected header names the forge. v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.
'refresh-local-llm-catalog': 4, // v4: follows the current no-per-branch-changelog contract and relies on a release-note-quality commit subject. v3: catalog maintenance now preserves the primary-lane + cross-lane recommendation taxonomy and reserves featured treatment for a deliberate first choice. v2: PortOS-only task, so it names the retired fragment command directly. v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)
+ 'user-action-review': 1, // v1: install-wide review of the operator-action ledger (#5595) — query the last 7 days, group repetition by type + target, propose 1–5 automations delivered per {userActionDelivery} (tracker issues by default, queued CoS tasks when the operator flips fileIssues off); never mutates settings or schedule types, summarizes CoS prompts instead of pasting them, exits immediately on an empty log.
'plan-feature': 5, // v5: absent optional preload sections explicitly fall back to normal inventory/source reads. v4: truncated/unreadable preloads explicitly allow a direct source read. v3: consumes programmatically preloaded PRD/GOALS/open-issue/open-PR/closed-unmerged-PR snapshots and explicitly avoids re-fetching them. v2: PRD.md is the primary product/evaluation source, GOALS.md supplements or falls back, and repository documentation is the best-effort fallback when neither exists. v1: net-new planning-only sibling of feature-ideas.
// Basic self-improvement tasks — versioned so installs created before the
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index dd94c080fa..cf95a6edba 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -1339,6 +1339,13 @@ export async function getScheduleStatus() {
if (auditDoWorkRequiresWorktree(taskType)) {
taskStatus.doWorkRequiresWorktree = true;
}
+ } else if (taskType === 'user-action-review') {
+ // Not an audit-catalog type (no mode-contract injection — its
+ // alternative to filing issues is queueing CoS tasks, not editing code),
+ // but its deliverable posture is the same fileIssues toggle, so the
+ // schedule UI surfaces the switch the same way.
+ taskStatus.fileIssuesCapable = true;
+ taskStatus.defaultFileIssues = true;
}
// Perpetual tasks park PER-APP (parkPerpetual is called with the appId), so
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index b2e0f9b49d..5283f3232a 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -272,7 +272,9 @@ describe('taskSchedule', () => {
describe('INSTALL_WIDE_TASK_TYPES', () => {
it('names only task types that really sweep the whole install', () => {
- expect([...INSTALL_WIDE_TASK_TYPES]).toEqual(['repo-sync'])
+ // repo-sync sweeps every managed checkout; user-action-review reads the
+ // install-wide operator-action ledger — neither is a per-app run.
+ expect([...INSTALL_WIDE_TASK_TYPES]).toEqual(['repo-sync', 'user-action-review'])
})
it('every install-wide type is a registered task type', () => {
@@ -309,6 +311,33 @@ describe('taskSchedule', () => {
})
})
+ describe('user-action-review (operator-ledger automation proposals)', () => {
+ it('is registered install-wide with an on-demand + enabled default and a v1 prompt', () => {
+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('user-action-review');
+ expect(INSTALL_WIDE_TASK_TYPES.has('user-action-review')).toBe(true);
+ expect(TASK_TYPE_DESCRIPTIONS['user-action-review']).toContain('propose automations');
+ expect(DEFAULT_TASK_INTERVALS['user-action-review']).toMatchObject({ type: INTERVAL_TYPES.ON_DEMAND, enabled: true });
+ expect(PROMPT_VERSIONS['user-action-review']).toBe(1);
+ expect(DEFAULT_TASK_PROMPTS['user-action-review']).toContain('{userActionDelivery}');
+ // The prompt proposes; it must never instruct the agent to enact.
+ expect(DEFAULT_TASK_PROMPTS['user-action-review']).toContain('NEVER change settings');
+ });
+
+ it('defaults to file-issues with the no-code posture', () => {
+ expect(DEFAULT_TASK_INTERVALS['user-action-review'].taskMetadata).toMatchObject({
+ fileIssues: true, useWorktree: false, openPR: false
+ });
+ });
+
+ it('surfaces the fileIssues toggle on schedule status without joining the audit catalog', async () => {
+ mockSchedule({ tasks: {}, executions: {} });
+ const status = await getScheduleStatus();
+ expect(status.tasks['user-action-review']).toMatchObject({
+ installWide: true, fileIssuesCapable: true, defaultFileIssues: true
+ });
+ });
+ });
+
describe('layered-intelligence (programmatic-I/O agent task)', () => {
it('is registered as a self-improvement task with a description and an on-demand default', () => {
expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('layered-intelligence');
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index e69ecb7c5a..3c473e93e3 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -93,6 +93,15 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// claim flows pick up later. Always-filing tracker-filing type
// (TRACKER_FILING_PRESETS['plan-feature']), like reference-watch/repo-study.
'plan-feature',
+ // user-action-review reads the machine-local operator-action ledger
+ // (services/userActions.js) for repeated manual work — Run Now on the same
+ // schedule type over and over, near-duplicate task prompts, negative feedback
+ // clusters, settings churn — and PROPOSES automations as filed tracker issues
+ // (default) or queued CoS tasks. It never edits settings or schedules itself.
+ // Install-wide: the ledger records PortOS-operator activity, not one managed
+ // app's tree. Its buildTaskInput hook (userActionReviewHooks.js) skips the
+ // dispatch entirely when the ledger is empty, so no provider call is burned.
+ 'user-action-review',
// layered-intelligence is a PROGRAMMATIC-I/O task: it spawns a NORMAL reasoning
// agent (visible in the CoS queue + Active Agents, TUI-attachable) with two
// deterministic hooks around it — buildTaskInput gathers the app's goals +
@@ -189,7 +198,7 @@ export const DEFAULT_BRANCHES_PER_AGENT = 3;
* instead of forcing every run through the app picker (which would make the
* install-wide lane unreachable on any install that has apps).
*/
-export const INSTALL_WIDE_TASK_TYPES = new Set(['repo-sync']);
+export const INSTALL_WIDE_TASK_TYPES = new Set(['repo-sync', 'user-action-review']);
// Fresh installs expose every task as an enabled manual action. The on-demand
// type keeps provider work silent until the user explicitly runs a task, while
@@ -385,6 +394,18 @@ export const DEFAULT_TASK_INTERVALS = {
// runAfter do-replan so proposals are checked against the freshest available
// work tracker before a new feature plan is filed.
'plan-feature': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['product-requirements', 'project-goals', 'open-issues', 'open-pull-requests', 'closed-unmerged-pull-requests'], runAfter: ['do-replan'], taskMetadata: { useWorktree: false, openPR: false, readOnly: false } },
+ // user-action-review proposes automations from the operator-action ledger.
+ // fileIssues defaults ON (safer unattended: a filed issue over queued work);
+ // flipping it OFF makes the agent queue CoS tasks instead — either way it
+ // ships no code of its own (useWorktree/openPR off, like the other
+ // file-issues types; dispatch stamps noCodeOutput). On-demand + enabled per
+ // the AI-provider policy: a manual Run is the consent for the review's LLM
+ // run, and the empty-ledger skip in its buildTaskInput hook keeps an idle
+ // install silent. Effectively on-demand-only today: the hook also skips
+ // every per-app dispatch (a per-app cadence would queue one identical
+ // global-ledger review PER app) and scheduled dispatch has no global lane
+ // for install-wide types yet — see #5629.
+ 'user-action-review': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
// layered-intelligence is a programmatic-I/O task (agent-backed, hooked). On-demand
// by default; per-app scheduling (enabled/interval/provider/model) is set in the
// Intelligence tab and stored on the app's taskTypeOverrides['layered-intelligence'].
@@ -535,6 +556,7 @@ export const TASK_TYPE_DESCRIPTIONS = {
'stash-cleanup': 'Triage git stash list — drop entries superseded by or stale relative to main, leave real unlanded work in place',
'repo-sync': 'Sync every managed app with origin — back on the default branch, pushed and pulled, merged branches/worktrees and redundant stashes cleared',
'plan-feature': "Brainstorm one feature and file its decision-complete plan to the app's work tracker (no code)",
+ 'user-action-review': 'Review the operator-action log for repeated manual work and propose automations — file issues (default) or queue CoS tasks',
'layered-intelligence': "Use app goals + performance metrics to file at most one deduplicated improvement issue; inspect read-only context and file a visibility gap when evidence is insufficient — no code"
};
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index 1c28e428af..801394a6da 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -62,6 +62,12 @@ const HOOK_MODULES = {
'layered-intelligence': {
load: () => import('./autonomousJobs/layeredIntelligenceHooks.js')
},
+ // buildTaskInput only: skips the dispatch when the operator-action ledger is
+ // empty. No output hook — the agent's deliverable is filed issues / queued
+ // tasks, and registering here already exempts it from the commit criterion.
+ 'user-action-review': {
+ load: () => import('./userActionReviewHooks.js')
+ },
};
const PAYLOAD_OPTIONAL_OUTPUT_HOOKS = new Set();
diff --git a/server/services/taskTypeHooks.test.js b/server/services/taskTypeHooks.test.js
index c79ce240c1..d642cb21d1 100644
--- a/server/services/taskTypeHooks.test.js
+++ b/server/services/taskTypeHooks.test.js
@@ -14,6 +14,13 @@ describe('taskTypeHooks registry', () => {
expect(typeof await getTaskOutputHook('issue-watcher')).toBe('function');
});
+ it('resolves an input hook but no output hook for user-action-review', async () => {
+ // Input-only registration: the empty-ledger skip is the whole hook. The
+ // agent's deliverable (filed issues / queued tasks) has no output payload.
+ expect(typeof await getTaskInputHook('user-action-review')).toBe('function');
+ expect(await getTaskOutputHook('user-action-review')).toBeNull();
+ });
+
it('returns null for a task type with no registered hooks', async () => {
expect(await getTaskInputHook('security')).toBeNull();
expect(await getTaskOutputHook('security')).toBeNull();
diff --git a/server/services/userActionReviewHooks.js b/server/services/userActionReviewHooks.js
new file mode 100644
index 0000000000..36f6712e57
--- /dev/null
+++ b/server/services/userActionReviewHooks.js
@@ -0,0 +1,26 @@
+/**
+ * Programmatic pre-agent hook for the `user-action-review` scheduled task
+ * (#5595, epic #5593).
+ *
+ * The review's whole input is the operator-action ledger; when the last 7 days
+ * hold nothing, dispatching an agent would burn a provider call to conclude
+ * "nothing to review". This deterministic hook (no LLM) makes that the
+ * generator's decision instead: `resolveTaskInputHook` records the execution
+ * (so the cadence advances) and spawns nothing.
+ */
+
+import { listUserActions } from './userActions.js';
+
+export const USER_ACTION_REVIEW_LOOKBACK_DAYS = 7;
+
+export async function buildTaskInput({ app } = {}) {
+ // The ledger is one install-wide log; INSTALL_WIDE_TASK_TYPES only shapes the
+ // UI, so a per-app cadence override would otherwise dispatch one identical
+ // global review PER APP. Only the global lane (synthetic null-id app) runs.
+ if (app?.id) return { skip: { reason: 'install-wide-only' } };
+ const from = new Date(Date.now() - USER_ACTION_REVIEW_LOOKBACK_DAYS * 24 * 60 * 60 * 1000).toISOString();
+ // One row is enough to answer "is there anything to review?".
+ const events = await listUserActions({ from, limit: 1 });
+ if (events.length === 0) return { skip: { reason: 'no-user-actions' } };
+ return {};
+}
diff --git a/server/services/userActionReviewHooks.test.js b/server/services/userActionReviewHooks.test.js
new file mode 100644
index 0000000000..80201bf637
--- /dev/null
+++ b/server/services/userActionReviewHooks.test.js
@@ -0,0 +1,35 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ listUserActions: vi.fn() }));
+vi.mock('./userActions.js', () => ({
+ listUserActions: (...args) => mocks.listUserActions(...args),
+}));
+
+import { USER_ACTION_REVIEW_LOOKBACK_DAYS, buildTaskInput } from './userActionReviewHooks.js';
+
+describe('user-action-review buildTaskInput hook', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('skips the dispatch when the last 7 days of the ledger are empty', async () => {
+ mocks.listUserActions.mockResolvedValueOnce([]);
+ await expect(buildTaskInput()).resolves.toEqual({ skip: { reason: 'no-user-actions' } });
+ const filters = mocks.listUserActions.mock.calls[0][0];
+ expect(filters.limit).toBe(1);
+ const lookbackMs = Date.now() - Date.parse(filters.from);
+ expect(lookbackMs).toBeGreaterThan((USER_ACTION_REVIEW_LOOKBACK_DAYS - 1) * 24 * 60 * 60 * 1000);
+ expect(lookbackMs).toBeLessThanOrEqual(USER_ACTION_REVIEW_LOOKBACK_DAYS * 24 * 60 * 60 * 1000 + 60_000);
+ });
+
+ it('dispatches normally (no prompt override) when events exist', async () => {
+ mocks.listUserActions.mockResolvedValueOnce([{ id: 'evt-1', type: 'settings.update' }]);
+ await expect(buildTaskInput({ app: { id: null, name: 'PortOS' } })).resolves.toEqual({});
+ });
+
+ it('skips any per-app dispatch — the review is install-wide only', async () => {
+ // A per-app cadence override would otherwise queue one identical
+ // global-ledger review PER managed app.
+ await expect(buildTaskInput({ app: { id: 'app-1', name: 'Acme App' } }))
+ .resolves.toEqual({ skip: { reason: 'install-wide-only' } });
+ expect(mocks.listUserActions).not.toHaveBeenCalled();
+ });
+});