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

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 (116) hide show
  1. package/README.md +16 -2
  2. package/docs/contracts.md +261 -33
  3. package/docs/release-notes/0.1.0-alpha.36.md +26 -0
  4. package/docs/release-notes/0.1.0-alpha.37.md +40 -0
  5. package/docs/standalone.md +20 -0
  6. package/docs/toolchains.md +57 -2
  7. package/docs/upgrade.md +108 -0
  8. package/lib/agents/schemas.d.ts +84 -2
  9. package/lib/agents/schemas.js +49 -1
  10. package/lib/cli.js +149 -1
  11. package/lib/contracts/cli.d.ts +1495 -170
  12. package/lib/contracts/cli.js +232 -2
  13. package/lib/contracts/diagnosis.d.ts +8 -4
  14. package/lib/contracts/diagnosis.js +3 -0
  15. package/lib/contracts/errors.d.ts +7 -1
  16. package/lib/contracts/errors.js +6 -0
  17. package/lib/contracts/events.d.ts +453 -60
  18. package/lib/contracts/events.js +79 -0
  19. package/lib/contracts/execution.d.ts +270 -50
  20. package/lib/contracts/execution.js +41 -0
  21. package/lib/contracts/failure.d.ts +14 -1
  22. package/lib/contracts/failure.js +9 -1
  23. package/lib/contracts/handoff.d.ts +70 -20
  24. package/lib/contracts/handoff.js +42 -1
  25. package/lib/contracts/index.d.ts +1 -0
  26. package/lib/contracts/index.js +1 -0
  27. package/lib/contracts/input-state.d.ts +13 -0
  28. package/lib/contracts/input-state.js +32 -0
  29. package/lib/contracts/input.d.ts +442 -0
  30. package/lib/contracts/input.js +321 -0
  31. package/lib/contracts/planning.d.ts +2 -0
  32. package/lib/contracts/policy.d.ts +17 -2
  33. package/lib/contracts/policy.js +31 -2
  34. package/lib/contracts/ports.d.ts +54 -0
  35. package/lib/contracts/project.d.ts +127 -0
  36. package/lib/contracts/project.js +99 -0
  37. package/lib/contracts/published.d.ts +603 -92
  38. package/lib/contracts/published.js +4 -1
  39. package/lib/contracts/repair-policy.d.ts +20 -0
  40. package/lib/contracts/repair-policy.js +34 -0
  41. package/lib/contracts/report.d.ts +53 -21
  42. package/lib/contracts/report.js +33 -2
  43. package/lib/contracts/result.d.ts +26 -24
  44. package/lib/contracts/review.d.ts +47 -8
  45. package/lib/contracts/review.js +21 -1
  46. package/lib/control/harness.d.ts +2555 -51
  47. package/lib/control/harness.js +112 -6
  48. package/lib/control/recovery.d.ts +2 -2
  49. package/lib/control/report.js +1 -0
  50. package/lib/control/status.d.ts +30 -22
  51. package/lib/control/status.js +11 -1
  52. package/lib/control/workflow.d.ts +8 -8
  53. package/lib/engine/budget.d.ts +86 -3
  54. package/lib/engine/budget.js +45 -10
  55. package/lib/engine/engine.d.ts +3091 -85
  56. package/lib/engine/engine.js +1206 -101
  57. package/lib/engine/input-policy.d.ts +68 -0
  58. package/lib/engine/input-policy.js +285 -0
  59. package/lib/engine/input-requests.d.ts +64 -0
  60. package/lib/engine/input-requests.js +187 -0
  61. package/lib/engine/measured.d.ts +6 -1
  62. package/lib/engine/measured.js +12 -1
  63. package/lib/engine/prompt.d.ts +4 -2
  64. package/lib/engine/prompt.js +3 -1
  65. package/lib/engine/property-recovery.js +2 -0
  66. package/lib/engine/repair.d.ts +2 -0
  67. package/lib/engine/repair.js +10 -3
  68. package/lib/engine/runner.d.ts +33 -4
  69. package/lib/engine/runner.js +266 -23
  70. package/lib/environment/lifecycle.d.ts +8 -0
  71. package/lib/environment/lifecycle.js +15 -2
  72. package/lib/explain/state.d.ts +16 -2
  73. package/lib/explain/state.js +254 -77
  74. package/lib/handoff/markdown.js +10 -0
  75. package/lib/handoff/pack.js +42 -1
  76. package/lib/index.d.ts +10 -0
  77. package/lib/index.js +10 -0
  78. package/lib/init/inspect.d.ts +34 -0
  79. package/lib/init/inspect.js +292 -0
  80. package/lib/init/project.js +14 -31
  81. package/lib/integrations/connector/commands.d.ts +12 -12
  82. package/lib/integrations/connector/config.d.ts +4 -4
  83. package/lib/integrations/connector/delivery.d.ts +1 -1
  84. package/lib/integrations/relay-v2/protocol.d.ts +4 -4
  85. package/lib/profiles/resolve.d.ts +2 -1
  86. package/lib/projections/enums.d.ts +1 -1
  87. package/lib/projections/enums.js +4 -0
  88. package/lib/projections/index.d.ts +1 -0
  89. package/lib/projections/index.js +1 -0
  90. package/lib/projections/input.d.ts +17 -0
  91. package/lib/projections/input.js +28 -0
  92. package/lib/projections/stop.d.ts +40 -1
  93. package/lib/projections/stop.js +87 -4
  94. package/lib/report/compute.d.ts +4 -1
  95. package/lib/report/compute.js +25 -0
  96. package/lib/report/document.js +1 -0
  97. package/lib/storage/document.d.ts +66 -28
  98. package/lib/testing/index.d.ts +1 -1
  99. package/lib/testing/index.js +1 -1
  100. package/lib/testing/store-contract.d.ts +8 -1
  101. package/lib/testing/store-contract.js +194 -1
  102. package/lib/verification/confirm.d.ts +3 -3
  103. package/lib/verification/corpus.d.ts +9 -9
  104. package/lib/verification/gates.d.ts +119 -0
  105. package/lib/verification/gates.js +311 -4
  106. package/package.json +1 -1
  107. package/schemas/execution-document.schema.json +130 -0
  108. package/schemas/execution-policy.schema.json +26 -0
  109. package/schemas/handoff-pack.schema.json +146 -4
  110. package/schemas/input-request.schema.json +665 -0
  111. package/schemas/project-facts.schema.json +393 -0
  112. package/schemas/result-envelope.schema.json +1 -0
  113. package/schemas/run-event.schema.json +625 -0
  114. package/schemas/run-result.schema.json +1 -0
  115. package/schemas/stop-diagnosis.schema.json +5 -1
  116. package/schemas/value-report.schema.json +78 -7
