work-ally 0.2.0-alpha.1

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 (172) hide show
  1. package/AGENTS.md +110 -0
  2. package/DASHBOARD.md +160 -0
  3. package/PRODUCT.md +113 -0
  4. package/README.md +403 -0
  5. package/ally.sh +171 -0
  6. package/bridge/src/approval-rules.ts +360 -0
  7. package/bridge/src/channel-delivery.ts +207 -0
  8. package/bridge/src/channel-types.ts +22 -0
  9. package/bridge/src/channels/fake/adapter.ts +31 -0
  10. package/bridge/src/channels/feishu/adapter.ts +411 -0
  11. package/bridge/src/channels/feishu/approvals.ts +6 -0
  12. package/bridge/src/channels/feishu/formatter.ts +276 -0
  13. package/bridge/src/channels/feishu/normalize.ts +368 -0
  14. package/bridge/src/codex-config.ts +52 -0
  15. package/bridge/src/config.ts +240 -0
  16. package/bridge/src/fake-runtime-client.ts +505 -0
  17. package/bridge/src/handoff-service.ts +494 -0
  18. package/bridge/src/logger.ts +194 -0
  19. package/bridge/src/memory-digest.ts +186 -0
  20. package/bridge/src/receiver-approval-autonomy.ts +158 -0
  21. package/bridge/src/receiver-control-core.ts +140 -0
  22. package/bridge/src/receiver-control-work-session.ts +218 -0
  23. package/bridge/src/receiver-control.ts +83 -0
  24. package/bridge/src/receiver-delivery.ts +136 -0
  25. package/bridge/src/receiver-helpers.ts +96 -0
  26. package/bridge/src/receiver-human-gate.ts +333 -0
  27. package/bridge/src/receiver-inbound-preflight.ts +162 -0
  28. package/bridge/src/receiver-recovery.ts +236 -0
  29. package/bridge/src/receiver-runtime-callbacks.ts +367 -0
  30. package/bridge/src/receiver-runtime-policy.ts +132 -0
  31. package/bridge/src/receiver-runtime-state.ts +124 -0
  32. package/bridge/src/receiver-support-actions.ts +189 -0
  33. package/bridge/src/receiver-thread-start.ts +57 -0
  34. package/bridge/src/receiver-turn-coordination.ts +94 -0
  35. package/bridge/src/receiver-turn-execution.ts +257 -0
  36. package/bridge/src/receiver-turn-failure.ts +143 -0
  37. package/bridge/src/receiver-turn-result.ts +185 -0
  38. package/bridge/src/receiver-turn-steer.ts +70 -0
  39. package/bridge/src/receiver-work-session.ts +76 -0
  40. package/bridge/src/receiver.ts +329 -0
  41. package/bridge/src/router.ts +62 -0
  42. package/bridge/src/runtime-client-agent-messages.ts +150 -0
  43. package/bridge/src/runtime-client-message-dispatch.ts +176 -0
  44. package/bridge/src/runtime-client-protocol.ts +411 -0
  45. package/bridge/src/runtime-client-request-ops.ts +56 -0
  46. package/bridge/src/runtime-client-run-turn.ts +158 -0
  47. package/bridge/src/runtime-client-thread-ops.ts +270 -0
  48. package/bridge/src/runtime-client-transport.ts +309 -0
  49. package/bridge/src/runtime-client-turn-poll.ts +224 -0
  50. package/bridge/src/runtime-client-turn-read.ts +185 -0
  51. package/bridge/src/runtime-client-turn-state.ts +105 -0
  52. package/bridge/src/runtime-client.ts +344 -0
  53. package/bridge/src/runtime-user-input.ts +403 -0
  54. package/bridge/src/scheduler.ts +239 -0
  55. package/bridge/src/server-handoff-command.ts +364 -0
  56. package/bridge/src/server-main.ts +80 -0
  57. package/bridge/src/server-routine-command.ts +60 -0
  58. package/bridge/src/server-routine-execution.ts +222 -0
  59. package/bridge/src/server-runtime-app-support.ts +107 -0
  60. package/bridge/src/server-runtime-app.ts +238 -0
  61. package/bridge/src/server-thread-sync-command.ts +63 -0
  62. package/bridge/src/server.ts +17 -0
  63. package/bridge/src/session-store-delivery.ts +220 -0
  64. package/bridge/src/session-store-human-gate.ts +380 -0
  65. package/bridge/src/session-store-inbound-acceptance.ts +66 -0
  66. package/bridge/src/session-store-meta.ts +134 -0
  67. package/bridge/src/session-store-turn-ledger.ts +272 -0
  68. package/bridge/src/session-store.ts +380 -0
  69. package/bridge/src/system-notify.ts +220 -0
  70. package/bridge/src/thread-sync.ts +200 -0
  71. package/bridge/src/translator.ts +494 -0
  72. package/bridge/src/types.ts +289 -0
  73. package/bridge/src/utils.ts +104 -0
  74. package/bridge/src/work-session-store.ts +471 -0
  75. package/docs/.gitkeep +0 -0
  76. package/docs/architecture/codex-feishu-bridge-proposal.md +2742 -0
  77. package/docs/completed/FEATURE-feishu-markdown-and-reply-support.md +327 -0
  78. package/docs/completed/README.md +21 -0
  79. package/docs/completed/SPEC-approval-autonomy-and-safe-defaults.md +205 -0
  80. package/docs/completed/SPEC-approval-batch-and-strict-reply-shortcuts.md +153 -0
  81. package/docs/completed/SPEC-conversation-noise-reduction-and-busy-input-gate.md +538 -0
  82. package/docs/completed/SPEC-engineering-sop-skillization.md +190 -0
  83. package/docs/completed/SPEC-faithful-bridge-core-thinning-v2.md +376 -0
  84. package/docs/completed/SPEC-faithful-bridge-core-thinning.md +1071 -0
  85. package/docs/completed/SPEC-group-chat-sender-identity.md +301 -0
  86. package/docs/completed/SPEC-middleware-exception-visibility.md +227 -0
  87. package/docs/completed/SPEC-nightly-memory-digest-visibility.md +121 -0
  88. package/docs/completed/SPEC-project-group-chat-human-centered-conversation-mapping.md +326 -0
  89. package/docs/completed/SPEC-remove-cli-persona-bootstrap.md +201 -0
  90. package/docs/developer-workflow.md +49 -0
  91. package/docs/implementation/SPEC-codex-same-machine-session-handoff-implementation.md +239 -0
  92. package/docs/implementation/test-coverage-map.md +363 -0
  93. package/docs/implementation/work-ally-implementation-guide.md +790 -0
  94. package/docs/issues/README.md +10 -0
  95. package/docs/issues/pending/ANALYSIS-ally-premature-recovery-notice-and-task-state-semantics-2026-03-18.md +295 -0
  96. package/docs/issues/resolved/ANALYSIS-approval-waiting-visible-but-approval-artifact-missing-2026-03-16.md +466 -0
  97. package/docs/issues/resolved/ANALYSIS-blocking-state-visible-without-user-actionable-artifact-2026-03-16.md +261 -0
  98. package/docs/issues/resolved/ANALYSIS-codex-app-server-transport-disconnect-semantics-2026-03-14.md +606 -0
  99. package/docs/issues/resolved/ANALYSIS-premature-terminalization-on-fresh-thread-poll-and-object-error-leak-2026-03-16.md +348 -0
  100. package/docs/issues/resolved/ANALYSIS-runtime-turn-delivery-and-recovery-2026-03-14.md +603 -0
  101. package/docs/issues/resolved/ANALYSIS-self-test-gap-approval-waiting-visible-but-approval-artifact-missing-2026-03-16.md +166 -0
  102. package/docs/issues/resolved/ANALYSIS-self-test-gap-blocking-state-visible-without-user-actionable-artifact-2026-03-16.md +186 -0
  103. package/docs/issues/resolved/ANALYSIS-self-test-gap-premature-terminalization-on-fresh-thread-poll-and-object-error-leak-2026-03-16.md +166 -0
  104. package/docs/issues/resolved/REPORT-ally-runtime-turn-delivery-3b42fb8-2026-03-15.md +373 -0
  105. package/docs/manual-acceptance.md +127 -0
  106. package/docs/ops-runbook.md +44 -0
  107. package/docs/planning/FEATURE-memory-system.md +748 -0
  108. package/docs/planning/SPEC-active-turn-steer-and-context-compaction-visibility.md +269 -0
  109. package/docs/planning/SPEC-approval-rules-inheritance-and-local-validation-lane.md +450 -0
  110. package/docs/planning/SPEC-assistant-persona-bootstrap.md +199 -0
  111. package/docs/planning/SPEC-assistant-rename.md +610 -0
  112. package/docs/planning/SPEC-bridge-app-server-protocol-alignment.md +667 -0
  113. package/docs/planning/SPEC-claude-runtime-host-for-work-ally.md +434 -0
  114. package/docs/planning/SPEC-cli-feishu-codex-session-unification.md +236 -0
  115. package/docs/planning/SPEC-codex-same-machine-session-handoff.md +873 -0
  116. package/docs/planning/SPEC-feishu-reaction-shortcuts.md +282 -0
  117. package/docs/planning/SPEC-local-stable-release-boundary.md +166 -0
  118. package/docs/planning/SPEC-managed-thread-entry-and-surface-mobility.md +862 -0
  119. package/docs/planning/SPEC-minimal-bridge-semantics-and-user-visible-surface.md +362 -0
  120. package/docs/planning/SPEC-npm-alpha-distribution-and-install-first-release.md +222 -0
  121. package/docs/planning/SPEC-remove-websocket-runtime-transport.md +364 -0
  122. package/docs/planning/SPEC-runtime-abstraction-phase-1.md +424 -0
  123. package/docs/planning/SPEC-runtime-connection-and-turn-recovery-semantics.md +274 -0
  124. package/docs/planning/SPEC-session-presence-and-state-visibility.md +397 -0
  125. package/docs/planning/SPEC-skill-first-capability-packaging.md +338 -0
  126. package/docs/planning/SPEC-stable-archive-contract.md +456 -0
  127. package/docs/planning/SPEC-supervised-start-boundary.md +127 -0
  128. package/docs/planning/SPEC-user-barrier-reduction-and-activation.md +832 -0
  129. package/docs/planning/ally-next.md +1278 -0
  130. package/docs/planning/assistant-workbench-spec.md +725 -0
  131. package/docs/planning/product-workbench.md +283 -0
  132. package/docs/product-onboarding.md +227 -0
  133. package/docs/product-spec-standard.md +528 -0
  134. package/docs/troubleshooting.md +45 -0
  135. package/docs/user-quickstart.md +46 -0
  136. package/internal/dispatch.sh +95 -0
  137. package/internal/lib/common.sh +1450 -0
  138. package/internal/modules/assistant/manage.sh +1312 -0
  139. package/internal/modules/bootstrap/setup.sh +144 -0
  140. package/internal/modules/config/init-env.sh +10 -0
  141. package/internal/modules/global/manage.sh +154 -0
  142. package/internal/modules/handoff/manage.sh +54 -0
  143. package/internal/modules/mcp/manage.sh +83 -0
  144. package/internal/modules/ops/logs.sh +76 -0
  145. package/internal/modules/routines/manage.sh +55 -0
  146. package/internal/modules/runtime/assistant-autosave.sh +26 -0
  147. package/internal/modules/runtime/restart.sh +6 -0
  148. package/internal/modules/runtime/start.sh +283 -0
  149. package/internal/modules/runtime/status.sh +194 -0
  150. package/internal/modules/runtime/stop.sh +55 -0
  151. package/internal/modules/runtime/supervisor.sh +216 -0
  152. package/internal/modules/runtime/update.sh +26 -0
  153. package/package.json +41 -0
  154. package/runtime/config/.gitkeep +0 -0
  155. package/runtime/host/.gitkeep +0 -0
  156. package/runtime/host/healthcheck-codex-app-server.ts +22 -0
  157. package/runtime/host/ping-pong-codex-app-server.ts +66 -0
  158. package/runtime/host/probe-codex-app-server.ts +115 -0
  159. package/skills/archive-reader/SKILL.md +9 -0
  160. package/skills/feishu-production-debug/SKILL.md +37 -0
  161. package/skills/feishu-production-debug/references/feishu-debug-order.md +49 -0
  162. package/skills/feishu-production-debug/references/platform-permission-baseline.md +23 -0
  163. package/skills/issue-to-spec-triage/SKILL.md +44 -0
  164. package/skills/issue-to-spec-triage/references/triage-rules.md +66 -0
  165. package/skills/memory-digest/SKILL.md +9 -0
  166. package/skills/post-implementation-closure/SKILL.md +39 -0
  167. package/skills/post-implementation-closure/references/closure-checklist.md +45 -0
  168. package/skills/post-implementation-closure/references/doc-drift-map.md +49 -0
  169. package/skills/product-spec/SKILL.md +244 -0
  170. package/templates/env.example +5 -0
  171. package/templates/routines/nightly-memory-digest.yaml +10 -0
  172. package/templates/workspace/AGENTS.md +26 -0
