Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions apps/server/src/mcp/toolkits/thread/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,15 @@ 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;
Expand Down
13 changes: 12 additions & 1 deletion apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
? {}
: {
Expand Down
4 changes: 3 additions & 1 deletion apps/server/src/t4/T4AutoArchive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/t4/T4Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<worktrees>/<issue id or slug>` (t4); `branch`: upstream. */
Expand All @@ -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<Record<string, ModelSelection>>;
readonly stallRecovery: {
Expand All @@ -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 },
Expand All @@ -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: {
Expand Down
16 changes: 14 additions & 2 deletions apps/server/src/t4/T4Facts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -23,8 +23,10 @@ export const roleOf = (
thread: { readonly id: string; readonly title: string },
isReleaseManager: boolean,
given: ReadonlyMap<string, string>,
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";
Expand All @@ -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;
Expand All @@ -60,7 +65,14 @@ 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,
Expand Down
39 changes: 39 additions & 0 deletions apps/server/src/t4/T4Http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -644,6 +647,42 @@ 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
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/t4/T4Jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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),
Expand Down
21 changes: 21 additions & 0 deletions apps/server/src/t4/T4Ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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). */
Expand All @@ -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<Shell>;
readonly byId: ReadonlyMap<string, Shell>;
readonly releaseManagers: ReadonlySet<string>;
/** Thread id -> its standing role (AI-140); absent in older fixtures. */
readonly standingRoles?: ReadonlyMap<string, T4StandingRole>;
readonly open: ReadonlyArray<T4Store.T4Handoff>;
readonly live: ReadonlyArray<T4Store.T4Handoff>;
}
Expand Down Expand Up @@ -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),
};
Expand Down
20 changes: 20 additions & 0 deletions apps/server/src/t4/T4Migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({});
Expand Down
Loading
Loading