@@ -42,8 +42,11 @@ export function executionEnvironment(profiles, devcontour = {}, source = process
42
42
  if (source[key] === undefined)
43
43
  throw new Error(`Не задана переменная окружения: ${key}`);
44
44
  env[key] = source[key];
45
- // Inherited values are also redacted: callers need not classify every provider token.
46
- if (source[key])
45
+ // Наследуемые значения тоже маскируются — вызывающему не нужно
46
+ // объявлять каждый токен провайдера, — но только похожие на секрет:
47
+ // по имени или длиной. Очень короткое общее значение (`FORCE_COLOR=1`,
48
+ // `CI=true`) иначе вырезалось бы из каждой строки вывода.
49
+ if (source[key] && inheritedSecret(key, source[key]))
47
50
  secretValues.push(source[key]);
48
51
  }
49
52
  Object.assign(env, profile.values);
@@ -63,6 +66,16 @@ export function executionEnvironment(profiles, devcontour = {}, source = process
63
66
  }
64
67
  return { env, redact: redactor(secretValues) };
65
68
  }
69
+ /** Имя переменной похоже на секрет. */
70
+ const SECRET_NAME = /(TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|CREDENTIAL|AUTH|PRIVATE)/i;
71
+ /** Наименьшая длина наследуемого значения без секретного имени, которое маскируется. */
72
+ export const INHERITED_SECRET_MIN = 8;
73
+ /**
74
+ * Маскировать ли наследуемое значение: имя похоже на секрет (значение не
75
+ * короче 4 знаков, как у настроек коннектора) или значение длинное
76
+ * (`INHERITED_SECRET_MIN`). Объявленные `secrets` маскируются всегда.
77
+ */
78
+ export const inheritedSecret = (key, value) => SECRET_NAME.test(key) ? value.length >= 4 : value.length >= INHERITED_SECRET_MIN;
66
79
  /**
67
80
  * Маска по тем секретам и наследуемым значениям, что заданы, — даже когда
68
81
  * окружение целиком собрать нельзя. Незаданный секрет — причина отказа, но не
@@ -23,7 +23,13 @@ export interface StopSource {
23
23
  export interface StopInputOptions {
24
24
  maxAttempts: number;
25
25
  repairBudget: number;
26
+ /** Одна работа; неизвестная — `NOT_FOUND`. */
26
27
  workId?: string;
28
+ /**
29
+ * Набор работ (не вместе с `workId`): входы каждой — те же, что у вызова с
30
+ * её `workId`, за одно чтение. Неизвестная — `NOT_FOUND`.
31
+ */
32
+ workIds?: readonly string[];
27
33
  }
28
34
  /**
29
35
  * Control таким, каким его увидит следующий run этого процесса: run снимает
@@ -37,10 +43,10 @@ export declare function nextRunControl(h: {
37
43
  }, v: ExecutionView): {
38
44
  control: {
39
45
  paused: boolean;
40
- pauseReason?: "runtime" | "operator" | "shutdown" | "base-check" | "reconfigure" | undefined;
46
+ pauseReason?: "operator" | "runtime" | "shutdown" | "base-check" | "reconfigure" | undefined;
41
47
  pausedAt?: string | undefined;
42
48
  pauseOperation?: string | undefined;
43
- 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;
49
+ 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" | "needs-input")[] | undefined;
44
50
  waits?: {
45
51
  kind: "base-check" | "context-lock";
46
52
  detail: string;
@@ -73,5 +79,13 @@ export declare function nextRunControl(h: {
73
79
  * отпечатка повторять нечего, без задания графа движок сам не чинит.
74
80
  * Первым идёт вход действующей роли controller, затем поручения (кроме
75
81
  * принятых) в порядке состояния.
82
+ *
83
+ * Выбор: `workId` — одна работа, `workIds` — набор (входы каждой — те же,
84
+ * что у вызова с её `workId`, в порядке состояния), без них — доска. Всё, что
85
+ * общее для работ (прогноз групп, обратные зависимости, запросы, попытки,
86
+ * записи вызовов и статусы бюджетов), читается один раз за вызов, поэтому
87
+ * диагноз набора и доски линеен по числу работ и их связей. Исключение —
88
+ * порты хоста, которые движок спрашивает о каждой работе (основание
89
+ * постановки, `claimable`, группа бюджета при пределе группы).
76
90
  */
