devcontour-harness 0.1.0-alpha.31 → 0.1.0-alpha.35

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 (84) hide show
  1. package/README.md +28 -3
  2. package/docs/architecture.md +12 -0
  3. package/docs/compatibility.md +21 -18
  4. package/docs/contracts.md +189 -21
  5. package/docs/release-notes/0.1.0-alpha.32.md +33 -0
  6. package/docs/release-notes/0.1.0-alpha.33.md +29 -0
  7. package/docs/release-notes/0.1.0-alpha.34.md +32 -0
  8. package/docs/release-notes/0.1.0-alpha.35.md +27 -0
  9. package/docs/upgrade.md +172 -0
  10. package/lib/agents/cli-adapter.d.ts +10 -1
  11. package/lib/agents/cli-adapter.js +38 -7
  12. package/lib/agents/usage.d.ts +9 -0
  13. package/lib/agents/usage.js +22 -1
  14. package/lib/cli.js +2 -2
  15. package/lib/contracts/cli.d.ts +344 -6
  16. package/lib/contracts/cli.js +1 -0
  17. package/lib/contracts/diagnosis.d.ts +3 -1
  18. package/lib/contracts/diagnosis.js +1 -0
  19. package/lib/contracts/errors.d.ts +3 -1
  20. package/lib/contracts/errors.js +2 -0
  21. package/lib/contracts/events.d.ts +365 -4
  22. package/lib/contracts/events.js +63 -2
  23. package/lib/contracts/execution.d.ts +32 -1
  24. package/lib/contracts/execution.js +19 -0
  25. package/lib/contracts/failure.d.ts +12 -3
  26. package/lib/contracts/failure.js +10 -2
  27. package/lib/contracts/handoff.d.ts +17 -0
  28. package/lib/contracts/handoff.js +17 -3
  29. package/lib/contracts/planning.d.ts +2 -0
  30. package/lib/contracts/ports.d.ts +10 -2
  31. package/lib/contracts/published.d.ts +205 -3
  32. package/lib/contracts/repair-policy.d.ts +10 -1
  33. package/lib/contracts/repair-policy.js +18 -0
  34. package/lib/contracts/report.d.ts +118 -2
  35. package/lib/contracts/report.js +61 -3
  36. package/lib/contracts/result.d.ts +2 -0
  37. package/lib/control/base-move.d.ts +7 -2
  38. package/lib/control/base-move.js +14 -1
  39. package/lib/control/harness.d.ts +54 -18
  40. package/lib/control/harness.js +8 -96
  41. package/lib/control/recovery.d.ts +1 -1
  42. package/lib/control/status.d.ts +235 -0
  43. package/lib/control/status.js +101 -0
  44. package/lib/engine/budget.d.ts +78 -0
  45. package/lib/engine/budget.js +13 -2
  46. package/lib/engine/classify.d.ts +14 -1
  47. package/lib/engine/classify.js +34 -0
  48. package/lib/engine/engine.d.ts +25 -11
  49. package/lib/engine/engine.js +78 -5
  50. package/lib/engine/failure.d.ts +1 -1
  51. package/lib/engine/failure.js +1 -1
  52. package/lib/engine/prompt.js +11 -1
  53. package/lib/engine/property-recovery.js +2 -0
  54. package/lib/engine/repair.js +4 -2
  55. package/lib/engine/reuse.js +2 -0
  56. package/lib/engine/runner.js +13 -5
  57. package/lib/environment/isolation.d.ts +67 -3
  58. package/lib/environment/isolation.js +148 -5
  59. package/lib/environment/lifecycle.js +1 -1
  60. package/lib/explain/state.d.ts +26 -5
  61. package/lib/explain/state.js +39 -4
  62. package/lib/handoff/index.d.ts +1 -1
  63. package/lib/handoff/markdown.js +4 -2
  64. package/lib/handoff/pack.d.ts +38 -8
  65. package/lib/handoff/pack.js +57 -18
  66. package/lib/index.d.ts +19 -4
  67. package/lib/index.js +19 -3
  68. package/lib/integrations/connector/testing.js +1 -1
  69. package/lib/projections/next.d.ts +3 -1
  70. package/lib/projections/next.js +4 -1
  71. package/lib/projections/stop.d.ts +14 -1
  72. package/lib/projections/stop.js +68 -11
  73. package/lib/report/compute.js +229 -21
  74. package/lib/report/document.js +32 -8
  75. package/lib/storage/document.d.ts +8 -6
  76. package/lib/verification/gates.js +20 -4
  77. package/package.json +1 -1
  78. package/schemas/execution-document.schema.json +11 -0
  79. package/schemas/handoff-pack.schema.json +15 -0
  80. package/schemas/result-envelope.schema.json +1 -0
  81. package/schemas/run-event.schema.json +322 -0
  82. package/schemas/run-result.schema.json +1 -0
  83. package/schemas/stop-diagnosis.schema.json +2 -0
  84. package/schemas/value-report.schema.json +236 -3
