@zq-silk/yui 0.12.2 → 0.12.4

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.
@@ -0,0 +1,221 @@
1
+ import { contextContentDigest, validateContextSnapshotRef } from "../context/contextSnapshot.js";
2
+ import { computeYieldOutcomeDigest } from "./yieldReceipt.js";
3
+ export const RUN_YIELD_REJECTED_EVENT = "run.yield-rejected";
4
+ const MAX_SUMMARY_CHARACTERS = 2_000;
5
+ const MAX_REPORT_CHARACTERS = 8_000;
6
+ const MAX_CHECKS = 16;
7
+ const MAX_FINDINGS = 16;
8
+ const MAX_EVIDENCE = 16;
9
+ const MAX_LABEL_CHARACTERS = 128;
10
+ const MAX_DETAILS_CHARACTERS = 512;
11
+ const MAX_EVIDENCE_CHARACTERS = 512;
12
+ /**
13
+ * Creates the bounded diagnostic projection persisted when a Reviewer report
14
+ * cannot cross the exact terminalization fence. The full validated submission
15
+ * participates in the immutable digest, while only known, size-bounded fields
16
+ * are retained as non-authoritative evidence.
17
+ */
18
+ export function createRejectedYieldAttempt(input) {
19
+ const reviewResult = input.reviewResult;
20
+ const fullReport = reviewResult?.report ?? input.summary;
21
+ const contentDigest = computeYieldOutcomeDigest({
22
+ status: "yielded",
23
+ summary: input.summary,
24
+ ...(reviewResult === undefined ? {} : { reviewResult })
25
+ });
26
+ const summary = boundedText(input.summary, MAX_SUMMARY_CHARACTERS);
27
+ const report = boundedText(fullReport, MAX_REPORT_CHARACTERS);
28
+ const checks = (reviewResult?.checks ?? []).slice(0, MAX_CHECKS).map((check) => ({
29
+ name: boundedText(check.name, MAX_LABEL_CHARACTERS),
30
+ outcome: check.outcome,
31
+ ...(check.details === undefined
32
+ ? {}
33
+ : { details: boundedText(check.details, MAX_DETAILS_CHARACTERS) })
34
+ }));
35
+ const findings = (reviewResult?.findings ?? []).slice(0, MAX_FINDINGS).map((finding) => ({
36
+ id: boundedText(finding.id, MAX_LABEL_CHARACTERS),
37
+ severity: finding.severity,
38
+ status: finding.status,
39
+ summary: boundedText(finding.summary, MAX_DETAILS_CHARACTERS)
40
+ }));
41
+ const evidence = (reviewResult?.evidence ?? []).slice(0, MAX_EVIDENCE)
42
+ .map((entry) => boundedText(entry, MAX_EVIDENCE_CHARACTERS));
43
+ const deltaReasoning = reviewResult?.deltaReasoning === undefined
44
+ ? undefined
45
+ : boundedText(reviewResult.deltaReasoning, MAX_DETAILS_CHARACTERS);
46
+ const projectionTruncated = summary !== input.summary
47
+ || report !== fullReport
48
+ || checks.length !== (reviewResult?.checks?.length ?? 0)
49
+ || checks.some((check, index) => (check.name !== reviewResult?.checks?.[index]?.name
50
+ || check.details !== reviewResult?.checks?.[index]?.details))
51
+ || findings.length !== (reviewResult?.findings?.length ?? 0)
52
+ || findings.some((finding, index) => (finding.id !== reviewResult?.findings?.[index]?.id
53
+ || finding.summary !== reviewResult?.findings?.[index]?.summary))
54
+ || evidence.length !== (reviewResult?.evidence?.length ?? 0)
55
+ || evidence.some((entry, index) => entry !== reviewResult?.evidence?.[index])
56
+ || deltaReasoning !== reviewResult?.deltaReasoning
57
+ || reviewResult?.gitSnapshot !== undefined;
58
+ const observed = Object.freeze({
59
+ nativeSessionId: input.nativeSessionId ?? null,
60
+ launchId: input.launchId ?? null,
61
+ durableNativeSessionId: input.durableNativeSessionId ?? null,
62
+ durableLaunchId: input.durableLaunchId ?? null,
63
+ inFlightRunId: input.inFlightRunId ?? null,
64
+ inFlightReceiptId: input.inFlightReceiptId ?? null,
65
+ activeRunId: input.activeRun?.id ?? null,
66
+ activeReceiptId: input.activeRun?.receiptId ?? null,
67
+ contextSnapshot: input.contextSnapshot ?? null,
68
+ activeContextSnapshot: input.activeRun?.contextSnapshot ?? null
69
+ });
70
+ const attemptDigest = contextContentDigest({
71
+ taskId: input.taskId,
72
+ runId: input.runId,
73
+ reviewRoundId: input.reviewRoundId,
74
+ receiptId: input.receiptId,
75
+ rejectionReason: input.rejectionReason,
76
+ contentDigest,
77
+ observed
78
+ });
79
+ return Object.freeze({
80
+ schemaVersion: 1,
81
+ authority: "unaccepted",
82
+ semanticStatus: "diagnostic-only",
83
+ taskId: input.taskId,
84
+ runId: input.runId,
85
+ roleName: input.roleName,
86
+ purpose: "review",
87
+ reviewRoundId: input.reviewRoundId,
88
+ receiptId: input.receiptId,
89
+ rejectionReason: input.rejectionReason,
90
+ summary,
91
+ report,
92
+ checks: Object.freeze(checks),
93
+ findings: Object.freeze(findings),
94
+ evidence: Object.freeze(evidence),
95
+ ...(reviewResult?.evidenceCommit === undefined
96
+ ? {}
97
+ : { evidenceCommit: reviewResult.evidenceCommit }),
98
+ ...(reviewResult?.deltaDisposition === undefined
99
+ ? {}
100
+ : { deltaDisposition: reviewResult.deltaDisposition }),
101
+ ...(deltaReasoning === undefined ? {} : { deltaReasoning }),
102
+ projectionTruncated,
103
+ observed,
104
+ attemptedAt: input.attemptedAt.toISOString(),
105
+ contentDigest,
106
+ attemptDigest
107
+ });
108
+ }
109
+ export function rejectedYieldAttemptEventPayload(attempt) {
110
+ return {
111
+ runId: attempt.runId,
112
+ roleName: attempt.roleName,
113
+ reviewRoundId: attempt.reviewRoundId,
114
+ receiptId: attempt.receiptId,
115
+ rejectionReason: attempt.rejectionReason,
116
+ authority: attempt.authority,
117
+ semanticStatus: attempt.semanticStatus,
118
+ contentDigest: attempt.contentDigest,
119
+ attemptDigest: attempt.attemptDigest,
120
+ attempt: JSON.stringify(attempt)
121
+ };
122
+ }
123
+ /** Reads only canonical records emitted by rejectedYieldAttemptEventPayload. */
124
+ export function rejectedYieldAttemptFromTaskEvent(event) {
125
+ if (event.type !== RUN_YIELD_REJECTED_EVENT)
126
+ return null;
127
+ try {
128
+ const parsed = JSON.parse(event.payload.attempt ?? "");
129
+ if (!isRejectedYieldAttempt(parsed))
130
+ return null;
131
+ const expectedAttemptDigest = contextContentDigest({
132
+ taskId: parsed.taskId,
133
+ runId: parsed.runId,
134
+ reviewRoundId: parsed.reviewRoundId,
135
+ receiptId: parsed.receiptId,
136
+ rejectionReason: parsed.rejectionReason,
137
+ contentDigest: parsed.contentDigest,
138
+ observed: parsed.observed
139
+ });
140
+ if (parsed.schemaVersion !== 1
141
+ || parsed.authority !== "unaccepted"
142
+ || parsed.semanticStatus !== "diagnostic-only"
143
+ || parsed.purpose !== "review"
144
+ || parsed.taskId !== event.taskId
145
+ || parsed.runId !== event.payload.runId
146
+ || parsed.roleName !== event.payload.roleName
147
+ || parsed.reviewRoundId !== event.payload.reviewRoundId
148
+ || parsed.receiptId !== event.payload.receiptId
149
+ || parsed.rejectionReason !== event.payload.rejectionReason
150
+ || parsed.contentDigest !== event.payload.contentDigest
151
+ || parsed.attemptDigest !== event.payload.attemptDigest
152
+ || parsed.attemptDigest !== expectedAttemptDigest
153
+ || parsed.attemptedAt !== event.createdAt
154
+ || !/^[a-f0-9]{64}$/u.test(parsed.contentDigest)) {
155
+ return null;
156
+ }
157
+ return parsed;
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ }
163
+ function isRejectedYieldAttempt(value) {
164
+ if (typeof value !== "object" || value === null || Array.isArray(value))
165
+ return false;
166
+ const attempt = value;
167
+ const observed = attempt.observed;
168
+ if (typeof observed !== "object" || observed === null || Array.isArray(observed))
169
+ return false;
170
+ const nullableObserved = [
171
+ observed.nativeSessionId,
172
+ observed.launchId,
173
+ observed.durableNativeSessionId,
174
+ observed.durableLaunchId,
175
+ observed.inFlightRunId,
176
+ observed.inFlightReceiptId,
177
+ observed.activeRunId,
178
+ observed.activeReceiptId
179
+ ];
180
+ if (nullableObserved.some((entry) => entry !== null && typeof entry !== "string")) {
181
+ return false;
182
+ }
183
+ if (observed.contextSnapshot !== null)
184
+ validateContextSnapshotRef(observed.contextSnapshot);
185
+ if (observed.activeContextSnapshot !== null) {
186
+ validateContextSnapshotRef(observed.activeContextSnapshot);
187
+ }
188
+ return typeof attempt.taskId === "string"
189
+ && typeof attempt.runId === "string"
190
+ && typeof attempt.roleName === "string"
191
+ && typeof attempt.reviewRoundId === "string"
192
+ && typeof attempt.receiptId === "string"
193
+ && typeof attempt.rejectionReason === "string"
194
+ && typeof attempt.summary === "string"
195
+ && typeof attempt.report === "string"
196
+ && typeof attempt.projectionTruncated === "boolean"
197
+ && typeof attempt.attemptedAt === "string"
198
+ && typeof attempt.contentDigest === "string"
199
+ && typeof attempt.attemptDigest === "string"
200
+ && Array.isArray(attempt.checks)
201
+ && attempt.checks.every((check) => (typeof check === "object" && check !== null
202
+ && typeof check.name === "string"
203
+ && ["passed", "failed", "skipped"].includes(check.outcome)
204
+ && (check.details === undefined || typeof check.details === "string")))
205
+ && Array.isArray(attempt.findings)
206
+ && attempt.findings.every((finding) => (typeof finding === "object" && finding !== null
207
+ && typeof finding.id === "string"
208
+ && typeof finding.summary === "string"))
209
+ && Array.isArray(attempt.evidence)
210
+ && attempt.evidence.every((entry) => typeof entry === "string");
211
+ }
212
+ function boundedText(value, maximum) {
213
+ const safe = value
214
+ .replaceAll(/\u001B\][^\u0007]*(?:\u0007|\u001B\\|\u009C)/gu, " ")
215
+ .replaceAll(/\u001B\[[0-?]*[ -/]*[@-~]/gu, " ")
216
+ .replaceAll(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/gu, " ");
217
+ const characters = Array.from(safe);
218
+ if (characters.length <= maximum)
219
+ return safe;
220
+ return `${characters.slice(0, maximum - 1).join("")}…`;
221
+ }
@@ -183,9 +183,18 @@ export class TmuxSessionHost {
183
183
  : { environment: request.environment }),
184
184
  ...(request.mode === "resume" ? { nativeSessionId: request.nativeSessionId } : {})
185
185
  };