77
91
  export declare function stopInputsOf(h: StopSource, options: StopInputOptions): StopInput[];
@@ -1,6 +1,10 @@
1
1
  import { HarnessError } from "../contracts/errors.js";
2
- import { MAX_NEUTRAL_FAILURES, lastContextLimit, repairPolicy, repairRepeats, } from "../contracts/repair-policy.js";
2
+ import { blocksWork } from "../contracts/index.js";
3
+ import { MAX_NEUTRAL_FAILURES, failedBeforeWork, lastContextLimit, repairPolicy, repairRepeats, } from "../contracts/repair-policy.js";
3
4
  import { acceptanceGap, repairDecision } from "../engine/repair.js";
5
+ import { requestsIndex } from "../engine/input-requests.js";
6
+ import { activeOf } from "../engine/engine.js";
7
+ import { inputStateOf } from "../projections/input.js";
4
8
  /**
5
9
  * Control таким, каким его увидит следующий run этого процесса: run снимает
6
10
  * паузу «не запускали» (без причины) и штатную остановку, а применимый запрос
@@ -34,14 +38,36 @@ const phaseOf = {
34
38
  * отпечатка повторять нечего, без задания графа движок сам не чинит.
35
39
  * Первым идёт вход действующей роли controller, затем поручения (кроме
36
40
  * принятых) в порядке состояния.
41
+ *
42
+ * Выбор: `workId` — одна работа, `workIds` — набор (входы каждой — те же,
43
+ * что у вызова с её `workId`, в порядке состояния), без них — доска. Всё, что
44
+ * общее для работ (прогноз групп, обратные зависимости, запросы, попытки,
45
+ * записи вызовов и статусы бюджетов), читается один раз за вызов, поэтому
46
+ * диагноз набора и доски линеен по числу работ и их связей. Исключение —
47
+ * порты хоста, которые движок спрашивает о каждой работе (основание
48
+ * постановки, `claimable`, группа бюджета при пределе группы).
37
49
  */
