ftown-bridge 0.25.3 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/attention-cli.d.ts +32 -0
  2. package/dist/attention-cli.js +310 -0
  3. package/dist/attention-cli.js.map +1 -0
  4. package/dist/attention-events.d.ts +2 -1
  5. package/dist/attention-events.js.map +1 -1
  6. package/dist/attention-store.d.ts +6 -3
  7. package/dist/attention-store.js +60 -2
  8. package/dist/attention-store.js.map +1 -1
  9. package/dist/brief-cli.d.ts +10 -0
  10. package/dist/brief-cli.js +163 -0
  11. package/dist/brief-cli.js.map +1 -0
  12. package/dist/command-rpc.js +18 -15
  13. package/dist/command-rpc.js.map +1 -1
  14. package/dist/coordination/attention-routing.d.ts +37 -0
  15. package/dist/coordination/attention-routing.js +154 -0
  16. package/dist/coordination/attention-routing.js.map +1 -0
  17. package/dist/coordination/board.d.ts +12 -0
  18. package/dist/coordination/board.js +240 -0
  19. package/dist/coordination/board.js.map +1 -0
  20. package/dist/coordination/card-store.d.ts +9 -0
  21. package/dist/coordination/card-store.js +188 -0
  22. package/dist/coordination/card-store.js.map +1 -0
  23. package/dist/coordination/contract-b.d.ts +206 -0
  24. package/dist/coordination/contract-b.js +58 -0
  25. package/dist/coordination/contract-b.js.map +1 -0
  26. package/dist/coordination/contract.d.ts +236 -0
  27. package/dist/coordination/contract.js +63 -0
  28. package/dist/coordination/contract.js.map +1 -0
  29. package/dist/coordination/format.d.ts +5 -0
  30. package/dist/coordination/format.js +73 -0
  31. package/dist/coordination/format.js.map +1 -0
  32. package/dist/coordination/routes-brief.d.ts +10 -0
  33. package/dist/coordination/routes-brief.js +149 -0
  34. package/dist/coordination/routes-brief.js.map +1 -0
  35. package/dist/coordination/routes-worktrees.d.ts +29 -0
  36. package/dist/coordination/routes-worktrees.js +138 -0
  37. package/dist/coordination/routes-worktrees.js.map +1 -0
  38. package/dist/coordination/tree-events.d.ts +31 -0
  39. package/dist/coordination/tree-events.js +226 -0
  40. package/dist/coordination/tree-events.js.map +1 -0
  41. package/dist/coordination/wiring.d.ts +57 -0
  42. package/dist/coordination/wiring.js +165 -0
  43. package/dist/coordination/wiring.js.map +1 -0
  44. package/dist/coordination-cli.d.ts +34 -0
  45. package/dist/coordination-cli.js +466 -0
  46. package/dist/coordination-cli.js.map +1 -0
  47. package/dist/create-ftown-session.d.ts +8 -1
  48. package/dist/create-ftown-session.js +164 -104
  49. package/dist/create-ftown-session.js.map +1 -1
  50. package/dist/ftown-cli.js +18 -2
  51. package/dist/ftown-cli.js.map +1 -1
  52. package/dist/index.js +34 -7
  53. package/dist/index.js.map +1 -1
  54. package/dist/local-api-server.d.ts +30 -1
  55. package/dist/local-api-server.js +740 -32
  56. package/dist/local-api-server.js.map +1 -1
  57. package/dist/mail-delivery.d.ts +34 -6
  58. package/dist/mail-delivery.js +381 -85
  59. package/dist/mail-delivery.js.map +1 -1
  60. package/dist/mail-store.d.ts +7 -0
  61. package/dist/mail-store.js +71 -1
  62. package/dist/mail-store.js.map +1 -1
  63. package/dist/pull-request-events.d.ts +5 -0
  64. package/dist/pull-request-events.js +21 -1
  65. package/dist/pull-request-events.js.map +1 -1
  66. package/dist/security/bridge/permissions.js +54 -4
  67. package/dist/security/bridge/permissions.js.map +1 -1
  68. package/dist/session-controller.d.ts +17 -1
  69. package/dist/session-controller.js +93 -2
  70. package/dist/session-controller.js.map +1 -1
  71. package/dist/sessions-commands.js +65 -5
  72. package/dist/sessions-commands.js.map +1 -1
  73. package/dist/types.d.ts +10 -1
  74. package/dist/wire-types.d.ts +17 -1
  75. package/dist/wire-types.js +1 -1
  76. package/dist/wire-types.js.map +1 -1
  77. package/dist/worktrees-cli.d.ts +39 -0
  78. package/dist/worktrees-cli.js +168 -0
  79. package/dist/worktrees-cli.js.map +1 -0
  80. package/dist/worktrees.d.ts +16 -0
  81. package/dist/worktrees.js +292 -0
  82. package/dist/worktrees.js.map +1 -0
  83. package/hooks/ftown-antigravity-hook.sh +12 -6
  84. package/package.json +2 -2
  85. package/skills/ftown/SKILL.md +75 -9
  86. package/skills/ftown/references/orchestrator.md +27 -23
  87. package/skills/ftown/references/sessions.md +136 -11