@@ -0,0 +1,235 @@
1
+ import { type ExecutionPolicy } from '../contracts/index.ts';
2
+ import type { Engine } from '../engine/engine.ts';
3
+ /**
4
+ * Что читает `statusOf`: движок над хранилищем и политика исполнения.
5
+ * `Harness` удовлетворяет ему структурно; хост со своим `Engine` передаёт
6
+ * `{ engine, policy }`.
7
+ */
8
+ export interface StatusSource {
9
+ readonly engine: Engine;
10
+ readonly policy: ExecutionPolicy;
11
+ }
12
+ /**
13
+ * Состояние очереди, графов и поручений (`Harness.status`, `harness status`)
14
+ * над движком и политикой источника. С `detail` — ещё снимок наблюдателя:
15
+ * почему стоит выдача (`queueStop` и `queuePause`) и активные попытки
16
+ * (`attemptView`); без него ответ прежний. Только чтение, один `read`.
17
+ */
18
+ export declare function statusOf(source: StatusSource, graphId?: string, options?: {
19
+ detail?: boolean;
20
+ }): {
21
+ detail?: {
22
+ at: string;
23
+ queue: {
24
+ liftedByRun: true;
25
+ code: "NOT_READY";
26
+ cause: "not-ready";
27
+ actor: "controller";
28
+ action: "wait";
29
+ operation?: string | undefined;
30
+ since?: string | undefined;
31
+ detail: string;
32
+ reason?: "runtime" | "operator" | "shutdown" | "base-check" | "reconfigure" | undefined;
33
+ paused: boolean;
34
+ } | {
35
+ code?: "INVALID_INPUT" | "UNSUPPORTED_COMMAND" | "UNSUPPORTED_VERSION" | "GRAPH_CYCLE" | "GRAPH_UNKNOWN_DEPENDENCY" | "GRAPH_DUPLICATE_ID" | "GATE_UNKNOWN" | "GATE_GROUP_CYCLE" | "REVIEWER_SAME_VENDOR" | "REVIEWER_MISSING" | "RESPONSE_TOO_LARGE" | "APPROVAL_STALE" | "APPROVAL_REQUIRED" | "LEASE_STALE" | "CONTROLLER_BUSY" | "PAUSED" | "NOT_READY" | "SCOPE_VIOLATION" | "GATE_FAILED" | "REVIEW_REJECTED" | "BUDGET_EXHAUSTED" | "BUDGET_UNKNOWN" | "ATTEMPTS_EXHAUSTED" | "CONTEXT_EXHAUSTED" | "REVISION_CONFLICT" | "CANCELLED" | "NOT_FOUND" | "PATH_CONFLICT" | "STATE_VERSION_UNSUPPORTED" | "RUNTIME_UNAVAILABLE" | "REVIEW_PROTOCOL_INVALID" | "SANDBOX_UNAVAILABLE" | "GIT_FAILED" | "STORAGE_FAILED" | "DELIVERY_FAILED" | "INTERNAL" | undefined;
36
+ cause?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | "runtime-missing" | "controller-busy" | "operator-pause" | "approval-required" | "not-ready" | undefined;
37
+ actor?: import("../projections/enums.ts").Actor | undefined;
38
+ action?: "none" | "wait" | "retry" | "review-plan" | "diagnose-failure" | "reset-attempts" | "raise-budget" | "replan-dependents" | "recovery-decision" | "user-decision" | "resume-queue" | "fix-environment" | "fix-access" | undefined;
39
+ failures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
40
+ operation?: string | undefined;
41
+ since?: string | undefined;
42
+ detail?: string;
43
+ paused: boolean;
44
+ reason?: import("../contracts/execution.ts").PauseReason;
45
+ };
46
+ attempts: import("../projections/attempt.ts").AttemptView[];
47
+ } | undefined;
48
+ budgets: {
49
+ onUnknown: "continue" | "stop";
50
+ budgets: {
51
+ reason?: string | undefined;
52
+ scope: import("../engine/budget.ts").BudgetScope;
53
+ state: "exceeded" | "undetermined" | "within";
54
+ limit: {
55
+ usd?: number;
56
+ timeMs?: number;
57
+ };
58
+ reportedUsd: number;
59
+ estimatedUsd: number;
60
+ unknownCalls: number;
61
+ unfinishedCalls: number;
62
+ abandonedCalls: number;
63
+ errorCalls: number;
64
+ uncoveredRuns: number;
65
+ durationMs: number;
66
+ remainingUsd: number | null;
67
+ remainingMs: number | null;
68
+ }[];
69
+ };
70
+ graphs: {
71
+ id: string;
72
+ digest: string;
73
+ source: {
74
+ connector: string;
75
+ ref: string;
76
+ revision: string;
77
+ };
78
+ approved: boolean;
79
+ }[];
80
+ works: ({
81
+ blockers: {
82
+ code: "NOT_READY" | "PAUSED" | "ATTEMPTS_EXHAUSTED" | "APPROVAL_STALE" | "APPROVAL_REQUIRED" | "BUDGET_EXHAUSTED" | "REVIEWER_SAME_VENDOR" | "REVIEWER_MISSING" | "INVALID_INPUT";
83
+ message: string;
84
+ }[];
85
+ resultSha?: string | undefined;
86
+ liveness: "stalled" | "quiet";
87
+ activeRunId?: string | undefined;
88
+ id: string;
89
+ graphId: string;
90
+ status: "ready" | "failed" | "cancelled" | "draft" | "running" | "verifying" | "reviewing" | "integrating" | "done";
91
+ attempt: number;
92
+ } | {
93
+ blockers: {
94
+ code: "NOT_READY" | "PAUSED" | "ATTEMPTS_EXHAUSTED" | "APPROVAL_STALE" | "APPROVAL_REQUIRED" | "BUDGET_EXHAUSTED" | "REVIEWER_SAME_VENDOR" | "REVIEWER_MISSING" | "INVALID_INPUT";
95
+ message: string;
96
+ }[];
97
+ resultSha?: string | undefined;
98
+ liveness?: undefined;
99
+ activeRunId?: string | undefined;
100
+ id: string;
101
+ graphId: string;
102
+ status: "ready" | "failed" | "cancelled" | "draft" | "running" | "verifying" | "reviewing" | "integrating" | "done";
103
+ attempt: number;
104
+ })[];
105
+ controller?: {
106
+ owner: string;
107
+ leaseUntil: number;
108
+ engineVersion?: string | undefined;
109
+ } | undefined;
110
+ stateVersion: 1;
111
+ control: {
112
+ paused: boolean;
113
+ pauseReason?: "runtime" | "operator" | "shutdown" | "base-check" | "reconfigure" | undefined;
114
+ pausedAt?: string | undefined;
115
+ pauseOperation?: string | undefined;
116
+ pauseFailures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
117
+ waits?: {
118
+ kind: "base-check" | "context-lock";
119
+ detail: string;
120
+ at: string;
121
+ operation?: string | undefined;
122
+ }[] | undefined;
123
+ appliedPolicy?: {
124
+ digest: string;
125
+ at: string;
126
+ by: string;
127
+ generation?: number | undefined;
128
+ } | undefined;
129
+ reconfigure?: {
130
+ operation: string;
131
+ digest: string;
132
+ requestedAt: string;
133
+ appliedAt?: string | undefined;
134
+ appliedBy?: string | undefined;
135
+ error?: string | undefined;
136
+ } | undefined;
137
+ };
138
+ } | {
139
+ detail?: {
140
+ at: string;
141
+ queue: {
142
+ liftedByRun: true;
143
+ code: "NOT_READY";
144
+ cause: "not-ready";
145
+ actor: "controller";
146
+ action: "wait";
147
+ operation?: string | undefined;
148
+ since?: string | undefined;
149
+ detail: string;
150
+ reason?: "runtime" | "operator" | "shutdown" | "base-check" | "reconfigure" | undefined;
151
+ paused: boolean;
152
+ } | {
153
+ code?: "INVALID_INPUT" | "UNSUPPORTED_COMMAND" | "UNSUPPORTED_VERSION" | "GRAPH_CYCLE" | "GRAPH_UNKNOWN_DEPENDENCY" | "GRAPH_DUPLICATE_ID" | "GATE_UNKNOWN" | "GATE_GROUP_CYCLE" | "REVIEWER_SAME_VENDOR" | "REVIEWER_MISSING" | "RESPONSE_TOO_LARGE" | "APPROVAL_STALE" | "APPROVAL_REQUIRED" | "LEASE_STALE" | "CONTROLLER_BUSY" | "PAUSED" | "NOT_READY" | "SCOPE_VIOLATION" | "GATE_FAILED" | "REVIEW_REJECTED" | "BUDGET_EXHAUSTED" | "BUDGET_UNKNOWN" | "ATTEMPTS_EXHAUSTED" | "CONTEXT_EXHAUSTED" | "REVISION_CONFLICT" | "CANCELLED" | "NOT_FOUND" | "PATH_CONFLICT" | "STATE_VERSION_UNSUPPORTED" | "RUNTIME_UNAVAILABLE" | "REVIEW_PROTOCOL_INVALID" | "SANDBOX_UNAVAILABLE" | "GIT_FAILED" | "STORAGE_FAILED" | "DELIVERY_FAILED" | "INTERNAL" | undefined;
154
+ cause?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | "runtime-missing" | "controller-busy" | "operator-pause" | "approval-required" | "not-ready" | undefined;
155
+ actor?: import("../projections/enums.ts").Actor | undefined;
156
+ action?: "none" | "wait" | "retry" | "review-plan" | "diagnose-failure" | "reset-attempts" | "raise-budget" | "replan-dependents" | "recovery-decision" | "user-decision" | "resume-queue" | "fix-environment" | "fix-access" | undefined;
157
+ failures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
158
+ operation?: string | undefined;
159
+ since?: string | undefined;
160
+ detail?: string;
161
+ paused: boolean;
162
+ reason?: import("../contracts/execution.ts").PauseReason;
163
+ };
164
+ attempts: import("../projections/attempt.ts").AttemptView[];
165
+ } | undefined;
166
+ budgets?: undefined;
167
+ graphs: {
168
+ id: string;
169
+ digest: string;
170
+ source: {
171
+ connector: string;
172
+ ref: string;
173
+ revision: string;
174
+ };
175
+ approved: boolean;
176
+ }[];
177
+ works: ({
178
+ blockers: {
179
+ code: "NOT_READY" | "PAUSED" | "ATTEMPTS_EXHAUSTED" | "APPROVAL_STALE" | "APPROVAL_REQUIRED" | "BUDGET_EXHAUSTED" | "REVIEWER_SAME_VENDOR" | "REVIEWER_MISSING" | "INVALID_INPUT";
180
+ message: string;
181
+ }[];
182
+ resultSha?: string | undefined;
183
+ liveness: "stalled" | "quiet";
184
+ activeRunId?: string | undefined;
185
+ id: string;
186
+ graphId: string;
187
+ status: "ready" | "failed" | "cancelled" | "draft" | "running" | "verifying" | "reviewing" | "integrating" | "done";
188
+ attempt: number;
189
+ } | {
190
+ blockers: {
191
+ code: "NOT_READY" | "PAUSED" | "ATTEMPTS_EXHAUSTED" | "APPROVAL_STALE" | "APPROVAL_REQUIRED" | "BUDGET_EXHAUSTED" | "REVIEWER_SAME_VENDOR" | "REVIEWER_MISSING" | "INVALID_INPUT";
192
+ message: string;
193
+ }[];
194
+ resultSha?: string | undefined;
195
+ liveness?: undefined;
196
+ activeRunId?: string | undefined;
197
+ id: string;
198
+ graphId: string;
199
+ status: "ready" | "failed" | "cancelled" | "draft" | "running" | "verifying" | "reviewing" | "integrating" | "done";
200
+ attempt: number;
201
+ })[];
202
+ controller?: {
203
+ owner: string;
204
+ leaseUntil: number;
205
+ engineVersion?: string | undefined;
206
+ } | undefined;
207
+ stateVersion: 1;
208
+ control: {
209
+ paused: boolean;
210
+ pauseReason?: "runtime" | "operator" | "shutdown" | "base-check" | "reconfigure" | undefined;
211
+ pausedAt?: string | undefined;
212
+ pauseOperation?: string | undefined;
213
+ pauseFailures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
214
+ waits?: {
215
+ kind: "base-check" | "context-lock";
216
+ detail: string;
217
+ at: string;
218
+ operation?: string | undefined;
219
+ }[] | undefined;
220
+ appliedPolicy?: {
221
+ digest: string;
222
+ at: string;
223
+ by: string;
224
+ generation?: number | undefined;
225
+ } | undefined;
226
+ reconfigure?: {
227
+ operation: string;
228
+ digest: string;
229
+ requestedAt: string;
230
+ appliedAt?: string | undefined;
231
+ appliedBy?: string | undefined;
232
+ error?: string | undefined;
233
+ } | undefined;
234
+ };
235
+ };
@@ -0,0 +1,101 @@
1
+ import { STATE_VERSION } from "../contracts/index.js";
2
+ import { budgetOverview } from "../engine/budget.js";
3
+ import { nextRunControl } from "../explain/state.js";
4
+ import { CLIP_DIAGNOSTIC, attemptView, clipText, queuePause, queueStop, } from "../projections/index.js";
5
+ /**
6
+ * Состояние очереди, графов и поручений (`Harness.status`, `harness status`)
7
+ * над движком и политикой источника. С `detail` — ещё снимок наблюдателя:
8
+ * почему стоит выдача (`queueStop` и `queuePause`) и активные попытки
9
+ * (`attemptView`); без него ответ прежний. Только чтение, один `read`.
10
+ */
11
+ export function statusOf(source, graphId, options = {}) {
12
+ const { engine } = source;
13
+ return engine.read((v) => ({
14
+ stateVersion: STATE_VERSION,
15
+ control: v.control(),
16
+ ...(v.controller() ? { controller: v.controller() } : {}),
17
+ graphs: v
18
+ .graphs()
19
+ .filter((g) => !graphId || g.id === graphId)
20
+ .map((g) => ({
21
+ id: g.id,
22
+ digest: g.digest,
23
+ source: g.graph.source,
24
+ approved: g.approval?.digest === g.digest,
25
+ })),
26
+ works: v.works(graphId).map((w) => ({
27
+ id: w.id,
28
+ graphId: w.graphId,
29
+ status: w.status,
30
+ attempt: w.attempt,
31
+ ...(w.activeRunId ? { activeRunId: w.activeRunId } : {}),
32
+ ...((a) => a?.status === 'active' && a.liveness && a.liveness.state !== 'active'
33
+ ? { liveness: a.liveness.state }
34
+ : {})(w.activeRunId ? v.attempt(w.activeRunId) : undefined),
35
+ ...(w.resultSha ? { resultSha: w.resultSha } : {}),
36
+ blockers: engine.blockers(w, v),
37
+ })),
38
+ ...((budgets) => (budgets ? { budgets } : {}))(budgetOverview(engine.budgetContext(), v)),
39
+ ...(options.detail ? { detail: statusDetail(source, v, graphId) } : {}),
40
+ }));
41
+ }
42
+ function statusDetail(source, v, graphId) {
43
+ const { engine, policy } = source;
44
+ const now = engine.clock();
45
+ const control = v.control();
46
+ const works = v.works(graphId);
47
+ const attempts = v.works().flatMap((w) => v.attempts(w.id));
48
+ // Последний отказ классов паузы runtime — её подробность (как `queueStop`
49
+ // хоста по ошибкам планировщика): порядок — по времени завершения.
50
+ const failures = new Set(control.pauseFailures ?? []);
51
+ const errors = attempts
52
+ .filter((a) => a.status === 'failed' && a.failureKind && failures.has(a.failureKind))
53
+ .sort((a, b) => (a.finishedAt ?? '').localeCompare(b.finishedAt ?? ''))
54
+ .map((a, i) => ({ seq: i + 1, ...(a.error ? { message: a.error } : {}) }));
55
+ const stop = queueStop({
56
+ paused: control.paused,
57
+ ...(control.pauseReason ? { pauseReason: control.pauseReason } : {}),
58
+ errors,
59
+ });
60
+ const repositoryGates = (id) => policy.repositories.find((r) => r.id === id)?.gates.map((g) => g.id);
61
+ // Пауза, которую снимет следующий run, глазами explain: выдача не стоит,
62
+ // поручения ждут controller.
63
+ const queue = nextRunControl(source, v).lifted
64
+ ? {
65
+ paused: true,
66
+ ...(control.pauseReason ? { reason: control.pauseReason } : {}),
67
+ detail: 'Паузу снимет следующий harness run',
68
+ ...(control.pausedAt ? { since: control.pausedAt } : {}),
69
+ ...(control.pauseOperation ? { operation: control.pauseOperation } : {}),
70
+ liftedByRun: true,
71
+ code: 'NOT_READY',
72
+ cause: 'not-ready',
73
+ actor: 'controller',
74
+ action: 'wait',
75
+ }
76
+ : {
77
+ ...stop,
78
+ ...(stop.detail ? { detail: clipText(stop.detail, CLIP_DIAGNOSTIC) } : {}),
79
+ ...(control.paused && control.pausedAt ? { since: control.pausedAt } : {}),
80
+ ...(control.paused && control.pauseOperation ? { operation: control.pauseOperation } : {}),
81
+ ...(control.paused && control.pauseFailures?.length
82
+ ? { failures: [...control.pauseFailures] }
83
+ : {}),
84
+ ...(queuePause(control) ?? {}),
85
+ };
86
+ return {
87
+ at: new Date(now).toISOString(),
88
+ queue,
89
+ attempts: works
90
+ .map((w) => (w.activeRunId ? v.attempt(w.activeRunId) : undefined))
91
+ .filter((a) => a?.status === 'active')
92
+ .map((a) => {
93
+ const gates = repositoryGates(a.repositoryId);
94
+ return attemptView(a, {
95
+ now,
96
+ leaseMs: policy.leaseMs,
97
+ ...(gates ? { repositoryGates: gates } : {}),
98
+ });
99
+ }),
100
+ };
101
+ }
@@ -111,6 +111,82 @@ export declare function scopeRecords(c: BudgetContext, view: ExecutionView, reco
111
111
  } | undefined;
