@akagilnc/pi-workflow-roles 0.1.5241 → 0.1.5252

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 (41) hide show
  1. package/README.md +2 -3
  2. package/README.zh-CN.md +2 -3
  3. package/dist/acp-host/production-host.js +482 -3141
  4. package/dist/collector-config.js +0 -1
  5. package/dist/headless-host/production-host.js +590 -3249
  6. package/dist/migrate-book-topology.js +40 -107
  7. package/dist/navigator-invocation-identity.js +0 -57
  8. package/dist/package-contracts/collector-output.js +1 -90
  9. package/dist/package-contracts/terminating-tools.js +2 -2
  10. package/dist/packaged-role-registry.js +8 -11
  11. package/dist/public-cli/invocation.js +2 -22
  12. package/dist/public-cli/main.js +256 -749
  13. package/dist/public-cli/option-definitions.js +4 -19
  14. package/dist/public-cli/settlement.js +12 -138
  15. package/package.json +1 -1
  16. package/resources/collector-bot-handbook.md +4 -2
  17. package/src/collector-config.ts +0 -1
  18. package/src/collector-role.ts +40 -535
  19. package/src/collector-tool-schemas.ts +7 -117
  20. package/src/gh-api-runner.ts +102 -0
  21. package/src/navigator-invocation-identity.ts +4 -121
  22. package/src/package-contracts/collector-output.ts +15 -174
  23. package/src/package-contracts/terminating-tools.ts +0 -2
  24. package/src/packaged-role-registry.ts +7 -10
  25. package/src/public-cli/invocation.ts +3 -27
  26. package/src/public-cli/option-definitions.ts +4 -19
  27. package/src/public-cli/settlement.ts +11 -177
  28. package/src/role-runtime-dependencies.ts +0 -4
  29. package/src/role-runtime.ts +39 -103
  30. package/src/ticket-snapshot.ts +1 -1
  31. package/dist/collector-evidence.js +0 -319
  32. package/dist/collector-github.js +0 -725
  33. package/dist/collector-identity.js +0 -92
  34. package/dist/collector-ledger.js +0 -888
  35. package/dist/collector-target.js +0 -169
  36. package/src/collector-evidence.ts +0 -466
  37. package/src/collector-github.ts +0 -1032
  38. package/src/collector-handbook.ts +0 -194
  39. package/src/collector-identity.ts +0 -151
  40. package/src/collector-ledger.ts +0 -1186
  41. package/src/collector-target.ts +0 -207