@@ -0,0 +1,206 @@
1
+ /**
2
+ * FROZEN CONTRACT — coordination phase B: parent-first attention, manager brief +
3
+ * dashboard overview, optional bridge-owned worktrees. Types/constants/interfaces only.
4
+ * Implementers must not modify this file.
5
+ */
6
+ import type { IncomingMessage, ServerResponse } from 'node:http';
7
+ import type { AttentionAnswer, AttentionPrompt } from '../attention-prompt-protocol.js';
8
+ import type { AttentionItem } from '../attention-events.js';
9
+ import type { Session } from '../types.js';
10
+ /**
11
+ * Routing rules (single hop; the tree is one level deep):
12
+ * - An attention item created by a session S (POST /api/sessions/:id/attention or /ask) gets
13
+ * route 'parent' iff S.parentSessionId is set, the parent session exists, status 'running',
14
+ * shellType !== 'shell', runner reports it running, AND the request did not ask `to: 'human'`.
15
+ * Otherwise route 'human' (today's behaviour).
16
+ * - route 'parent': NO dashboard notice publish and NO push for this item. The parent receives ONE
17
+ * waking mail, type 'escalation', from S, body = PARENT_QUESTION_MAIL(...) below. A tree event
18
+ * kind 'attention' is emitted (phase A already emits it). S's card is untouched (the agent may set it).
19
+ * The item IS visible in the human's inbox (greyed "with parent"), and the human may still answer it.
20
+ * - The parent answers → item answered exactly as a human answer (same delivery: live waiter or
21
+ * mail from "You"; for parent answers the mail sender is the parent session), plus answeredBy.
22
+ * - The parent escalates (or the parent exits/stops/errors while the item is open and route==='parent')
23
+ * → route flips to 'human', escalatedAt set, escalationNote set (parent note, or PARENT_UNAVAILABLE_NOTE),
24
+ * and the normal dashboard notice + push flow fires NOW, as if the item had just been created.
25
+ * - No timers. Only the parent (or parent unavailability) moves an item to the human.
26
+ * - Repeating an identical open request keeps its current route (occurrence count only).
27
+ */
28
+ export type AttentionRoute = 'parent' | 'human';
29
+ export interface AttentionAnsweredBy {
30
+ kind: 'human' | 'session';
31
+ sessionId?: string;
32
+ name?: string;
33
+ }
34
+ /** Fields added to AttentionItem (declared optional on AttentionItem in attention-events.ts). */
35
+ export interface AttentionRoutingFields {
36
+ route?: AttentionRoute;
37
+ routedTo?: string;
38
+ escalatedAt?: string;
39
+ escalationNote?: string;
40
+ answeredBy?: AttentionAnsweredBy;
41
+ }
42
+ export declare const ESCALATION_NOTE_MAX = 500;
43
+ export declare const PARENT_UNAVAILABLE_NOTE = "Parent session is not running; routed to you.";
44
+ /**
45
+ * Exact mail body to the parent (type 'escalation', threadId = item id):
46
+ * `[ftown question id=<eventId> from=<childName> (<childId>)] <title>\n<message>\n` +
47
+ * (options ? `Options: 1) <label> 2) <label> ...\n` : '') +
48
+ * `Answer: ftown attention answer <childId> <eventId> --option <n> | --text "<reply>"\n` +
49
+ * `Escalate to the human: ftown attention escalate <childId> <eventId> --note "<context>"`
50
+ * For multi-question prompts list each question as `Q<i>: <question>` with its options.
51
+ */
52
+ export declare const PARENT_QUESTION_PREFIX = "[ftown question";
53
+ /** AttentionStore additions (bridge/src/attention-store.ts). */
54
+ export interface AttentionRoutingStoreApi {
55
+ /** set route fields on an existing open item; returns updated item or undefined if missing/resolved */
56
+ setRoute(sessionId: string, eventId: string, fields: AttentionRoutingFields): Promise<AttentionItem | undefined>;
57
+ /** open items (not resolved) of childId with route==='parent' */
58
+ listRouted(childId: string): Promise<AttentionItem[]>;
59
+ }
60
+ /** Local API (via dispatchSecure). Caller identity = x-ftown-session-id (local-cli principal). */
61
+ export declare const ATTENTION_ROUTES: {
62
+ /** POST body { answers: AttentionAnswerEntry[] } — caller must be the child's parent (403 otherwise); 409 if resolved; 400 invalid answers. → { event: AttentionItem } */
63
+ readonly answer: "/api/sessions/:id/attention/:eventId/answer";
64
+ /** POST body { note?: string } — caller must be the parent; 409 if route already 'human' or resolved. → { event: AttentionItem } */
65
+ readonly escalate: "/api/sessions/:id/attention/:eventId/escalate";
66
+ /** GET → { items: Array<{ sessionId: string; sessionName: string; event: AttentionItem }> } — open parent-routed items of all children of :id */
67
+ readonly routed: "/api/sessions/:id/attention/routed";
68
+ };
69
+ /** Existing POST /api/sessions/:id/attention and /attention/ask accept a new optional body key `to: 'human'`. */
70
+ /**
71
+ * CLI (new group `ftown attention`, bridge/src/attention-cli.ts):
72
+ * ftown attention list [--json] → routed items for my children (plain: `<child> <eventId> <title>` + options)
73
+ * ftown attention answer <child-id> <event-id> (--option <n|label>... | --text <t> | --answers-json <json>) [--json]
74
+ * ftown attention escalate <child-id> <event-id> [--note <t>] [--json]
75
+ * `ftown sessions attention ... --to human` bypasses the parent.
76
+ * Exit codes: 0 ok, 1 error, 2 usage, 4 forbidden (not the parent), 5 conflict (already resolved/escalated).
77
+ */
78
+ /** Dashboard wire: AttentionItem fields above flow unchanged through existing attention reads. */
79
+ export type AttentionPromptRef = AttentionPrompt;
80
+ export type AttentionAnswerRef = AttentionAnswer;
81
+ export declare const BRIEF_LIMITS: {
82
+ readonly text: 16384;
83
+ readonly note: 280;
84
+ readonly notes: 50;
85
+ };
86
+ export interface BriefNote {
87
+ ts: string;
88
+ text: string;
89
+ }
90
+ /** Stored on Session.brief (session.json) → flows to dashboard via toWireSession. */
91
+ export interface SessionBrief {
92
+ text?: string;
93
+ notes: BriefNote[];
94
+ updatedAt: string;
95
+ }
96
+ export declare const BRIEF_ROUTES: {
97
+ /** GET → { brief: SessionBrief | null }; PUT body { text: string | null } → { brief }; DELETE → { ok: true } */
98
+ readonly brief: "/api/sessions/:id/brief";
99
+ /** POST body { text: string } → { brief } (appends one note) */
100
+ readonly notes: "/api/sessions/:id/brief/notes";
101
+ };
102
+ /**
103
+ * CLI (bridge/src/brief-cli.ts, group `ftown brief`):
104
+ * ftown brief show [--json] [--session-id <id>]
105
+ * ftown brief set (--file <path.md> | --text <t> | --clear) [--session-id <id>]
106
+ * ftown brief note <text...> [--session-id <id>]
107
+ * Validation: control chars except \n\t stripped; text over limit → error exit 1 (no truncation).
108
+ * Every successful write publishes the session to the dashboard.
109
+ *
110
+ * Dashboard overview (UI): for a selected session that has ≥1 child, an "Overview" view showing:
111
+ * the brief (markdown, rendered like existing markdown previews, sanitized), the last 10 notes,
112
+ * and a table of children: name, card chip (state/headline/progress/blocked), activity + idle,
113
+ * PR link + check state, open attention count incl. "with parent" items, worktree branch.
114
+ * Rendered client-side from data the dashboard already has (sessions with card/brief/worktree,
115
+ * PR statuses hook, attention). Each card's age is shown ("updated 4m ago").
116
+ */
117
+ /** Stored on Session.worktree. Only createdByBridge worktrees are ever removed by the bridge. */
118
+ export interface SessionWorktree {
119
+ repoRoot: string;
120
+ path: string;
121
+ branch: string;
122
+ base: string;
123
+ createdByBridge: true;
124
+ retained?: {
125
+ reason: string;
126
+ at: string;
127
+ };
128
+ }
129
+ export interface WorktreeCreateRequest {
130
+ /** directory inside a git repo (the requested workdir, or the parent's workingDir when omitted) */
131
+ fromDir: string;
132
+ /** session name → default branch `ftown/<slug(name)>` and path `<repoRoot>/.claude/worktrees/<slug(name)>` */
133
+ name: string;
134
+ branch?: string;
135
+ base?: string;
136
+ }
137
+ export interface WorktreeStatus {
138
+ path: string;
139
+ branch: string;
140
+ base: string;
141
+ exists: boolean;
142
+ dirty: boolean;
143
+ ahead: number;
144
+ unpushed: number | null;
145
+ mergedIntoBase: boolean;
146
+ }
147
+ export type WorktreeRetireDecision = {
148
+ action: 'remove';
149
+ deleteBranch: boolean;
150
+ } | {
151
+ action: 'retain';
152
+ reason: string;
153
+ };
154
+ /** Implementation: bridge/src/worktrees.ts — all git calls via execFile('git', [...]) with cwd, no shell, timeout 30s. */
155
+ export interface WorktreeApi {
156
+ create(req: WorktreeCreateRequest): Promise<SessionWorktree>;
157
+ status(wt: SessionWorktree): Promise<WorktreeStatus>;
158
+ /** pure: retire iff exists && !dirty && (mergedIntoBase || (unpushed === 0)); else retain with reason */
159
+ decide(status: WorktreeStatus): WorktreeRetireDecision;
160
+ /** git worktree remove (no --force unless force) + optional `git branch -d` (never -D) */
161
+ remove(wt: SessionWorktree, opts: {
162
+ force: boolean;
163
+ deleteBranch: boolean;
164
+ }): Promise<void>;
165
+ }
166
+ export declare class WorktreeError extends Error {
167
+ readonly code: 'not_a_repo' | 'detached_head' | 'bad_branch' | 'exists' | 'git_failed';
168
+ constructor(code: 'not_a_repo' | 'detached_head' | 'bad_branch' | 'exists' | 'git_failed', message: string);
169
+ }
170
+ /**
171
+ * Create: POST /api/sessions body gains `worktree?: true | { branch?: string; base?: string }`.
172
+ * CLI: `ftown sessions create --worktree [--branch <b>] [--base <ref>]` (with --workdir optional).
173
+ * The worktree is created before the session launches; session.workingDir = worktree.path. On WorktreeError → 400 with message, no session created.
174
+ * Remove: DELETE /api/sessions/:id accepts query `worktree=keep|force` (default: auto-decide).
175
+ * CLI: `ftown sessions remove <id> [--keep-worktree | --force-worktree]`; output states removed/retained + reason.
176
+ * Auto: status → decide → remove or set worktree.retained. Errors never block archiving the session.
177
+ * List/prune:
178
+ * GET /api/worktrees → { worktrees: Array<{ sessionId: string; sessionName: string; archived: boolean; worktree: SessionWorktree; status: WorktreeStatus | null; error?: string }> } (status null + error when the git probe failed for that row)
179
+ * POST /api/worktrees/prune → { removed: string[]; retained: Array<{ path: string; reason: string }> } (archived sessions only, same decide rule)
180
+ * CLI (bridge/src/worktrees-cli.ts, group `ftown worktrees`): `list [--json]`, `prune [--json]`.
181
+ */
182
+ export declare const WORKTREE_ROUTES: {
183
+ readonly list: "/api/worktrees";
184
+ readonly prune: "/api/worktrees/prune";
185
+ };
186
+ export interface RouteContext {
187
+ req: IncomingMessage;
188
+ res: ServerResponse;
189
+ method: string;
190
+ /** pathname without query */
191
+ path: string;
192
+ query: URLSearchParams;
193
+ /** x-ftown-session-id of a local-cli caller, else undefined */
194
+ callerSessionId?: string;
195
+ parseBody(): Promise<Record<string, unknown>>;
196
+ json(status: number, body: unknown): void;
197
+ loadSession(id: string): Promise<Session | null>;
198
+ saveSession(session: Session): Promise<void>;
199
+ publishSession(session: Session): void;
200
+ }
201
+ /** Each route module exports `handle(ctx): Promise<boolean>` (true = handled). Throw BadRequestError-like errors as `{ status, message }`. */
202
+ export type RouteModule = (ctx: RouteContext) => Promise<boolean>;
203
+ export declare class RouteError extends Error {
204
+ readonly status: number;
205
+ constructor(status: number, message: string);
206
+ }
@@ -0,0 +1,58 @@
1
+ export const ESCALATION_NOTE_MAX = 500;
2
+ export const PARENT_UNAVAILABLE_NOTE = 'Parent session is not running; routed to you.';
3
+ /**
4
+ * Exact mail body to the parent (type 'escalation', threadId = item id):
5
+ * `[ftown question id=<eventId> from=<childName> (<childId>)] <title>\n<message>\n` +
6
+ * (options ? `Options: 1) <label> 2) <label> ...\n` : '') +
7
+ * `Answer: ftown attention answer <childId> <eventId> --option <n> | --text "<reply>"\n` +
8
+ * `Escalate to the human: ftown attention escalate <childId> <eventId> --note "<context>"`
9
+ * For multi-question prompts list each question as `Q<i>: <question>` with its options.
10
+ */
11
+ export const PARENT_QUESTION_PREFIX = '[ftown question';
12
+ /** Local API (via dispatchSecure). Caller identity = x-ftown-session-id (local-cli principal). */
13
+ export const ATTENTION_ROUTES = {
14
+ /** POST body { answers: AttentionAnswerEntry[] } — caller must be the child's parent (403 otherwise); 409 if resolved; 400 invalid answers. → { event: AttentionItem } */
15
+ answer: '/api/sessions/:id/attention/:eventId/answer',
16
+ /** POST body { note?: string } — caller must be the parent; 409 if route already 'human' or resolved. → { event: AttentionItem } */
17
+ escalate: '/api/sessions/:id/attention/:eventId/escalate',
18
+ /** GET → { items: Array<{ sessionId: string; sessionName: string; event: AttentionItem }> } — open parent-routed items of all children of :id */
19
+ routed: '/api/sessions/:id/attention/routed',
20
+ };
21
+ // ───────────────────────── C: manager brief + dashboard overview ─────────────────────────
22
+ export const BRIEF_LIMITS = { text: 16_384, note: 280, notes: 50 };
23
+ export const BRIEF_ROUTES = {
24
+ /** GET → { brief: SessionBrief | null }; PUT body { text: string | null } → { brief }; DELETE → { ok: true } */
25
+ brief: '/api/sessions/:id/brief',
26
+ /** POST body { text: string } → { brief } (appends one note) */
27
+ notes: '/api/sessions/:id/brief/notes',
28
+ };
29
+ export class WorktreeError extends Error {
30
+ code;
31
+ constructor(code, message) {
32
+ super(message);
33
+ this.code = code;
34
+ this.name = 'WorktreeError';
35
+ }
36
+ }
37
+ /**
38
+ * Create: POST /api/sessions body gains `worktree?: true | { branch?: string; base?: string }`.
39
+ * CLI: `ftown sessions create --worktree [--branch <b>] [--base <ref>]` (with --workdir optional).
40
+ * The worktree is created before the session launches; session.workingDir = worktree.path. On WorktreeError → 400 with message, no session created.
41
+ * Remove: DELETE /api/sessions/:id accepts query `worktree=keep|force` (default: auto-decide).
42
+ * CLI: `ftown sessions remove <id> [--keep-worktree | --force-worktree]`; output states removed/retained + reason.
43
+ * Auto: status → decide → remove or set worktree.retained. Errors never block archiving the session.
44
+ * List/prune:
45
+ * GET /api/worktrees → { worktrees: Array<{ sessionId: string; sessionName: string; archived: boolean; worktree: SessionWorktree; status: WorktreeStatus | null; error?: string }> } (status null + error when the git probe failed for that row)
46
+ * POST /api/worktrees/prune → { removed: string[]; retained: Array<{ path: string; reason: string }> } (archived sessions only, same decide rule)
47
+ * CLI (bridge/src/worktrees-cli.ts, group `ftown worktrees`): `list [--json]`, `prune [--json]`.
48
+ */
49
+ export const WORKTREE_ROUTES = { list: '/api/worktrees', prune: '/api/worktrees/prune' };
50
+ export class RouteError extends Error {
51
+ status;
52
+ constructor(status, message) {
53
+ super(message);
54
+ this.status = status;
55
+ this.name = 'RouteError';
56
+ }
57
+ }
58
+ //# sourceMappingURL=contract-b.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-b.js","sourceRoot":"","sources":["../../src/coordination/contract-b.ts"],"names":[],"mappings":"AA2CA,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AACvC,MAAM,CAAC,MAAM,uBAAuB,GAAG,+CAA+C,CAAC;AAEvF;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,iBAAiB,CAAC;AAUxD,kGAAkG;AAClG,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,0KAA0K;IAC1K,MAAM,EAAE,6CAA6C;IACrD,oIAAoI;IACpI,QAAQ,EAAE,+CAA+C;IACzD,iJAAiJ;IACjJ,MAAM,EAAE,oCAAoC;CACpC,CAAC;AAgBX,4FAA4F;AAE5F,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,EAAW,CAAC;AAU5E,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,gHAAgH;IAChH,KAAK,EAAE,yBAAyB;IAChC,gEAAgE;IAChE,KAAK,EAAE,+BAA+B;CAC9B,CAAC;AA8DX,MAAM,OAAO,aAAc,SAAQ,KAAK;IACV;IAA5B,YAA4B,IAA6E,EAAE,OAAe;QACxH,KAAK,CAAC,OAAO,CAAC,CAAC;QADW,SAAI,GAAJ,IAAI,CAAyE;QACvF,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9C,CAAC;CACF;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,sBAAsB,EAAW,CAAC;AAsBlG,MAAM,OAAO,UAAW,SAAQ,KAAK;IACP;IAA5B,YAA4B,MAAc,EAAE,OAAe;QAAI,KAAK,CAAC,OAAO,CAAC,CAAC;QAAlD,WAAM,GAAN,MAAM,CAAQ;QAAqC,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;IAAC,CAAC;CAC3G"}
@@ -0,0 +1,236 @@
1
+ /**
2
+ * FROZEN CONTRACT — coordination phase A (session cards, board, tree events,
3
+ * nudge-once mail, digest). Types, constants and interfaces only; no logic.
4
+ * Implementers must not modify this file. Changes go through the orchestrator.
5
+ */
6
+ import type { Activity } from '../attention-events.js';
7
+ import type { PullRequestState } from '../pull-request-status-protocol.js';
8
+ import type { MailMessage, Session, SessionStatus } from '../types.js';
9
+ export declare const CARD_STATES: readonly ["working", "blocked", "waiting_review", "done", "failed"];
10
+ export type CardState = typeof CARD_STATES[number];
11
+ export declare const BLOCKED_ON_KINDS: readonly ["human", "parent", "session", "external"];
12
+ export type BlockedOnKind = typeof BLOCKED_ON_KINDS[number];
13
+ export declare const CARD_LIMITS: {
14
+ readonly headline: 140;
15
+ readonly next: 280;
16
+ readonly blockedText: 280;
17
+ /** progress.total upper bound; done must be 0..total. */
18
+ readonly progressTotal: 10000;
19
+ };
20
+ export interface CardProgress {
21
+ done: number;
22
+ total: number;
23
+ }
24
+ export interface CardBlockedOn {
25
+ kind: BlockedOnKind; /** session id when kind==='session' */
26
+ ref?: string;
27
+ text: string;
28
+ }
29
+ /** Stored on Session.card (session.json) so it flows to the dashboard via toWireSession. */
30
+ export interface SessionCardDeclared {
31
+ state: CardState;
32
+ headline: string;
33
+ progress?: CardProgress;
34
+ blockedOn?: CardBlockedOn;
35
+ next?: string;
36
+ updatedAt: string;
37
+ }
38
+ /**
39
+ * Partial update. Omitted field = unchanged; null = remove.
40
+ * The first write to a session with no card must include state and headline.
41
+ * Setting state to anything other than 'blocked' clears blockedOn unless blockedOn is also given.
42
+ */
43
+ export interface CardPatch {
44
+ state?: CardState;
45
+ headline?: string;
46
+ progress?: CardProgress | null;
47
+ blockedOn?: CardBlockedOn | null;
48
+ next?: string | null;
49
+ }
50
+ export declare class CardValidationError extends Error {
51
+ constructor(message: string);
52
+ }
53
+ export interface CardPr {
54
+ url: string;
55
+ state: PullRequestState;
56
+ stale: boolean;
57
+ checkedAt: string | null;
58
+ }
59
+ export interface CardDerived {
60
+ status: SessionStatus;
61
+ activity: Activity['state'];
62
+ /** activity.lastActivityAt when activity === 'idle'. */
63
+ idleSince?: string;
64
+ openAttention: number;
65
+ /** inbox messages without deliveredAt */
66
+ unreadMail: number;
67
+ pr?: CardPr;
68
+ previews: string[];
69
+ shellType?: string;
70
+ model?: string;
71
+ }
72
+ export interface SessionCard {
73
+ sessionId: string;
74
+ name: string;
75
+ parentSessionId?: string;
76
+ declared: SessionCardDeclared | null;
77
+ derived: CardDerived;
78
+ /** declared exists and activity.lastActivityAt is more than CARD_STALE_MS after declared.updatedAt */
79
+ stale: boolean;
80
+ }
81
+ export declare const CARD_STALE_MS: number;
82
+ export interface CardStoreDeps {
83
+ loadSession(id: string): Promise<Session | null>;
84
+ saveSession(session: Session): Promise<void>;
85
+ /** called after a successful set/clear with the saved session (publish to dashboard + emit tree event) */
86
+ onChange?(session: Session, previous: SessionCardDeclared | null): void | Promise<void>;
87
+ now(): number;
88
+ }
89
+ /** Implementation: bridge/src/coordination/card-store.ts → `export class CardStore implements CardStoreApi { constructor(deps: CardStoreDeps) }` */
90
+ export interface CardStoreApi {
91
+ get(sessionId: string): Promise<SessionCardDeclared | null>;
92
+ /** validates (CardValidationError), merges, stamps updatedAt, saves. Throws Error('Session not found') if missing. */
93
+ set(sessionId: string, patch: CardPatch): Promise<SessionCardDeclared>;
94
+ clear(sessionId: string): Promise<void>;
95
+ }
96
+ /** Root of a tree = session.parentSessionId ?? session.id (tree is one level deep). */
97
+ export declare const TREE_EVENTS_FILE = "tree-events.jsonl";
98
+ export declare const TREE_EVENTS_RETAIN = 5000;
99
+ export declare const TREE_EVENTS_COMPACT_AT = 6000;
100
+ export declare const TREE_EVENTS_MAX_WAIT_MS = 300000;
101
+ export declare const TREE_EVENT_SUMMARY_MAX = 300;
102
+ export declare const TREE_EVENT_KINDS: readonly ["status", "attention", "pr", "preview", "exit", "idle", "result", "mail"];
103
+ export type TreeEventKind = typeof TREE_EVENT_KINDS[number];
104
+ export interface TreeEvent {
105
+ seq: number;
106
+ ts: string;
107
+ sessionId: string;
108
+ sessionName: string;
109
+ kind: TreeEventKind;
110
+ summary: string;
111
+ ref?: string;
112
+ }
113
+ export type TreeEventInput = Omit<TreeEvent, 'seq' | 'ts'>;
114
+ export interface TreeEventPage {
115
+ events: TreeEvent[]; /** highest seq returned, or `since` if none */
116
+ cursor: number;
117
+ timedOut?: boolean;
118
+ }
119
+ export interface TreeEventLogDeps {
120
+ sessionDir(id: string): string;
121
+ now(): number;
122
+ }
123
+ /** Implementation: bridge/src/coordination/tree-events.ts → `export class TreeEventLog implements TreeEventLogApi { constructor(deps: TreeEventLogDeps) }` */
124
+ export interface TreeEventLogApi {
125
+ append(rootId: string, event: TreeEventInput): Promise<TreeEvent>;
126
+ /** events with seq > since (default 0), oldest first, at most limit (default 100, max 500) */
127
+ read(rootId: string, opts?: {
128
+ since?: number;
129
+ limit?: number;
130
+ }): Promise<TreeEventPage>;
131
+ /** resolves immediately if events exist after since; otherwise on next append or timeout (clamped to TREE_EVENTS_MAX_WAIT_MS) with timedOut: true */
132
+ wait(rootId: string, since: number, timeoutMs: number, signal?: AbortSignal): Promise<TreeEventPage>;
133
+ /** highest seq for root (0 if none) */
134
+ head(rootId: string): Promise<number>;
135
+ }
136
+ export type BoardRollupKey = CardState | 'unset';
137
+ export interface Board {
138
+ rootId: string;
139
+ /** tree event head at render time; pass back as `since` */
140
+ cursor: number;
141
+ /** children of rootId (not the root itself), ordered by createdAt ascending; filtered when ready/since */
142
+ cards: SessionCard[];
143
+ rollup: Record<BoardRollupKey, number>;
144
+ }
145
+ export interface BoardQuery {
146
+ /** any session id; root is resolved */
147
+ sessionId: string;
148
+ /** only children with tree events of seq > since */
149
+ since?: number;
150
+ /** only children whose derived.pr.state === 'passed' and declared.state !== 'done' (approval/mergeable not tracked in phase A) */
151
+ ready?: boolean;
152
+ /** include archived/completed children; default false = status running|pending only plus any with events after since */
153
+ all?: boolean;
154
+ }
155
+ export interface BoardDeps {
156
+ loadSession(id: string): Promise<Session | null>;
157
+ listSessions(): Promise<Session[]>;
158
+ attention(id: string): Promise<{
159
+ activity: Activity;
160
+ openCount: number;
161
+ }>;
162
+ prStatus(url: string): Promise<{
163
+ state: PullRequestState;
164
+ stale: boolean;
165
+ checkedAt: string | null;
166
+ } | null>;
167
+ unreadMail(id: string): Promise<number>;
168
+ events: TreeEventLogApi;
169
+ now(): number;
170
+ }
171
+ /** Implementation: bridge/src/coordination/board.ts → `export class BoardService implements BoardServiceApi { constructor(deps: BoardDeps) }` */
172
+ export interface BoardServiceApi {
173
+ card(sessionId: string): Promise<SessionCard | null>;
174
+ board(query: BoardQuery): Promise<Board>;
175
+ /** deterministic one-line digest of tree events after sinceSeq for the root of sessionId; null if nothing new */
176
+ digest(sessionId: string, sinceSeq: number): Promise<{
177
+ line: string | null;
178
+ cursor: number;
179
+ }>;
180
+ }
181
+ /**
182
+ * Digest line format (exact):
183
+ * `[ftown] since HH:MM: <part> | <part> | ...`
184
+ * Parts, in order, one per child with events (latest event per child wins, max 6 children then `+N more`):
185
+ * `<name> <state>` + (headline ? ` "<headline ≤60>"` : '') + (pr ? ` (PR <state>)` : '')
186
+ * then, if any: `<n> question(s) waiting`. Total line ≤ 500 chars. HH:MM is local time of the first event.
187
+ */
188
+ export declare const DIGEST_MAX = 500;
189
+ /** Plain `ftown board` row (exact column order, single spaces):
190
+ * `<name> <state|-> <activity>[ idle <Nm>] <headline>[ PR:<state>][ !<openAttention>][ ✉<unreadMail>][ (stale)]`
191
+ */
192
+ /** Replaces MAIL_TYPES in mail-delivery.ts and wire-types.ts. */
193
+ export declare const MAIL_TYPES_V2: readonly ["message", "task", "result", "escalation", "fyi"];
194
+ export type MailTypeV2 = typeof MAIL_TYPES_V2[number];
195
+ /** fyi never schedules a nudge or wake; collected only at the next natural drain/read. */
196
+ export declare const NON_WAKING_MAIL_TYPES: ReadonlySet<MailTypeV2>;
197
+ /** Max native-wake attempts (codex/muse) for one batch before the batch is stamped and left. */
198
+ export declare const MAX_WAKE_ATTEMPTS = 3;
199
+ /**
200
+ * Nudge-once rules (MailMessage.nudgedAt):
201
+ * 1. A nudge/wake fires only if ≥1 undelivered, waking message has no nudgedAt.
202
+ * 2. On firing (any path: PTY, codex, muse, plugin), stamp nudgedAt on every undelivered waking message → that is the batch.
203
+ * 3. A stamped message never causes another nudge on any path (new mail, recovery, retry).
204
+ * 4. Recovery (recoverPendingMail) skips stamped mail.
205
+ * 5. Nudge text: NUDGE_TEXT(counts, digest).
206
+ */
207
+ export type MailCounts = Partial<Record<MailTypeV2, number>>;
208
+ export interface DigestProvider {
209
+ /** one-line digest for the recipient (as tree root), or null. Must not throw; return null on error. */
210
+ digestFor(recipientSessionId: string): Promise<string | null>;
211
+ }
212
+ /** Event sink so mail-delivery can record child→parent `result` mail on the tree log without importing it. */
213
+ export interface MailEventSink {
214
+ onAccepted(message: MailMessage, recipient: Session): void | Promise<void>;
215
+ }
216
+ export declare const COORDINATION_ROUTES: {
217
+ /** GET → SessionCard; PUT body CardPatch → SessionCard (400 on CardValidationError); DELETE → { ok: true } */
218
+ readonly card: "/api/sessions/:id/card";
219
+ /** GET ?since=<n>&ready=1&all=1 → Board */
220
+ readonly board: "/api/sessions/:id/board";
221
+ /** GET ?since=<n>&limit=<n>&waitSeconds=<0..300> → TreeEventPage (root of :id) */
222
+ readonly events: "/api/sessions/:id/events";
223
+ };
224
+ /**
225
+ * ftown status [--json] [--session-id <id>] → print own card (SessionCard)
226
+ * ftown status set [--state <s>] [--headline <t>] [--progress <d>/<t>|--no-progress]
227
+ * [--on human|parent|external|session:<id>] [--text <t>] [--next <t>|--no-next] [--session-id <id>]
228
+ * ftown status clear [--session-id <id>]
229
+ * ftown board [--json] [--since <n>] [--ready] [--all] [--session-id <id>]
230
+ * [--wait --until any-change|any-done|any-blocked|all-done|any-ready [--timeout <s≤300>]]
231
+ * ftown events [--json] [--since <n>] [--limit <n>] [--wait [--timeout <s≤300>]] [--session-id <id>]
232
+ * Exit codes: 0 ok, 1 error, 2 usage, 3 wait timed out with condition unmet.
233
+ * Default session id: FTOWN_SESSION_ID.
234
+ */
235
+ export declare const BOARD_WAIT_CONDITIONS: readonly ["any-change", "any-done", "any-blocked", "all-done", "any-ready"];
236
+ export type BoardWaitCondition = typeof BOARD_WAIT_CONDITIONS[number];
@@ -0,0 +1,63 @@
1
+ // ───────────────────────── Session card (declared by the agent) ─────────────────────────
2
+ export const CARD_STATES = ['working', 'blocked', 'waiting_review', 'done', 'failed'];
3
+ export const BLOCKED_ON_KINDS = ['human', 'parent', 'session', 'external'];
4
+ export const CARD_LIMITS = {
5
+ headline: 140,
6
+ next: 280,
7
+ blockedText: 280,
8
+ /** progress.total upper bound; done must be 0..total. */
9
+ progressTotal: 10_000,
10
+ };
11
+ export class CardValidationError extends Error {
12
+ constructor(message) { super(message); this.name = 'CardValidationError'; }
13
+ }
14
+ export const CARD_STALE_MS = 10 * 60_000;
15
+ // ───────────────────────── Tree event log ─────────────────────────
16
+ /** Root of a tree = session.parentSessionId ?? session.id (tree is one level deep). */
17
+ export const TREE_EVENTS_FILE = 'tree-events.jsonl'; // in sessionDir(rootId)
18
+ export const TREE_EVENTS_RETAIN = 5_000; // keep newest N on compaction
19
+ export const TREE_EVENTS_COMPACT_AT = 6_000;
20
+ export const TREE_EVENTS_MAX_WAIT_MS = 300_000;
21
+ export const TREE_EVENT_SUMMARY_MAX = 300;
22
+ export const TREE_EVENT_KINDS = ['status', 'attention', 'pr', 'preview', 'exit', 'idle', 'result', 'mail'];
23
+ /**
24
+ * Digest line format (exact):
25
+ * `[ftown] since HH:MM: <part> | <part> | ...`
26
+ * Parts, in order, one per child with events (latest event per child wins, max 6 children then `+N more`):
27
+ * `<name> <state>` + (headline ? ` "<headline ≤60>"` : '') + (pr ? ` (PR <state>)` : '')
28
+ * then, if any: `<n> question(s) waiting`. Total line ≤ 500 chars. HH:MM is local time of the first event.
29
+ */
30
+ export const DIGEST_MAX = 500;
31
+ /** Plain `ftown board` row (exact column order, single spaces):
32
+ * `<name> <state|-> <activity>[ idle <Nm>] <headline>[ PR:<state>][ !<openAttention>][ ✉<unreadMail>][ (stale)]`
33
+ */
34
+ // ───────────────────────── Mail: nudge once + fyi ─────────────────────────
35
+ /** Replaces MAIL_TYPES in mail-delivery.ts and wire-types.ts. */
36
+ export const MAIL_TYPES_V2 = ['message', 'task', 'result', 'escalation', 'fyi'];
37
+ /** fyi never schedules a nudge or wake; collected only at the next natural drain/read. */
38
+ export const NON_WAKING_MAIL_TYPES = new Set(['fyi']);
39
+ /** Max native-wake attempts (codex/muse) for one batch before the batch is stamped and left. */
40
+ export const MAX_WAKE_ATTEMPTS = 3;
41
+ // ───────────────────────── Local API (all via dispatchSecure, :id = target session) ─────────────────────────
42
+ export const COORDINATION_ROUTES = {
43
+ /** GET → SessionCard; PUT body CardPatch → SessionCard (400 on CardValidationError); DELETE → { ok: true } */
44
+ card: '/api/sessions/:id/card',
45
+ /** GET ?since=<n>&ready=1&all=1 → Board */
46
+ board: '/api/sessions/:id/board',
47
+ /** GET ?since=<n>&limit=<n>&waitSeconds=<0..300> → TreeEventPage (root of :id) */
48
+ events: '/api/sessions/:id/events',
49
+ };
50
+ // ───────────────────────── CLI (new top-level groups in ftown-cli.ts) ─────────────────────────
51
+ /**
52
+ * ftown status [--json] [--session-id <id>] → print own card (SessionCard)
53
+ * ftown status set [--state <s>] [--headline <t>] [--progress <d>/<t>|--no-progress]
54
+ * [--on human|parent|external|session:<id>] [--text <t>] [--next <t>|--no-next] [--session-id <id>]
55
+ * ftown status clear [--session-id <id>]
56
+ * ftown board [--json] [--since <n>] [--ready] [--all] [--session-id <id>]
57
+ * [--wait --until any-change|any-done|any-blocked|all-done|any-ready [--timeout <s≤300>]]
58
+ * ftown events [--json] [--since <n>] [--limit <n>] [--wait [--timeout <s≤300>]] [--session-id <id>]
59
+ * Exit codes: 0 ok, 1 error, 2 usage, 3 wait timed out with condition unmet.
60
+ * Default session id: FTOWN_SESSION_ID.
61
+ */
62
+ export const BOARD_WAIT_CONDITIONS = ['any-change', 'any-done', 'any-blocked', 'all-done', 'any-ready'];
63
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src/coordination/contract.ts"],"names":[],"mappings":"AASA,2FAA2F;AAE3F,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,SAAS,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,EAAE,QAAQ,CAAU,CAAC;AAG/F,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,CAAU,CAAC;AAGpF,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,QAAQ,EAAE,GAAG;IACb,IAAI,EAAE,GAAG;IACT,WAAW,EAAE,GAAG;IAChB,yDAAyD;IACzD,aAAa,EAAE,MAAM;CACb,CAAC;AA4BX,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC5C,YAAY,OAAe,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC,CAAC,CAAC;CACpF;AA8BD,MAAM,CAAC,MAAM,aAAa,GAAG,EAAE,GAAG,MAAM,CAAC;AAoBzC,qEAAqE;AAErE,uFAAuF;AACvF,MAAM,CAAC,MAAM,gBAAgB,GAAG,mBAAmB,CAAC,CAAC,wBAAwB;AAC7E,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,CAAC,CAAG,8BAA8B;AACzE,MAAM,CAAC,MAAM,sBAAsB,GAAG,KAAK,CAAC;AAC5C,MAAM,CAAC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAC/C,MAAM,CAAC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAE1C,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAU,CAAC;AAwEpH;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAE9B;;GAEG;AAEH,6EAA6E;AAE7E,iEAAiE;AACjE,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,KAAK,CAAU,CAAC;AAEzF,0FAA0F;AAC1F,MAAM,CAAC,MAAM,qBAAqB,GAA4B,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAC/E,gGAAgG;AAChG,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAsBnC,+GAA+G;AAE/G,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,8GAA8G;IAC9G,IAAI,EAAE,wBAAwB;IAC9B,2CAA2C;IAC3C,KAAK,EAAE,yBAAyB;IAChC,kFAAkF;IAClF,MAAM,EAAE,0BAA0B;CAC1B,CAAC;AAEX,iGAAiG;AACjG;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,UAAU,EAAE,WAAW,CAAU,CAAC"}
@@ -0,0 +1,5 @@
1
+ import { type Board, type SessionCard, type TreeEvent } from './contract.js';
2
+ export declare function formatLocalHHMM(iso: string): string;
3
+ export declare function formatBoardRow(card: SessionCard, nowMs: number): string;
4
+ export declare function formatBoard(board: Board, nowMs: number): string;
5
+ export declare function formatEvent(e: TreeEvent): string;
@@ -0,0 +1,73 @@
1
+ import { CARD_STATES, } from './contract.js';
2
+ const ROLLUP_ORDER = [...CARD_STATES, 'unset'];
3
+ const BLOCKED_TEXT_MAX = 60;
4
+ function pad2(n) {
5
+ return String(n).padStart(2, '0');
6
+ }
7
+ function truncate(text, max) {
8
+ return [...text].slice(0, max).join('');
9
+ }
10
+ export function formatLocalHHMM(iso) {
11
+ const d = new Date(iso);
12
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
13
+ }
14
+ export function formatBoardRow(card, nowMs) {
15
+ const state = card.declared?.state ?? '-';
16
+ const activity = card.derived.activity;
17
+ let idlePart = '';
18
+ if (activity === 'idle') {
19
+ const idleSinceMs = card.derived.idleSince !== undefined
20
+ ? Date.parse(card.derived.idleSince)
21
+ : NaN;
22
+ const idleMin = Number.isNaN(idleSinceMs)
23
+ ? 0
24
+ : Math.max(0, Math.floor((nowMs - idleSinceMs) / 60_000));
25
+ idlePart = ` idle ${idleMin}m`;
26
+ }
27
+ const headline = card.declared?.headline || '-';
28
+ let suffix = '';
29
+ const progress = card.declared?.progress;
30
+ if (progress && state !== 'done') {
31
+ suffix += ` ${progress.done}/${progress.total}`;
32
+ }
33
+ const blockedOn = card.declared?.blockedOn;
34
+ if (blockedOn) {
35
+ const ref = blockedOn.ref ? `:${blockedOn.ref}` : '';
36
+ suffix += ` blocked on ${blockedOn.kind}${ref}: ${truncate(blockedOn.text, BLOCKED_TEXT_MAX)}`;
37
+ }
38
+ if (card.derived.pr) {
39
+ suffix += ` PR:${card.derived.pr.state}`;
40
+ }
41
+ if (card.derived.openAttention > 0) {
42
+ suffix += ` !${card.derived.openAttention}`;
43
+ }
44
+ if (card.derived.unreadMail > 0) {
45
+ suffix += ` ✉${card.derived.unreadMail}`;
46
+ }
47
+ if (card.stale) {
48
+ suffix += ' (stale)';
49
+ }
50
+ return `${card.name} ${state} ${activity}${idlePart} ${headline}${suffix}`;
51
+ }
52
+ export function formatBoard(board, nowMs) {
53
+ if (board.cards.length === 0) {
54
+ return 'no child sessions';
55
+ }
56
+ const rows = board.cards.map((card) => formatBoardRow(card, nowMs));
57
+ const rollupParts = [];
58
+ for (const key of ROLLUP_ORDER) {
59
+ const count = board.rollup[key] ?? 0;
60
+ if (count > 0) {
61
+ rollupParts.push(`${count} ${key}`);
62
+ }
63
+ }
64
+ if (rollupParts.length > 0) {
65
+ rows.push(rollupParts.join(', '));
66
+ }
67
+ return rows.join('\n');
68
+ }
69
+ export function formatEvent(e) {
70
+ const hhmm = formatLocalHHMM(e.ts);
71
+ return `#${e.seq} ${hhmm} ${e.sessionName} ${e.kind}: ${e.summary}`;
72
+ }
73
+ //# sourceMappingURL=format.js.map