112
112
  } | undefined;
113
113
  }[];
114
+ /**
115
+ * Собственные вызовы поручения: его попытки и вызовы о нём. Вызовы о группе
116
+ * (ревью и проверка плана), которые `scopeRecords` целиком засчитывает каждому
117
+ * её поручению, сюда не входят: это один расход группы, а не каждого.
118
+ */
119
+ export declare function ownWorkRecords(view: ExecutionView, records: CallRecord[], workId: string): {
120
+ id: string;
121
+ stage: string;
122
+ runtime: string;
123
+ model: string | null;
124
+ runtimeVersion: string | null;
125
+ startedAt: string;
126
+ outcome: "error" | "active" | "abandoned" | "returned";
127
+ promptBytes: number;
128
+ promptDigest: string;
129
+ usage: {
130
+ inputTokens: number | null;
131
+ outputTokens: number | null;
132
+ cacheReadTokens: number | null;
133
+ cacheWriteTokens: number | null;
134
+ reportedUsd: number | null;
135
+ complete: boolean;
136
+ source: "fixture" | "unavailable" | "codex-turn-events" | "claude-result";
137
+ };
138
+ costUsd: number | null;
139
+ costSource: "unknown" | "provider-reported" | "tariff-estimate";
140
+ repositoryId?: string | undefined;
141
+ runId?: string | undefined;
142
+ subjectId?: string | undefined;
143
+ subjectKind?: "work" | "group" | "other" | undefined;
144
+ finishedAt?: string | undefined;
145
+ process?: {
146
+ id: string;
147
+ pid: number;
148
+ startedAt?: number | undefined;
149
+ } | undefined;
150
+ abandonedAt?: string | undefined;
151
+ durationMs?: number | undefined;
152
+ elapsedMs?: number | undefined;
153
+ startedHr?: string | undefined;
154
+ durationUnknown?: true | undefined;
155
+ bootId?: string | undefined;
156
+ workId?: string | undefined;
157
+ groupId?: string | undefined;
158
+ workIds?: string[] | undefined;
159
+ price?: {
160
+ runtime: "codex" | "claude";
161
+ model: string;
162
+ effectiveAt: string;
163
+ input: number;
164
+ output: number;
165
+ cacheRead: number;
166
+ cacheWrite: number;
167
+ } | undefined;
168
+ diagnostics?: {
169
+ startedAt: string;
170
+ finishedAt: string;
171
+ lastOutputAt: string | null;
172
+ exitCode: number | null;
173
+ signal: string | null;
174
+ timedOut: boolean;
175
+ aborted: boolean;
176
+ stdoutTail: string;
177
+ stderrTail: string;
178
+ processTree?: {
179
+ available: boolean;
180
+ processes: {
181
+ pid: number;
182
+ parentPid: number;
183
+ groupPid: number;
184
+ name: string;
185
+ }[];
186
+ reason?: string | undefined;
187
+ } | undefined;
188
+ } | undefined;
189
+ }[];
114
190
  export type BudgetStatus = {
115
191
  scope: BudgetScope;
116
192
  limit: {
@@ -298,6 +374,8 @@ export declare function callBudgets(c: BudgetContext, view: ExecutionView, meta:
298
374
  export declare function callAttribution(c: BudgetContext, view: ExecutionView, meta: Pick<CallMeta, 'runId' | 'subjectId' | 'subjectKind' | 'group'>, all?: boolean): Pick<CallRecord, 'workId' | 'groupId' | 'workIds'>;
299
375
  /** Бюджет, который запрещает тратить: превышен или не определён при `onUnknown: stop`. */
300
376
  export declare function blockingBudget(c: BudgetContext, statuses: BudgetStatus[]): BudgetStatus | undefined;
377
+ /** Запрещает ли тратить бюджет в этом состоянии: превышен или не определён при `onUnknown: stop`. */
378
+ export declare function budgetBlocks(state: BudgetStatus['state'], onUnknown: 'stop' | 'continue' | undefined): boolean;
301
379
  /** Отказ до траты: превышенный или неопределённый бюджет не даёт начать вызов. */
302
380
  export declare function assertBudget(c: BudgetContext, statuses: BudgetStatus[]): void;
303
381
  /** Компактный вид бюджета для статуса и потребителей. */
@@ -72,6 +72,14 @@ export function scopeRecords(c, view, records, scope) {
72
72
  return work === scope.id || (!work && groups.has(recordGroup(c, view, r) ?? ''));
73
73
  });
74
74
  }
75
+ /**
76
+ * Собственные вызовы поручения: его попытки и вызовы о нём. Вызовы о группе
77
+ * (ревью и проверка плана), которые `scopeRecords` целиком засчитывает каждому
78
+ * её поручению, сюда не входят: это один расход группы, а не каждого.
79
+ */
80
+ export function ownWorkRecords(view, records, workId) {
81
+ return records.filter((r) => !r.workIds && recordWork(view, r) === workId);
82
+ }
75
83
  /**
76
84
  * Попытки области, вызовы которых не записаны: выданы до учёта вызовов (без
77
85
  * отметки `callsRecorded`), модель в них вызывалась (есть кандидат или замер
@@ -220,8 +228,11 @@ export function callAttribution(c, view, meta, all = false) {
220
228
  }
221
229
  /** Бюджет, который запрещает тратить: превышен или не определён при `onUnknown: stop`. */
222
230
  export function blockingBudget(c, statuses) {
223
- const stopOnUnknown = (c.policy.budgets?.onUnknown ?? 'stop') === 'stop';
224
- return statuses.find((b) => b.state === 'exceeded' || (b.state === 'undetermined' && stopOnUnknown));
231
+ return statuses.find((b) => budgetBlocks(b.state, c.policy.budgets?.onUnknown));
232
+ }
233
+ /** Запрещает ли тратить бюджет в этом состоянии: превышен или не определён при `onUnknown: stop`. */
234
+ export function budgetBlocks(state, onUnknown) {
235
+ return state === 'exceeded' || (state === 'undetermined' && (onUnknown ?? 'stop') === 'stop');
225
236
  }
226
237
  /** Отказ до траты: превышенный или неопределённый бюджет не даёт начать вызов. */
227
238
  export function assertBudget(c, statuses) {
@@ -1,4 +1,4 @@
1
- import { BlockedError, type FailureKind } from '../contracts/index.ts';
1
+ import { BlockedError, type EnvironmentCause, type FailureKind } from '../contracts/index.ts';
2
2
  export { BlockedError };
3
3
  /**
4
4
  * Отказ провайдера, а не работы: он повторится на любой следующей выдаче.
@@ -6,3 +6,16 @@ export { BlockedError };
6
6
  */
7
7
  export declare const providerRefusal: (message: string) => boolean;
8
8
  export declare function classifyFailure(error: unknown, message: string): FailureKind;
9
+ /**
10
+ * Причина отказа окружения (`attempt.diagnosed`): названная в точке
11
+ * обнаружения (`TaskFailure.diagnosis`), иначе — по тем же признакам, что
12
+ * класс отказа. Отказ не окружения — `none`; движок приводит причину к
13
+ * классу сам, поэтому здесь достаточно лучшей догадки.
14
+ */
15
+ export declare function environmentCauseOf(error: unknown, message: string, kind: FailureKind): EnvironmentCause;
16
+ /**
17
+ * Отказ с дописанной причиной (например, неудавшейся очисткой): класс,
18
+ * свойства и причина окружения `TaskFailure` сохраняются; прочий отказ —
19
+ * `Error` с исходным в `cause`.
20
+ */
21
+ export declare function withSuffix(failure: Error, suffix: string): Error;
@@ -39,3 +39,37 @@ export function classifyFailure(error, message) {
39
39
  return 'environment';
40
40
  return 'unknown';
41
41
  }
42
+ /** Предел или баланс провайдера, а не учётные данные (часть `providerRefusal`). */
43
+ const providerLimit = (message) => /credit balance|insufficient credit|insufficient_quota|session limit|usage limit|rate limit|rate_limit|limit reached|too many requests|\b429\b|overloaded/i.test(message);
44
+ /**
45
+ * Причина отказа окружения (`attempt.diagnosed`): названная в точке
46
+ * обнаружения (`TaskFailure.diagnosis`), иначе — по тем же признакам, что
47
+ * класс отказа. Отказ не окружения — `none`; движок приводит причину к
48
+ * классу сам, поэтому здесь достаточно лучшей догадки.
49
+ */
50
+ export function environmentCauseOf(error, message, kind) {
51
+ if (kind === 'stalled')
52
+ return 'stalled';
53
+ if (kind === 'provider-auth')
54
+ return providerLimit(message) ? 'provider-limit' : 'provider-auth';
55
+ if (kind !== 'environment')
56
+ return 'none';
57
+ if (error instanceof TaskFailure && error.diagnosis)
58
+ return error.diagnosis;
59
+ if (transportFailure(message) ||
60
+ /econnreset|epipe|socket hang up|connection reset|stream closed|channel closed|fetch failed|network error/i.test(message))
61
+ return 'transport';
62
+ if (error instanceof BlockedError)
63
+ return 'preflight';
64
+ return 'other';
65
+ }
66
+ /**
67
+ * Отказ с дописанной причиной (например, неудавшейся очисткой): класс,
68
+ * свойства и причина окружения `TaskFailure` сохраняются; прочий отказ —
69
+ * `Error` с исходным в `cause`.
70
+ */
71
+ export function withSuffix(failure, suffix) {
72
+ return failure instanceof TaskFailure
73
+ ? new TaskFailure(failure.kind, `${failure.message}; ${suffix}`, failure.properties, failure.diagnosis, failure.contextLimit)
74
+ : new Error(`${failure.message}; ${suffix}`, { cause: failure });
75
+ }
@@ -1,4 +1,4 @@
1
- import { type ReproductionRecord, type AttemptState, type RunEventPayload, type Author, type CallRecord, type ContractDocument, type EvidenceRecord, type ExecutionHost, type ExecutionPolicy, type ExecutionTransaction, type ExecutionView, type FailureKind, type GraphState, type JointVerification, type JointVerificationState, type NotPromise, type Prerequisite, type PropertyRecovery, type ReviewRecord, type TechnicalApproval, type TransactionKind, type WorkGraph, type WorkState } from '../contracts/index.ts';
1
+ import { type ReproductionRecord, type AttemptState, type RunEventPayload, type CancelActor, type ContextLimit, type EnvironmentCause, type RetryActor, type Author, type CallRecord, type ContractDocument, type EvidenceRecord, type ExecutionHost, type ExecutionPolicy, type ExecutionTransaction, type ExecutionView, type FailureKind, type GraphState, type JointVerification, type JointVerificationState, type NotPromise, type Prerequisite, type PropertyRecovery, type ReviewRecord, type TechnicalApproval, type TransactionKind, type WorkGraph, type WorkState } from '../contracts/index.ts';
2
2
  import { type BudgetContext, type CallMeta } from './budget.ts';
3
3
  /** Префикс причины неудавшегося продления: первая причина не затирается следствиями. */
4
4
  export declare const HEARTBEAT_FAILED = "\u041F\u0440\u043E\u0434\u043B\u0435\u043D\u0438\u0435 \u0432\u043B\u0430\u0434\u0435\u043D\u0438\u044F \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C";
@@ -255,7 +255,7 @@ export declare class Engine {
255
255
  pauseReason?: "runtime" | "operator" | "shutdown" | "base-check" | "reconfigure" | undefined;
256
256
  pausedAt?: string | undefined;
257
257
  pauseOperation?: string | undefined;
258
- pauseFailures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
258
+ pauseFailures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
259
259
  waits?: {
260
260
  kind: "base-check" | "context-lock";
261
261
  detail: string;
@@ -291,7 +291,7 @@ export declare class Engine {
291
291
  pauseReason?: "runtime" | "operator" | "shutdown" | "base-check" | "reconfigure" | undefined;
292
292
  pausedAt?: string | undefined;
293
293
  pauseOperation?: string | undefined;
294
- pauseFailures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
294
+ pauseFailures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
295
295
  waits?: {
296
296
  kind: "base-check" | "context-lock";
297
297
  detail: string;
@@ -321,7 +321,7 @@ export declare class Engine {
321
321
  pauseReason?: "runtime" | "operator" | "shutdown" | "base-check" | "reconfigure" | undefined;
322
322
  pausedAt?: string | undefined;
323
323
  pauseOperation?: string | undefined;
324
- pauseFailures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
324
+ pauseFailures?: ("gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead")[] | undefined;
325
325
  waits?: {
326
326
  kind: "base-check" | "context-lock";
327
327
  detail: string;
@@ -709,6 +709,14 @@ export declare class Engine {
709
709
  * ждёт восстановления. Интегрированная попытка так не возвращается.
710
710
  */
711
711
  interrupted?: boolean;
712
+ /**
713
+ * Причина отказа окружения, известная в точке обнаружения
714
+ * (`attempt.diagnosed`). Для отказа не окружения — всегда `none`;
715
+ * без неё — по классу отказа.
716
+ */
717
+ cause?: EnvironmentCause;
718
+ /** Предел окна контекста — пишется только у отказа `context-exhausted`. */
719
+ contextLimit?: ContextLimit;
712
720
  }): {
713
721
  recovery?: {
714
722
  id: string;
@@ -717,7 +725,7 @@ export declare class Engine {
717
725
  properties?: string[] | undefined;
718
726
  workId: string;
719
727
  runId: string;
720
- kind: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead";
728
+ kind: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead";
721
729
  blocked: boolean;
722
730
  /** Работа возвращена в очередь (штатная остановка); иначе — обычный отказ. */
723
731
  interrupted: boolean;
@@ -1407,8 +1415,12 @@ export declare class Engine {
1407
1415
  adopt(id: string, owner: string): AttemptState;
1408
1416
  /** Recovery отклонил продолжение: попытка истечёт на следующем `expire`. */
1409
1417
  rejectRecovery(id: string, reason: string): boolean;
1410
- /** Отмена: активная попытка теряет владение, поручение — cancelled. Принятое не отменяется. */
1411
- cancel(workId: string, reason?: string): {
1418
+ /**
1419
+ * Отмена: активная попытка теряет владение, поручение — cancelled. Принятое
1420
+ * не отменяется. `by` — кто отменил (`work.cancelled`): CLI — `operator`,
1421
+ * хост, не назвавший актёра, — `host`.
1422
+ */
1423
+ cancel(workId: string, reason?: string, by?: CancelActor): {
1412
1424
  work: {
1413
1425
  id: string;
1414
1426
  graphId: string;
@@ -1455,7 +1467,7 @@ export declare class Engine {
1455
1467
  activeRunId?: string | undefined;
1456
1468
  resultSha?: string | undefined;
1457
1469
  failure?: string | undefined;
1458
- failureKind?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
1470
+ failureKind?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
1459
1471
  failureFingerprint?: string | undefined;
1460
1472
  approvedAt?: string | undefined;
1461
1473
  approvedDigest?: string | undefined;
@@ -1562,11 +1574,13 @@ export declare class Engine {
1562
1574
  /**
1563
1575
  * Повтор неуспешного или отменённого поручения. Пока попытки не
1564
1576
  * исчерпаны — без сброса; исчерпаны — только явный сброс с причиной.
1565
- * Класс и отпечаток прошлого отказа снимаются.
1577
+ * Класс и отпечаток прошлого отказа снимаются. `by` — кто повторил
1578
+ * (`work.retried`): CLI — `operator`, восстановление очереди — `recovery`,
1579
+ * хост, не назвавший актёра, — `host`.
1566
1580
  */
1567
1581
  retry(workId: string, reset?: {
1568
1582
  reason: string;
1569
- }): {
1583
+ }, by?: RetryActor): {
1570
1584
  work: {
1571
1585
  id: string;
1572
1586
  graphId: string;
@@ -1613,7 +1627,7 @@ export declare class Engine {
1613
1627
  activeRunId?: string | undefined;
1614
1628
  resultSha?: string | undefined;
1615
1629
  failure?: string | undefined;
1616
- failureKind?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
1630
+ failureKind?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stalled" | "context-exhausted" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
1617
1631
  failureFingerprint?: string | undefined;
1618
1632
  approvedAt?: string | undefined;
1619
1633
  approvedDigest?: string | undefined;