186
- const planned = request.owner.scope === "task"
187
- ? this.planner.plan({ taskId: request.owner.taskId, ...input })
188
- : this.planner.planGlobalRole(input);
186
+ let planned;
187
+ try {
188
+ planned = request.owner.scope === "task"
189
+ ? this.planner.plan({ taskId: request.owner.taskId, ...input })
190
+ : this.planner.planGlobalRole(input);
191
+ }
192
+ catch (error) {
193
+ throw toRuntimeLaunchFailure(error, "validation", {
194
+ cwd: request.workspace,
195
+ agentId: request.agentId
196
+ });
197
+ }
189
198
  if (planned.role.name !== request.owner.roleName) {
190
199
  throw new Error("Planned Role does not match the runtime owner.");
191
200
  }
@@ -304,6 +304,9 @@ export async function processActiveRoleRunDeliveries(store, delivery, now, selec
304
304
  run,
305
305
  session: existingSession,
306
306
  summary: error.message,
307
+ leaderRecovery: role.name === "leader" && error.diagnostic.kind === "config"
308
+ ? "blocked"
309
+ : "automatic",
307
310
  now
308
311
  });
309
312
  results.push({
@@ -375,6 +378,7 @@ export async function processActiveRoleRunDeliveries(store, delivery, now, selec
375
378
  run,
376
379
  session: existingSession,
377
380
  summary: `Role Run could not start: ${message}`,
381
+ leaderRecovery: "automatic",
378
382
  now
379
383
  });
380
384
  results.push({
@@ -535,6 +535,24 @@ export class SqliteTaskStore {
535
535
  ON CONFLICT(task_id, kind) DO UPDATE SET high_water = MAX(high_water, ?)`).run(taskId, kind, highWater, highWater);
536
536
  });
537
537
  }
538
+ /** Restore one validated historical grant into a disposable migration output. */
539
+ migrationRestoreCapabilityGrant(taskId, grant) {
540
+ if (!this.#migration) {
541
+ throw new StorageRecordError("Historical capability grants may only be restored into a migration sidecar.");
542
+ }
543
+ const stored = storedCapabilityGrant(grant);
544
+ if (stored.taskId !== taskId) {
545
+ throw new StorageRecordError(`Capability grant belongs to another Task: ${stored.taskId}`);
546
+ }
547
+ this.#requireTask(taskId);
548
+ this.#mutate(() => {
549
+ const existing = this.#getPayload("capability_grants", "task_id = ? AND grant_id = ?", [taskId, stored.id]);
550
+ if (existing !== null) {
551
+ throw new StorageRecordError(`Migration cannot overwrite capability grant: ${taskId}/${stored.id}`);
552
+ }
553
+ this.#db.prepare("INSERT INTO capability_grants (task_id, grant_id, payload, updated_at) VALUES (?, ?, ?, ?)").run(taskId, stored.id, this.#json(stored), this.#now());
554
+ });
555
+ }
538
556
  // -- generic payload helpers ------------------------------------------------
539
557
  #getPayload(table, where, params) {
540
558
  const row = this.#db.prepare(`SELECT payload FROM ${table} WHERE ${where}`).get(...params);
@@ -404,7 +404,7 @@ export function populateSqliteFromState(home, state, databaseFilename) {
404
404
  }
405
405
  // Capability grants and release workflows (task-15 record families).
406
406
  for (const grant of Object.values(stored.capabilityGrants)) {
407
- store.saveCapabilityGrant(taskId, grant);
407
+ store.migrationRestoreCapabilityGrant(taskId, grant);
408
408
  }
409
409
  for (const workflow of Object.values(stored.releaseWorkflows)) {
410
410
  store.saveReleaseWorkflow(taskId, workflow);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zq-silk/yui",
3
- "version": "0.12.2",
3
+ "version": "0.12.4",
4
4
  "description": "Local control plane for long-running native agent CLI sessions backed by tmux.",
5
5
  "license": "MIT",
6
6
  "private": false,