Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/architecture/org-staffing.md
Original file line number Diff line number Diff line change
Expand Up @@ -1094,7 +1094,7 @@ Written 2026-09-29, replacing escalation (`cast escalate`, org-roles-run-work.md

**The route.** A session under a role that is waiting on anyone, for any reason (an open prompt, a stopped process, a declared blocked state, a question asked in prose), fires its role's needs-input trigger (S25): one run per ask, where a declared block is one ask per pinned state line and a stall is one per settle, and the key clears when the session works again (`agentTasks.routeUpWaitingSession`). Any agent can also write to a role with `cast role wake @handle "<the request>"`. The role answers when it can. A role that cannot answer tells the role it reports to the same way: its own waiting fires its parent's trigger, speaking as the role. The role that reports to a person raises it in its own thread and nowhere else: its pinned state says what the person will decide and why (`cast state --status blocked`), and a real choice between options is a `cast decide` card posted there with the role's recommendation. That card reaches the person the role reports to, not whoever hosts its session.

**A decision travels the same way.** A `cast decide` posted by a session under a role fires that role's needs-input trigger, naming the session and the question (the waiting session's reason is "decision", with its short id); the role answers it when it holds the grant, or hands the same card up to its people: with the option it recommends, or passed up with no recommendation, and either way with a note giving the person what the role knows that the card does not say. The note shows on the role's line of the card's ladder; there is no second card and no separate surface. A role that does neither within five minutes hands it up by lapse, so a decision never waits on a role that stays silent. It reaches a person's queue at once only when the role cannot be told. A decision posted by a lead that reports to a person goes to that person.
**A decision travels the same way.** A `cast decide` posted by a session under a role fires that role's needs-input trigger, naming the session and the question (the waiting session's reason is "decision", with its short id); the role answers it when it holds the grant, or hands the same card up to its people: with the option it recommends, or passed up with no recommendation, and either way with a note giving the person what the role knows that the card does not say. The note shows on the role's line of the card's ladder; there is no second card and no separate surface. A role that does neither within five minutes hands it up by lapse, so a decision never waits on a role that stays silent. It reaches a person's queue at once only when the role cannot be told. A decision posted by a lead that reports to a person goes to that person; one posted by a sub-lead goes, after its parent lead, to the person the line ends at, never to whoever started the sub-lead's seat. A decision that climbs a reporting line is never shared out by decision areas: areas route only what the org chart does not (`decisionRouting.routeByArea`).

**A role's own session belongs to whom the role reports to.** Reporting to someone is being in their inbox, so there is one fact, `reports_to`, and the standing session's owners follow it (`sessionOwners.stampSeatOwners`, called wherever a role's parent is set: provisioning, a move, a retire's re-home, the backfill `migrations:stampStandingSeats`). Under a person, that person is its only owner; under a role, it has no person owner and rides the parent lead's card. The owner gesture on a standing session refuses and names the role move, the owner menu there offers "Reports to" instead of an owner list, and writing to it never claims it. The machine and account it runs on stay separate: that is where it runs, not whom it answers to.

Expand Down
34 changes: 30 additions & 4 deletions packages/convex/convex/decisionRouting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,36 @@ describe("ask time: the project picks its members", () => {
expect(askedOf(tables, none.id)).toEqual([HOST]);
});

