From a04b211a1173bedfea030b531adbacd39803ce95 Mon Sep 17 00:00:00 2001 From: Maxwell Weinzierl Date: Mon, 23 Nov 2026 16:46:25 -0800 Subject: [PATCH 1/3] AI-140 Standing roles: persistent badged threads with check-ins, polled triggers and per-thread compaction A role is a pinned thread per client that never settles, snoozes or archives (like the release manager). It wakes on check-ins (scheduled tasks bound to its thread) and on triggers: commands run every N minutes in the project's main checkout that print new items (t4-probe). New items are deduped, batched, held in quiet hours and capped per day, then delivered as one message; nothing is spent while nothing is new. Roles and release managers get a compaction point per thread (Codex model_auto_compact_token_limit, Claude autoCompactWindow): usa-rs's release manager carried ~286k tokens into each of 3,172 requests in two days. API: GET/POST /api/t4/roles, /roles/:id/delete, /roles/:id/run, /roles/release-manager; /api/t4/state gains standingRoles. --- .../src/mcp/toolkits/thread/handlers.ts | 8 + .../Adapters/ClaudeAdapterV2.ts | 13 +- .../Adapters/CodexAdapterV2.ts | 5 + apps/server/src/t4/T4AutoArchive.ts | 4 +- apps/server/src/t4/T4Config.ts | 6 + apps/server/src/t4/T4Facts.ts | 11 +- apps/server/src/t4/T4Http.ts | 37 + apps/server/src/t4/T4Jobs.ts | 2 + apps/server/src/t4/T4Ledger.ts | 21 + apps/server/src/t4/T4Migrations.ts | 20 + apps/server/src/t4/T4Roles.test.ts | 82 ++ apps/server/src/t4/T4Roles.ts | 778 ++++++++++++++++++ apps/server/src/t4/T4Settle.ts | 4 + apps/server/src/t4/T4Store.ts | 68 ++ apps/server/src/t4/threadCompaction.ts | 24 + 15 files changed, 1079 insertions(+), 4 deletions(-) create mode 100644 apps/server/src/t4/T4Roles.test.ts create mode 100644 apps/server/src/t4/T4Roles.ts create mode 100644 apps/server/src/t4/threadCompaction.ts diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 81ba0ed795f9b..47ebeeb8f485a 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -420,6 +420,14 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { message: `a release manager is never ${input.action}d - it stays visible to the user. To hold a release until a time, \`schedule_task\` a wake into this thread for then and end your turn.`, }); } + // AI-140: a standing role stays visible as the release manager does. + const role = world === null ? undefined : T4Ledger.standingRoleOf(world, projection.thread.id); + if (role !== undefined) { + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: `"${role.title}" is a standing role and is never ${input.action}d - it stays visible to the user. Its check-ins and triggers wake it; the user changes them in the dashboard (Settings -> Roles).`, + }); + } } } let command: OrchestrationV2Command; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 1ae01c5f974ef..5b46115937242 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -179,6 +179,7 @@ import { // t4 fork: questionsAsMessages, declineSafetyChecks. import { QUESTION_POSTED_NOTE, t4QuestionsAsMessages } from "../../t4/questionsAsMessages.ts"; import { awaitsOnItsOwn } from "../../t4/autoAwait.ts"; +import { claudeAutoCompactWindowFor, compactAtTokensFor } from "../../t4/threadCompaction.ts"; import { safetyCheckDeclinedNote, safetyCheckKind, @@ -296,6 +297,15 @@ function isClaudeEnvTruthy(value: string | undefined): boolean { return value !== undefined && ["1", "true", "yes", "on"].includes(value.trim().toLowerCase()); } +function withT4Compaction( + settings: ClaudeSettings | undefined, + threadId: string, +): ClaudeSettings | undefined { + const compactAt = compactAtTokensFor(threadId); + if (compactAt === undefined || settings === undefined) return settings; + return { ...settings, autoCompactWindow: claudeAutoCompactWindowFor(compactAt) }; +} + function claudeAutoCompactThreshold(autoCompactWindow: string, maxTokens: number | null) { const windowTokens = Number(autoCompactWindow); return windowTokens > 0 && (maxTokens === null || windowTokens < maxTokens) @@ -13199,7 +13209,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing.queryPolicyKey === queryPolicyKey && !existing.stopping; const readLaunchSettings = readClaudeLaunchArgSettings({ - settings: adapterOptions.settings, + // t4 fork (AI-140): a standing role's or release manager's compaction point. + settings: withT4Compaction(adapterOptions.settings, turnInput.threadId), cwd: turnInput.runtimePolicy.cwd, fileSystem, path, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 68a87a5f0bed4..404446ed66351 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -162,6 +162,7 @@ import { } from "@t3tools/provider-core/server/subagentProjection"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { compactAtTokensFor } from "../../t4/threadCompaction.ts"; const CODEX_PROVIDER = ProviderDriverKind.make("codex"); const CODEX_CAPACITY_MAX_RETRIES = 5; @@ -1549,6 +1550,10 @@ function codexThreadRuntimeParams(input: { config: { ...CODEX_THREAD_CONFIG, // One app-server serves many threads, so the id goes in per-thread shell config, not its env. + // t4 fork (AI-140): a standing role's or release manager's compaction point. + ...(compactAtTokensFor(input.threadId) === undefined + ? {} + : { model_auto_compact_token_limit: compactAtTokensFor(input.threadId)! }), ...(input.threadId === null ? {} : { diff --git a/apps/server/src/t4/T4AutoArchive.ts b/apps/server/src/t4/T4AutoArchive.ts index 27516778dd9d2..65d5a41ece14a 100644 --- a/apps/server/src/t4/T4AutoArchive.ts +++ b/apps/server/src/t4/T4AutoArchive.ts @@ -69,7 +69,9 @@ export const sweep = Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; const targets = toArchive( world.threads, - (thread) => ledger.isReleaseManager(world, thread), + (thread) => + ledger.isReleaseManager(world, thread) || + T4Ledger.standingRoleOf(world, thread.id) !== undefined, now, ARCHIVE_SETTLED_MS, ); diff --git a/apps/server/src/t4/T4Config.ts b/apps/server/src/t4/T4Config.ts index ded57093da1d4..a5c4cec6fef7b 100644 --- a/apps/server/src/t4/T4Config.ts +++ b/apps/server/src/t4/T4Config.ts @@ -19,6 +19,8 @@ export const T4ServerConfigJson = Schema.Struct({ Schema.Struct({ titlePrefix: Schema.optional(Schema.String), model: Schema.optional(Schema.NullOr(ModelSelection)), + /** AI-140: compact a release manager's provider session at this many tokens (null: provider default). */ + compactAtTokens: Schema.optional(Schema.NullOr(Schema.Number)), }), ), /** `issueId`: worktrees at `/` (t4); `branch`: upstream. */ @@ -42,6 +44,7 @@ export type T4ServerConfigJson = typeof T4ServerConfigJson.Type; export interface T4ServerConfigShape { readonly releaseManagerTitlePrefix: string; readonly releaseManagerModel: ModelSelection | null; + readonly releaseManagerCompactAtTokens: number | null; readonly worktreeNaming: "branch" | "issueId"; readonly launchPresets: Readonly>; readonly stallRecovery: { @@ -56,6 +59,7 @@ export interface T4ServerConfigShape { export const defaultT4ServerConfig: T4ServerConfigShape = { releaseManagerTitlePrefix: "Release manager", releaseManagerModel: null, + releaseManagerCompactAtTokens: null, worktreeNaming: "branch", launchPresets: {}, stallRecovery: { enabled: false, silenceMinutes: 15, repeatHours: 6 }, @@ -68,6 +72,8 @@ function resolveT4ServerConfig(json: T4ServerConfigJson): T4ServerConfigShape { return { releaseManagerTitlePrefix: json.releaseManager?.titlePrefix ?? d.releaseManagerTitlePrefix, releaseManagerModel: json.releaseManager?.model ?? d.releaseManagerModel, + releaseManagerCompactAtTokens: + json.releaseManager?.compactAtTokens ?? d.releaseManagerCompactAtTokens, worktreeNaming: json.worktreeNaming ?? d.worktreeNaming, launchPresets: json.launchPresets ?? d.launchPresets, stallRecovery: { diff --git a/apps/server/src/t4/T4Facts.ts b/apps/server/src/t4/T4Facts.ts index 6c43a662e13da..92cd768f2c027 100644 --- a/apps/server/src/t4/T4Facts.ts +++ b/apps/server/src/t4/T4Facts.ts @@ -11,7 +11,7 @@ import * as T4Ledger from "./T4Ledger.ts"; import * as T4Store from "./T4Store.ts"; import { stateOf } from "./T4Threads.ts"; -export type T4Role = "owner" | "pm" | "release-manager"; +export type T4Role = "owner" | "pm" | "release-manager" | "role"; /** * A thread's role (AI-58): a release manager by the project's record or title; @@ -23,8 +23,10 @@ export const roleOf = ( thread: { readonly id: string; readonly title: string }, isReleaseManager: boolean, given: ReadonlyMap, + standing = false, ): T4Role => { if (isReleaseManager) return "release-manager"; + if (standing) return "role"; const set = given.get(thread.id); if (set === "pm" || set === "owner") return set; return /\bPM\b/.test(thread.title) ? "pm" : "owner"; @@ -34,6 +36,9 @@ export interface T4ThreadFacts { readonly state: string; readonly isReleaseManager: boolean; readonly role: T4Role; + /** A standing role's kind and title (AI-140), when `role` is "role". */ + readonly roleKind: string | null; + readonly roleTitle: string | null; readonly parentThreadId: string | null; readonly owes: number; readonly owedBy: number; @@ -60,7 +65,9 @@ export const factsFor = Effect.fn("t4.factsFor")(function* ( facts.set(id, { state: stateOf(thread, now), isReleaseManager: f.isReleaseManager, - role: roleOf(thread, f.isReleaseManager, roles), + role: roleOf(thread, f.isReleaseManager, roles, T4Ledger.standingRoleOf(world, id) !== undefined), + roleKind: T4Ledger.standingRoleOf(world, id)?.kind ?? null, + roleTitle: T4Ledger.standingRoleOf(world, id)?.title ?? null, parentThreadId: parents.get(id) ?? null, owes: f.owes, owedBy: f.owedBy, diff --git a/apps/server/src/t4/T4Http.ts b/apps/server/src/t4/T4Http.ts index f89ce8d36832c..4501bac147411 100644 --- a/apps/server/src/t4/T4Http.ts +++ b/apps/server/src/t4/T4Http.ts @@ -42,6 +42,7 @@ import * as T4Delivery from "./T4Delivery.ts"; import { factsFor } from "./T4Facts.ts"; import * as T4Ledger from "./T4Ledger.ts"; import * as T4RunWatch from "./T4RunWatch.ts"; +import * as T4Roles from "./T4Roles.ts"; import * as T4Schedules from "./T4Schedules.ts"; import * as T4Spawn from "./T4Spawn.ts"; import { clientDefaultModelSelection } from "./T4DefaultModel.ts"; @@ -226,6 +227,8 @@ export const layer = Layer.mergeAll( // dashboard's roles and By PM view. roles: Object.fromEntries(yield* store.threadRoles()), parents: Object.fromEntries(yield* store.spawnParents()), + // Standing roles' threads (AI-140): badge and Roles group on the dashboard. + standingRoles: yield* T4Roles.standingRolesForState, issueLinks: yield* store.issueLinks(), settleRequests: Object.fromEntries(yield* store.settleRequests()), // Release managers' queues (AI-71): the dashboard's "on staging" list, @@ -644,6 +647,40 @@ export const layer = Layer.mergeAll( }), ), + // Standing roles (t4/T4Roles.ts, AI-140), managed from the dashboard's Roles tab. + route("GET", "/api/t4/roles", AuthOrchestrationReadScope, () => + T4Roles.listRoles().pipe(Effect.map((result) => json(result))), + ), + route("POST", "/api/t4/roles", AuthOrchestrationOperateScope, () => + Effect.gen(function* () { + const input = yield* body(T4Roles.SaveRoleBody); + const saved = yield* T4Roles.saveRole(input).pipe( + Effect.catch((error) => + Effect.succeed({ error: String((error as { message?: unknown }).message ?? error) }), + ), + ); + return "error" in saved ? json({ error: saved.error }, 400) : json({ role: saved.role }); + }), + ), + route("POST", "/api/t4/roles/release-manager", AuthOrchestrationOperateScope, () => + Effect.gen(function* () { + const input = yield* body(T4Roles.RmCompactionBody); + return json({ releaseManager: yield* T4Roles.setReleaseManagerCompaction(input.compactAtTokens) }); + }), + ), + route("POST", "/api/t4/roles/:id/delete", AuthOrchestrationOperateScope, (params) => + T4Roles.deleteRole(params.id ?? "").pipe( + Effect.map((result) => ("error" in result ? json(result, 404) : json(result))), + ), + ), + route("POST", "/api/t4/roles/:id/run", AuthOrchestrationOperateScope, (params) => + Effect.gen(function* () { + const input = yield* body(T4Roles.RunRoleBody); + const result = yield* T4Roles.runRole(params.id ?? "", input.triggerId); + return "error" in result ? json(result, 404) : json(result); + }), + ), + // The dashboard answers a one-question card the way T3's own card does. // t4 fork: an open question in full, with what the agent wrote around it // (the messages of the turn that asked), for the dashboard's own question diff --git a/apps/server/src/t4/T4Jobs.ts b/apps/server/src/t4/T4Jobs.ts index 8b467716385f9..aaf931663de14 100644 --- a/apps/server/src/t4/T4Jobs.ts +++ b/apps/server/src/t4/T4Jobs.ts @@ -14,6 +14,7 @@ import * as T4LegacyImport from "./T4LegacyImport.ts"; import * as T4AutoArchive from "./T4AutoArchive.ts"; import * as T4ReleaseGuard from "./T4ReleaseGuard.ts"; import * as T4Releases from "./T4Releases.ts"; +import * as T4Roles from "./T4Roles.ts"; import * as T4Schedules from "./T4Schedules.ts"; import * as T4RunWatch from "./T4RunWatch.ts"; import * as T4Settle from "./T4Settle.ts"; @@ -47,6 +48,7 @@ export const layer = Layer.effectDiscard( yield* scheduler.register("t4-release-guard", yield* throttled(120_000, T4ReleaseGuard.sweep)); yield* scheduler.register("t4-release-stale", yield* throttled(600_000, T4Releases.sweepStale)); yield* scheduler.register("t4-auto-archive", yield* throttled(600_000, T4AutoArchive.sweep)); + yield* scheduler.register("t4-roles", yield* throttled(60_000, T4Roles.sweep)); yield* scheduler.register( "t4-schedule-models", yield* throttled(60_000, T4Schedules.syncDefaultModels), diff --git a/apps/server/src/t4/T4Ledger.ts b/apps/server/src/t4/T4Ledger.ts index 104d5ef93c5f6..f1b7750a99acf 100644 --- a/apps/server/src/t4/T4Ledger.ts +++ b/apps/server/src/t4/T4Ledger.ts @@ -41,6 +41,10 @@ function liveEntries( return entries.filter((entry) => entry.settledAt === null && !requesterClosed(entry, byId)); } +/** The standing role a thread holds (AI-140), if any. */ +export const standingRoleOf = (world: T4World, threadId: string): T4StandingRole | undefined => + world.standingRoles?.get(threadId); + export interface T4ThreadLedgerFacts { readonly isReleaseManager: boolean; /** Live entries this thread owes (open handoffs to it). */ @@ -49,10 +53,19 @@ export interface T4ThreadLedgerFacts { readonly owedBy: number; } +/** A thread that is an enabled standing role's (AI-140). */ +export interface T4StandingRole { + readonly roleId: string; + readonly kind: string; + readonly title: string; +} + export interface T4World { readonly threads: ReadonlyArray; readonly byId: ReadonlyMap; readonly releaseManagers: ReadonlySet; + /** Thread id -> its standing role (AI-140); absent in older fixtures. */ + readonly standingRoles?: ReadonlyMap; readonly open: ReadonlyArray; readonly live: ReadonlyArray; } @@ -94,10 +107,18 @@ const make = Effect.gen(function* () { const byId = new Map(threads.map((thread) => [thread.id as string, thread])); const rms = yield* store.releaseManagers(); const open = yield* store.openHandoffs(); + const roles = yield* store.roles(); return { threads, byId, releaseManagers: new Set(rms.values()), + standingRoles: new Map( + roles.flatMap((role) => + role.enabled && role.threadId !== null + ? [[role.threadId, { roleId: role.id, kind: role.kind, title: role.title }] as const] + : [], + ), + ), open, live: liveEntries(open, byId), }; diff --git a/apps/server/src/t4/T4Migrations.ts b/apps/server/src/t4/T4Migrations.ts index f85b2963bc712..25cafb48739c8 100644 --- a/apps/server/src/t4/T4Migrations.ts +++ b/apps/server/src/t4/T4Migrations.ts @@ -169,11 +169,31 @@ const Migration0004 = Effect.gen(function* () { yield* sql`CREATE INDEX IF NOT EXISTS t4_tool_calls_thread ON t4_tool_calls (thread_id)`; }); +// Standing roles (AI-140): persistent, pinned threads that wake on check-ins and +// on polled triggers. A role's trigger state and check-in task ids live in t4_meta. +const Migration0005 = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + CREATE TABLE IF NOT EXISTS t4_roles ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + title TEXT NOT NULL, + project_id TEXT NOT NULL, + thread_id TEXT, + enabled INTEGER NOT NULL, + config_json TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ) WITHOUT ROWID + `; +}); + const t4MigrationEntries = [ [1, "T4SessionTooling", Migration0001], [2, "T4ThreadRoles", Migration0002], [3, "T4ReleaseQueue", Migration0003], [4, "T4WaitersAndToolCalls", Migration0004], + [5, "T4Roles", Migration0005], ] as const; const run = Migrator.make({}); diff --git a/apps/server/src/t4/T4Roles.test.ts b/apps/server/src/t4/T4Roles.test.ts new file mode 100644 index 0000000000000..efc4b28b3ee23 --- /dev/null +++ b/apps/server/src/t4/T4Roles.test.ts @@ -0,0 +1,82 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { roleOf } from "./T4Facts.ts"; +import { inQuietHours, mergeItems, triggerMessage } from "./T4Roles.ts"; +import { claudeAutoCompactWindowFor, compactAtTokensFor, setThreadCompaction } from "./threadCompaction.ts"; + +const empty = { + state: "", + since: null, + lastRunAt: null, + lastOk: null, + lastError: null, + failures: 0, + lastFailNoteAt: null, + lastFiredAt: null, + seen: [], + pending: [], + pendingSince: null, +}; +const item = (id: string) => ({ id, title: `issue ${id}`, url: `https://x/${id}` }); +const now = Date.parse("2026-11-23T20:00:00.000Z"); + +describe("t4 roles", () => { + it("records a trigger's first run as a baseline without pending items", () => { + const { next, added } = mergeItems(empty, [item("a"), item("b")], now); + assert.equal(added, 0); + assert.deepEqual(next.seen, ["a", "b"]); + assert.equal(next.pending.length, 0); + }); + + it("queues only items it has not seen, from the second run on", () => { + const second = { ...empty, lastOk: true, since: "2026-11-23T19:55:00.000Z", seen: ["a"] }; + const { next, added } = mergeItems(second, [item("a"), item("c")], now); + assert.equal(added, 1); + assert.deepEqual( + next.pending.map((p) => p.id), + ["c"], + ); + assert.equal(next.pendingSince, "2026-11-23T20:00:00.000Z"); + const again = mergeItems(next, [item("c")], now + 60_000); + assert.equal(again.added, 0); + // The batch window keeps counting from the first pending item. + assert.equal(again.next.pendingSince, "2026-11-23T20:00:00.000Z"); + }); + + it("writes one message for several triggers, capped per trigger", () => { + const many = Array.from({ length: 33 }, (_, i) => item(String(i))); + const text = triggerMessage([ + { label: "New Sentry issues", items: [item("x")] }, + { label: "Red main", items: many }, + ]); + assert.include(text, "**New Sentry issues**: 1 new"); + assert.include(text, "- [issue x](https://x/x)"); + assert.include(text, "**Red main**: 33 new"); + assert.include(text, "- and 3 more"); + assert.include(text, "end your turn in one line"); + }); + + it("knows quiet hours in Pacific time, across midnight", () => { + const quiet = { start: "22:00", end: "07:00" }; + // 2026-11-24T06:30Z is 22:30 PST on the 23rd; 15:00Z is 07:00 PST. + assert.isTrue(inQuietHours(quiet, Date.parse("2026-11-24T06:30:00.000Z"))); + assert.isTrue(inQuietHours(quiet, Date.parse("2026-11-24T14:59:00.000Z"))); + assert.isFalse(inQuietHours(quiet, Date.parse("2026-11-24T15:00:00.000Z"))); + assert.isFalse(inQuietHours(null, Date.parse("2026-11-24T06:30:00.000Z"))); + assert.isTrue(inQuietHours({ start: "12:00", end: "13:00" }, Date.parse("2026-11-23T20:30:00.000Z"))); + }); + + it("gives a standing role thread the role role", () => { + assert.equal(roleOf({ id: "t", title: "Sentry watch PM" }, false, new Map(), true), "role"); + assert.equal(roleOf({ id: "t", title: "Release manager" }, true, new Map(), true), "release-manager"); + }); + + it("keeps a compaction point per thread", () => { + setThreadCompaction(new Map([["t4-rm-1", 150_000]])); + assert.equal(compactAtTokensFor("t4-rm-1"), 150_000); + assert.equal(compactAtTokensFor("other"), undefined); + assert.equal(compactAtTokensFor(null), undefined); + assert.equal(claudeAutoCompactWindowFor(150_000), "183000"); + setThreadCompaction(new Map()); + }); +}); diff --git a/apps/server/src/t4/T4Roles.ts b/apps/server/src/t4/T4Roles.ts new file mode 100644 index 0000000000000..c3ff19266008e --- /dev/null +++ b/apps/server/src/t4/T4Roles.ts @@ -0,0 +1,778 @@ +// @effect-diagnostics processEnvInEffect:off -- trigger commands run with the container's env. +/** + * t4 fork (AI-140): standing roles. A role is a persistent, pinned thread per client - like the + * release manager it never settles, snoozes or archives (T4Ledger.standingRoleOf) - that acts in + * a set way (its brief and its kind's `role-` skill) and wakes on: + * + * - check-ins: T3 scheduled tasks bound to its thread on t4's cron (server time zone, Pacific); + * - triggers: commands t4 runs every N minutes in the project's main checkout, which print the + * items that are new since their last run (`t4-probe`, or any command; contract below). New + * items are deduped per trigger, gathered for `batchMinutes`, and delivered as one message + * when the thread is idle, outside quiet hours and under the daily cap - no tokens are spent + * while nothing is new. A trigger's first run only records what it sees. + * + * Trigger command contract: `bash -c ` with T4_PROBE_STATE (the last run's `state`), + * T4_PROBE_SINCE (ISO time of the last good run), T4_ROLE_ID, T4_ROLE_KIND, T4_TRIGGER_ID; stdout + * `{"items":[{"id","title","url"?,"detail"?}],"state"?}`; non-zero exit or bad JSON = failed. + * + * It also keeps the per-thread compaction table (threadCompaction.ts) for roles and release + * managers: usa-rs's release manager carried ~286k tokens into every request. + */ +import { + CommandId, + MessageId, + ModelSelection, + ProjectId, + ScheduledTaskId, + ThreadId, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; + +import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as Project from "../project/ProjectService.ts"; +import * as ScheduledTasks from "../scheduledTasks/ScheduledTaskService.ts"; +import { clientDefaultModelSelection } from "./T4DefaultModel.ts"; +import * as T4Config from "./T4Config.ts"; +import * as T4Delivery from "./T4Delivery.ts"; +import * as T4Store from "./T4Store.ts"; +import { isRunning, stateOf } from "./T4Threads.ts"; +import { setThreadCompaction } from "./threadCompaction.ts"; + +// ---------------------------------------------------------------- schemas + +const CheckIn = Schema.Struct({ + id: Schema.String, + label: Schema.String, + /** Five-field cron in the server's time zone. */ + cron: Schema.String, + prompt: Schema.String, +}); + +const Trigger = Schema.Struct({ + id: Schema.String, + label: Schema.String, + command: Schema.String, + everyMinutes: Schema.Number, + batchMinutes: Schema.Number, + enabled: Schema.Boolean, +}); + +const QuietHours = Schema.Struct({ start: Schema.String, end: Schema.String }); + +export const RoleConfig = Schema.Struct({ + brief: Schema.String, + model: Schema.NullOr(ModelSelection), + compactAtTokens: Schema.NullOr(Schema.Number), + checkIns: Schema.Array(CheckIn), + triggers: Schema.Array(Trigger), + quietHours: Schema.NullOr(QuietHours), + maxTriggerTurnsPerDay: Schema.Number, +}); +export type RoleConfig = typeof RoleConfig.Type; + +export const SaveRoleBody = Schema.Struct({ + id: Schema.optional(Schema.String), + kind: Schema.String, + title: Schema.String, + projectId: Schema.String, + enabled: Schema.Boolean, + config: RoleConfig, +}); +export type SaveRoleBody = typeof SaveRoleBody.Type; + +export const RunRoleBody = Schema.Struct({ triggerId: Schema.optional(Schema.String) }); +export const RmCompactionBody = Schema.Struct({ compactAtTokens: Schema.NullOr(Schema.Number) }); + +const ConfigJson = Schema.fromJsonString(RoleConfig); +const decodeConfig = Schema.decodeEffect(ConfigJson); +const encodeConfig = Schema.encodeEffect(ConfigJson); + +const Item = Schema.Struct({ + id: Schema.String, + title: Schema.String, + url: Schema.optional(Schema.NullOr(Schema.String)), + detail: Schema.optional(Schema.NullOr(Schema.String)), +}); +type Item = typeof Item.Type; +const ProbeOutput = Schema.Struct({ + items: Schema.Array(Item), + state: Schema.optional(Schema.NullOr(Schema.String)), +}); +const decodeProbe = Schema.decodeUnknownEffect(Schema.fromJsonString(ProbeOutput)); + +const TriggerState = Schema.Struct({ + state: Schema.String, + since: Schema.NullOr(Schema.String), + lastRunAt: Schema.NullOr(Schema.String), + lastOk: Schema.NullOr(Schema.Boolean), + lastError: Schema.NullOr(Schema.String), + failures: Schema.Number, + lastFailNoteAt: Schema.NullOr(Schema.String), + lastFiredAt: Schema.NullOr(Schema.String), + seen: Schema.Array(Schema.String), + pending: Schema.Array(Item), + pendingSince: Schema.NullOr(Schema.String), +}); +type TriggerState = typeof TriggerState.Type; +const TriggerStateJson = Schema.fromJsonString(TriggerState); +const decodeTriggerState = Schema.decodeEffect(TriggerStateJson); +const encodeTriggerState = Schema.encodeEffect(TriggerStateJson); + +const CheckInIds = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String)); +const decodeCheckInIds = Schema.decodeEffect(CheckInIds); +const encodeCheckInIds = Schema.encodeEffect(CheckInIds); + +// ---------------------------------------------------------------- constants and pure helpers + +const SEEN_MAX = 1000; +const PENDING_MAX = 200; +const ITEMS_PER_MESSAGE = 30; +const FAIL_NOTE_AFTER = 3; +const FAIL_NOTE_EVERY_MS = 6 * 3600_000; +const PROBE_TIMEOUT = "60 seconds"; +const RM_COMPACT_KEY = "rm-compact-at"; +const triggerKey = (roleId: string, triggerId: string) => `role-trigger:${roleId}:${triggerId}`; +const checkInsKey = (roleId: string) => `role-checkins:${roleId}`; +const turnsKey = (roleId: string) => `role-turns:${roleId}`; + +const emptyTriggerState = (): TriggerState => ({ + state: "", + since: null, + lastRunAt: null, + lastOk: null, + lastError: null, + failures: 0, + lastFailNoteAt: null, + lastFiredAt: null, + seen: [], + pending: [], + pendingSince: null, +}); + +const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); +const msOf = (text: string | null) => (text === null ? 0 : Date.parse(text)); + +const pacificParts = (ms: number) => { + const parts = new Intl.DateTimeFormat("en-CA", { + timeZone: "America/Los_Angeles", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }).formatToParts(ms); + const get = (type: string) => parts.find((part) => part.type === type)?.value ?? "00"; + return { day: `${get("year")}-${get("month")}-${get("day")}`, minutes: Number(get("hour")) * 60 + Number(get("minute")) }; +}; + +const minutesOf = (hhmm: string) => { + const match = /^(\d{1,2}):(\d{2})$/.exec(hhmm.trim()); + return match === null ? null : Number(match[1]) * 60 + Number(match[2]); +}; + +/** Inside quiet hours (Pacific); a window may wrap midnight. */ +export const inQuietHours = (quiet: RoleConfig["quietHours"], nowMs: number): boolean => { + if (quiet === null) return false; + const start = minutesOf(quiet.start); + const end = minutesOf(quiet.end); + if (start === null || end === null || start === end) return false; + const now = pacificParts(nowMs).minutes; + return start < end ? now >= start && now < end : now >= start || now < end; +}; + +/** Merges a run's items into a trigger's state: new ones (not seen) become pending. */ +export const mergeItems = ( + previous: TriggerState, + items: ReadonlyArray, + nowMs: number, +): { readonly next: TriggerState; readonly added: number } => { + const seen = new Set(previous.seen); + const baseline = previous.lastOk === null && previous.since === null; + const fresh = items.filter((item) => !seen.has(item.id)); + const seenNext = [...previous.seen, ...fresh.map((item) => item.id)].slice(-SEEN_MAX); + if (baseline || fresh.length === 0) { + return { next: { ...previous, seen: seenNext }, added: 0 }; + } + const pending = [...previous.pending, ...fresh].slice(-PENDING_MAX); + return { + next: { + ...previous, + seen: seenNext, + pending, + pendingSince: previous.pendingSince ?? iso(nowMs), + }, + added: fresh.length, + }; +}; + +export const triggerMessage = ( + batches: ReadonlyArray<{ readonly label: string; readonly items: ReadonlyArray }>, +): string => { + const sections = batches.map(({ label, items }) => { + const lines = items.slice(0, ITEMS_PER_MESSAGE).map((item) => { + const title = item.url ? `[${item.title}](${item.url})` : item.title; + return `- ${title}${item.detail ? ` - ${item.detail}` : ""}`; + }); + const more = items.length > ITEMS_PER_MESSAGE ? [`- and ${items.length - ITEMS_PER_MESSAGE} more`] : []; + return [`t4 role trigger - **${label}**: ${items.length} new`, ...lines, ...more].join("\n"); + }); + return `${sections.join("\n\n")}\n\nHandle them as your role skill says. If none needs anything, end your turn in one line.`; +}; + +const roleIntro = (role: T4Store.T4RoleRow, config: RoleConfig) => { + const checkIns = config.checkIns.map((c) => `- ${c.label}: \`${c.cron}\``).join("\n") || "- none"; + const triggers = + config.triggers.map((t) => `- ${t.label}: \`${t.command}\` every ${t.everyMinutes} min`).join("\n") || "- none"; + return [ + `You are the standing role **${role.title}** (role id \`${role.id}\`, kind \`${role.kind}\`) for this client: a persistent thread that never settles.`, + `Load the \`standing-role\` skill and the \`role-${role.kind}\` skill if there is one, and follow them. You run in the project's main checkout. Your notebook is \`~/.config/t4/roles/${role.id}.md\`.`, + "", + "Check-ins (scheduled messages into this thread):", + checkIns, + "", + "Triggers (t4 runs these and messages you only when something is new):", + triggers, + "", + "Your brief from the user:", + "", + config.brief.trim() || "(none)", + "", + "Start by reading your notebook (create it if missing) and the skill, then end your turn in one line: your first check-in or trigger will wake you.", + ].join("\n"); +}; + +// ---------------------------------------------------------------- reads + +const readTriggerState = (store: T4Store.T4StoreShape, roleId: string, triggerId: string) => + store.meta(triggerKey(roleId, triggerId)).pipe( + Effect.flatMap((text) => (text === undefined ? Effect.succeed(emptyTriggerState()) : decodeTriggerState(text))), + Effect.orElseSucceed(emptyTriggerState), + ); +const writeTriggerState = ( + store: T4Store.T4StoreShape, + roleId: string, + triggerId: string, + state: TriggerState, +) => + encodeTriggerState(state).pipe( + Effect.flatMap((text) => store.setMeta(triggerKey(roleId, triggerId), text)), + Effect.ignore, + ); + +const readCheckInIds = (store: T4Store.T4StoreShape, roleId: string) => + store.meta(checkInsKey(roleId)).pipe( + Effect.flatMap( + (text): Effect.Effect, unknown> => + text === undefined ? Effect.succeed({}) : decodeCheckInIds(text), + ), + Effect.orElseSucceed((): Record => ({})), + ); + +const turnsToday = (store: T4Store.T4StoreShape, roleId: string, nowMs: number) => + store.meta(turnsKey(roleId)).pipe( + Effect.map((text) => { + const [day, count] = (text ?? "").split(" "); + return day === pacificParts(nowMs).day ? Number(count) || 0 : 0; + }), + Effect.orElseSucceed(() => 0), + ); + +const configOf = (row: T4Store.T4RoleRow) => + decodeConfig(row.configJson).pipe(Effect.orElseSucceed((): RoleConfig | undefined => undefined)); + +const rmCompaction = Effect.gen(function* () { + const store = yield* T4Store.T4Store; + const config = yield* T4Config.T4ServerConfig; + const text = yield* store.meta(RM_COMPACT_KEY).pipe(Effect.orElseSucceed(() => undefined)); + const override = text === undefined || text === "" ? undefined : Number(text); + return { + compactAtTokens: + override !== undefined && Number.isFinite(override) && override > 0 ? override : null, + defaultCompactAtTokens: config.releaseManagerCompactAtTokens, + }; +}); + +export const listRoles = Effect.fn("t4.T4Roles.list")(function* () { + const store = yield* T4Store.T4Store; + const threads = yield* ThreadManagementService.ThreadManagementService; + const scheduled = yield* ScheduledTasks.ScheduledTaskService; + const rows = yield* store.roles(); + const now = yield* Clock.currentTimeMillis; + const { tasks } = yield* scheduled.list().pipe(Effect.orElseSucceed(() => ({ tasks: [] }))); + const roles = []; + for (const row of rows) { + const config = yield* configOf(row); + if (config === undefined) continue; + const shell = + row.threadId === null + ? null + : yield* threads.getThreadShell(ThreadId.make(row.threadId)).pipe(Effect.orElseSucceed(() => null)); + const ids = yield* readCheckInIds(store, row.id); + const triggerStatus = []; + for (const trigger of config.triggers) { + const state = yield* readTriggerState(store, row.id, trigger.id); + triggerStatus.push({ + id: trigger.id, + lastRunAt: state.lastRunAt, + lastOk: state.lastOk, + lastError: state.lastError, + lastFiredAt: state.lastFiredAt, + pending: state.pending.length, + seen: state.seen.length, + }); + } + roles.push({ + id: row.id, + kind: row.kind, + title: row.title, + projectId: row.projectId, + threadId: row.threadId, + enabled: row.enabled, + config, + status: { + threadState: shell === null ? null : stateOf(shell, now), + checkIns: config.checkIns.map((checkIn) => { + const task = tasks.find((t) => t.id === ids[checkIn.id]); + return { + id: checkIn.id, + nextRunAt: task?.nextRunAt == null ? null : String(task.nextRunAt), + lastRunAt: task?.lastRunAt == null ? null : String(task.lastRunAt), + }; + }), + triggers: triggerStatus, + triggerTurnsToday: yield* turnsToday(store, row.id, now), + }, + }); + } + return { roles, releaseManager: yield* rmCompaction }; +}); + +// ---------------------------------------------------------------- writes + +const pinCommand = (type: "thread.pin" | "thread.unpin", threadId: string, uuid: string) => ({ + type, + commandId: CommandId.make(`t4:role-${type === "thread.pin" ? "pin" : "unpin"}:${uuid}`), + threadId: ThreadId.make(threadId), +}); + +/** Brings a role's check-in tasks in line with its config (and its enabled state). */ +const syncCheckIns = Effect.fn("t4.T4Roles.syncCheckIns")(function* ( + row: T4Store.T4RoleRow, + config: RoleConfig, + modelSelection: ModelSelection, +) { + const store = yield* T4Store.T4Store; + const scheduled = yield* ScheduledTasks.ScheduledTaskService; + const ids = yield* readCheckInIds(store, row.id); + const next: Record = {}; + const live = row.enabled && row.threadId !== null; + for (const checkIn of config.checkIns) { + if (!live || checkIn.cron.trim() === "" || checkIn.prompt.trim() === "") continue; + const existing = ids[checkIn.id]; + const result = yield* scheduled + .upsert({ + ...(existing === undefined ? {} : { id: ScheduledTaskId.make(existing) }), + title: `${row.title}: ${checkIn.label || "check-in"}`, + prompt: `Scheduled check-in - **${checkIn.label || "check-in"}** (${row.title}).\n\n${checkIn.prompt.trim()}`, + enabled: true, + schedule: { type: "cron", expression: checkIn.cron.trim() }, + projectId: ProjectId.make(row.projectId), + threadId: ThreadId.make(row.threadId!), + threadMode: "continue", + workspaceStrategy: { type: "root" }, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "user", + creationSource: "web", + }) + .pipe(Effect.option); + if (Option.isSome(result)) next[checkIn.id] = result.value.task.id; + } + for (const [checkInId, taskId] of Object.entries(ids)) { + if (next[checkInId] === taskId) continue; + yield* scheduled.delete({ id: ScheduledTaskId.make(taskId) }).pipe(Effect.ignore); + } + yield* encodeCheckInIds(next).pipe( + Effect.flatMap((text) => store.setMeta(checkInsKey(row.id), text)), + Effect.ignore, + ); +}); + +export const saveRole = Effect.fn("t4.T4Roles.save")(function* (input: SaveRoleBody) { + const store = yield* T4Store.T4Store; + const threads = yield* ThreadManagementService.ThreadManagementService; + const launches = yield* ThreadLaunch.ThreadLaunchService; + const projects = yield* Project.ProjectService; + const crypto = yield* SecureRandom.SecureRandom; + const now = yield* Clock.currentTimeMillis; + const title = input.title.trim(); + if (title === "") return { error: "a role needs a title" } as const; + const project = Option.getOrUndefined( + yield* projects.getById(ProjectId.make(input.projectId)).pipe(Effect.orElseSucceed(() => Option.none())), + ); + if (project === undefined) return { error: "project not found" } as const; + for (const trigger of input.config.triggers) { + if (!(trigger.everyMinutes >= 1)) return { error: `trigger "${trigger.label}" must run at most once a minute` } as const; + } + const rows = yield* store.roles(); + const previous = input.id === undefined ? undefined : rows.find((row) => row.id === input.id); + if (input.id !== undefined && previous === undefined) return { error: "role not found" } as const; + const modelSelection = + input.config.model ?? (yield* clientDefaultModelSelection(project.id)); + if (modelSelection === undefined || modelSelection === null) { + return { error: "this client has no default model set - choose a model" } as const; + } + const id = previous?.id ?? `role-${yield* crypto.uuidV4().pipe(Effect.orDie)}`; + let threadId = previous?.threadId ?? null; + // A role thread that was deleted is made again. + if (threadId !== null) { + const shell = yield* threads.getThreadShell(ThreadId.make(threadId)).pipe(Effect.orElseSucceed(() => null)); + if (shell === null || shell.deletedAt !== null) threadId = null; + } + let row: T4Store.T4RoleRow = { + id, + kind: input.kind.trim() || "custom", + title, + projectId: project.id, + threadId, + enabled: input.enabled, + configJson: yield* encodeConfig(input.config).pipe(Effect.orDie), + createdAt: previous?.createdAt ?? iso(now), + updatedAt: iso(now), + }; + if (row.enabled && threadId === null) { + const uuid = yield* crypto.uuidV4().pipe(Effect.orDie); + const launched = yield* launches.launch({ + commandId: CommandId.make(`t4:role:${uuid}`), + threadId: ThreadId.make(`t4-role-${uuid}`), + projectId: project.id, + title, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { type: "root" }, + initialMessage: { + messageId: MessageId.make(`t4:role:${uuid}`), + text: roleIntro(row, input.config), + attachments: [], + }, + createdBy: "user", + creationSource: "web", + }); + threadId = launched.projection.thread.id; + row = { ...row, threadId }; + } + yield* store.upsertRole(row); + if (threadId !== null) { + const uuid = yield* crypto.uuidV4().pipe(Effect.orDie); + yield* threads.dispatch(pinCommand(row.enabled ? "thread.pin" : "thread.unpin", threadId, uuid)).pipe(Effect.ignore); + if (previous !== undefined && previous.title !== title) { + yield* threads + .dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`t4:role-title:${uuid}`), + threadId: ThreadId.make(threadId), + title, + }) + .pipe(Effect.ignore); + } + } + yield* syncCheckIns(row, input.config, modelSelection); + // Trigger states of triggers that were removed. + const kept = new Set(input.config.triggers.map((trigger) => trigger.id)); + const before = previous === undefined ? undefined : yield* configOf(previous); + for (const trigger of before?.triggers ?? []) { + if (!kept.has(trigger.id)) yield* store.deleteMeta(triggerKey(id, trigger.id)).pipe(Effect.ignore); + } + yield* syncCompaction; + return { role: { ...row, config: input.config } } as const; +}); + +export const deleteRole = Effect.fn("t4.T4Roles.delete")(function* (id: string) { + const store = yield* T4Store.T4Store; + const threads = yield* ThreadManagementService.ThreadManagementService; + const scheduled = yield* ScheduledTasks.ScheduledTaskService; + const crypto = yield* SecureRandom.SecureRandom; + const row = (yield* store.roles()).find((r) => r.id === id); + if (row === undefined) return { error: "role not found" } as const; + for (const taskId of Object.values(yield* readCheckInIds(store, id))) { + yield* scheduled.delete({ id: ScheduledTaskId.make(taskId) }).pipe(Effect.ignore); + } + if (row.threadId !== null) { + const uuid = yield* crypto.uuidV4().pipe(Effect.orDie); + yield* threads.dispatch(pinCommand("thread.unpin", row.threadId, uuid)).pipe(Effect.ignore); + } + yield* store.deleteMeta(`role-trigger:${id}:`).pipe(Effect.ignore); + yield* store.deleteMeta(checkInsKey(id)).pipe(Effect.ignore); + yield* store.deleteMeta(turnsKey(id)).pipe(Effect.ignore); + yield* store.deleteRole(id); + yield* syncCompaction; + return { ok: true } as const; +}); + +export const setReleaseManagerCompaction = Effect.fn("t4.T4Roles.setRmCompaction")(function* ( + compactAtTokens: number | null, +) { + const store = yield* T4Store.T4Store; + const value = compactAtTokens !== null && compactAtTokens > 0 ? String(Math.round(compactAtTokens)) : ""; + yield* store.setMeta(RM_COMPACT_KEY, value); + yield* syncCompaction; + return yield* rmCompaction; +}); + +// ---------------------------------------------------------------- compaction + +/** Rebuilds the per-thread compaction table from the roles and release managers. */ +export const syncCompaction = Effect.gen(function* () { + const store = yield* T4Store.T4Store; + const rms = yield* store.releaseManagers(); + const rows = yield* store.roles(); + const rm = yield* rmCompaction; + const table = new Map(); + const rmAt = rm.compactAtTokens ?? rm.defaultCompactAtTokens; + if (rmAt !== null && rmAt > 0) for (const threadId of rms.values()) table.set(threadId, rmAt); + for (const row of rows) { + if (!row.enabled || row.threadId === null) continue; + const config = yield* configOf(row); + if (config?.compactAtTokens != null && config.compactAtTokens > 0) { + table.set(row.threadId, config.compactAtTokens); + } + } + setThreadCompaction(table); +}).pipe(Effect.ignoreCause({ log: true })); + +// ---------------------------------------------------------------- triggers + +const runProbe = Effect.fn("t4.T4Roles.runProbe")(function* ( + row: T4Store.T4RoleRow, + trigger: RoleConfig["triggers"][number], + previous: TriggerState, + cwd: string, + nowMs: number, +) { + const processes = yield* ProcessRunner.ProcessRunner; + const since = previous.since ?? iso(nowMs - trigger.everyMinutes * 60_000); + const result = yield* processes + .run({ + command: "bash", + args: ["-c", trigger.command], + cwd, + env: { + ...process.env, + T4_PROBE_STATE: previous.state, + T4_PROBE_SINCE: since, + T4_ROLE_ID: row.id, + T4_ROLE_KIND: row.kind, + T4_TRIGGER_ID: trigger.id, + }, + timeout: PROBE_TIMEOUT, + timeoutBehavior: "timedOutResult", + maxOutputBytes: 2_000_000, + outputMode: "truncate", + }) + .pipe(Effect.result); + const failed = (error: string): TriggerState => ({ + ...previous, + lastRunAt: iso(nowMs), + lastOk: false, + lastError: error.slice(-400), + failures: previous.failures + 1, + }); + if (Result.isFailure(result)) return { next: failed(String(result.failure)), added: 0 }; + const out = result.success; + if (out.timedOut) return { next: failed("timed out after 60 s"), added: 0 }; + if (out.code !== 0) { + return { next: failed(`exit ${out.code}: ${out.stderr.trim() || out.stdout.trim()}`), added: 0 }; + } + const parsed = yield* decodeProbe(out.stdout.trim()).pipe(Effect.result); + if (Result.isFailure(parsed)) return { next: failed(`not the trigger JSON: ${out.stdout.trim().slice(0, 200)}`), added: 0 }; + const merged = mergeItems(previous, parsed.success.items, nowMs); + return { + next: { + ...merged.next, + state: parsed.success.state ?? previous.state, + since: iso(nowMs), + lastRunAt: iso(nowMs), + lastOk: true, + lastError: null, + failures: 0, + }, + added: merged.added, + }; +}); + +interface RoleRuntime { + readonly row: T4Store.T4RoleRow; + readonly config: RoleConfig; + readonly cwd: string; +} + +/** Runs one role's due triggers (or the one asked for) and delivers what is due. */ +const tickRole = Effect.fn("t4.T4Roles.tickRole")(function* ( + role: RoleRuntime, + options: { readonly forceTriggerId?: string; readonly forceCheckIn?: boolean }, +) { + const store = yield* T4Store.T4Store; + const threads = yield* ThreadManagementService.ThreadManagementService; + const delivery = yield* T4Delivery.T4Delivery; + const now = yield* Clock.currentTimeMillis; + const { row, config } = role; + const states = new Map(); + for (const trigger of config.triggers) { + const previous = yield* readTriggerState(store, row.id, trigger.id); + const forced = options.forceTriggerId === trigger.id; + const due = + forced || + (trigger.enabled && now - msOf(previous.lastRunAt) >= trigger.everyMinutes * 60_000 - 5_000); + if (!due) { + states.set(trigger.id, previous); + continue; + } + const { next } = yield* runProbe(row, trigger, previous, role.cwd, now); + states.set(trigger.id, next); + yield* writeTriggerState(store, row.id, trigger.id, next); + } + if (row.threadId === null) return 0; + const shell = yield* threads + .getThreadShell(ThreadId.make(row.threadId)) + .pipe(Effect.orElseSucceed(() => null)); + if (shell === null || shell.deletedAt !== null) return 0; + + // Failing triggers: one note after a few failures in a row, at most every 6 h. + for (const trigger of config.triggers) { + const state = states.get(trigger.id)!; + if (state.failures < FAIL_NOTE_AFTER || now - msOf(state.lastFailNoteAt) < FAIL_NOTE_EVERY_MS) continue; + yield* delivery + .deliver({ + target: shell, + text: `t4: your trigger **${trigger.label}** (\`${trigger.command}\`) failed ${state.failures} times in a row: ${state.lastError ?? "no output"}. If it needs a key or a fix only the user can make, say so in one Update card with the exact change (dashboard: Settings -> Roles); otherwise end your turn in one line.`, + force: true, + patient: true, + createdBy: "system", + creationSource: "server", + }) + .pipe(Effect.ignore); + const noted = { ...state, lastFailNoteAt: iso(now) }; + states.set(trigger.id, noted); + yield* writeTriggerState(store, row.id, trigger.id, noted); + } + + if (options.forceCheckIn === true) { + yield* delivery + .deliver({ + target: shell, + text: `Check-in requested from the dashboard (${row.title}). Do your regular check-in now.`, + force: true, + patient: true, + createdBy: "user", + creationSource: "web", + }) + .pipe(Effect.ignore); + } + + const forced = options.forceTriggerId !== undefined; + const ready = config.triggers.filter((trigger) => { + const state = states.get(trigger.id)!; + if (state.pending.length === 0) return false; + return forced || now - msOf(state.pendingSince) >= trigger.batchMinutes * 60_000; + }); + if (ready.length === 0) return 0; + if (!forced) { + if (isRunning(shell)) return 0; + if (inQuietHours(config.quietHours, now)) return 0; + if ((yield* turnsToday(store, row.id, now)) >= config.maxTriggerTurnsPerDay) return 0; + } + const batches = ready.map((trigger) => ({ label: trigger.label, items: states.get(trigger.id)!.pending })); + const delivered = yield* delivery + .deliver({ + target: shell, + text: triggerMessage(batches), + force: true, + patient: true, + createdBy: "system", + creationSource: "server", + }) + .pipe(Effect.as(true), Effect.orElseSucceed(() => false)); + if (!delivered) return 0; + let count = 0; + for (const trigger of ready) { + const state = states.get(trigger.id)!; + count += state.pending.length; + yield* writeTriggerState(store, row.id, trigger.id, { + ...state, + pending: [], + pendingSince: null, + lastFiredAt: iso(now), + }); + } + const today = pacificParts(now).day; + const turns = yield* turnsToday(store, row.id, now); + yield* store.setMeta(turnsKey(row.id), `${today} ${turns + 1}`).pipe(Effect.ignore); + yield* Effect.logInfo("t4: role trigger delivered", { roleId: row.id, items: count }); + return count; +}); + +const runtimes = Effect.gen(function* () { + const store = yield* T4Store.T4Store; + const projects = yield* Project.ProjectService; + const out: Array = []; + for (const row of yield* store.roles()) { + if (!row.enabled) continue; + const config = yield* configOf(row); + if (config === undefined) continue; + const project = Option.getOrUndefined( + yield* projects.getById(ProjectId.make(row.projectId)).pipe(Effect.orElseSucceed(() => Option.none())), + ); + if (project === undefined) continue; + out.push({ row, config, cwd: project.workspaceRoot }); + } + return out; +}); + +/** Every minute: compaction table, then each enabled role's due triggers. */ +export const sweep = Effect.gen(function* () { + yield* syncCompaction; + const roles = yield* runtimes; + yield* Effect.forEach( + roles, + (role) => tickRole(role, {}).pipe(Effect.ignoreCause({ log: true })), + { concurrency: 4, discard: true }, + ); +}).pipe(Effect.ignoreCause({ log: true })); + +export const runRole = Effect.fn("t4.T4Roles.run")(function* (id: string, triggerId?: string) { + const roles = yield* runtimes; + const role = roles.find((r) => r.row.id === id); + if (role === undefined) return { error: "role not found or turned off" } as const; + if (triggerId !== undefined && !role.config.triggers.some((t) => t.id === triggerId)) { + return { error: "trigger not found" } as const; + } + const delivered = yield* tickRole( + role, + triggerId === undefined ? { forceCheckIn: true } : { forceTriggerId: triggerId }, + ); + return { ok: true, delivered } as const; +}); + +/** For `/api/t4/state`: thread id -> its role. */ +export const standingRolesForState = Effect.gen(function* () { + const store = yield* T4Store.T4Store; + const out: Record = {}; + for (const row of yield* store.roles()) { + if (row.enabled && row.threadId !== null) { + out[row.threadId] = { roleId: row.id, kind: row.kind, title: row.title }; + } + } + return out; +}).pipe(Effect.orElseSucceed(() => ({}))); + diff --git a/apps/server/src/t4/T4Settle.ts b/apps/server/src/t4/T4Settle.ts index 042948dcba4f2..162ba5dce1949 100644 --- a/apps/server/src/t4/T4Settle.ts +++ b/apps/server/src/t4/T4Settle.ts @@ -61,6 +61,10 @@ const make = Effect.gen(function* () { if (ledger.isReleaseManager(world, thread)) { return "release managers never settle - say 'nothing queued, nothing in flight' in one line and stop"; } + const role = T4Ledger.standingRoleOf(world, thread.id); + if (role !== undefined) { + return `this thread is the standing role "${role.title}" and never settles - end your turn in one line; the user turns roles off in the dashboard (Settings -> Roles)`; + } const owing = world.live.filter((entry) => entry.toThreadId === thread.id); if (owing.length > 0) { const names = owing diff --git a/apps/server/src/t4/T4Store.ts b/apps/server/src/t4/T4Store.ts index 13dcce8047fd9..933222cf8dc42 100644 --- a/apps/server/src/t4/T4Store.ts +++ b/apps/server/src/t4/T4Store.ts @@ -182,6 +182,19 @@ const BOOT_ID = `${process.pid}-${process.hrtime.bigint().toString(36)}`; let callSeq = 0; /** A unique id for a logged tool call. */ export const newToolCallId = () => `call:${BOOT_ID}:${(callSeq += 1)}`; +/** A standing role (AI-140); `configJson` is T4Roles' RoleConfig. */ +export interface T4RoleRow { + readonly id: string; + readonly kind: string; + readonly title: string; + readonly projectId: string; + readonly threadId: string | null; + readonly enabled: boolean; + readonly configJson: string; + readonly createdAt: string; + readonly updatedAt: string; +} + /** The result a call cut by a restart is left with. */ export const CUT_RESULT = "cut by a restart"; @@ -305,6 +318,10 @@ export interface T4StoreShape { readonly meta: (key: string) => Effect.Effect; readonly setMeta: (key: string, value: string) => Effect.Effect; + readonly deleteMeta: (keyPrefix: string) => Effect.Effect; + readonly roles: () => Effect.Effect, StoreError>; + readonly upsertRole: (row: T4RoleRow) => Effect.Effect; + readonly deleteRole: (id: string) => Effect.Effect; } export class T4Store extends Context.Service()("t3/t4/T4Store") {} @@ -842,6 +859,53 @@ const make = Effect.gen(function* () { ON CONFLICT (key) DO UPDATE SET value = excluded.value `.pipe(Effect.asVoid); + const deleteMeta: T4StoreShape["deleteMeta"] = (keyPrefix) => + sql`DELETE FROM t4_meta WHERE substr(key, 1, ${keyPrefix.length}) = ${keyPrefix}`.pipe( + Effect.asVoid, + ); + + const roles: T4StoreShape["roles"] = () => + sql<{ + readonly id: string; + readonly kind: string; + readonly title: string; + readonly project_id: string; + readonly thread_id: string | null; + readonly enabled: number; + readonly config_json: string; + readonly created_at: string; + readonly updated_at: string; + }>`SELECT * FROM t4_roles ORDER BY created_at`.pipe( + Effect.map((rows) => + rows.map( + (row): T4RoleRow => ({ + id: row.id, + kind: row.kind, + title: row.title, + projectId: row.project_id, + threadId: row.thread_id, + enabled: row.enabled === 1, + configJson: row.config_json, + createdAt: row.created_at, + updatedAt: row.updated_at, + }), + ), + ), + ); + + const upsertRole: T4StoreShape["upsertRole"] = (row) => + sql` + INSERT INTO t4_roles (id, kind, title, project_id, thread_id, enabled, config_json, created_at, updated_at) + VALUES (${row.id}, ${row.kind}, ${row.title}, ${row.projectId}, ${row.threadId}, + ${row.enabled ? 1 : 0}, ${row.configJson}, ${row.createdAt}, ${row.updatedAt}) + ON CONFLICT (id) DO UPDATE SET kind = excluded.kind, title = excluded.title, + project_id = excluded.project_id, thread_id = excluded.thread_id, enabled = excluded.enabled, + config_json = excluded.config_json, updated_at = excluded.updated_at + `.pipe(Effect.asVoid); + + const deleteRole: T4StoreShape["deleteRole"] = (id) => + sql`DELETE FROM t4_roles WHERE id = ${id}`.pipe(Effect.asVoid); + return T4Store.of({ openHandoffs, allHandoffs, @@ -882,6 +946,10 @@ const make = Effect.gen(function* () { takeRestartToolCalls, meta, setMeta, + deleteMeta, + roles, + upsertRole, + deleteRole, }); }); diff --git a/apps/server/src/t4/threadCompaction.ts b/apps/server/src/t4/threadCompaction.ts new file mode 100644 index 0000000000000..2511247694b3d --- /dev/null +++ b/apps/server/src/t4/threadCompaction.ts @@ -0,0 +1,24 @@ +/** + * t4 fork (AI-140): a compaction point per thread. Standing roles and release + * managers run in one long session each; usa-rs's release manager sent ~286k + * tokens of context with every Codex request (3,172 requests, 2026-11-21..23) + * because Codex compacts only near its 475k window. T4Roles fills this table + * every minute; the provider adapters read it when a session starts or resumes. + */ + +/** Claude Code compacts this many tokens short of its `autoCompactWindow`. */ +export const CLAUDE_AUTO_COMPACT_RESERVE_TOKENS = 33_000; + +let table: ReadonlyMap = new Map(); + +export const setThreadCompaction = (next: ReadonlyMap): void => { + table = next; +}; + +/** Tokens at which this thread's provider session should compact, if t4 set one. */ +export const compactAtTokensFor = (threadId: string | null | undefined): number | undefined => + threadId === null || threadId === undefined ? undefined : table.get(threadId); + +/** Claude's `autoCompactWindow` setting that makes it compact at `compactAt` tokens. */ +export const claudeAutoCompactWindowFor = (compactAt: number): string => + String(Math.round(compactAt + CLAUDE_AUTO_COMPACT_RESERVE_TOKENS)); From c711c0d37c2525e1af11a69e451ae0147e328651 Mon Sep 17 00:00:00 2001 From: Maxwell Weinzierl Date: Mon, 23 Nov 2026 17:50:22 -0800 Subject: [PATCH 2/3] AI-140 Keep syncCompaction and the Claude reserve file-local (knip) --- apps/server/src/t4/T4Roles.ts | 2 +- apps/server/src/t4/threadCompaction.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/server/src/t4/T4Roles.ts b/apps/server/src/t4/T4Roles.ts index c3ff19266008e..0cbf971699ead 100644 --- a/apps/server/src/t4/T4Roles.ts +++ b/apps/server/src/t4/T4Roles.ts @@ -533,7 +533,7 @@ export const setReleaseManagerCompaction = Effect.fn("t4.T4Roles.setRmCompaction // ---------------------------------------------------------------- compaction /** Rebuilds the per-thread compaction table from the roles and release managers. */ -export const syncCompaction = Effect.gen(function* () { +const syncCompaction = Effect.gen(function* () { const store = yield* T4Store.T4Store; const rms = yield* store.releaseManagers(); const rows = yield* store.roles(); diff --git a/apps/server/src/t4/threadCompaction.ts b/apps/server/src/t4/threadCompaction.ts index 2511247694b3d..01bc99e6ce18d 100644 --- a/apps/server/src/t4/threadCompaction.ts +++ b/apps/server/src/t4/threadCompaction.ts @@ -7,7 +7,7 @@ */ /** Claude Code compacts this many tokens short of its `autoCompactWindow`. */ -export const CLAUDE_AUTO_COMPACT_RESERVE_TOKENS = 33_000; +const CLAUDE_AUTO_COMPACT_RESERVE_TOKENS = 33_000; let table: ReadonlyMap = new Map(); From b3b6383533dfef9a1a58ad8f931cd68535ee57db Mon Sep 17 00:00:00 2001 From: Maxwell Weinzierl Date: Mon, 23 Nov 2026 17:55:31 -0800 Subject: [PATCH 3/3] AI-140 Format and trim comments for the fork's lint --- .../src/mcp/toolkits/thread/handlers.ts | 3 +- apps/server/src/t4/T4Facts.ts | 7 +- apps/server/src/t4/T4Http.ts | 4 +- apps/server/src/t4/T4Roles.test.ts | 15 ++- apps/server/src/t4/T4Roles.ts | 107 +++++++++--------- apps/server/src/t4/T4Store.ts | 24 ++-- apps/server/src/t4/threadCompaction.ts | 7 +- 7 files changed, 91 insertions(+), 76 deletions(-) diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 47ebeeb8f485a..835b91be55456 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -421,7 +421,8 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { }); } // AI-140: a standing role stays visible as the release manager does. - const role = world === null ? undefined : T4Ledger.standingRoleOf(world, projection.thread.id); + const role = + world === null ? undefined : T4Ledger.standingRoleOf(world, projection.thread.id); if (role !== undefined) { return yield* new OrchestratorMcpFailure({ code: "invalid_request", diff --git a/apps/server/src/t4/T4Facts.ts b/apps/server/src/t4/T4Facts.ts index 92cd768f2c027..2e60fc3a279ae 100644 --- a/apps/server/src/t4/T4Facts.ts +++ b/apps/server/src/t4/T4Facts.ts @@ -65,7 +65,12 @@ export const factsFor = Effect.fn("t4.factsFor")(function* ( facts.set(id, { state: stateOf(thread, now), isReleaseManager: f.isReleaseManager, - role: roleOf(thread, f.isReleaseManager, roles, T4Ledger.standingRoleOf(world, id) !== undefined), + role: roleOf( + thread, + f.isReleaseManager, + roles, + T4Ledger.standingRoleOf(world, id) !== undefined, + ), roleKind: T4Ledger.standingRoleOf(world, id)?.kind ?? null, roleTitle: T4Ledger.standingRoleOf(world, id)?.title ?? null, parentThreadId: parents.get(id) ?? null, diff --git a/apps/server/src/t4/T4Http.ts b/apps/server/src/t4/T4Http.ts index 4501bac147411..c38c2f96f79c1 100644 --- a/apps/server/src/t4/T4Http.ts +++ b/apps/server/src/t4/T4Http.ts @@ -665,7 +665,9 @@ export const layer = Layer.mergeAll( route("POST", "/api/t4/roles/release-manager", AuthOrchestrationOperateScope, () => Effect.gen(function* () { const input = yield* body(T4Roles.RmCompactionBody); - return json({ releaseManager: yield* T4Roles.setReleaseManagerCompaction(input.compactAtTokens) }); + return json({ + releaseManager: yield* T4Roles.setReleaseManagerCompaction(input.compactAtTokens), + }); }), ), route("POST", "/api/t4/roles/:id/delete", AuthOrchestrationOperateScope, (params) => diff --git a/apps/server/src/t4/T4Roles.test.ts b/apps/server/src/t4/T4Roles.test.ts index efc4b28b3ee23..48169ad289689 100644 --- a/apps/server/src/t4/T4Roles.test.ts +++ b/apps/server/src/t4/T4Roles.test.ts @@ -2,7 +2,11 @@ import { assert, describe, it } from "@effect/vitest"; import { roleOf } from "./T4Facts.ts"; import { inQuietHours, mergeItems, triggerMessage } from "./T4Roles.ts"; -import { claudeAutoCompactWindowFor, compactAtTokensFor, setThreadCompaction } from "./threadCompaction.ts"; +import { + claudeAutoCompactWindowFor, + compactAtTokensFor, + setThreadCompaction, +} from "./threadCompaction.ts"; const empty = { state: "", @@ -63,12 +67,17 @@ describe("t4 roles", () => { assert.isTrue(inQuietHours(quiet, Date.parse("2026-11-24T14:59:00.000Z"))); assert.isFalse(inQuietHours(quiet, Date.parse("2026-11-24T15:00:00.000Z"))); assert.isFalse(inQuietHours(null, Date.parse("2026-11-24T06:30:00.000Z"))); - assert.isTrue(inQuietHours({ start: "12:00", end: "13:00" }, Date.parse("2026-11-23T20:30:00.000Z"))); + assert.isTrue( + inQuietHours({ start: "12:00", end: "13:00" }, Date.parse("2026-11-23T20:30:00.000Z")), + ); }); it("gives a standing role thread the role role", () => { assert.equal(roleOf({ id: "t", title: "Sentry watch PM" }, false, new Map(), true), "role"); - assert.equal(roleOf({ id: "t", title: "Release manager" }, true, new Map(), true), "release-manager"); + assert.equal( + roleOf({ id: "t", title: "Release manager" }, true, new Map(), true), + "release-manager", + ); }); it("keeps a compaction point per thread", () => { diff --git a/apps/server/src/t4/T4Roles.ts b/apps/server/src/t4/T4Roles.ts index 0cbf971699ead..27d3de2739894 100644 --- a/apps/server/src/t4/T4Roles.ts +++ b/apps/server/src/t4/T4Roles.ts @@ -1,22 +1,8 @@ // @effect-diagnostics processEnvInEffect:off -- trigger commands run with the container's env. /** - * t4 fork (AI-140): standing roles. A role is a persistent, pinned thread per client - like the - * release manager it never settles, snoozes or archives (T4Ledger.standingRoleOf) - that acts in - * a set way (its brief and its kind's `role-` skill) and wakes on: - * - * - check-ins: T3 scheduled tasks bound to its thread on t4's cron (server time zone, Pacific); - * - triggers: commands t4 runs every N minutes in the project's main checkout, which print the - * items that are new since their last run (`t4-probe`, or any command; contract below). New - * items are deduped per trigger, gathered for `batchMinutes`, and delivered as one message - * when the thread is idle, outside quiet hours and under the daily cap - no tokens are spent - * while nothing is new. A trigger's first run only records what it sees. - * - * Trigger command contract: `bash -c ` with T4_PROBE_STATE (the last run's `state`), - * T4_PROBE_SINCE (ISO time of the last good run), T4_ROLE_ID, T4_ROLE_KIND, T4_TRIGGER_ID; stdout - * `{"items":[{"id","title","url"?,"detail"?}],"state"?}`; non-zero exit or bad JSON = failed. - * - * It also keeps the per-thread compaction table (threadCompaction.ts) for roles and release - * managers: usa-rs's release manager carried ~286k tokens into every request. + * t4 fork (AI-140): standing roles - pinned threads that never settle, woken by check-ins + * (scheduled tasks bound to the thread) and by triggers: commands printing new items as + * `{"items":[{id,title,url?,detail?}],"state"?}`, deduped, batched and delivered as one message. */ import { CommandId, @@ -46,8 +32,6 @@ import * as T4Store from "./T4Store.ts"; import { isRunning, stateOf } from "./T4Threads.ts"; import { setThreadCompaction } from "./threadCompaction.ts"; -// ---------------------------------------------------------------- schemas - const CheckIn = Schema.Struct({ id: Schema.String, label: Schema.String, @@ -130,8 +114,6 @@ const CheckInIds = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Str const decodeCheckInIds = Schema.decodeEffect(CheckInIds); const encodeCheckInIds = Schema.encodeEffect(CheckInIds); -// ---------------------------------------------------------------- constants and pure helpers - const SEEN_MAX = 1000; const PENDING_MAX = 200; const ITEMS_PER_MESSAGE = 30; @@ -171,7 +153,10 @@ const pacificParts = (ms: number) => { hourCycle: "h23", }).formatToParts(ms); const get = (type: string) => parts.find((part) => part.type === type)?.value ?? "00"; - return { day: `${get("year")}-${get("month")}-${get("day")}`, minutes: Number(get("hour")) * 60 + Number(get("minute")) }; + return { + day: `${get("year")}-${get("month")}-${get("day")}`, + minutes: Number(get("hour")) * 60 + Number(get("minute")), + }; }; const minutesOf = (hhmm: string) => { @@ -222,7 +207,8 @@ export const triggerMessage = ( const title = item.url ? `[${item.title}](${item.url})` : item.title; return `- ${title}${item.detail ? ` - ${item.detail}` : ""}`; }); - const more = items.length > ITEMS_PER_MESSAGE ? [`- and ${items.length - ITEMS_PER_MESSAGE} more`] : []; + const more = + items.length > ITEMS_PER_MESSAGE ? [`- and ${items.length - ITEMS_PER_MESSAGE} more`] : []; return [`t4 role trigger - **${label}**: ${items.length} new`, ...lines, ...more].join("\n"); }); return `${sections.join("\n\n")}\n\nHandle them as your role skill says. If none needs anything, end your turn in one line.`; @@ -231,7 +217,9 @@ export const triggerMessage = ( const roleIntro = (role: T4Store.T4RoleRow, config: RoleConfig) => { const checkIns = config.checkIns.map((c) => `- ${c.label}: \`${c.cron}\``).join("\n") || "- none"; const triggers = - config.triggers.map((t) => `- ${t.label}: \`${t.command}\` every ${t.everyMinutes} min`).join("\n") || "- none"; + config.triggers + .map((t) => `- ${t.label}: \`${t.command}\` every ${t.everyMinutes} min`) + .join("\n") || "- none"; return [ `You are the standing role **${role.title}** (role id \`${role.id}\`, kind \`${role.kind}\`) for this client: a persistent thread that never settles.`, `Load the \`standing-role\` skill and the \`role-${role.kind}\` skill if there is one, and follow them. You run in the project's main checkout. Your notebook is \`~/.config/t4/roles/${role.id}.md\`.`, @@ -250,11 +238,11 @@ const roleIntro = (role: T4Store.T4RoleRow, config: RoleConfig) => { ].join("\n"); }; -// ---------------------------------------------------------------- reads - const readTriggerState = (store: T4Store.T4StoreShape, roleId: string, triggerId: string) => store.meta(triggerKey(roleId, triggerId)).pipe( - Effect.flatMap((text) => (text === undefined ? Effect.succeed(emptyTriggerState()) : decodeTriggerState(text))), + Effect.flatMap((text) => + text === undefined ? Effect.succeed(emptyTriggerState()) : decodeTriggerState(text), + ), Effect.orElseSucceed(emptyTriggerState), ); const writeTriggerState = ( @@ -270,9 +258,8 @@ const writeTriggerState = ( const readCheckInIds = (store: T4Store.T4StoreShape, roleId: string) => store.meta(checkInsKey(roleId)).pipe( - Effect.flatMap( - (text): Effect.Effect, unknown> => - text === undefined ? Effect.succeed({}) : decodeCheckInIds(text), + Effect.flatMap((text): Effect.Effect, unknown> => + text === undefined ? Effect.succeed({}) : decodeCheckInIds(text), ), Effect.orElseSucceed((): Record => ({})), ); @@ -315,7 +302,9 @@ export const listRoles = Effect.fn("t4.T4Roles.list")(function* () { const shell = row.threadId === null ? null - : yield* threads.getThreadShell(ThreadId.make(row.threadId)).pipe(Effect.orElseSucceed(() => null)); + : yield* threads + .getThreadShell(ThreadId.make(row.threadId)) + .pipe(Effect.orElseSucceed(() => null)); const ids = yield* readCheckInIds(store, row.id); const triggerStatus = []; for (const trigger of config.triggers) { @@ -356,8 +345,6 @@ export const listRoles = Effect.fn("t4.T4Roles.list")(function* () { return { roles, releaseManager: yield* rmCompaction }; }); -// ---------------------------------------------------------------- writes - const pinCommand = (type: "thread.pin" | "thread.unpin", threadId: string, uuid: string) => ({ type, commandId: CommandId.make(`t4:role-${type === "thread.pin" ? "pin" : "unpin"}:${uuid}`), @@ -418,17 +405,19 @@ export const saveRole = Effect.fn("t4.T4Roles.save")(function* (input: SaveRoleB const title = input.title.trim(); if (title === "") return { error: "a role needs a title" } as const; const project = Option.getOrUndefined( - yield* projects.getById(ProjectId.make(input.projectId)).pipe(Effect.orElseSucceed(() => Option.none())), + yield* projects + .getById(ProjectId.make(input.projectId)) + .pipe(Effect.orElseSucceed(() => Option.none())), ); if (project === undefined) return { error: "project not found" } as const; for (const trigger of input.config.triggers) { - if (!(trigger.everyMinutes >= 1)) return { error: `trigger "${trigger.label}" must run at most once a minute` } as const; + if (!(trigger.everyMinutes >= 1)) + return { error: `trigger "${trigger.label}" must run at most once a minute` } as const; } const rows = yield* store.roles(); const previous = input.id === undefined ? undefined : rows.find((row) => row.id === input.id); if (input.id !== undefined && previous === undefined) return { error: "role not found" } as const; - const modelSelection = - input.config.model ?? (yield* clientDefaultModelSelection(project.id)); + const modelSelection = input.config.model ?? (yield* clientDefaultModelSelection(project.id)); if (modelSelection === undefined || modelSelection === null) { return { error: "this client has no default model set - choose a model" } as const; } @@ -436,7 +425,9 @@ export const saveRole = Effect.fn("t4.T4Roles.save")(function* (input: SaveRoleB let threadId = previous?.threadId ?? null; // A role thread that was deleted is made again. if (threadId !== null) { - const shell = yield* threads.getThreadShell(ThreadId.make(threadId)).pipe(Effect.orElseSucceed(() => null)); + const shell = yield* threads + .getThreadShell(ThreadId.make(threadId)) + .pipe(Effect.orElseSucceed(() => null)); if (shell === null || shell.deletedAt !== null) threadId = null; } let row: T4Store.T4RoleRow = { @@ -475,7 +466,9 @@ export const saveRole = Effect.fn("t4.T4Roles.save")(function* (input: SaveRoleB yield* store.upsertRole(row); if (threadId !== null) { const uuid = yield* crypto.uuidV4().pipe(Effect.orDie); - yield* threads.dispatch(pinCommand(row.enabled ? "thread.pin" : "thread.unpin", threadId, uuid)).pipe(Effect.ignore); + yield* threads + .dispatch(pinCommand(row.enabled ? "thread.pin" : "thread.unpin", threadId, uuid)) + .pipe(Effect.ignore); if (previous !== undefined && previous.title !== title) { yield* threads .dispatch({ @@ -492,7 +485,8 @@ export const saveRole = Effect.fn("t4.T4Roles.save")(function* (input: SaveRoleB const kept = new Set(input.config.triggers.map((trigger) => trigger.id)); const before = previous === undefined ? undefined : yield* configOf(previous); for (const trigger of before?.triggers ?? []) { - if (!kept.has(trigger.id)) yield* store.deleteMeta(triggerKey(id, trigger.id)).pipe(Effect.ignore); + if (!kept.has(trigger.id)) + yield* store.deleteMeta(triggerKey(id, trigger.id)).pipe(Effect.ignore); } yield* syncCompaction; return { role: { ...row, config: input.config } } as const; @@ -524,14 +518,13 @@ export const setReleaseManagerCompaction = Effect.fn("t4.T4Roles.setRmCompaction compactAtTokens: number | null, ) { const store = yield* T4Store.T4Store; - const value = compactAtTokens !== null && compactAtTokens > 0 ? String(Math.round(compactAtTokens)) : ""; + const value = + compactAtTokens !== null && compactAtTokens > 0 ? String(Math.round(compactAtTokens)) : ""; yield* store.setMeta(RM_COMPACT_KEY, value); yield* syncCompaction; return yield* rmCompaction; }); -// ---------------------------------------------------------------- compaction - /** Rebuilds the per-thread compaction table from the roles and release managers. */ const syncCompaction = Effect.gen(function* () { const store = yield* T4Store.T4Store; @@ -551,8 +544,6 @@ const syncCompaction = Effect.gen(function* () { setThreadCompaction(table); }).pipe(Effect.ignoreCause({ log: true })); -// ---------------------------------------------------------------- triggers - const runProbe = Effect.fn("t4.T4Roles.runProbe")(function* ( row: T4Store.T4RoleRow, trigger: RoleConfig["triggers"][number], @@ -592,10 +583,14 @@ const runProbe = Effect.fn("t4.T4Roles.runProbe")(function* ( const out = result.success; if (out.timedOut) return { next: failed("timed out after 60 s"), added: 0 }; if (out.code !== 0) { - return { next: failed(`exit ${out.code}: ${out.stderr.trim() || out.stdout.trim()}`), added: 0 }; + return { + next: failed(`exit ${out.code}: ${out.stderr.trim() || out.stdout.trim()}`), + added: 0, + }; } const parsed = yield* decodeProbe(out.stdout.trim()).pipe(Effect.result); - if (Result.isFailure(parsed)) return { next: failed(`not the trigger JSON: ${out.stdout.trim().slice(0, 200)}`), added: 0 }; + if (Result.isFailure(parsed)) + return { next: failed(`not the trigger JSON: ${out.stdout.trim().slice(0, 200)}`), added: 0 }; const merged = mergeItems(previous, parsed.success.items, nowMs); return { next: { @@ -651,7 +646,8 @@ const tickRole = Effect.fn("t4.T4Roles.tickRole")(function* ( // Failing triggers: one note after a few failures in a row, at most every 6 h. for (const trigger of config.triggers) { const state = states.get(trigger.id)!; - if (state.failures < FAIL_NOTE_AFTER || now - msOf(state.lastFailNoteAt) < FAIL_NOTE_EVERY_MS) continue; + if (state.failures < FAIL_NOTE_AFTER || now - msOf(state.lastFailNoteAt) < FAIL_NOTE_EVERY_MS) + continue; yield* delivery .deliver({ target: shell, @@ -692,7 +688,10 @@ const tickRole = Effect.fn("t4.T4Roles.tickRole")(function* ( if (inQuietHours(config.quietHours, now)) return 0; if ((yield* turnsToday(store, row.id, now)) >= config.maxTriggerTurnsPerDay) return 0; } - const batches = ready.map((trigger) => ({ label: trigger.label, items: states.get(trigger.id)!.pending })); + const batches = ready.map((trigger) => ({ + label: trigger.label, + items: states.get(trigger.id)!.pending, + })); const delivered = yield* delivery .deliver({ target: shell, @@ -702,7 +701,10 @@ const tickRole = Effect.fn("t4.T4Roles.tickRole")(function* ( createdBy: "system", creationSource: "server", }) - .pipe(Effect.as(true), Effect.orElseSucceed(() => false)); + .pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); if (!delivered) return 0; let count = 0; for (const trigger of ready) { @@ -731,7 +733,9 @@ const runtimes = Effect.gen(function* () { const config = yield* configOf(row); if (config === undefined) continue; const project = Option.getOrUndefined( - yield* projects.getById(ProjectId.make(row.projectId)).pipe(Effect.orElseSucceed(() => Option.none())), + yield* projects + .getById(ProjectId.make(row.projectId)) + .pipe(Effect.orElseSucceed(() => Option.none())), ); if (project === undefined) continue; out.push({ row, config, cwd: project.workspaceRoot }); @@ -775,4 +779,3 @@ export const standingRolesForState = Effect.gen(function* () { } return out; }).pipe(Effect.orElseSucceed(() => ({}))); - diff --git a/apps/server/src/t4/T4Store.ts b/apps/server/src/t4/T4Store.ts index 933222cf8dc42..fd390580f1313 100644 --- a/apps/server/src/t4/T4Store.ts +++ b/apps/server/src/t4/T4Store.ts @@ -877,19 +877,17 @@ const make = Effect.gen(function* () { readonly updated_at: string; }>`SELECT * FROM t4_roles ORDER BY created_at`.pipe( Effect.map((rows) => - rows.map( - (row): T4RoleRow => ({ - id: row.id, - kind: row.kind, - title: row.title, - projectId: row.project_id, - threadId: row.thread_id, - enabled: row.enabled === 1, - configJson: row.config_json, - createdAt: row.created_at, - updatedAt: row.updated_at, - }), - ), + rows.map((row): T4RoleRow => ({ + id: row.id, + kind: row.kind, + title: row.title, + projectId: row.project_id, + threadId: row.thread_id, + enabled: row.enabled === 1, + configJson: row.config_json, + createdAt: row.created_at, + updatedAt: row.updated_at, + })), ), ); diff --git a/apps/server/src/t4/threadCompaction.ts b/apps/server/src/t4/threadCompaction.ts index 01bc99e6ce18d..b0be4f2e4882b 100644 --- a/apps/server/src/t4/threadCompaction.ts +++ b/apps/server/src/t4/threadCompaction.ts @@ -1,9 +1,6 @@ /** - * t4 fork (AI-140): a compaction point per thread. Standing roles and release - * managers run in one long session each; usa-rs's release manager sent ~286k - * tokens of context with every Codex request (3,172 requests, 2026-11-21..23) - * because Codex compacts only near its 475k window. T4Roles fills this table - * every minute; the provider adapters read it when a session starts or resumes. + * t4 fork (AI-140): a compaction point per thread for standing roles and release managers, + * filled by T4Roles every minute and read by the provider adapters at session start or resume. */ /** Claude Code compacts this many tokens short of its `autoCompactWindow`. */