38
50
  export function stopInputsOf(h, options) {
51
+ if (options.workId !== undefined && options.workIds !== undefined)
52
+ throw new HarnessError('INVALID_INPUT', 'Укажите workId или workIds, не оба');
53
+ const selected = options.workIds !== undefined
54
+ ? new Set(options.workIds)
55
+ : options.workId !== undefined
56
+ ? new Set([options.workId])
57
+ : undefined;
39
58
  const jobs = h.workflows.list().filter((j) => j.kind === 'graph');
40
59
  const now = h.engine.clock();
41
60
  return h.engine.read((v) => {
42
61
  const works = v.works();
43
- if (options.workId !== undefined && !works.some((w) => w.id === options.workId))
44
- throw new HarnessError('NOT_FOUND', 'Поручение не найдено: ' + options.workId);
62
+ // Первая работа с этим id — как `v.work(id)`; все зависимости графа — в нём.
63
+ const byId = new Map();
64
+ for (const w of works)
65
+ if (!byId.has(w.id))
66
+ byId.set(w.id, w);
67
+ if (selected)
68
+ for (const id of selected)
69
+ if (!byId.has(id))
70
+ throw new HarnessError('NOT_FOUND', 'Поручение не найдено: ' + id);
45
71
  const inputs = [];
46
72
  const lease = v.controller();
47
73
  if (lease && lease.leaseUntil > now)
@@ -54,60 +80,217 @@ export function stopInputsOf(h, options) {
54
80
  });
55
81
  const { control } = nextRunControl(h, v);
56
82
  const reconfigureApplies = h.engine.reconfigureApplies(v);
83
+ const memo = (fn) => {
84
+ const cache = new Map();
85
+ return (key) => {
86
+ if (!cache.has(key))
87
+ cache.set(key, fn(key));
88
+ return cache.get(key);
89
+ };
90
+ };
91
+ const once = (fn) => {
92
+ let value;
93
+ return () => (value ??= { result: fn() }).result;
94
+ };
57
95
  // Бюджет держит выдачу по тому же расчёту, которым следующий claim ставит
58
96
  // или снимает budgetBlock; записанное поле — лишь кэш этого расчёта
59
97
  // (после повышения бюджета оно устаревает, выключенные бюджеты не держат).
60
- const budgetReason = (w) => h.engine.budgetBlockOf(w.id, v);
98
+ const budgetBlock = h.engine.budgetBlockers(v);
99
+ const budgetById = memo((id) => budgetBlock(id));
100
+ const budgetReason = (w) => budgetById(w.id);
61
101
  const budgetHeld = (w) => Boolean(budgetReason(w));
62
102
  // Внешние предпосылки графа claim не проверяет, даже если id совпал с работой.
63
- const external = (graphId) => new Set(v.graph(graphId)?.graph.prerequisites.map((p) => p.id) ?? []);
64
- const pauseLifts = (group) => control.pauseReason === 'runtime' &&
65
- (control.pauseFailures ?? []).length > 0 &&
66
- (control.pauseFailures ?? []).every((kind) => works.some((w) => w.status === 'failed' &&
67
- !w.recovery &&
68
- w.failureKind === kind &&
69
- repairPolicy[kind].blocksQueue === true &&
70
- group.get(w.id) === 'retry'));
103
+ const external = memo((graphId) => new Set(v.graph(graphId)?.graph.prerequisites.map((p) => p.id) ?? []));
104
+ // Набор и доска читают попытки одним проходом (порядок — как у `v.attempts(id)`).
105
+ let attemptsByWork;
106
+ const attemptsOf = memo((workId) => {
107
+ if (selected?.size === 1)
108
+ return v.attempts(workId);
109
+ if (!attemptsByWork) {
110
+ attemptsByWork = new Map();
111
+ for (const a of v.attempts()) {
112
+ const list = attemptsByWork.get(a.workId);
113
+ if (list)
114
+ list.push(a);
115
+ else
116
+ attemptsByWork.set(a.workId, [a]);
117
+ }
118
+ }
119
+ return attemptsByWork.get(workId) ?? [];
120
+ });
121
+ const requestsFor = requestsIndex(v);
122
+ const requestsById = memo((id) => requestsFor(byId.get(id)));
71
123
  // Согласование графа, устаревшее для этой политики: в режиме agent run сам
72
124
  // пересогласует план и начнёт новое задание (бюджет восстановлений с нуля),
73
125
  // в режиме operator работа не выдаётся до согласования человеком.
74
126
  const agentMode = h.policy.approvalMode === 'agent';
75
- const staleOf = (w) => h.engine.blockers(w, v).find((b) => b.code === 'APPROVAL_STALE')?.message;
127
+ const staleness = h.engine.approvalStaleness(v);
128
+ const staleById = memo((id) => staleness(byId.get(id)));
129
+ const staleOf = (w) => staleById(w.id);
130
+ const liveJob = memo((graphId) => jobs.find((j) => j.id === graphId && h.workflows.continues(j, v, { reconfigureApplies })));
76
131
  const jobOf = (graphId, w) => {
77
- const live = jobs.find((j) => j.id === graphId && h.workflows.continues(j, v, { reconfigureApplies }));
132
+ const live = liveJob(graphId);
78
133
  if (live)
79
134
  return live;
80
135
  if (agentMode && staleOf(w) && jobs.some((j) => j.id === graphId))
81
136
  return { repairs: 0 };
82
137
  return undefined;
83
138
  };
84
- // Прогноз по каждому графу; снятие паузы runtime — глобальное (clearFailure).
85
- const groups = new Map();
86
- const groupOf = (graphId, w) => {
87
- if (!groups.has(graphId)) {
88
- const job = jobOf(graphId, w);
89
- groups.set(graphId, job
90
- ? outlookOf(v, graphId, job.repairs ?? 0, options, control, budgetHeld)
91
- : new Map());
92
- }
93
- return groups.get(graphId);
94
- };
139
+ // Прогноз по каждому графу — с первой работой графа в порядке состояния;
140
+ // снятие паузы runtime — глобальное (clearFailure), ему нужны все графы.
141
+ const firstOf = new Map();
95
142
  for (const w of works)
96
- groupOf(w.graphId, w);
97
- const everyGroup = new Map([...groups.values()].flatMap((g) => [...g]));
143
+ if (!firstOf.has(w.graphId))
144
+ firstOf.set(w.graphId, w);
145
+ const byGraph = new Map();
146
+ for (const w of works) {
147
+ const list = byGraph.get(w.graphId);
148
+ if (list)
149
+ list.push(w);
150
+ else
151
+ byGraph.set(w.graphId, [w]);
152
+ }
153
+ const ctx = {
154
+ v,
155
+ byId,
156
+ external,
157
+ attemptsOf,
158
+ requestsOf: requestsById,
159
+ };
160
+ const groupOf = memo((graphId) => {
161
+ const job = jobOf(graphId, firstOf.get(graphId));
162
+ return job
163
+ ? outlookOf(ctx, graphId, byGraph.get(graphId) ?? [], job.repairs ?? 0, options, control, budgetHeld)
164
+ : new Map();
165
+ });
166
+ const pauseLifts = once(() => {
167
+ if (!(control.pauseReason === 'runtime' && (control.pauseFailures ?? []).length > 0))
168
+ return false;
169
+ const everyGroup = new Map([...firstOf.keys()].flatMap((g) => [...groupOf(g)]));
170
+ return (control.pauseFailures ?? []).every((kind) => works.some((w) => w.status === 'failed' &&
171
+ !w.recovery &&
172
+ w.failureKind === kind &&
173
+ repairPolicy[kind].blocksQueue === true &&
174
+ everyGroup.get(w.id) === 'retry'));
175
+ });
98
176
  // Незавершённые работы, которые прямо ждут отменённую: только их и
99
177
  // перепланирует replan-dependents. Ждущая через отменённую же
100
178
  // промежуточную — забота диагноза той; через принятую — не ждёт вовсе.
101
- const openDependentsOf = (id) => works
102
- .filter((w) => w.status !== 'done' &&
103
- w.status !== 'cancelled' &&
104
- w.order.dependsOn.includes(id) &&
105
- !external(w.graphId).has(id))
106
- .map((w) => w.id);
179
+ let dependents;
180
+ const openDependentsOf = (id) => {
181
+ if (!dependents) {
182
+ dependents = new Map();
183
+ for (const w of works) {
184
+ if (w.status === 'done' || w.status === 'cancelled')
185
+ continue;
186
+ const outside = external(w.graphId);
187
+ for (const dep of new Set(w.order.dependsOn)) {
188
+ if (outside.has(dep))
189
+ continue;
190
+ const list = dependents.get(dep);
191
+ if (list)
192
+ list.push(w.id);
193
+ else
194
+ dependents.set(dep, [w.id]);
195
+ }
196
+ }
197
+ }
198
+ return [...(dependents.get(id) ?? [])];
199
+ };
200
+ // Первая отменённая работа графа: она останавливает восстановление группы.
201
+ const cancelledIn = new Map();
202
+ for (const w of works)
203
+ if (w.status === 'cancelled' && !cancelledIn.has(w.graphId))
204
+ cancelledIn.set(w.graphId, w.id);
205
+ const active = once(() => activeOf(v));
206
+ // Вопрос исполнителя, держащий работу: состояние, вопрос и варианты
207
+ // (усекает explain), ответ — версией и digest; почему ответ сейчас не
208
+ // применится — по тем же пределам, что у applyInput.
209
+ const inputOf = (work, attempts) => {
210
+ // Вопрос держит и готовую работу (новая редакция графа, устаревшее
211
+ // применение): диагноз называет его при любом статусе, кроме итоговых.
212
+ if (work.status === 'done' || work.status === 'cancelled')
213
+ return undefined;
214
+ const requests = requestsById(work.id);
215
+ const question = requests
216
+ .filter((r) => r.kind === 'question' && r.blocking && inputStateOf(r))
217
+ .at(-1);
218
+ if (!question)
219
+ return undefined;
220
+ const answer = question.answers.at(-1);
221
+ const refusal = [
222
+ question.stale ? `основание устарело до выдачи (${question.stale.reason})` : '',
223
+ work.attempt >= options.maxAttempts
224
+ ? `исчерпаны попытки (${work.attempt} из ${options.maxAttempts}): применение — со сбросом и причиной`
225
+ : '',
226
+ budgetReason(work) ?? '',
227
+ active().some((a) => byId.get(a.workId)?.graphId === work.graphId)
228
+ ? 'в графе идут попытки: новое согласование ждёт их окончания'
229
+ : '',
230
+ ].filter(Boolean);
231
+ const own = attempts.flatMap((a) => a.assumptions ?? []).length;
232
+ const followUps = requests.filter((r) => r.kind === 'follow-up' && r.lifecycle === 'pending').length;
233
+ return {
234
+ requestId: question.id,
235
+ state: inputStateOf(question),
236
+ question: question.question.question,
237
+ options: question.question.options.map((o) => o.id),
238
+ ...(answer ? { answer: { revision: answer.revision, digest: answer.digest } } : {}),
239
+ ...(refusal.length ? { refusal: refusal.join('; ') } : {}),
240
+ ...(own ? { assumptions: own } : {}),
241
+ ...(followUps ? { followUps } : {}),
242
+ };
243
+ };
244
+ // Готовая работа ждёт предпосылку, на которой движок остановит задание:
245
+ // сломанную без автоматического шага или саму ждущую такую (транзитивно).
246
+ // Готовая и выдаваемая предпосылка движок не останавливает. Ответ зависит
247
+ // только от предпосылки и графа ждущей работы (есть ли у неё задание,
248
+ // прогноз группы, внешние предпосылки): граф ацикличен (graphIssues
249
+ // отвергает цикл и зависимость вне графа и его предпосылок, register —
250
+ // чужой ID), поэтому ответ запоминается для всех ждущих работ графа;
251
+ // работа на пути обхода — false, как повторный визит прежнего обхода.
252
+ const stopsFor = memo((key) => {
253
+ const [graphId, hasJob] = [key.slice(0, -2), key.endsWith('\u00001')];
254
+ const known = new Map();
255
+ const visiting = new Set();
256
+ const outside = external(graphId);
257
+ const decide = (id) => {
258
+ if (outside.has(id))
259
+ return false;
260
+ const dep = byId.get(id);
261
+ if (!dep || dep.status === 'done')
262
+ return false;
263
+ // Сломанная без автоматического шага — или такая, которую повтор переведёт
264
+ // в готовую, но бюджет её не выдаст.
265
+ if (dep.status === 'failed' || dep.status === 'cancelled')
266
+ return !hasJob || groupOf(graphId).get(id) === 'stop' || budgetHeld(dep);
267
+ // Готовая, которую движок не выдаст: эпизод (blocksClaim), бюджет
268
+ // (budgetBlock) или исчерпанные попытки.
269
+ if (dep.status === 'ready' &&
270
+ ((dep.recovery && !['retry', 'closed'].includes(dep.recovery.status)) ||
271
+ budgetHeld(dep) ||
272
+ dep.attempt >= options.maxAttempts))
273
+ return true;
274
+ return dep.status === 'ready' && dep.order.dependsOn.some((d) => stops(d));
275
+ };
276
+ const stops = (id) => {
277
+ const cached = known.get(id);
278
+ if (cached !== undefined)
279
+ return cached;
280
+ if (visiting.has(id))
281
+ return false;
282
+ visiting.add(id);
283
+ const result = decide(id);
284
+ visiting.delete(id);
285
+ known.set(id, result);
286
+ return result;
287
+ };
288
+ return stops;
289
+ });
107
290
  for (const work of works) {
108
291
  if (work.status === 'done')
109
292
  continue;
110
- if (options.workId !== undefined && work.id !== options.workId)
293
+ if (selected && !selected.has(work.id))
111
294
  continue;
112
295
  // Отменённая (или упавшая отменой) — решение, только пока её ждут.
113
296
  const openDependents = work.status === 'cancelled' ||
@@ -118,12 +301,9 @@ export function stopInputsOf(h, options) {
118
301
  // не входит (как принятая); explain этой работы её показывает. Упавшая
119
302
  // отменой остаётся открытой работой: её диагноз (действия нет) нужен
120
303
  // строке поручения в пакете.
121
- if (work.status === 'cancelled' &&
122
- openDependents &&
123
- !openDependents.length &&
124
- options.workId === undefined)
304
+ if (work.status === 'cancelled' && openDependents && !openDependents.length && !selected)
125
305
  continue;
126
- const attempts = v.attempts(work.id);
306
+ const attempts = attemptsOf(work.id);
127
307
  const last = attempts.filter((a) => a.status !== 'active').at(-1);
128
308
  const kind = work.failureKind ?? 'unknown';
129
309
  const fingerprint = work.failureFingerprint;
@@ -133,34 +313,9 @@ export function stopInputsOf(h, options) {
133
313
  // Чинит только задание, которое продолжит работу: активное, по текущей
134
314
  // редакции графа и с непотраченными попытками стадии (как `claim`).
135
315
  const job = jobOf(work.graphId, work);
136
- const group = groupOf(work.graphId, work);
316
+ const group = groupOf(work.graphId);
137
317
  const approvalStale = !agentMode ? staleOf(work) : undefined;
138
- // Готовая работа ждёт предпосылку, на которой движок остановит задание:
139
- // сломанную без автоматического шага или саму ждущую такую (транзитивно).
140
- // Готовая и выдаваемая предпосылка движок не останавливает.
141
- const stops = (id, seen = new Set()) => {
142
- if (seen.has(id))
143
- return false;
144
- seen.add(id);
145
- if (external(work.graphId).has(id))
146
- return false;
147
- const dep = v.work(id);
148
- if (!dep || dep.status === 'done')
149
- return false;
150
- // Сломанная без автоматического шага.
151
- // Сломанная без автоматического шага — или такая, которую повтор переведёт
152
- // в готовую, но бюджет её не выдаст.
153
- if (dep.status === 'failed' || dep.status === 'cancelled')
154
- return !job || group.get(id) === 'stop' || budgetHeld(dep);
155
- // Готовая, которую движок не выдаст: эпизод (blocksClaim), бюджет
156
- // (budgetBlock) или исчерпанные попытки.
157
- if (dep.status === 'ready' &&
158
- ((dep.recovery && !['retry', 'closed'].includes(dep.recovery.status)) ||
159
- budgetHeld(dep) ||
160
- dep.attempt >= options.maxAttempts))
161
- return true;
162
- return dep.status === 'ready' && dep.order.dependsOn.some((d) => stops(d, seen));
163
- };
318
+ const stops = stopsFor(work.graphId + (job ? '\u00001' : '\u00000'));
164
319
  const waitingOn = work.status === 'ready' ? work.order.dependsOn.filter((d) => stops(d)) : [];
165
320
  const outlook = !job || approvalStale ? 'stop' : waitingOn.length ? 'stop' : group.get(work.id);
166
321
  const evidence = last
@@ -181,11 +336,15 @@ export function stopInputsOf(h, options) {
181
336
  ...(work.failureKind === 'context-exhausted' && lastContextLimit(attempts)
182
337
  ? { contextLimit: lastContextLimit(attempts) }
183
338
  : {}),
339
+ ...((input) => (input ? { input } : {}))(inputOf(work, attempts)),
184
340
  ...(work.failure !== undefined ? { failure: work.failure } : {}),
341
+ ...(work.status === 'failed' && failedBeforeWork(kind, attempts)
342
+ ? { preflight: true }
343
+ : {}),
185
344
  ...(work.hold
186
345
  ? { hold: { operation: work.hold.operation, reason: work.hold.reason } }
187
346
  : {}),
188
- ...(budgetReason(work) ? { budgetBlock: { reason: budgetReason(work) } } : {}),
347
+ ...((reason) => (reason ? { budgetBlock: { reason } } : {}))(budgetReason(work)),
189
348
  ...(work.recovery ? { recovery: { status: work.recovery.status } } : {}),
190
349
  ...(waitingOn.length ? { waitingOn } : {}),
191
350
  ...(approvalStale ? { approvalStale } : {}),
@@ -193,7 +352,7 @@ export function stopInputsOf(h, options) {
193
352
  ...((stoppedBy) => (stoppedBy ? { repairStoppedBy: stoppedBy } : {}))(
194
353
  // Отмена в группе останавливает её восстановление: сёстрам — почему.
195
354
  work.status === 'failed' && work.failureKind !== 'cancelled' && !work.recovery && job
196
- ? works.find((w) => w.graphId === work.graphId && w.status === 'cancelled')?.id
355
+ ? cancelledIn.get(work.graphId)
197
356
  : undefined),
198
357
  ...((live) => live && live.state !== 'active'
199
358
  ? {
@@ -220,7 +379,7 @@ export function stopInputsOf(h, options) {
220
379
  control: {
221
380
  // Пауза runtime, все причины которой снимет назначенный repair группы
222
381
  // (clearFailure блокирующего класса), для остальных работ не держит выдачу.
223
- paused: control.paused && !(work.status !== 'failed' && pauseLifts(everyGroup)),
382
+ paused: control.paused && !(work.status !== 'failed' && pauseLifts()),
224
383
  ...(control.pauseReason ? { pauseReason: control.pauseReason } : {}),
225
384
  ...(control.pauseFailures ? { pauseFailures: [...control.pauseFailures] } : {}),
226
385
  },
@@ -228,6 +387,23 @@ export function stopInputsOf(h, options) {
228
387
  evidence,
229
388
  });
230
389
  }
390
+ // Неблокирующие запросы ведущему (автономный режим): отдельными
391
+ // диагнозами — работу они не держат, но ждут решения.
392
+ for (const work of works) {
393
+ if (selected && !selected.has(work.id))
394
+ continue;
395
+ for (const r of requestsById(work.id))
396
+ if (r.kind === 'follow-up' && r.lifecycle === 'pending')
397
+ inputs.push({
398
+ kind: 'input',
399
+ request: {
400
+ id: r.id,
401
+ workId: r.workId,
402
+ question: r.question.question,
403
+ severity: r.effectiveSeverity,
404
+ },
405
+ });
406
+ }
231
407
  return inputs;
232
408
  });
233
409
  }
@@ -242,8 +418,7 @@ export function stopInputsOf(h, options) {
242
418
  * хватает общего бюджета, первая без повтора останавливает остальных.
243
419
  * Обещается только то, что движок сделает без человека.
244
420
  */
245
- function outlookOf(v, graphId, repairsUsed, options, control, budgetHeld) {
246
- const works = v.works(graphId);
421
+ function outlookOf(ctx, graphId, works, repairsUsed, options, control, budgetHeld) {
247
422
  const out = new Map();
248
423
  for (const w of works)
249
424
  out.set(w.id, 'stop');
@@ -251,14 +426,14 @@ function outlookOf(v, graphId, repairsUsed, options, control, budgetHeld) {
251
426
  // Предпосылка, которая не станет принятой, пока движок идёт по эпизодам:
252
427
  // отменённая, сломанная без обещанного раньше в проходе шага, готовая, которую
253
428
  // claim не выдаст, — или ждущая такую (транзитивно). Внешние не держат.
254
- const external = new Set(v.graph(graphId)?.graph.prerequisites.map((p) => p.id) ?? []);
429
+ const external = ctx.external(graphId);
255
430
  const depStops = (id, seen = new Set()) => {
256
431
  if (seen.has(id))
257
432
  return false;
258
433
  seen.add(id);
259
434
  if (external.has(id))
260
435
  return false;
261
- const dep = v.work(id);
436
+ const dep = ctx.byId.get(id);
262
437
  if (!dep || dep.status === 'done')
263
438
  return false;
264
439
  if (dep.status === 'cancelled')
@@ -333,7 +508,8 @@ function outlookOf(v, graphId, repairsUsed, options, control, budgetHeld) {
333
508
  if (works.some((w) => w.status === 'cancelled'))
334
509
  return out;
335
510
  if (!episodes.length) {
336
- const decision = repairDecision(v, works, {
511
+ const decision = repairDecision(ctx.v, [...works], {
512
+ blocking: (w) => ctx.requestsOf(w.id).find(blocksWork),
337
513
  budgetLeft: options.repairBudget - used,
338
514
  maxAttempts: options.maxAttempts,
339
515
  });
@@ -344,13 +520,14 @@ function outlookOf(v, graphId, repairsUsed, options, control, budgetHeld) {
344
520
  const ahead = episodes.length ? 'wait' : 'retry';
345
521
  for (const [i, w] of plain.entries()) {
346
522
  const rule = repairPolicy[w.failureKind ?? 'unknown'];
347
- const repeats = repairRepeats(w.failureKind ?? 'unknown', lastContextLimit(v.attempts(w.id)));
523
+ const attempts = ctx.attemptsOf(w.id);
524
+ const repeats = repairRepeats(w.failureKind ?? 'unknown', lastContextLimit(attempts));
348
525
  const identical = w.failureFingerprint
349
- ? v.attempts(w.id).filter((a) => a.failureFingerprint === w.failureFingerprint).length
526
+ ? attempts.filter((a) => a.failureFingerprint === w.failureFingerprint).length
350
527
  : repeats + 1;
351
528
  const retry = rule.action === 'retry' &&
352
529
  identical - 1 < repeats &&
353
- !acceptanceGap(v, w) &&
530
+ !acceptanceGap(ctx.v, w) &&
354
531
  (w.neutralFailures ?? 0) < MAX_NEUTRAL_FAILURES &&
355
532
  w.attempt < options.maxAttempts &&
356
533
  used + i < options.repairBudget;
@@ -112,6 +112,16 @@ export function handoffMarkdown(pack) {
112
112
  if (pack.queue.paused &&
113
113
  pack.works.some((w) => w.next.actor === 'controller' && w.next.action === 'retry'))
114
114
  out.push('', 'Повтор ждёт снятия паузы очереди.');
115
+ if (pack.inputs?.length || pack.truncated.inputs) {
116
+ out.push('', '## Вопросы исполнителя', '');
117
+ for (const r of pack.inputs ?? [])
118
+ out.push(`- ${r.requestId} ${r.workId} [${r.kind}, ${r.state}, серьёзность ${r.severity}]: ${cell(r.question)}` +
119
+ (r.options.length ? ` (варианты: ${r.options.join(', ')})` : '') +
120
+ (r.answer
121
+ ? ` — ответ r${r.answer.revision} ${r.answer.digest.slice(0, 12)}: ${cell(r.answer.excerpt)}`
122
+ : ''));
123
+ out.push(...more(pack.truncated.inputs, 'вопросов'));
124
+ }
115
125
  out.push('', '## Последние провалы', '');
116
126
  if (!pack.failures.length)
117
127
  out.push('Провалов нет.');
@@ -6,6 +6,8 @@ import { callRecords } from "../engine/usage.js";
6
6
  import { policySecrets, redactor } from "../environment/redaction.js";
7
7
  import { stopInputsOf } from "../explain/state.js";
8
8
  import { handoffMarkdown } from "./markdown.js";
9
+ import { requestsOf } from "../engine/input-requests.js";
10
+ import { inputStateOf } from "../projections/input.js";
9
11
  import { activeStatuses } from "../projections/enums.js";
10
12
  import { nextAction } from "../projections/next.js";
11
13
  import { explainStop, stopCodeOf } from "../projections/stop.js";
@@ -100,7 +102,16 @@ function build(h, options, maxBytes, measure) {
100
102
  // которого — вызовы о его группе, повторяла бы строку группы N раз.
101
103
  const calls = callRecords(v);
102
104
  const ownSpend = new Set(works.filter((w) => ownWorkRecords(v, calls, w.id).length > 0).map((w) => w.id));
103
- return { works, attempts, ownSpend };
105
+ // Открытые запросы исполнителя: вопросы, затем запросы ведущему.
106
+ const inputs = works
107
+ .flatMap((w) => requestsOf(v, w))
108
+ .filter((r) => (r.kind === 'question' &&
109
+ r.blocking &&
110
+ inputStateOf(r) &&
111
+ inputStateOf(r) !== 'delivered') ||
112
+ (r.kind === 'follow-up' && r.lifecycle === 'pending'))
113
+ .sort((a, b) => a.kind === b.kind ? a.createdAt.localeCompare(b.createdAt) : a.kind === 'question' ? -1 : 1);
114
+ return { works, attempts, ownSpend, inputs };
104
115
  });
105
116
  const byId = new Map(read.works.map((w) => [w.id, w]));
106
117
  const title = (id) => text(byId.get(id)?.order.title ?? id);
@@ -372,6 +383,33 @@ function build(h, options, maxBytes, measure) {
372
383
  live: status.controller.leaseUntil > now,
373
384
  }
374
385
  : undefined;
386
+ const inputs = read.inputs.slice(0, HANDOFF_LIMITS.inputs).map((r) => {
387
+ const answer = r.answers.at(-1);
388
+ return {
389
+ requestId: name(r.id),
390
+ workId: r.workId,
391
+ kind: r.kind,
392
+ state: inputStateOf(r),
393
+ severity: r.effectiveSeverity,
394
+ question: text(r.question.question),
395
+ options: r.question.options.map((o) => name(o.id)),
396
+ ...(answer
397
+ ? {
398
+ answer: {
399
+ revision: answer.revision,
400
+ digest: answer.digest,
401
+ excerpt: text(answer.text, HANDOFF_LIMITS.answerChars),
402
+ },
403
+ }
404
+ : {}),
405
+ origin: {
406
+ graphDigest: r.originBasis.graphDigest,
407
+ orderDigest: r.originBasis.orderDigest,
408
+ contextDigest: r.originBasis.contextDigest,
409
+ },
410
+ ...opt('targetDigest', r.target?.digest),
411
+ };
412
+ });
375
413
  const cleanIntentions = intentions.map(plainText);
376
414
  const clippedIntentions = cleanIntentions.map((s) => clipSafe(s, HANDOFF_LIMITS.intentionChars));
377
415
  const pack = {
@@ -395,6 +433,7 @@ function build(h, options, maxBytes, measure) {
395
433
  failures,
396
434
  ...opt('budgets', budgets),
397
435
  repairs,
436
+ ...(inputs.length ? { inputs } : {}),
398
437
  next: boardNext({
399
438
  diagnoses,
400
439
  active,
@@ -414,6 +453,7 @@ function build(h, options, maxBytes, measure) {
414
453
  budgetsWithin: relevant.length - listed.length,
415
454
  budgetsShared: listed.length - shown.length,
416
455
  repairs: repairsAll.length - repairs.length,
456
+ inputs: read.inputs.length - inputs.length,
417
457
  intentions: cleanIntentions.filter((s, i) => s !== clippedIntentions[i]).length,
418
458
  intentionsDropped: 0,
419
459
  bySize: false,
@@ -451,6 +491,7 @@ export function fitPack(pack, maxBytes = HANDOFF_MAX_BYTES, measure = 'json') {
451
491
  () => dropLast(pack.works) && (t.works++, true),
452
492
  () => dropLast(pack.stops) && (t.stops++, true),
453
493
  () => Boolean(pack.budgets && dropLast(pack.budgets.entries)) && (t.budgets++, true),
494
+ () => Boolean(pack.inputs && dropLast(pack.inputs)) && (t.inputs++, true),
454
495
  ];
455
496
  for (const step of steps)
456
497
  while (size() > maxBytes) {