test("a role scope's project, then the session's work, when there is no task", async () => {
test("the session's work, when there is no task", async () => {
const { ctx, tables } = seed();
const byRole = await ask(ctx, { session_id: "sess-role" });
expect(askedOf(tables, byRole.id)).toEqual([KIM]);
const bySession = await ask(ctx, { session_id: "sess-desk" });
expect(askedOf(tables, bySession.id)).toEqual([KIM]);
});

test("a session under a role follows the org chart, never an area", async () => {
const { ctx, tables } = seed();
// The Desk lead reports to HOST; Kim covers Desk and Deals is Sam's and Jas's.
for (const task of [undefined, "ct-1", "ct-2"]) {
const r = await ask(ctx, { session_id: "sess-role", ...(task ? { task } : {}) });
expect(askedOf(tables, r.id)).toEqual([HOST]);
}
expect(tables.notifications.filter((x: any) => x.type === "decision_assigned")).toEqual([]);
});

test("a lead that reports to a person asks that person, never an area, on ask and on reroute", async () => {
const { ctx, tables } = seed();
// The Desk lead's own seat: it reports to HOST, so its ladder is empty.
tables.conversations.push({ _id: "conversations_seat", session_id: "sess-seat", user_id: HOST, team_id: TEAM, message_count: 1, standing_role_id: "org_roles_desk" });
const r = await ask(ctx, { session_id: "sess-seat", task: "ct-2" });
expect(row(tables, r.id).hops).toEqual([]);
expect(askedOf(tables, r.id)).toContain(HOST);
expect(askedOf(tables, r.id)).not.toContain(KIM);
await reroutePendingDecisionsForConversation(ctx, "conversations_seat" as any, NOW);
expect(askedOf(tables, r.id)).toContain(HOST);
expect(askedOf(tables, r.id)).not.toContain(KIM);
expect(tables.notifications.filter((x: any) => x.type === "decision_assigned")).toEqual([]);
});

test("the area owner is told, once, and the asker never", async () => {
const { ctx, tables } = seed();
const r = await ask(ctx, { task: "ct-2" });
Expand Down Expand Up @@ -305,7 +327,11 @@ describe("Share out", () => {
open("session_decisions_loose", { task_id: "tasks_loose" }),
open("session_decisions_named", { addressed: true }),
open("session_decisions_prod", { category: "production" }),
open("session_decisions_charted", { hops: [{ role_id: "org_roles_desk", at: NOW - 100 }] }),
// The Desk lead's own seat reports to HOST: no ladder, still the org chart's.
open("session_decisions_seat", { conversation_id: "conversations_seat", session_id: "sess-seat", task_id: "tasks_desk", hops: [] }),
);
s.tables.conversations.push({ _id: "conversations_seat", session_id: "sess-seat", user_id: HOST, team_id: TEAM, message_count: 1, standing_role_id: "org_roles_desk" });
return s;
};

Expand All @@ -329,7 +355,7 @@ describe("Share out", () => {
expect(askedOf(tables, m.decision_id)).toEqual([m.to]);
expect(row(tables, m.decision_id).holder_key).toBe(`user:${m.to}`);
}
for (const kept of ["session_decisions_loose", "session_decisions_named", "session_decisions_prod"]) expect(askedOf(tables, kept)).toEqual([HOST]);
for (const kept of ["session_decisions_loose", "session_decisions_named", "session_decisions_prod", "session_decisions_charted", "session_decisions_seat"]) expect(askedOf(tables, kept)).toEqual([HOST]);
// One notice per person.
const notes = tables.notifications.filter((x: any) => x.type === "decision_assigned");
expect(notes.map((x: any) => String(x.recipient_user_id)).sort()).toEqual([JAS, KIM, SAM].sort());
Expand Down
24 changes: 13 additions & 11 deletions packages/convex/convex/decisionRouting.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Sharing decisions out by area (contracts/decisionAreas). At ask time an
// unaddressed decision's project picks the members covering it: its task's
// project, else its role scope's, else its session's. The member with the
// Sharing decisions out by area (contracts/decisionAreas): the fallback for a
// decision the org chart does not route. A decision that climbs a reporting
// line (its session is or works under a role) goes to the person that line
// ends at, never to an area. At ask time any other unaddressed decision's
// project picks the members covering it: its task's project, else its
// session's. The member with the
// fewest decisions waiting in their queue owns it; a tie goes to whoever was
// given one longest ago (both read from decision_inbox, memberLoad); members who are away, who take no decisions, and bots are skipped.
// No match leaves the ask on the chain it always had (sessionDecisions
Expand Down Expand Up @@ -64,14 +67,12 @@ export async function readLoads(ctx: Ctx, members: AreaMemberRow[]): Promise<voi
for (const m of members) Object.assign(m, await memberLoad(ctx, m.user_id));
}

/** The projects a decision is about: its task's, else its role scope's, else its session's work. */
export async function areaProjectsOf(ctx: Ctx, a: { task?: any; role?: { scope?: { project_ids?: Id<"projects">[] } } | null; conversation?: any }): Promise<string[]> {
/** The projects a decision is about: its task's, else its session's work. */
export async function areaProjectsOf(ctx: Ctx, a: { task?: any; conversation?: any }): Promise<string[]> {
if (a.task) {
const work = await taskWork(ctx, a.task);
if (work.project_id) return [String(work.project_id)];
}
const scope = a.role?.scope?.project_ids ?? [];
if (scope.length) return scope.map(String);
const work = a.conversation ? await sessionWork(ctx, a.conversation) : {};
return work.project_id ? [String(work.project_id)] : [];
}
Expand All @@ -90,26 +91,27 @@ export function teamReadsDecision(conversation: any, task: any, workflowRunId: u
export type AreaRouteArgs = {
conversation: any;
task: any;
role: any;
category: string;
team_id: Id<"teams"> | undefined;
/** Asked of named people (--to). */
addressed: boolean;
/** A trial's decision (routeFor's trial). */
trial: string | null;
/** The asking session is a role's seat or works under one, or the decision climbs a ladder: the org chart routes it, not areas. */
charted: boolean;
workflow_run_id?: unknown;
/** A re-ask keeps its owner while they still cover its project. */
keep?: Id<"users">;
now: number;
};

/**
* The person an unaddressed decision is shared out to, or null to leave it
* on the chain it always had. A workspace with no areas set yet asks its
* The person an unaddressed decision off the org chart is shared out to, or
* null to leave it on the chain it always had. A workspace with no areas set yet asks its
* admins who decides for which areas (decisionAreas.scheduleAreasCard) instead.
*/
export async function routeByArea(ctx: Ctx, a: AreaRouteArgs): Promise<Id<"users"> | null> {
if (!a.team_id || a.addressed || a.trial || isHostedAgentType(a.conversation.agent_type) || isProtectedCategory(a.category)) return null;
if (!a.team_id || a.charted || a.addressed || a.trial || isHostedAgentType(a.conversation.agent_type) || isProtectedCategory(a.category)) return null;
if (!teamReadsDecision(a.conversation, a.task, a.workflow_run_id, a.team_id)) return null;
const members = await teamAreaMembers(ctx, a.team_id);
if (members.length === 0) {
Expand Down
10 changes: 6 additions & 4 deletions packages/convex/convex/decisionShareOut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import { getAuthUserId } from "@convex-dev/auth/server";
import { isHostedAgentType } from "@codecast/shared/contracts";
import { decisionOwnerOf, planShareOut, type ShareOutMove, type ShareOutRow } from "@codecast/shared/contracts/decisionAreas";
import { isProtectedCategory } from "./lib/decisionCategory";
import { syncDecisionInbox } from "./lib/decisionInbox";
import { roleOfConversation } from "./lib/actor";
import { syncDecisionInbox } from "./lib/decisionInbox";
import { areaProjectsOf, noticeAreaOwner, readLoads, teamAreaMembers, teamReadsDecision } from "./decisionRouting";

type Ctx = { db: any; scheduler?: any };
Expand All @@ -44,9 +44,11 @@ async function requireAdmin(ctx: Ctx, userId: Id<"users">, teamId: Id<"teams">):
/** Whether Share out may move this decision at all (the header's list). */
async function movable(ctx: Ctx, d: DecisionRow, teamId: Id<"teams">): Promise<{ conversation: any; task: any } | null> {
if (d.status !== "pending" || d.trial || d.silent || d.passed_to || d.escalated || d.addressed) return null;
if (isProtectedCategory(d.category) || d.holder?.kind === "role") return null;
// A decision that climbs a reporting line is the org chart's to route, never an area's.
if (isProtectedCategory(d.category) || d.holder?.kind === "role" || d.hops?.length) return null;
const conversation = await ctx.db.get(d.conversation_id);
if (!conversation || isHostedAgentType(conversation.agent_type)) return null;
// A role's own seat (a lead that reports to a person climbs no ladder) is on the chart too.
if (!conversation || isHostedAgentType(conversation.agent_type) || (await roleOfConversation(ctx, conversation))) return null;
const task = d.task_id ? await ctx.db.get(d.task_id) : null;
if (!teamReadsDecision(conversation, task, d.workflow_run_id, teamId)) return null;
return { conversation, task };
Expand All @@ -66,7 +68,7 @@ async function planFor(ctx: Ctx, teamId: Id<"teams">, now: number): Promise<{ mo
rows.set(String(d._id), d);
input.push({
id: String(d._id),
project_ids: await areaProjectsOf(ctx, { task: ok.task, role: await roleOfConversation(ctx, ok.conversation), conversation: ok.conversation }),
project_ids: await areaProjectsOf(ctx, { task: ok.task, conversation: ok.conversation }),
owner: owner?.kind === "user" ? owner.id : null,
created_at: d.created_at,
});
Expand Down
36 changes: 25 additions & 11 deletions packages/convex/convex/sessionDecisions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,26 +167,40 @@ describe("ask: people, inbox, ladder, holder", () => {
expect(tables.decision_inbox.map((i: any) => i.user_id)).toEqual([BOSS]);
});

test("a standing session asks its owners, not the runner or the role parent", async () => {
test("a standing sub-lead asks its owners and the person its line ends at, not the runner", async () => {
const { ctx, tables } = seed();
const r = await askApproach(ctx, "sess-standing");
expect(r.error).toBeUndefined();
const row = tables.session_decisions[0];
expect(row.asked_user_ids).toEqual([OWNER2]);
expect(row.asked_user_ids).toEqual([OWNER2, BOSS]);
expect(row.holder).toEqual({ kind: "user", id: OWNER2 });
expect(tables.decision_inbox.map((i) => i.user_id)).toEqual([OWNER2]);
expect(tables.decision_inbox.map((i) => i.user_id)).toEqual([OWNER2, BOSS]);
expect((await listForUserCore(ctx, HOST, NOW)).map((d) => d._id)).toEqual([]);
expect((await listForUserCore(ctx, OWNER2, NOW)).map((d) => d._id)).toEqual([row._id]);
expect((await listForUserCore(ctx, BOSS, NOW)).map((d) => d._id)).toEqual([]);
expect((await listForUserCore(ctx, BOSS, NOW)).map((d) => d._id)).toEqual([row._id]);
});

test("a sub-lead seat nobody owns asks the person its line ends at, never whoever started it", async () => {
const { ctx, tables } = seed();
await ctx.db.patch("conversations_standing", { owner_user_id: undefined, author_user_id: OWNER2 });
for (const row of await ctx.db.query("session_owners").withIndex("by_conversation", (q: any) => q.eq("conversation_id", "conversations_standing")).collect()) {
await ctx.db.delete(row._id);
}
const r = await askApproach(ctx, "sess-standing");
expect(r.error).toBeUndefined();
const row = tables.session_decisions[0];
expect(row.asked_user_ids).toEqual([BOSS]);
expect(row.hops.map((h: any) => h.role_id)).toEqual(["org_roles_head"]);
expect((await listForUserCore(ctx, OWNER2, NOW)).map((d) => d._id)).toEqual([]);
});

test("a stale owner_user_id cache does not keep a standing session's questions on the runner", async () => {
const { ctx, tables } = seed();
await ctx.db.patch("conversations_standing", { owner_user_id: HOST });
const r = await askApproach(ctx, "sess-standing");
expect(r.error).toBeUndefined();
expect(tables.session_decisions[0].asked_user_ids).toEqual([OWNER2]);
expect(tables.decision_inbox.map((i) => i.user_id)).toEqual([OWNER2]);
expect(tables.session_decisions[0].asked_user_ids).toEqual([OWNER2, BOSS]);
expect(tables.decision_inbox.map((i) => i.user_id)).toEqual([OWNER2, BOSS]);
expect((await listForUserCore(ctx, HOST, NOW)).map((d) => d._id)).toEqual([]);
});

Expand All @@ -200,7 +214,7 @@ describe("ask: people, inbox, ladder, holder", () => {
expect((await listForUserCore(ctx, OWNER2, NOW)).map((d) => d._id)).toEqual([id]);
});

test("assigning a standing session moves questions off the runner and the role parent", async () => {
test("assigning a standing session moves questions off the runner, and the line's person keeps them", async () => {
const { ctx, tables } = seed();
await ctx.db.patch("conversations_standing", { owner_user_id: HOST });
for (const row of await ctx.db.query("session_owners").withIndex("by_conversation", (q: any) => q.eq("conversation_id", "conversations_standing")).collect()) {
Expand All @@ -210,7 +224,7 @@ describe("ask: people, inbox, ladder, holder", () => {
const r = await askApproach(ctx, "sess-standing");
expect(r.error).toBeUndefined();
const id = tables.session_decisions[0]._id;
expect(tables.session_decisions[0].asked_user_ids).toEqual([HOST]);
expect(tables.session_decisions[0].asked_user_ids).toEqual([HOST, BOSS]);
expect((await listForUserCore(ctx, HOST, NOW)).map((d) => d._id)).toEqual([id]);

await ctx.db.patch("conversations_standing", { owner_user_id: OWNER2 });
Expand All @@ -220,10 +234,10 @@ describe("ask: people, inbox, ladder, holder", () => {
await ctx.db.insert("session_owners", { _id: "so_stand_new", conversation_id: "conversations_standing", user_id: OWNER2, added_by: HOST, added_at: NOW });
const moved = await reroutePendingDecisionsForConversation(ctx, "conversations_standing" as any, NOW);
expect(moved.moved).toBe(1);
expect(tables.session_decisions[0].asked_user_ids).toEqual([OWNER2]);
expect(tables.decision_inbox.map((i) => i.user_id)).toEqual([OWNER2]);
expect(tables.session_decisions[0].asked_user_ids).toEqual([OWNER2, BOSS]);
expect(tables.decision_inbox.map((i) => i.user_id).sort()).toEqual([BOSS, OWNER2].sort());
expect((await listForUserCore(ctx, HOST, NOW)).map((d) => d._id)).toEqual([]);
expect((await listForUserCore(ctx, BOSS, NOW)).map((d) => d._id)).toEqual([]);
expect((await listForUserCore(ctx, BOSS, NOW)).map((d) => d._id)).toEqual([id]);
expect((await listForUserCore(ctx, OWNER2, NOW)).map((d) => d._id)).toEqual([id]);
});

Expand Down
Loading
Loading