@@ -0,0 +1,134 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { appendNdjson, ensureDir, nowIso, readJsonFile, writeJsonFile } from './utils.ts';
4
+ import type { ConversationRef, SessionMeta } from './types.ts';
5
+
6
+ export interface SessionMetaStoreDeps {
7
+ sessionsDir: string;
8
+ resolveSessionKey(ref: ConversationRef): string;
9
+ resolveSessionDir(ref: ConversationRef): string;
10
+ metaFile(ref: ConversationRef): string;
11
+ eventsFile(ref: ConversationRef): string;
12
+ }
13
+
14
+ export function ensureSessionDirs(deps: SessionMetaStoreDeps, ref: ConversationRef): string {
15
+ const sessionDir = deps.resolveSessionDir(ref);
16
+ ensureDir(sessionDir);
17
+ ensureDir(path.join(sessionDir, 'turns'));
18
+ ensureDir(path.join(sessionDir, 'turn-ledger'));
19
+ ensureDir(path.join(sessionDir, 'inbound-ledger'));
20
+ ensureDir(path.join(sessionDir, 'approvals'));
21
+ ensureDir(path.join(sessionDir, 'receipts'));
22
+ ensureDir(path.join(sessionDir, 'user-inputs'));
23
+ ensureDir(path.join(sessionDir, 'seen-inbounds'));
24
+ ensureDir(path.join(sessionDir, 'outbound-delivery'));
25
+ return sessionDir;
26
+ }
27
+
28
+ export function normalizeSessionMeta(
29
+ deps: SessionMetaStoreDeps,
30
+ ref: ConversationRef,
31
+ current: SessionMeta | null,
32
+ now = nowIso(),
33
+ ): SessionMeta {
34
+ const meta: SessionMeta = current || {
35
+ conversationRef: ref,
36
+ sessionKey: deps.resolveSessionKey(ref),
37
+ createdAt: now,
38
+ updatedAt: now,
39
+ threadId: null,
40
+ activeTurnId: null,
41
+ lastTurnId: null,
42
+ lastMessageId: null,
43
+ lastPromptPreview: null,
44
+ lastReplyPreview: null,
45
+ pendingApprovalIds: [],
46
+ pendingUserInputRequestId: null,
47
+ };
48
+
49
+ meta.conversationRef = ref;
50
+ if (!('activeTurnId' in meta)) meta.activeTurnId = null;
51
+ if (!('lastTurnId' in meta)) meta.lastTurnId = null;
52
+ if (!('lastMessageId' in meta)) meta.lastMessageId = null;
53
+ if (!('lastPromptPreview' in meta)) meta.lastPromptPreview = null;
54
+ if (!('lastReplyPreview' in meta)) meta.lastReplyPreview = null;
55
+ if (!('pendingApprovalIds' in meta) || !Array.isArray(meta.pendingApprovalIds)) meta.pendingApprovalIds = [];
56
+ if (!('pendingUserInputRequestId' in meta)) meta.pendingUserInputRequestId = null;
57
+ meta.updatedAt = now;
58
+ return meta;
59
+ }
60
+
61
+ export function ensureSession(deps: SessionMetaStoreDeps, ref: ConversationRef): SessionMeta {
62
+ ensureSessionDirs(deps, ref);
63
+ const metaFile = deps.metaFile(ref);
64
+ const meta = normalizeSessionMeta(deps, ref, readJsonFile(metaFile) as SessionMeta | null);
65
+ writeJsonFile(metaFile, meta);
66
+ return meta;
67
+ }
68
+
69
+ export function bindThread(
70
+ deps: SessionMetaStoreDeps,
71
+ ref: ConversationRef,
72
+ threadId: string | null,
73
+ ): SessionMeta {
74
+ const meta = ensureSession(deps, ref);
75
+ meta.threadId = threadId;
76
+ if (threadId === null) {
77
+ meta.activeTurnId = null;
78
+ meta.pendingApprovalIds = [];
79
+ meta.pendingUserInputRequestId = null;
80
+ }
81
+ meta.updatedAt = nowIso();
82
+ writeJsonFile(deps.metaFile(ref), meta);
83
+ writeJsonFile(path.join(deps.resolveSessionDir(ref), 'current-thread.json'), {
84
+ threadId,
85
+ updatedAt: meta.updatedAt,
86
+ });
87
+ return meta;
88
+ }
89
+
90
+ export function noteLatestInbound(
91
+ deps: SessionMetaStoreDeps,
92
+ ref: ConversationRef,
93
+ details: { messageId?: string | null; promptPreview?: string | null },
94
+ ): SessionMeta {
95
+ const meta = ensureSession(deps, ref);
96
+ if ('messageId' in details) {
97
+ meta.lastMessageId = details.messageId || meta.lastMessageId;
98
+ }
99
+ if ('promptPreview' in details) {
100
+ meta.lastPromptPreview = details.promptPreview || meta.lastPromptPreview;
101
+ }
102
+ meta.updatedAt = nowIso();
103
+ writeJsonFile(deps.metaFile(ref), meta);
104
+ appendNdjson(deps.eventsFile(ref), {
105
+ type: 'latest_inbound_noted',
106
+ at: meta.updatedAt,
107
+ messageId: details.messageId || null,
108
+ });
109
+ return meta;
110
+ }
111
+
112
+ export function clearActiveTurn(deps: SessionMetaStoreDeps, ref: ConversationRef): SessionMeta {
113
+ const meta = ensureSession(deps, ref);
114
+ meta.activeTurnId = null;
115
+ meta.updatedAt = nowIso();
116
+ writeJsonFile(deps.metaFile(ref), meta);
117
+ appendNdjson(deps.eventsFile(ref), {
118
+ type: 'active_turn_cleared',
119
+ at: meta.updatedAt,
120
+ });
121
+ return meta;
122
+ }
123
+
124
+ export function listSessions(deps: SessionMetaStoreDeps): SessionMeta[] {
125
+ const entries = fs.readdirSync(deps.sessionsDir, { withFileTypes: true });
126
+ const sessions: SessionMeta[] = [];
127
+ for (const entry of entries) {
128
+ if (!entry.isDirectory()) continue;
129
+ const meta = readJsonFile(path.join(deps.sessionsDir, entry.name, 'meta.json')) as SessionMeta | null;
130
+ if (!meta?.conversationRef) continue;
131
+ sessions.push(normalizeSessionMeta(deps, meta.conversationRef, meta, meta.updatedAt || nowIso()));
132
+ }
133
+ return sessions;
134
+ }
@@ -0,0 +1,272 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { appendNdjson, nowIso, readJsonFile, writeJsonFile } from './utils.ts';
4
+ import type {
5
+ ConversationRef,
6
+ InboundAcceptanceRecord,
7
+ SessionMeta,
8
+ TurnDeliveryStatus,
9
+ TurnExecutionStatus,
10
+ TurnLedgerRecord,
11
+ TurnRecord,
12
+ } from './types.ts';
13
+
14
+ export interface TurnLedgerStoreDeps {
15
+ ensureSessionDirs(ref: ConversationRef): string;
16
+ ensureSession(ref: ConversationRef): SessionMeta;
17
+ getSession(ref: ConversationRef): SessionMeta | null;
18
+ resolveSessionDir(ref: ConversationRef): string;
19
+ metaFile(ref: ConversationRef): string;
20
+ eventsFile(ref: ConversationRef): string;
21
+ turnLedgerFile(ref: ConversationRef, turnId: string): string;
22
+ updateInboundAcceptance(
23
+ ref: ConversationRef,
24
+ messageId: string,
25
+ seed?: Partial<InboundAcceptanceRecord>,
26
+ mutate?: (record: InboundAcceptanceRecord, now: string) => void,
27
+ ): InboundAcceptanceRecord;
28
+ }
29
+
30
+ function turnExecutionStatusFromRuntimeStatus(status: string): TurnExecutionStatus {
31
+ if (status === 'completed') {
32
+ return 'completed';
33
+ }
34
+ if (status === 'interrupted') {
35
+ return 'interrupted';
36
+ }
37
+ if (status === 'failed') {
38
+ return 'failed';
39
+ }
40
+ return 'failed';
41
+ }
42
+
43
+ function syncInboundAcceptanceFromTurn(
44
+ deps: TurnLedgerStoreDeps,
45
+ ref: ConversationRef,
46
+ ledger: TurnLedgerRecord,
47
+ now: string,
48
+ ): void {
49
+ if (!ledger.messageId) {
50
+ return;
51
+ }
52
+ deps.updateInboundAcceptance(ref, ledger.messageId, {
53
+ threadId: ledger.threadId || null,
54
+ turnId: ledger.turnId,
55
+ executionStatus: ledger.executionStatus,
56
+ }, (record) => {
57
+ record.threadId = ledger.threadId || record.threadId || null;
58
+ record.turnId = ledger.turnId;
59
+ record.executionStatus = ledger.executionStatus;
60
+ if (!record.acceptedAt) {
61
+ record.acceptedAt = now;
62
+ }
63
+ });
64
+ }
65
+
66
+ function normalizeTurnLedger(
67
+ deps: TurnLedgerStoreDeps,
68
+ ref: ConversationRef,
69
+ turnId: string,
70
+ current: TurnLedgerRecord | null,
71
+ seed: Partial<TurnLedgerRecord> = {},
72
+ now = nowIso(),
73
+ ): TurnLedgerRecord {
74
+ const session = deps.getSession(ref);
75
+ return {
76
+ turnId,
77
+ threadId: current?.threadId || seed.threadId || session?.threadId || '',
78
+ messageId: current?.messageId ?? seed.messageId ?? null,
79
+ promptPreview: current?.promptPreview ?? seed.promptPreview ?? null,
80
+ createdAt: current?.createdAt || now,
81
+ updatedAt: now,
82
+ executionStatus: current?.executionStatus || (seed.executionStatus as TurnExecutionStatus | undefined) || 'running',
83
+ replyPreview: current?.replyPreview ?? seed.replyPreview ?? null,
84
+ error: current?.error ?? seed.error ?? null,
85
+ deliveryStatus: current?.deliveryStatus || (seed.deliveryStatus as TurnDeliveryStatus | undefined) || 'not_ready',
86
+ deliveredAt: current?.deliveredAt ?? seed.deliveredAt ?? null,
87
+ suppressedByMessageId: current?.suppressedByMessageId ?? seed.suppressedByMessageId ?? null,
88
+ suppressedByTurnId: current?.suppressedByTurnId ?? seed.suppressedByTurnId ?? null,
89
+ suppressionReason: current?.suppressionReason ?? seed.suppressionReason ?? null,
90
+ };
91
+ }
92
+
93
+ function updateTurnLedger(
94
+ deps: TurnLedgerStoreDeps,
95
+ ref: ConversationRef,
96
+ turnId: string,
97
+ seed: Partial<TurnLedgerRecord> = {},
98
+ mutate?: (ledger: TurnLedgerRecord, now: string) => void,
99
+ ): TurnLedgerRecord {
100
+ deps.ensureSessionDirs(ref);
101
+ const file = deps.turnLedgerFile(ref, turnId);
102
+ const current = readJsonFile(file) as TurnLedgerRecord | null;
103
+ const now = nowIso();
104
+ const ledger = normalizeTurnLedger(deps, ref, turnId, current, seed, now);
105
+ mutate?.(ledger, now);
106
+ ledger.updatedAt = now;
107
+ writeJsonFile(file, ledger);
108
+ syncInboundAcceptanceFromTurn(deps, ref, ledger, now);
109
+ appendNdjson(deps.eventsFile(ref), {
110
+ type: 'turn_ledger_updated',
111
+ at: now,
112
+ turn: ledger,
113
+ });
114
+ return ledger;
115
+ }
116
+
117
+ export function markActiveTurn(
118
+ deps: TurnLedgerStoreDeps,
119
+ ref: ConversationRef,
120
+ turnId: string,
121
+ details?: { messageId?: string | null; promptPreview?: string | null },
122
+ ): SessionMeta {
123
+ const meta = deps.ensureSession(ref);
124
+ meta.activeTurnId = turnId;
125
+ meta.pendingUserInputRequestId = null;
126
+ if (details && 'messageId' in details) {
127
+ meta.lastMessageId = details.messageId || null;
128
+ }
129
+ if (details && 'promptPreview' in details) {
130
+ meta.lastPromptPreview = details.promptPreview || null;
131
+ }
132
+ meta.updatedAt = nowIso();
133
+ writeJsonFile(deps.metaFile(ref), meta);
134
+ appendNdjson(deps.eventsFile(ref), {
135
+ type: 'turn_started',
136
+ at: meta.updatedAt,
137
+ turnId,
138
+ });
139
+ updateTurnLedger(deps, ref, turnId, {
140
+ threadId: meta.threadId || '',
141
+ messageId: details?.messageId || null,
142
+ promptPreview: details?.promptPreview || null,
143
+ }, (ledger) => {
144
+ ledger.executionStatus = 'running';
145
+ ledger.error = null;
146
+ ledger.replyPreview = null;
147
+ ledger.deliveryStatus = 'not_ready';
148
+ ledger.deliveredAt = null;
149
+ ledger.suppressedByMessageId = null;
150
+ ledger.suppressedByTurnId = null;
151
+ ledger.suppressionReason = null;
152
+ });
153
+ return meta;
154
+ }
155
+
156
+ export function markTurnRunning(deps: TurnLedgerStoreDeps, ref: ConversationRef, turnId: string): TurnLedgerRecord {
157
+ return updateTurnLedger(deps, ref, turnId, {}, (ledger) => {
158
+ if (ledger.deliveryStatus === 'suppressed') {
159
+ return;
160
+ }
161
+ ledger.executionStatus = 'running';
162
+ });
163
+ }
164
+
165
+ export function noteTurnTerminalState(
166
+ deps: TurnLedgerStoreDeps,
167
+ ref: ConversationRef,
168
+ turnId: string,
169
+ details: { threadId: string; status: string; reply?: string | null; error?: string | null },
170
+ ): TurnLedgerRecord {
171
+ return updateTurnLedger(deps, ref, turnId, {
172
+ threadId: details.threadId,
173
+ }, (ledger, now) => {
174
+ ledger.threadId = details.threadId;
175
+ ledger.executionStatus = turnExecutionStatusFromRuntimeStatus(details.status || 'failed');
176
+ ledger.replyPreview = (details.reply || '').trim().slice(0, 160) || null;
177
+ ledger.error = details.error || null;
178
+ if (ledger.deliveryStatus !== 'suppressed') {
179
+ ledger.deliveryStatus = 'pending';
180
+ }
181
+ });
182
+ }
183
+
184
+ export function markTurnSuppressed(
185
+ deps: TurnLedgerStoreDeps,
186
+ ref: ConversationRef,
187
+ turnId: string,
188
+ details: { threadId?: string | null; suppressedByMessageId?: string | null; suppressedByTurnId?: string | null; reason: string },
189
+ ): TurnLedgerRecord {
190
+ return updateTurnLedger(deps, ref, turnId, {
191
+ threadId: details.threadId || undefined,
192
+ }, (ledger) => {
193
+ ledger.deliveryStatus = 'suppressed';
194
+ ledger.suppressedByMessageId = details.suppressedByMessageId || null;
195
+ ledger.suppressedByTurnId = details.suppressedByTurnId || null;
196
+ ledger.suppressionReason = details.reason;
197
+ });
198
+ }
199
+
200
+ export function markTurnDelivery(
201
+ deps: TurnLedgerStoreDeps,
202
+ ref: ConversationRef,
203
+ turnId: string,
204
+ status: 'delivered' | 'delivery_unavailable',
205
+ ): TurnLedgerRecord {
206
+ return updateTurnLedger(deps, ref, turnId, {}, (ledger, now) => {
207
+ if (ledger.deliveryStatus === 'suppressed') {
208
+ return;
209
+ }
210
+ ledger.deliveryStatus = status;
211
+ if (status === 'delivered') {
212
+ ledger.deliveredAt = now;
213
+ }
214
+ });
215
+ }
216
+
217
+ export function findLatestDeliveryIssue(deps: TurnLedgerStoreDeps, ref: ConversationRef): TurnLedgerRecord | null {
218
+ const dir = path.join(deps.resolveSessionDir(ref), 'turn-ledger');
219
+ if (!fs.existsSync(dir)) {
220
+ return null;
221
+ }
222
+ return fs.readdirSync(dir)
223
+ .filter((entry) => entry.endsWith('.json'))
224
+ .map((entry) => readJsonFile(path.join(dir, entry)) as TurnLedgerRecord | null)
225
+ .filter((ledger): ledger is TurnLedgerRecord => Boolean(ledger))
226
+ .filter((ledger) => ledger.deliveryStatus === 'delivery_unavailable')
227
+ .sort((left, right) => String(right.updatedAt).localeCompare(String(left.updatedAt)))[0] || null;
228
+ }
229
+
230
+ export function getTurnLedger(deps: TurnLedgerStoreDeps, ref: ConversationRef, turnId: string): TurnLedgerRecord | null {
231
+ return readJsonFile(deps.turnLedgerFile(ref, turnId)) as TurnLedgerRecord | null;
232
+ }
233
+
234
+ export function getTurnRecord(deps: TurnLedgerStoreDeps, ref: ConversationRef, turnId: string): TurnRecord | null {
235
+ const dir = path.join(deps.resolveSessionDir(ref), 'turns');
236
+ if (!fs.existsSync(dir)) {
237
+ return null;
238
+ }
239
+ const suffix = `-${turnId}.json`;
240
+ const match = fs.readdirSync(dir)
241
+ .filter((entry) => entry.endsWith(suffix))
242
+ .sort((left, right) => right.localeCompare(left))[0];
243
+ if (!match) {
244
+ return null;
245
+ }
246
+ return readJsonFile(path.join(dir, match)) as TurnRecord | null;
247
+ }
248
+
249
+ export function recordTurn(deps: TurnLedgerStoreDeps, ref: ConversationRef, turn: TurnRecord): void {
250
+ const sessionDir = deps.resolveSessionDir(ref);
251
+ deps.ensureSessionDirs(ref);
252
+ const meta = deps.ensureSession(ref);
253
+ meta.activeTurnId = null;
254
+ meta.lastTurnId = turn.turnId;
255
+ meta.lastReplyPreview = (turn.reply || '').trim().slice(0, 160) || null;
256
+ meta.pendingApprovalIds = [];
257
+ meta.pendingUserInputRequestId = null;
258
+ meta.updatedAt = nowIso();
259
+ writeJsonFile(deps.metaFile(ref), meta);
260
+ writeJsonFile(path.join(sessionDir, 'turns', `${turn.startedAt.replace(/[:.]/g, '-')}-${turn.turnId}.json`), turn);
261
+ appendNdjson(deps.eventsFile(ref), {
262
+ type: 'turn',
263
+ at: nowIso(),
264
+ turn,
265
+ });
266
+ noteTurnTerminalState(deps, ref, turn.turnId, {
267
+ threadId: turn.threadId,
268
+ status: turn.status || 'failed',
269
+ reply: turn.reply,
270
+ error: turn.error || null,
271
+ });
272
+ }