@@ -1,1186 +0,0 @@
1
- import type { CollectorManifest, CollectorRepository } from "./collector-config.ts";
2
- import {
3
- applyEvidenceVersionHistory,
4
- assignWindowRelations,
5
- COLLECTOR_DEFAULT_WAIT_WINDOW_MS,
6
- measureNormalizedBytes,
7
- normalizeAuthenticatedUserEvidence,
8
- normalizeIssueCommentEvidence,
9
- normalizePullRequestEvidence,
10
- normalizePullRequestReactionEvidence,
11
- normalizeReviewCommentEvidence,
12
- normalizeReviewEvidence,
13
- sha256Text,
14
- type CollectorClock,
15
- type CollectorEvidenceRecord,
16
- type CollectorSnapshot,
17
- type HeadRelation,
18
- type WindowRelation,
19
- } from "./collector-evidence.ts";
20
- import {
21
- buildCollectorRequestBody,
22
- type CollectorGitHubTransport,
23
- type GitHubPageDiagnostics,
24
- type GitHubPullRequest,
25
- } from "./collector-github.ts";
26
- import {
27
- CollectorNonOpenRequestError,
28
- CollectorWaitWindowClosedError,
29
- } from "./collector-identity.ts";
30
- import { COLLECTOR_OUTPUT_TOOL } from "./package-contracts/collector-output.ts";
31
-
32
- export const COLLECTOR_OBSERVE_TOOL = "ak_collector_observe";
33
- export const COLLECTOR_READ_TOOL = "ak_collector_read";
34
- export const COLLECTOR_REQUEST_TOOL = "ak_collector_request";
35
- export const COLLECTOR_WAIT_TOOL = "ak_collector_wait";
36
- /** #678 D4: open wait window at a work step — business tool, ledger-booked. */
37
- export const COLLECTOR_OPEN_WAIT_WINDOW_TOOL = "ak_collector_open_wait_window";
38
- /** #676 A: role-decided target bind — business tool, ledger-booked. */
39
- export const COLLECTOR_BIND_TARGET_TOOL = "ak_collector_bind_target";
40
- /** #677: opaque handbook write — business tool, ledger-booked. */
41
- export const COLLECTOR_HANDBOOK_WRITE_TOOL = "ak_collector_handbook_write";
42
- export { COLLECTOR_OUTPUT_TOOL };
43
-
44
- export const COLLECTOR_OPERATIONAL_TOOLS = [
45
- COLLECTOR_BIND_TARGET_TOOL,
46
- COLLECTOR_OBSERVE_TOOL,
47
- COLLECTOR_READ_TOOL,
48
- COLLECTOR_REQUEST_TOOL,
49
- COLLECTOR_OPEN_WAIT_WINDOW_TOOL,
50
- COLLECTOR_WAIT_TOOL,
51
- COLLECTOR_HANDBOOK_WRITE_TOOL,
52
- ] as const;
53
-
54
- // #836: observe body truncation deleted (A6.4). Full body is the material.
55
-
56
- export type ObserveEvidenceEntry = {
57
- evidenceId: string;
58
- kind: string;
59
- authorLogin?: string | undefined;
60
- state?: string | undefined;
61
- body?: string | undefined;
62
- commitOid?: string | null | undefined;
63
- htmlUrl?: string | undefined;
64
- path?: string | undefined;
65
- line?: number | null | undefined;
66
- side?: string | null | undefined;
67
- authoritativeTime?: string | null | undefined;
68
- windowRelation?: WindowRelation | undefined;
69
- pullRequestReviewId?: number | null | undefined;
70
- };
71
-
72
- export type ObserveModelView = {
73
- snapshotId: string;
74
- observedAt: string;
75
- completedAt: string;
76
- prState: string;
77
- headOid: string;
78
- /** PR create success time when known — new-PR wait-window startedAt (#678 D4). */
79
- prCreatedAt?: string;
80
- complete: boolean;
81
- evidence: ObserveEvidenceEntry[];
82
- requestAttempts: Array<{
83
- attemptId: string;
84
- requestId: string;
85
- observedHead: string;
86
- status: string;
87
- marker: string;
88
- recoverySnapshotId?: string | undefined;
89
- }>;
90
- };
91
-
92
- /** #836: observe context is the full volume view — no body truncation. */
93
- function projectObserveContextView(modelView: ObserveModelView): ObserveModelView {
94
- return modelView;
95
- }
96
-
97
- export type CollectorOperationalTool = (typeof COLLECTOR_OPERATIONAL_TOOLS)[number];
98
-
99
- export const COLLECTOR_ACTIVATION_ENTRY_TYPE = "ak-collector-activation" as const;
100
- const COLLECTOR_SNAPSHOT_ENTRY_TYPE = "ak-collector-snapshot" as const;
101
- const COLLECTOR_REQUEST_ENTRY_TYPE = "ak-collector-request" as const;
102
- const COLLECTOR_WAIT_ENTRY_TYPE = "ak-collector-wait" as const;
103
-
104
- export type CollectorRequestAttempt = {
105
- attemptId: string;
106
- requestId: string;
107
- observedHead: string;
108
- snapshotId: string;
109
- marker: string;
110
- body: string;
111
- startedAt: string;
112
- status: "started" | "succeeded" | "rejected" | "ambiguous_loss" | "recovered";
113
- responseDiagnostics?: string;
114
- commentEvidenceId?: string;
115
- /** Snapshot whose observation first established the authenticated marker. */
116
- recoverySnapshotId?: string;
117
- };
118
-
119
- export type CollectorWaitRecord = {
120
- waitId: string;
121
- requestedMs: number;
122
- effectiveMs: number;
123
- startedAt: string;
124
- endedAt: string;
125
- cutoffReached: boolean;
126
- };
127
-
128
- export type CollectorTransportFailure = {
129
- failureId: string;
130
- kind: "ambiguous_request_loss" | "api" | "pagination" | "size";
131
- message: string;
132
- requestId?: string;
133
- observedHead?: string;
134
- marker?: string;
135
- recovered: boolean;
136
- };
137
-
138
- export type CollectorConfigState = {
139
- repository: CollectorRepository;
140
- /** Bound PR target; undefined until explicit flag, admission bind, or role bind-target tool. */
141
- prNumber: number | undefined;
142
- manifest: CollectorManifest;
143
- /**
144
- * Wait window duration (#678 D4). Default 10 minutes; caller-configurable without code change.
145
- * Window opens at a work step (PR create success / trigger-phase end), not session activation.
146
- */
147
- waitWindowMs: number;
148
- };
149
-
150
- export type CollectorLedgerConfigInput = Omit<CollectorConfigState, "waitWindowMs"> & {
151
- waitWindowMs?: number;
152
- };
153
-
154
- /** Durable session journal sink owned by the shared execution seam. */
155
- export type CollectorDurableJournal = {
156
- append(customType: string, data: unknown): void;
157
- };
158
-
159
- export type CollectorLedgerOptions = {
160
- readonly clock?: CollectorClock | undefined;
161
- readonly journal?: CollectorDurableJournal | undefined;
162
- /** Prior dossier custom entries; replayed in order through live business transitions. */
163
- readonly dossierEntries?: Iterable<unknown> | undefined;
164
- };
165
-
166
- export type CollectorLedger = {
167
- readonly config: CollectorConfigState;
168
- readonly fatal: boolean;
169
- readonly fatalReason: string | undefined;
170
- readonly outputCandidate: boolean;
171
- /** Session ready (before_agent_start); not the wait window. */
172
- readonly activationRecorded: boolean;
173
- /** Wait-window start (receipt activationTime); undefined until openWaitWindow. */
174
- readonly activationTime: Date | undefined;
175
- /** Wait-window end; undefined until openWaitWindow. */
176
- readonly deadlineTime: Date | undefined;
177
- readonly activationMono: number | undefined;
178
- readonly deadlineMono: number | undefined;
179
- readonly requesterLogin: string | undefined;
180
- readonly latestCompleteSnapshotId: string | undefined;
181
- readonly finalObservationRequired: boolean;
182
- readonly finalObservationCompleted: boolean;
183
- readonly unresolvedTransportFailure: boolean;
184
- readonly mutationGeneration: number;
185
- readonly observedGeneration: number;
186
-
187
- latchFatal(reason: string, cause?: unknown): Error;
188
- assertNotFatal(): void;
189
- /** Mark session ready for prep observe/request; does not open the wait window (#678). */
190
- recordActivation(clock: CollectorClock): void;
191
- /**
192
- * Open the wait window once at a work step. Optional startedAt covers new-PR create success;
193
- * omit for existing-PR trigger-phase end (= now). Second call is a no-op (D6: updates do not reset).
194
- */
195
- openWaitWindow(clock: CollectorClock, options?: { startedAt?: Date }): void;
196
- recordOutputCandidate(): void;
197
- /** #676 A: role-decided unique PR bind (business fact on the ledger). */
198
- bindTarget(prNumber: number): void;
199
- beginOperational(toolName: string, toolCallId: string): void;
200
- completeOperational(toolCallId: string): void;
201
- noteCutoffObserved(): void;
202
- assertOutputObservationLaw(clock: CollectorClock): void;
203
-
204
- observe(
205
- transport: CollectorGitHubTransport,
206
- clock: CollectorClock,
207
- signal?: AbortSignal,
208
- ): Promise<{
209
- snapshot: CollectorSnapshot;
210
- contextView: ObserveModelView;
211
- }>;
212
-
213
- request(
214
- input: { requestId: string; snapshotId: string; body?: string },
215
- transport: CollectorGitHubTransport,
216
- clock: CollectorClock,
217
- signal?: AbortSignal,
218
- ): Promise<unknown>;
219
-
220
- wait(
221
- input: { durationMs: number },
222
- clock: CollectorClock,
223
- signal?: AbortSignal,
224
- ): Promise<unknown>;
225
-
226
- getSnapshot(snapshotId: string): CollectorSnapshot | undefined;
227
- getEvidence(evidenceId: string): CollectorEvidenceRecord | undefined;
228
- allEvidence(): readonly CollectorEvidenceRecord[];
229
- allSnapshots(): readonly CollectorSnapshot[];
230
- requestAttempts(): readonly CollectorRequestAttempt[];
231
- waits(): readonly CollectorWaitRecord[];
232
- transportFailures(): readonly CollectorTransportFailure[];
233
- requestById(requestId: string): CollectorConfigState["manifest"]["requests"][number] | undefined;
234
- };
235
-
236
- function isOperationalTool(name: string): name is CollectorOperationalTool {
237
- return (COLLECTOR_OPERATIONAL_TOOLS as readonly string[]).includes(name);
238
- }
239
-
240
- function resolveWaitWindowMs(raw: number | undefined): number {
241
- if (raw === undefined) return COLLECTOR_DEFAULT_WAIT_WINDOW_MS;
242
- if (!Number.isSafeInteger(raw) || raw < 1) {
243
- throw new Error("通进司 waitWindowMs 须为正安全整数毫秒");
244
- }
245
- return raw;
246
- }
247
-
248
- export function createCollectorLedger(
249
- input: CollectorLedgerConfigInput,
250
- options?: CollectorLedgerOptions,
251
- ): CollectorLedger {
252
- const config: CollectorConfigState = {
253
- repository: input.repository,
254
- prNumber: input.prNumber,
255
- manifest: input.manifest,
256
- waitWindowMs: resolveWaitWindowMs(input.waitWindowMs),
257
- };
258
- const clock = options?.clock;
259
- const journal = options?.journal;
260
- let fatal = false;
261
- let fatalReason: string | undefined;
262
- let outputCandidate = false;
263
- let pendingOutputCallId: string | undefined;
264
- let sessionReady = false;
265
- let activationTime: Date | undefined;
266
- let deadlineTime: Date | undefined;
267
- let activationMono: number | undefined;
268
- let deadlineMono: number | undefined;
269
- let requesterLogin: string | undefined;
270
- let latestCompleteSnapshotId: string | undefined;
271
- let finalObservationRequired = false;
272
- let finalObservationCompleted = false;
273
- let activeOperationalCallId: string | undefined;
274
- let mutationGeneration = 0;
275
- let observedGeneration = 0;
276
-
277
- const evidenceById = new Map<string, CollectorEvidenceRecord>();
278
- const evidenceByVersion = new Map<string, string>();
279
- const snapshots: CollectorSnapshot[] = [];
280
- const attempts: CollectorRequestAttempt[] = [];
281
- const attemptKeys = new Set<string>();
282
- const waits: CollectorWaitRecord[] = [];
283
- const transportFailures: CollectorTransportFailure[] = [];
284
-
285
- const latchFatal = (reason: string, cause?: unknown): Error => {
286
- fatal = true;
287
- fatalReason = reason;
288
- const error = new Error(reason, cause === undefined ? undefined : { cause });
289
- Object.assign(error, { collectorFatal: true });
290
- return error;
291
- };
292
-
293
- const assertNotFatal = (): void => {
294
- if (fatal) throw new Error(fatalReason ?? "通进司致命状态");
295
- };
296
-
297
- const storeEvidence = (record: CollectorEvidenceRecord): CollectorEvidenceRecord => {
298
- const existingId = evidenceByVersion.get(record.versionId);
299
- if (existingId !== undefined) {
300
- return evidenceById.get(existingId) ?? record;
301
- }
302
- evidenceByVersion.set(record.versionId, record.evidenceId);
303
- evidenceById.set(record.evidenceId, record);
304
- return record;
305
- };
306
-
307
- const monoNowOrThrow = (clock: CollectorClock): number => clock.monoNow();
308
-
309
- const pastCutoff = (clock: CollectorClock): boolean => {
310
- if (deadlineMono === undefined) return false;
311
- return monoNowOrThrow(clock) >= deadlineMono;
312
- };
313
-
314
- const remainingMs = (clock: CollectorClock): number => {
315
- if (deadlineMono === undefined) return config.waitWindowMs;
316
- return Math.max(0, deadlineMono - monoNowOrThrow(clock));
317
- };
318
-
319
- const prIdentity = (pr: GitHubPullRequest): string =>
320
- `${pr.state}|${pr.headOid}|${pr.updatedAt ?? ""}`;
321
-
322
- const requireBoundPr = (): number => {
323
- if (config.prNumber === undefined) {
324
- throw new Error("通进司 PR 目标未绑定");
325
- }
326
- return config.prNumber;
327
- };
328
-
329
- const fetchObserveSurfaces = async (
330
- transport: CollectorGitHubTransport,
331
- observedAt: string,
332
- signal?: AbortSignal,
333
- ) => {
334
- const owner = config.repository.owner;
335
- const repo = config.repository.repo;
336
- const prNumber = requireBoundPr();
337
- const signalOpt = signal === undefined ? {} : { signal };
338
- const user = await transport.getAuthenticatedUser(signalOpt);
339
- const prInitial = await transport.getPullRequest({
340
- owner,
341
- repo,
342
- prNumber,
343
- ...signalOpt,
344
- });
345
- const reviews = await transport.listPullRequestReviews({
346
- owner,
347
- repo,
348
- prNumber,
349
- ...signalOpt,
350
- });
351
- const reactions = transport.listPullRequestReactions === undefined
352
- ? { items: [], pages: [] }
353
- : await transport.listPullRequestReactions({ owner, repo, prNumber, ...signalOpt });
354
- const issueComments = await transport.listIssueComments({
355
- owner,
356
- repo,
357
- prNumber,
358
- ...signalOpt,
359
- });
360
- const reviewComments = await transport.listReviewComments({
361
- owner,
362
- repo,
363
- prNumber,
364
- ...signalOpt,
365
- });
366
- const prTerminal = await transport.getPullRequest({
367
- owner,
368
- repo,
369
- prNumber,
370
- ...signalOpt,
371
- });
372
- return { user, prInitial, reviews, reactions, issueComments, reviewComments, prTerminal };
373
- };
374
-
375
-
376
- const appendJournal = (customType: string, data: unknown): void => {
377
- journal?.append(customType, data);
378
- };
379
-
380
- const bindDeadlineMonoFromWall = (): void => {
381
- if (clock === undefined || activationTime === undefined || deadlineTime === undefined) return;
382
- const wallNow = clock.wallNow().getTime();
383
- const monoNow = clock.monoNow();
384
- activationMono = monoNow - (wallNow - activationTime.getTime());
385
- deadlineMono = monoNow + (deadlineTime.getTime() - wallNow);
386
- };
387
-
388
- const rebindSnapshotCompletedMono = (snapshot: CollectorSnapshot): CollectorSnapshot => {
389
- const copy: CollectorSnapshot = { ...snapshot, evidenceIds: [...snapshot.evidenceIds] };
390
- if (deadlineTime !== undefined && deadlineMono !== undefined && copy.completedAt !== undefined) {
391
- const completedWall = new Date(copy.completedAt).getTime();
392
- copy.completedMono = deadlineMono + (completedWall - deadlineTime.getTime());
393
- }
394
- return copy;
395
- };
396
-
397
- const commitActivationWindow = (nextActivation: Date, nextDeadline: Date): void => {
398
- // D6: once open, PR updates / second open must not reset the window.
399
- if (activationTime !== undefined) return;
400
- sessionReady = true;
401
- activationTime = nextActivation;
402
- deadlineTime = nextDeadline;
403
- bindDeadlineMonoFromWall();
404
- };
405
-
406
- const recoverAmbiguousRequestLosses = (
407
- snapshotId: string,
408
- observedRecords: readonly CollectorEvidenceRecord[],
409
- ): void => {
410
- for (const failure of transportFailures) {
411
- if (failure.recovered || failure.kind !== "ambiguous_request_loss") continue;
412
- if (failure.marker === undefined || failure.requestId === undefined) continue;
413
- const found = observedRecords.find((record) =>
414
- record.kind === "issue_comment" &&
415
- record.authorLogin === requesterLogin &&
416
- typeof record.body === "string" &&
417
- record.body.includes(failure.marker!)
418
- );
419
- if (found === undefined) continue;
420
- failure.recovered = true;
421
- const attempt = attempts.find((item) =>
422
- item.status === "ambiguous_loss" &&
423
- item.requestId === failure.requestId &&
424
- item.marker === failure.marker
425
- );
426
- if (attempt !== undefined) {
427
- attempt.status = "recovered";
428
- attempt.commentEvidenceId = found.evidenceId;
429
- attempt.recoverySnapshotId = snapshotId;
430
- }
431
- }
432
- };
433
-
434
- const finalizeObservedSnapshot = (snapshot: CollectorSnapshot): CollectorSnapshot => {
435
- if (requesterLogin === undefined) {
436
- for (const id of snapshot.evidenceIds) {
437
- const record = evidenceById.get(id);
438
- if (record?.kind === "authenticated_user" && record.authorLogin !== undefined) {
439
- requesterLogin = record.authorLogin.toLowerCase();
440
- break;
441
- }
442
- }
443
- }
444
- const stored = rebindSnapshotCompletedMono(snapshot);
445
- snapshots.push(stored);
446
- latestCompleteSnapshotId = stored.snapshotId;
447
- const observedRecords = stored.evidenceIds.flatMap((id) => {
448
- const record = evidenceById.get(id);
449
- return record === undefined ? [] : [record];
450
- });
451
- recoverAmbiguousRequestLosses(stored.snapshotId, observedRecords);
452
- observedGeneration = mutationGeneration;
453
- if (
454
- finalObservationRequired &&
455
- stored.completedMono !== undefined &&
456
- deadlineMono !== undefined &&
457
- stored.completedMono >= deadlineMono
458
- ) {
459
- finalObservationCompleted = true;
460
- } else if (
461
- clock !== undefined &&
462
- deadlineMono !== undefined &&
463
- clock.monoNow() >= deadlineMono &&
464
- stored.completedMono !== undefined &&
465
- stored.completedMono >= deadlineMono
466
- ) {
467
- finalObservationRequired = true;
468
- finalObservationCompleted = true;
469
- }
470
- return stored;
471
- };
472
-
473
- const commitObservedSnapshot = (
474
- snapshot: CollectorSnapshot,
475
- evidenceRecords: readonly CollectorEvidenceRecord[],
476
- ): CollectorSnapshot => {
477
- for (const record of evidenceRecords) {
478
- storeEvidence(record);
479
- }
480
- return finalizeObservedSnapshot(snapshot);
481
- };
482
-
483
- const commitRequestAttempt = (
484
- attempt: CollectorRequestAttempt,
485
- attemptKey: string,
486
- commentEvidence: CollectorEvidenceRecord | undefined,
487
- ): void => {
488
- if (commentEvidence !== undefined) {
489
- storeEvidence(commentEvidence);
490
- }
491
- const existing = attempts.find((item) => item.attemptId === attempt.attemptId);
492
- if (existing === undefined) {
493
- attempts.push({ ...attempt });
494
- attemptKeys.add(attemptKey);
495
- } else {
496
- Object.assign(existing, attempt);
497
- }
498
- if (attempt.status === "ambiguous_loss" && !transportFailures.some((failure) => failure.requestId === attempt.requestId && failure.observedHead === attempt.observedHead)) {
499
- transportFailures.push({
500
- failureId: sha256Text(`loss:${attempt.attemptId}`).slice(0, 16),
501
- kind: "ambiguous_request_loss",
502
- message: attempt.responseDiagnostics ?? "ambiguous request loss",
503
- requestId: attempt.requestId,
504
- observedHead: attempt.observedHead,
505
- marker: attempt.marker,
506
- recovered: false,
507
- });
508
- }
509
- if (attempt.status === "succeeded" || attempt.status === "ambiguous_loss") {
510
- mutationGeneration += 1;
511
- finalObservationCompleted = false;
512
- }
513
- };
514
-
515
- const commitWaitRecord = (wait: CollectorWaitRecord): void => {
516
- waits.push({ ...wait });
517
- if (wait.cutoffReached) finalObservationRequired = true;
518
- mutationGeneration += 1;
519
- finalObservationCompleted = false;
520
- };
521
-
522
- const replayDossierEntries = (entries: Iterable<unknown>): void => {
523
- const orderedEntries = Array.from(entries);
524
- const finalRequestStatus = new Map<string, CollectorRequestAttempt["status"]>();
525
- for (const raw of orderedEntries) {
526
- if (typeof raw !== "object" || raw === null) continue;
527
- const entry = raw as { type?: unknown; customType?: unknown; data?: unknown };
528
- if (entry.type !== "custom" || entry.customType !== COLLECTOR_REQUEST_ENTRY_TYPE || typeof entry.data !== "object" || entry.data === null) continue;
529
- const attempt = (entry.data as Record<string, unknown>).attempt as CollectorRequestAttempt | undefined;
530
- if (attempt?.attemptId !== undefined) finalRequestStatus.set(attempt.attemptId, attempt.status);
531
- }
532
- for (const raw of orderedEntries) {
533
- if (typeof raw !== "object" || raw === null) continue;
534
- const entry = raw as { type?: unknown; customType?: unknown; data?: unknown };
535
- if (entry.type !== "custom" || typeof entry.data !== "object" || entry.data === null) continue;
536
- const data = entry.data as Record<string, unknown>;
537
- if (entry.customType === COLLECTOR_ACTIVATION_ENTRY_TYPE) {
538
- if (typeof data.activationTime === "string" && typeof data.deadlineTime === "string") {
539
- commitActivationWindow(new Date(data.activationTime), new Date(data.deadlineTime));
540
- } else if (data.sessionReady === true) {
541
- sessionReady = true;
542
- }
543
- continue;
544
- }
545
- if (entry.customType === COLLECTOR_SNAPSHOT_ENTRY_TYPE) {
546
- const snapshot = data.snapshot as CollectorSnapshot | undefined;
547
- if (snapshot?.snapshotId === undefined || !Array.isArray(data.evidence)) continue;
548
- // Generations advance only via request/wait commits and observation sync — never from collection sizes or payload counters.
549
- commitObservedSnapshot(snapshot, data.evidence as CollectorEvidenceRecord[]);
550
- continue;
551
- }
552
- if (entry.customType === COLLECTOR_REQUEST_ENTRY_TYPE) {
553
- const attempt = data.attempt as CollectorRequestAttempt | undefined;
554
- if (attempt?.attemptId === undefined) continue;
555
- const attemptKey = typeof data.attemptKey === "string"
556
- ? data.attemptKey
557
- : [config.repository.canonical, String(config.prNumber), attempt.observedHead, attempt.requestId].join("|");
558
- const commentEvidence = data.commentEvidence as CollectorEvidenceRecord | undefined;
559
- const replayAttempt = attempt.status === "started" && finalRequestStatus.get(attempt.attemptId) === "started"
560
- ? {
561
- ...attempt,
562
- status: "ambiguous_loss" as const,
563
- responseDiagnostics: "request interrupted after dispatch before completion was recorded",
564
- }
565
- : attempt;
566
- commitRequestAttempt(replayAttempt, attemptKey, commentEvidence);
567
- continue;
568
- }
569
- if (entry.customType === COLLECTOR_WAIT_ENTRY_TYPE) {
570
- const wait = data.waitRecord as CollectorWaitRecord | undefined;
571
- if (wait?.waitId === undefined) continue;
572
- commitWaitRecord(wait);
573
- }
574
- }
575
- };
576
-
577
- if (options?.dossierEntries !== undefined) {
578
- replayDossierEntries(options.dossierEntries);
579
- }
580
- if (clock !== undefined && deadlineMono !== undefined && clock.monoNow() >= deadlineMono) {
581
- finalObservationRequired = true;
582
- const lastSnap = snapshots.find((item) => item.snapshotId === latestCompleteSnapshotId);
583
- if (lastSnap?.completedMono !== undefined && lastSnap.completedMono >= deadlineMono) {
584
- finalObservationCompleted = true;
585
- }
586
- }
587
-
588
-
589
- const ledger: CollectorLedger = {
590
- get config() {
591
- return config;
592
- },
593
- get fatal() {
594
- return fatal;
595
- },
596
- get fatalReason() {
597
- return fatalReason;
598
- },
599
- get outputCandidate() {
600
- return outputCandidate || pendingOutputCallId !== undefined;
601
- },
602
- get activationRecorded() {
603
- return sessionReady;
604
- },
605
- get activationTime() {
606
- return activationTime;
607
- },
608
- get deadlineTime() {
609
- return deadlineTime;
610
- },
611
- get activationMono() {
612
- return activationMono;
613
- },
614
- get deadlineMono() {
615
- return deadlineMono;
616
- },
617
- get requesterLogin() {
618
- return requesterLogin;
619
- },
620
- get latestCompleteSnapshotId() {
621
- return latestCompleteSnapshotId;
622
- },
623
- get finalObservationRequired() {
624
- return finalObservationRequired;
625
- },
626
- get finalObservationCompleted() {
627
- return finalObservationCompleted;
628
- },
629
- get unresolvedTransportFailure() {
630
- return transportFailures.some((failure) => !failure.recovered);
631
- },
632
- get mutationGeneration() {
633
- return mutationGeneration;
634
- },
635
- get observedGeneration() {
636
- return observedGeneration;
637
- },
638
-
639
- latchFatal,
640
- assertNotFatal,
641
-
642
- recordActivation(_clock) {
643
- assertNotFatal();
644
- if (sessionReady) return;
645
- sessionReady = true;
646
- // Session ready only — wait window opens later at a work step (#678 D4).
647
- appendJournal(COLLECTOR_ACTIVATION_ENTRY_TYPE, {
648
- sessionReady: true,
649
- });
650
- },
651
-
652
- openWaitWindow(clock, options) {
653
- assertNotFatal();
654
- if (!sessionReady) {
655
- throw latchFatal("通进司开启等待窗需要先激活会话");
656
- }
657
- if (activationTime !== undefined) return; // D6: do not reset
658
- const startedAt = options?.startedAt ?? clock.wallNow();
659
- if (!(startedAt instanceof Date) || Number.isNaN(startedAt.getTime())) {
660
- throw new Error("通进司等待窗 startedAt 须为有效时间");
661
- }
662
- const nextDeadline = new Date(startedAt.getTime() + config.waitWindowMs);
663
- // Bind mono relative to current clock so a past startedAt shortens remaining correctly.
664
- activationTime = startedAt;
665
- deadlineTime = nextDeadline;
666
- const wallNow = clock.wallNow().getTime();
667
- const monoNow = clock.monoNow();
668
- activationMono = monoNow - (wallNow - startedAt.getTime());
669
- deadlineMono = monoNow + (nextDeadline.getTime() - wallNow);
670
- appendJournal(COLLECTOR_ACTIVATION_ENTRY_TYPE, {
671
- activationTime: activationTime.toISOString(),
672
- deadlineTime: deadlineTime.toISOString(),
673
- waitWindowMs: config.waitWindowMs,
674
- });
675
- },
676
-
677
- recordOutputCandidate() {
678
- assertNotFatal();
679
- outputCandidate = true;
680
- },
681
-
682
- bindTarget(prNumber) {
683
- assertNotFatal();
684
- config.prNumber = prNumber;
685
- appendJournal("ak-collector-target-bound", {
686
- prNumber,
687
- repository: config.repository.canonical,
688
- });
689
- },
690
-
691
- beginOperational(toolName, toolCallId) {
692
- assertNotFatal();
693
- if (toolName === COLLECTOR_OUTPUT_TOOL) {
694
- pendingOutputCallId = toolCallId;
695
- return;
696
- }
697
- // Idempotent for the same call across tool_call preflight and execute.
698
- if (activeOperationalCallId === toolCallId) {
699
- return;
700
- }
701
- if (activeOperationalCallId !== undefined) {
702
- throw latchFatal("通进司操作调用已在进行");
703
- }
704
-
705
- if (!isOperationalTool(toolName)) {
706
- throw latchFatal(`未知通进司工具 ${toolName}`);
707
- }
708
- activeOperationalCallId = toolCallId;
709
- },
710
-
711
- completeOperational(toolCallId) {
712
- if (pendingOutputCallId === toolCallId) {
713
- pendingOutputCallId = undefined;
714
- }
715
- if (activeOperationalCallId === toolCallId) {
716
- activeOperationalCallId = undefined;
717
- }
718
- },
719
-
720
- noteCutoffObserved() {
721
- finalObservationRequired = true;
722
- },
723
-
724
- assertOutputObservationLaw(clock) {
725
- assertNotFatal();
726
- if (activationTime === undefined || deadlineTime === undefined || deadlineMono === undefined) {
727
- throw new Error("通进司回执需要激活时间线");
728
- }
729
- if (latestCompleteSnapshotId === undefined) {
730
- throw new Error("通进司回执需要完整终局快照");
731
- }
732
- if (observedGeneration !== mutationGeneration) {
733
- throw new Error(
734
- "通进司回执要求在最近 request/wait 变更后完成一次 observe",
735
- );
736
- }
737
- const snapshot = snapshots.find((item) => item.snapshotId === latestCompleteSnapshotId);
738
- if (snapshot === undefined || !snapshot.complete) {
739
- throw new Error("通进司终局快照缺失或不完整");
740
- }
741
-
742
- const mono = monoNowOrThrow(clock);
743
- const atOrAfterCutoff = mono >= deadlineMono;
744
- if (atOrAfterCutoff) {
745
- finalObservationRequired = true;
746
- if (
747
- snapshot.completedMono === undefined ||
748
- snapshot.completedMono < deadlineMono
749
- ) {
750
- throw new Error(
751
- "通进司截止时/后回执要求不早于截止完成的完整观察",
752
- );
753
- }
754
- finalObservationCompleted = true;
755
- }
756
- },
757
-
758
- async observe(transport, clock, signal) {
759
- assertNotFatal();
760
- if (!sessionReady) {
761
- throw latchFatal("通进司观察需要激活");
762
- }
763
- if (signal?.aborted) {
764
- const abortMessage = signal.reason instanceof Error
765
- ? signal.reason.message
766
- : String(signal.reason ?? "已中止");
767
- throw latchFatal(`通进司观察失败:${abortMessage}`, signal.reason);
768
- }
769
- const observedAt = clock.wallNow().toISOString();
770
- const cutoff = pastCutoff(clock);
771
- if (cutoff) {
772
- finalObservationRequired = true;
773
- }
774
-
775
- let surfaces;
776
- try {
777
- surfaces = await fetchObserveSurfaces(transport, observedAt, signal);
778
- if (prIdentity(surfaces.prInitial) !== prIdentity(surfaces.prTerminal)) {
779
- // Retry full surfaces once; bind only a consistent terminal read.
780
- surfaces = await fetchObserveSurfaces(transport, observedAt, signal);
781
- if (prIdentity(surfaces.prInitial) !== prIdentity(surfaces.prTerminal)) {
782
- throw new Error(
783
- `PR 身份在 observe 括弧重试后仍漂移(${prIdentity(surfaces.prInitial)} → ${prIdentity(surfaces.prTerminal)})`,
784
- );
785
- }
786
- }
787
- } catch (error) {
788
- const message = error instanceof Error ? error.message : "未知失败";
789
- throw latchFatal(`通进司观察失败:${message}`, error);
790
- }
791
-
792
- // First-sighting trust must not predate actual surface observation.
793
- // Observe-start may be before cutoff while surfaces arrive after; stamp
794
- // evidence wall metadata and mono trust only once surfaces are in hand
795
- // (budget retain during fetch may keep the temporary start stamp).
796
- const firstObservedAt = clock.wallNow().toISOString(); // metadata
797
- const firstObservedMono = monoNowOrThrow(clock); // trust
798
-
799
- // Always bind terminal PR identity fields.
800
- const pr = surfaces.prTerminal;
801
- const { user, reviews, reactions, issueComments, reviewComments } = surfaces;
802
-
803
- requesterLogin = user.login.toLowerCase();
804
-
805
- const pageDiagnostics: GitHubPageDiagnostics[] = [
806
- ...reviews.pages,
807
- ...reactions.pages,
808
- ...issueComments.pages,
809
- ...reviewComments.pages,
810
- ];
811
-
812
- const pendingRecords: CollectorEvidenceRecord[] = [];
813
- pendingRecords.push(normalizeAuthenticatedUserEvidence(user, firstObservedAt));
814
- pendingRecords.push(normalizePullRequestEvidence(pr, firstObservedAt));
815
- for (const review of reviews.items) {
816
- pendingRecords.push(normalizeReviewEvidence(review, firstObservedAt));
817
- }
818
- for (const reaction of reactions.items) {
819
- pendingRecords.push(normalizePullRequestReactionEvidence(reaction, firstObservedAt));
820
- }
821
- for (const comment of issueComments.items) {
822
- pendingRecords.push(normalizeIssueCommentEvidence(comment, firstObservedAt));
823
- }
824
- for (const comment of reviewComments.items) {
825
- pendingRecords.push(normalizeReviewCommentEvidence(comment, firstObservedAt));
826
- }
827
-
828
- applyEvidenceVersionHistory(
829
- pendingRecords,
830
- [...evidenceById.values()],
831
- { deadlineMono: deadlineMono!, firstObservedMono },
832
- );
833
- assignWindowRelations(pendingRecords, activationTime, deadlineTime);
834
-
835
- const normalizedByteLength = measureNormalizedBytes(pendingRecords);
836
-
837
- // Commit only after complete surfaces validated.
838
- const storedIds: string[] = [];
839
- for (const record of pendingRecords) {
840
- const stored = storeEvidence(record);
841
- storedIds.push(stored.evidenceId);
842
- }
843
- // Project modelView from canonical stored snapshot records (not mutable pending).
844
- const storedRecords = storedIds.map((id) => {
845
- const stored = evidenceById.get(id);
846
- if (stored === undefined) {
847
- throw latchFatal(`通进司观察丢失已存证据 ${id}`);
848
- }
849
- return stored;
850
- });
851
-
852
- const completedAt = clock.wallNow().toISOString();
853
- const completedMono = clock.monoNow();
854
- const snapshotId = sha256Text(
855
- `${completedAt}:${pr.headOid}:${storedIds.join(",")}`,
856
- ).slice(0, 16);
857
-
858
- const snapshot: CollectorSnapshot = {
859
- snapshotId,
860
- observedAt,
861
- completedAt,
862
- completedMono,
863
- host: "github.com",
864
- repository: config.repository.canonical,
865
- prNumber: requireBoundPr(),
866
- prState: pr.state,
867
- headOid: pr.headOid,
868
- ...(pr.createdAt === undefined ? {} : { prCreatedAt: pr.createdAt }),
869
- complete: true,
870
- evidenceIds: storedIds,
871
- pageDiagnostics,
872
- normalizedByteLength,
873
- };
874
- if (cutoff) {
875
- finalObservationRequired = true;
876
- }
877
- const committed = finalizeObservedSnapshot(snapshot);
878
- appendJournal(COLLECTOR_SNAPSHOT_ENTRY_TYPE, {
879
- snapshot: committed,
880
- evidence: committed.evidenceIds.flatMap((id) => {
881
- const record = evidenceById.get(id);
882
- return record === undefined ? [] : [record];
883
- }),
884
- });
885
-
886
- const modelView = buildObserveModelView({
887
- snapshot: committed,
888
- records: committed.evidenceIds.flatMap((id) => {
889
- const record = evidenceById.get(id);
890
- return record === undefined ? [] : [record];
891
- }),
892
- requesterLogin,
893
- attempts,
894
- });
895
-
896
- return {
897
- snapshot: committed,
898
- modelView,
899
- contextView: projectObserveContextView(modelView),
900
- };
901
- },
902
-
903
- async request(input, transport, clock, signal) {
904
- assertNotFatal();
905
- if (!sessionReady) {
906
- throw latchFatal("通进司请求需要激活");
907
- }
908
- if (ledger.unresolvedTransportFailure) {
909
- throw latchFatal("通进司请求时存在未恢复的传输失败");
910
- }
911
-
912
- // Sole request identity seam: trim once, then use everywhere (lookup/marker/attemptKey).
913
- // Schema pattern rejects leading/trailing whitespace at host; trim still collapses
914
- // direct ledger callers and any residual padding into one stable id (#677 D2).
915
- if (typeof input.requestId !== "string") {
916
- throw new Error("通进司 requestId 须为字符串");
917
- }
918
- const requestId = input.requestId.trim();
919
- if (requestId.length === 0) {
920
- throw new Error("通进司 requestId 须为非空(首尾空白不构成身份)");
921
- }
922
- const configured = config.manifest.requests.find((item) => item.id === requestId);
923
- const roleBody = typeof input.body === "string" ? input.body : undefined;
924
- if (configured === undefined) {
925
- // #677: role-decided trigger from handbook/field activity — body required when not in manifest.
926
- if (roleBody === undefined || roleBody.trim().length === 0) {
927
- throw new Error(
928
- `未知通进司 requestId "${requestId}" 且未提供 body;请提交角色判定的请求正文或使用 request-manifest`,
929
- );
930
- }
931
- }
932
-
933
- const snapshot = snapshots.find((item) => item.snapshotId === input.snapshotId);
934
- if (snapshot === undefined) {
935
- throw new Error(`未知通进司 snapshotId "${input.snapshotId}"`);
936
- }
937
- if (snapshot.snapshotId !== latestCompleteSnapshotId) {
938
- throw new Error("通进司请求要求最新完整快照");
939
- }
940
- if (snapshot.prState !== "OPEN") {
941
- // #676 D6: non-OPEN keeps materials; bounce before cutoff fatal so post-deadline materials still seal.
942
- throw new CollectorNonOpenRequestError(snapshot.prState);
943
- }
944
- if (pastCutoff(clock)) {
945
- finalObservationRequired = true;
946
- // #678: do not latch fatal — materials must still seal after the window ends.
947
- throw new CollectorWaitWindowClosedError("request");
948
- }
949
-
950
- // Caller manifest body wins when requestId is configured; otherwise role body.
951
- const configuredBody = configured?.requestBody ?? roleBody!;
952
- const { body, marker } = buildCollectorRequestBody({
953
- configuredBody,
954
- manifestDigest: config.manifest.digest,
955
- requestId,
956
- headOid: snapshot.headOid,
957
- });
958
- const existingMarker = snapshot.evidenceIds.some((id) => {
959
- const record = evidenceById.get(id);
960
- return record?.kind === "issue_comment" &&
961
- record.authorLogin === requesterLogin &&
962
- typeof record.body === "string" &&
963
- record.body.includes(marker);
964
- });
965
- if (existingMarker) {
966
- throw new Error(
967
- `通进司在此 HEAD 已有同 marker 的已认证请求 "${requestId}"`,
968
- );
969
- }
970
-
971
- const boundPr = requireBoundPr();
972
- const attemptKey = [
973
- config.repository.canonical,
974
- String(boundPr),
975
- snapshot.headOid,
976
- requestId,
977
- ].join("|");
978
- if (attemptKeys.has(attemptKey)) {
979
- throw new Error(
980
- `通进司进程内请求 "${requestId}" 在 HEAD ${snapshot.headOid} 的 attempt 已用`,
981
- );
982
- }
983
-
984
- const startedAt = clock.wallNow().toISOString();
985
- const attemptId = sha256Text(`${attemptKey}:${startedAt}`).slice(0, 16);
986
- const attempt: CollectorRequestAttempt = {
987
- attemptId,
988
- requestId,
989
- observedHead: snapshot.headOid,
990
- snapshotId: snapshot.snapshotId,
991
- marker,
992
- body,
993
- startedAt,
994
- status: "started",
995
- };
996
- commitRequestAttempt(attempt, attemptKey, undefined);
997
- appendJournal(COLLECTOR_REQUEST_ENTRY_TYPE, {
998
- attempt: { ...attempt },
999
- attemptKey,
1000
- });
1001
-
1002
- const result = await transport.createIssueComment({
1003
- owner: config.repository.owner,
1004
- repo: config.repository.repo,
1005
- prNumber: boundPr,
1006
- body,
1007
- ...(signal === undefined ? {} : { signal }),
1008
- });
1009
-
1010
- const journalRequest = (commentEvidence: CollectorEvidenceRecord | undefined): void => {
1011
- const attemptKey = [
1012
- config.repository.canonical,
1013
- String(config.prNumber),
1014
- attempt.observedHead,
1015
- attempt.requestId,
1016
- ].join("|");
1017
- appendJournal(COLLECTOR_REQUEST_ENTRY_TYPE, {
1018
- attempt: { ...attempt },
1019
- attemptKey,
1020
- commentEvidence,
1021
- });
1022
- };
1023
-
1024
- if (result.kind === "success") {
1025
- const record = normalizeIssueCommentEvidence(result.comment, startedAt);
1026
- attempt.status = "succeeded";
1027
- attempt.commentEvidenceId = record.evidenceId;
1028
- commitRequestAttempt(attempt, attemptKey, record);
1029
- journalRequest(record);
1030
- return {
1031
- status: "succeeded",
1032
- attemptId,
1033
- requestId,
1034
- observedHead: snapshot.headOid,
1035
- marker,
1036
- commentEvidenceId: record.evidenceId,
1037
- };
1038
- }
1039
-
1040
- if (result.kind === "ambiguous_loss") {
1041
- attempt.status = "ambiguous_loss";
1042
- attempt.responseDiagnostics = result.diagnostics;
1043
- commitRequestAttempt(attempt, attemptKey, undefined);
1044
- journalRequest(undefined);
1045
- return {
1046
- status: "ambiguous_loss",
1047
- attemptId,
1048
- requestId,
1049
- observedHead: snapshot.headOid,
1050
- marker,
1051
- diagnostics: result.diagnostics,
1052
- };
1053
- }
1054
-
1055
- attempt.status = "rejected";
1056
- attempt.responseDiagnostics = result.diagnostics;
1057
- commitRequestAttempt(attempt, attemptKey, undefined);
1058
- journalRequest(undefined);
1059
- throw latchFatal(`通进司请求被拒:${result.diagnostics}`);
1060
- },
1061
-
1062
- async wait(input, clock, signal) {
1063
- assertNotFatal();
1064
- if (!sessionReady) {
1065
- throw latchFatal("通进司等待需要激活");
1066
- }
1067
- // #678: wait never invents a window start. Work-step open (create-success / trigger-end)
1068
- // must be explicit — silent "now" would break the new-PR create-success clock.
1069
- if (activationTime === undefined || deadlineTime === undefined) {
1070
- throw new CollectorWaitWindowClosedError("wait-before-open");
1071
- }
1072
- // durationMs shape authority = collectorWaitArgsSchema (host parameters).
1073
- if (pastCutoff(clock)) {
1074
- finalObservationRequired = true;
1075
- throw new CollectorWaitWindowClosedError("wait");
1076
- }
1077
-
1078
- const remaining = remainingMs(clock);
1079
- // Cap only by remaining window — no package-local single-wait ceiling (ADR 0035 / #678).
1080
- const effectiveMs = Math.min(input.durationMs, remaining);
1081
- const startedAt = clock.wallNow().toISOString();
1082
- const waitId = sha256Text(`wait:${startedAt}:${effectiveMs}`).slice(0, 16);
1083
- await clock.sleep(effectiveMs, signal);
1084
- const endedAt = clock.wallNow().toISOString();
1085
- const cutoffReached = pastCutoff(clock);
1086
- const record: CollectorWaitRecord = {
1087
- waitId,
1088
- requestedMs: input.durationMs,
1089
- effectiveMs,
1090
- startedAt,
1091
- endedAt,
1092
- cutoffReached,
1093
- };
1094
- commitWaitRecord(record);
1095
- appendJournal(COLLECTOR_WAIT_ENTRY_TYPE, {
1096
- waitRecord: record,
1097
- });
1098
- return {
1099
- waitId,
1100
- requestedMs: input.durationMs,
1101
- effectiveMs,
1102
- cutoffReached,
1103
- remainingMsAfter: remainingMs(clock),
1104
- };
1105
- },
1106
-
1107
- getSnapshot(snapshotId) {
1108
- return snapshots.find((item) => item.snapshotId === snapshotId);
1109
- },
1110
- getEvidence(evidenceId) {
1111
- return evidenceById.get(evidenceId);
1112
- },
1113
- allEvidence() {
1114
- return [...evidenceById.values()];
1115
- },
1116
- allSnapshots() {
1117
- return [...snapshots];
1118
- },
1119
- requestAttempts() {
1120
- return [...attempts];
1121
- },
1122
- waits() {
1123
- return [...waits];
1124
- },
1125
- transportFailures() {
1126
- return [...transportFailures];
1127
- },
1128
- requestById(requestId) {
1129
- return config.manifest.requests.find((request) => request.id === requestId);
1130
- },
1131
- };
1132
-
1133
- return ledger;
1134
- }
1135
-
1136
- /**
1137
- * #641 chain①: single authoritative evidence-record projection shared by the
1138
- * observe model view and the pointer-open read tool.
1139
- */
1140
- export function projectEvidenceEntryView(record: CollectorEvidenceRecord): ObserveEvidenceEntry {
1141
- return {
1142
- evidenceId: record.evidenceId,
1143
- kind: record.kind,
1144
- authorLogin: record.authorLogin,
1145
- state: record.state,
1146
- body: record.body,
1147
- commitOid: record.commitOid,
1148
- htmlUrl: record.htmlUrl,
1149
- path: record.path,
1150
- // Single display fallback: current line, else originalLine.
1151
- line: record.line ?? record.originalLine,
1152
- side: record.side,
1153
- authoritativeTime: record.authoritativeTime,
1154
- windowRelation: record.windowRelation,
1155
- pullRequestReviewId: record.pullRequestReviewId,
1156
- };
1157
- }
1158
-
1159
- function buildObserveModelView(input: {
1160
- snapshot: CollectorSnapshot;
1161
- records: readonly CollectorEvidenceRecord[];
1162
- requesterLogin: string | undefined;
1163
- attempts: readonly CollectorRequestAttempt[];
1164
- }): ObserveModelView {
1165
- const relevant = input.records;
1166
- return {
1167
- snapshotId: input.snapshot.snapshotId,
1168
- observedAt: input.snapshot.observedAt,
1169
- completedAt: input.snapshot.completedAt,
1170
- prState: input.snapshot.prState,
1171
- headOid: input.snapshot.headOid,
1172
- ...(input.snapshot.prCreatedAt === undefined
1173
- ? {}
1174
- : { prCreatedAt: input.snapshot.prCreatedAt }),
1175
- complete: input.snapshot.complete,
1176
- evidence: relevant.map((record): ObserveEvidenceEntry => projectEvidenceEntryView(record)),
1177
- requestAttempts: input.attempts.map((attempt) => ({
1178
- attemptId: attempt.attemptId,
1179
- requestId: attempt.requestId,
1180
- observedHead: attempt.observedHead,
1181
- status: attempt.status,
1182
- marker: attempt.marker,
1183
- recoverySnapshotId: attempt.recoverySnapshotId,
1184
- })),
1185
- };
1186
- }