devcontour-harness 0.1.0-alpha.42 → 0.1.0-alpha.45

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 (65) hide show
  1. package/README.md +25 -2
  2. package/docs/architecture.md +38 -3
  3. package/docs/contracts.md +117 -3
  4. package/docs/release-notes/0.1.0-alpha.43.md +40 -0
  5. package/docs/release-notes/0.1.0-alpha.44.md +44 -0
  6. package/docs/release-notes/0.1.0-alpha.45.md +77 -0
  7. package/docs/upgrade.md +107 -17
  8. package/lib/contracts/cli.d.ts +115 -4
  9. package/lib/contracts/cli.js +6 -1
  10. package/lib/contracts/events.d.ts +65 -5
  11. package/lib/contracts/events.js +18 -1
  12. package/lib/contracts/execution.d.ts +76 -0
  13. package/lib/contracts/execution.js +35 -2
  14. package/lib/contracts/policy.d.ts +39 -0
  15. package/lib/contracts/policy.js +64 -0
  16. package/lib/contracts/profiles.d.ts +6 -0
  17. package/lib/contracts/published.d.ts +97 -2
  18. package/lib/contracts/report.d.ts +8 -0
  19. package/lib/contracts/report.js +7 -1
  20. package/lib/contracts/result.d.ts +93 -0
  21. package/lib/contracts/result.js +37 -1
  22. package/lib/contracts/review.d.ts +1 -1
  23. package/lib/control/harness.d.ts +29 -2
  24. package/lib/engine/engine.d.ts +54 -6
  25. package/lib/engine/engine.js +191 -24
  26. package/lib/engine/joint-runner.d.ts +2 -0
  27. package/lib/engine/joint-runner.js +13 -3
  28. package/lib/engine/result.js +7 -3
  29. package/lib/engine/runner.d.ts +8 -0
  30. package/lib/engine/runner.js +91 -3
  31. package/lib/environment/git-trust.js +3 -0
  32. package/lib/environment/isolation.d.ts +1 -1
  33. package/lib/environment/isolation.js +38 -4
  34. package/lib/environment/process.d.ts +2 -0
  35. package/lib/environment/process.js +7 -1
  36. package/lib/explain/state.js +1 -1
  37. package/lib/index.d.ts +1 -0
  38. package/lib/index.js +1 -0
  39. package/lib/integrations/connector/history.js +1 -1
  40. package/lib/integrations/connector/summary.js +2 -1
  41. package/lib/profiles/resolve.d.ts +6 -0
  42. package/lib/projections/attempt.d.ts +4 -2
  43. package/lib/projections/attempt.js +14 -1
  44. package/lib/report/compute.js +7 -3
  45. package/lib/report/document.js +1 -1
  46. package/lib/storage/document.d.ts +28 -2
  47. package/lib/testing/store-contract.d.ts +8 -2
  48. package/lib/testing/store-contract.js +56 -1
  49. package/lib/verification/acceptance.d.ts +12 -0
  50. package/lib/verification/acceptance.js +62 -7
  51. package/lib/verification/applicability.d.ts +134 -0
  52. package/lib/verification/applicability.js +373 -0
  53. package/lib/verification/gates.d.ts +6 -0
  54. package/lib/verification/joint.d.ts +179 -1
  55. package/lib/verification/joint.js +23 -3
  56. package/lib/verification/proof.d.ts +18 -4
  57. package/lib/verification/proof.js +52 -9
  58. package/package.json +1 -1
  59. package/schemas/execution-document.schema.json +77 -1
  60. package/schemas/execution-policy.schema.json +38 -0
  61. package/schemas/joint-verification.schema.json +4 -0
  62. package/schemas/result-envelope.schema.json +138 -2
  63. package/schemas/run-event.schema.json +100 -0
  64. package/schemas/run-result.schema.json +138 -2
  65. package/schemas/value-report.schema.json +20 -0
@@ -19,6 +19,9 @@ import { basename, dirname, join, resolve, sep } from 'node:path';
19
19
  * исполняемые настройки, которые git читает сам.
20
20
  */
21
21
  export const gitHardening = [
22
+ // Объекты замены (`refs/replace/*`) пишет любой, кто пишет в репозиторий:
23
+ // git хоста читает только настоящие объекты (diff, требования, области).
24
+ '--no-replace-objects',
22
25
  '-c',
23
26
  // Older Git treats 'false' as a hook executable; empty disables the hook
24
27
  // there and is false for versions supporting the built-in fsmonitor.
@@ -277,7 +277,7 @@ export declare function protectedChanges(before: Map<string, string>, root: stri
277
277
  /**
278
278
  * Пути относительно `root`, которыми владеет подготовка фазы (вложенные
279
279
  * `.git`, см. `preparationGuard`): не в счёт только их исчезновение
280
- * (уборка фикстуры переносом родителя). Изменение — в том числе подмена
280
+ * (уборка фикстуры переносом родителя, см. `removedInPlace`). Изменение — в том числе подмена
281
281
  * переносом другого `.git` на то же место — нарушение: подменённый
282
282
  * `gitdir` подмодуля git хоста прочитал бы при следующей команде.
283
283
  */
@@ -744,9 +744,13 @@ export function protectedSnapshot(root) {
744
744
  if (stat.isSymbolicLink())
745
745
  return 'l:' + readlinkSync(path);
746
746
  // Не каталог и не ссылка — файл, FIFO, сокет, устройство: всё это
747
- // содержимое, пустым деревом не бывает.
747
+ // содержимое, пустым деревом не бывает. mtime возвращает `utimes`,
748
+ // ctime — нет: правка на месте в перенесённом наружу родителе с
749
+ // восстановленными размером и mtime всё равно меняет подпись. Ту же
750
+ // ctime меняют chmod/chown и новая жёсткая ссылка на файл — для
751
+ // защищённой конфигурации это тоже изменение.
748
752
  if (!stat.isDirectory())
749
- return `f:${stat.size}:${stat.mtimeMs}:${stat.ino}`;
753
+ return `f:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}`;
750
754
  const mode = stat.mode & 0o7777;
751
755
  const names = readdirSync(path).sort();
752
756
  const inner = names.map((name) => signature(join(path, name)));
@@ -802,6 +806,36 @@ export function protectedSnapshot(root) {
802
806
  walk(root);
803
807
  return found;
804
808
  }
809
+ /**
810
+ * Исчез ли `path` из дерева сам, а не скрылся за подменённым родителем.
811
+ *
812
+ * Снимок не спускается в символьные ссылки на каталоги: родитель `sub`,
813
+ * перенесённый наружу и заменённый ссылкой на каталог вне дерева с другим
814
+ * `.git`, выглядел бы как исчезновение `sub/.git`, а git хоста прочитал бы
815
+ * подменённый `gitdir` через ссылку. Исчезновением считается только путь,
816
+ * у которого цепочка родителей от `root` — настоящие каталоги до первого
817
+ * отсутствующего звена (родитель удалён или перенесён наружу) или до
818
+ * самого пути. Ссылка или не каталог на месте родителя — подмена.
819
+ */
820
+ function removedInPlace(root, path) {
821
+ const parts = relative(root, path).split(sep).slice(0, -1);
822
+ let dir = root;
823
+ for (const part of parts) {
824
+ dir = join(dir, part);
825
+ let stat;
826
+ try {
827
+ stat = lstatSync(dir);
828
+ }
829
+ catch (error) {
830
+ if (missing(error))
831
+ return true;
832
+ return unreadable(root, dir, error);
833
+ }
834
+ if (stat.isSymbolicLink() || !stat.isDirectory())
835
+ return false;
836
+ }
837
+ return true;
838
+ }
805
839
  /**
806
840
  * Защищённые пути, которые появились или изменились после снимка `before`.
807
841
  *
@@ -823,13 +857,13 @@ export function protectedChanges(before, root,
823
857
  /**
824
858
  * Пути относительно `root`, которыми владеет подготовка фазы (вложенные
825
859
  * `.git`, см. `preparationGuard`): не в счёт только их исчезновение
826
- * (уборка фикстуры переносом родителя). Изменение — в том числе подмена
860
+ * (уборка фикстуры переносом родителя, см. `removedInPlace`). Изменение — в том числе подмена
827
861
  * переносом другого `.git` на то же место — нарушение: подменённый
828
862
  * `gitdir` подмодуля git хоста прочитал бы при следующей команде.
829
863
  */
830
864
  owned) {
831
865
  const after = protectedSnapshot(root);
832
- const mine = (path) => !owned?.has(relative(root, path));
866
+ const mine = (path) => !owned?.has(relative(root, path)) || !removedInPlace(root, path);
833
867
  const changed = [...after]
834
868
  .filter(([path, sig]) => {
835
869
  if (sig === 'missing')
@@ -59,6 +59,8 @@ export declare function hostGitArgs(cwd: string, args: string[]): string[];
59
59
  * содержимого файла, которое разбирают, усечение незаметно и опасно.
60
60
  */
61
61
  export declare function gitOutput(cwd: string, ...args: string[]): Promise<string>;
62
+ /** Вывод git целиком и без обрезки пробелов: для `-z`-списков путей. */
63
+ export declare function gitRawOutput(cwd: string, ...args: string[]): Promise<string>;
62
64
  /**
63
65
  * Содержимое объектов git одним `cat-file --batch`: байты, без усечения и
64
66
  * без процесса на объект. Отсутствующий объект — отказ.
@@ -264,6 +264,8 @@ export function hostGitArgs(cwd, args) {
264
264
  const gitEnv = () => ({
265
265
  ...process.env,
266
266
  GIT_TERMINAL_PROMPT: '0',
267
+ // Дублирует `--no-replace-objects` из `gitHardening` для дочерних git.
268
+ GIT_NO_REPLACE_OBJECTS: '1',
267
269
  GIT_AUTHOR_NAME: 'devcontour-harness',
268
270
  GIT_AUTHOR_EMAIL: 'harness@localhost',
269
271
  GIT_COMMITTER_NAME: 'devcontour-harness',
@@ -274,6 +276,10 @@ const gitEnv = () => ({
274
276
  * содержимого файла, которое разбирают, усечение незаметно и опасно.
275
277
  */
276
278
  export async function gitOutput(cwd, ...args) {
279
+ return (await gitRawOutput(cwd, ...args)).trim();
280
+ }
281
+ /** Вывод git целиком и без обрезки пробелов: для `-z`-списков путей. */
282
+ export async function gitRawOutput(cwd, ...args) {
277
283
  let text = '';
278
284
  const result = await command(['git', ...hostGitArgs(cwd, args)], cwd, {
279
285
  env: gitEnv(),
@@ -283,7 +289,7 @@ export async function gitOutput(cwd, ...args) {
283
289
  });
284
290
  if (result.code !== 0)
285
291
  throw new Error(`git ${args[0]}: ${result.stderr.trim()}`);
286
- return text.trim();
292
+ return text;
287
293
  }
288
294
  /**
289
295
  * Содержимое объектов git одним `cat-file --batch`: байты, без усечения и
@@ -322,7 +322,7 @@ export function stopInputsOf(h, options) {
322
322
  ? [
323
323
  { kind: 'attempt', id: last.id },
324
324
  ...last.evidence
325
- .filter((e) => !e.passed)
325
+ .filter((e) => !e.passed && e.kind !== 'not-applicable')
326
326
  .map((e) => ({ kind: 'evidence', id: e.id, sha: e.sha })),
327
327
  ]
328
328
  : [];
package/lib/index.d.ts CHANGED
@@ -69,6 +69,7 @@ export { runGatesAt, type GatesAtContext, type GatesAtInput, type GatesAtResult,
69
69
  export { dependencyStoreRoot, materializeStore, type StoreContext, type StoreReceipt, } from './verification/dependency-store.ts';
70
70
  export { explicitPrerequisites, gatePrerequisites, orderedScope, standaloneScope, } from './verification/gate-scope.ts';
71
71
  export { requirementProof, uncoveredGates, unprovenReason } from './verification/proof.ts';
72
+ export { changedPaths, coverageChanges, gateBasis, gateDecisions, gatePathRegExp, matchingPaths, notApplicableProblem, pathApplicability, proofGates, type ChangedPaths, type GateDecision, type PathDecision, } from './verification/applicability.ts';
72
73
  export { ReviewProbes, probeLimits, observeReproductions } from './agents/review-probe.ts';
73
74
  export { composeRedactors, outputRedactor,
74
75
  /**
package/lib/index.js CHANGED
@@ -69,6 +69,7 @@ export { runGatesAt, } from "./verification/gates-at.js";
69
69
  export { dependencyStoreRoot, materializeStore, } from "./verification/dependency-store.js";
70
70
  export { explicitPrerequisites, gatePrerequisites, orderedScope, standaloneScope, } from "./verification/gate-scope.js";
71
71
  export { requirementProof, uncoveredGates, unprovenReason } from "./verification/proof.js";
72
+ export { changedPaths, coverageChanges, gateBasis, gateDecisions, gatePathRegExp, matchingPaths, notApplicableProblem, pathApplicability, proofGates, } from "./verification/applicability.js";
72
73
  export { ReviewProbes, probeLimits, observeReproductions } from "./agents/review-probe.js";
73
74
  export { composeRedactors, outputRedactor,
74
75
  /**
@@ -466,7 +466,7 @@ export class HistoryRecorder {
466
466
  return { status: 'none' };
467
467
  const gates = result.evidence
468
468
  .filter((e) => e.kind !== 'review')
469
- .map((e) => `${e.gate} [${e.phase}] ${e.passed ? 'passed' : 'failed'} @ ${e.sha.slice(0, 12)}`)
469
+ .map((e) => `${e.gate} [${e.phase}] ${e.kind === 'not-applicable' ? 'not applicable' : e.passed ? 'passed' : 'failed'} @ ${e.sha.slice(0, 12)}`)
470
470
  .join('\n');
471
471
  const accepted = result.outcome === 'accepted';
472
472
  const body = accepted
@@ -12,7 +12,8 @@ export function summaryText(input) {
12
12
  const tests = e.tests
13
13
  ? ` (${e.tests.filter((t) => t.status === 'passed').length}/${e.tests.length} тестов)`
14
14
  : '';
15
- return `- ${e.gate} [${e.phase}]: ${e.passed ? 'passed' : 'failed'}${tests} @ ${shortSha(e.sha)}`;
15
+ const outcome = e.kind === 'not-applicable' ? 'not applicable' : e.passed ? 'passed' : 'failed';
16
+ return `- ${e.gate} [${e.phase}]: ${outcome}${tests} @ ${shortSha(e.sha)}`;
16
17
  });
17
18
  const reviews = r.evidence.filter((e) => e.kind === 'review');
18
19
  const lines = [
@@ -126,6 +126,9 @@ export declare function repositoryFromProfile(profile: ResolvedProfile, own: Pic
126
126
  command: string[];
127
127
  timeoutMs: number;
128
128
  artifacts?: string[] | undefined;
129
+ when?: {
130
+ paths: string[];
131
+ } | undefined;
129
132
  property?: {
130
133
  path?: string | undefined;
131
134
  } | undefined;
@@ -142,6 +145,9 @@ export declare function repositoryFromProfile(profile: ResolvedProfile, own: Pic
142
145
  path: string;
143
146
  } | undefined;
144
147
  artifacts?: string[] | undefined;
148
+ when?: {
149
+ paths: string[];
150
+ } | undefined;
145
151
  property?: {
146
152
  path?: string | undefined;
147
153
  } | undefined;
@@ -24,7 +24,7 @@ export interface AttemptViewInput {
24
24
  candidateSha?: string;
25
25
  integrationSha?: string;
26
26
  evidence: readonly {
27
- kind: 'test' | 'review';
27
+ kind: 'test' | 'review' | 'not-applicable';
28
28
  phase: 'candidate' | 'integration';
29
29
  sha: string;
30
30
  gate: string;
@@ -94,7 +94,7 @@ export interface AttemptView {
94
94
  * Обязательные gates текущей фазы (интеграции — в `integrating`, иначе
95
95
  * кандидата) по последней записи каждого gate на текущем SHA фазы, без
96
96
  * проверок потребителей: прошли, не прошли, ещё без записи. Записи других
97
- * gates и других SHA не считаются: `passed + failed + remaining = required`.
97
+ * gates и других SHA не считаются: `passed + failed + remaining (+ notApplicable) = required`.
98
98
  */
99
99
  gates: {
100
100
  phase: 'candidate' | 'integration';
@@ -102,6 +102,8 @@ export interface AttemptView {
102
102
  passed: number;
103
103
  failed: number;
104
104
  remaining: number;
105
+ /** Не исполнены по `when.paths` (нет поля — таких нет); входят в `required`. */
106
+ notApplicable?: number;
105
107
  };
106
108
  /**
107
109
  * Живость по последнему переходу обхода controller: `quiet` и `stalled`
@@ -15,6 +15,16 @@ export function attemptView(input, options) {
15
15
  const sha = phase === 'integration' ? input.integrationSha : input.candidateSha;
16
16
  const required = [...new Set(input.requiredGates ?? options.repositoryGates ?? [])];
17
17
  const latest = new Map();
18
+ // Gate, не исполненный по `when.paths`: ни PASS, ни провал, но и не ждёт.
19
+ const notApplicable = new Set();
20
+ for (const e of input.evidence)
21
+ if (e.kind === 'not-applicable' &&
22
+ e.phase === phase &&
23
+ !e.consumer &&
24
+ sha !== undefined &&
25
+ e.sha === sha &&
26
+ required.includes(e.gate))
27
+ notApplicable.add(e.gate);
18
28
  for (const e of input.evidence)
19
29
  if (e.kind === 'test' &&
20
30
  e.phase === phase &&
@@ -58,7 +68,10 @@ export function attemptView(input, options) {
58
68
  required: required.length,
59
69
  passed,
60
70
  failed: latest.size - passed,
61
- remaining: required.filter((g) => !latest.has(g)).length,
71
+ remaining: required.filter((g) => !latest.has(g) && !notApplicable.has(g)).length,
72
+ ...(notApplicable.size
73
+ ? { notApplicable: [...notApplicable].filter((g) => !latest.has(g)).length }
74
+ : {}),
62
75
  },
63
76
  ...(input.liveness
64
77
  ? {
@@ -401,7 +401,8 @@ export function valueReport(input, options = {}) {
401
401
  const defectAttempts = windowAttempts.filter((a) => failureBucketOf(a) === 'defect');
402
402
  const failingOf = (a) => {
403
403
  const kind = a.failureKind === 'gate' ? 'test' : a.failureKind === 'review' ? 'review' : null;
404
- return a.evidence.filter((e) => !e.passed && (kind === null || e.kind === kind));
404
+ // Неприменимый gate (`when.paths`) не исполнялся и провалом не считается.
405
+ return a.evidence.filter((e) => !e.passed && e.kind !== 'not-applicable' && (kind === null || e.kind === kind));
405
406
  };
406
407
  const byKind = { gate: 0, review: 0, 'scope-violation': 0 };
407
408
  const byPhase = { candidate: 0, integration: 0, unknown: 0 };
@@ -444,12 +445,12 @@ export function valueReport(input, options = {}) {
444
445
  for (const e of a.evidence) {
445
446
  if (e.kind !== 'review' || e.phase !== 'candidate')
446
447
  continue;
447
- const allGreen = required.every((g) => a.evidence.some((x) => x.kind === 'test' &&
448
+ // Неприменимый gate (`when.paths`) зелёного состава не нарушает.
449
+ const allGreen = required.every((g) => a.evidence.some((x) => (x.kind === 'not-applicable' || (x.kind === 'test' && x.passed)) &&
448
450
  x.phase === 'candidate' &&
449
451
  !x.consumer &&
450
452
  x.gate === g &&
451
453
  x.sha === e.sha &&
452
- x.passed &&
453
454
  (x.checks === undefined || e.checks === undefined || x.checks === e.checks)));
454
455
  if (!allGreen)
455
456
  continue;
@@ -644,6 +645,7 @@ export function valueReport(input, options = {}) {
644
645
  cancelledWithoutAttempt: 0,
645
646
  baseMoves: zero(['operator', 'controller', 'host']),
646
647
  baseMovesBound: 'lower',
648
+ jointResets: zero(['operator', 'host']),
647
649
  gaps: gapInWindow.size,
648
650
  };
649
651
  for (const e of windowEvents)
@@ -659,6 +661,8 @@ export function valueReport(input, options = {}) {
659
661
  }
660
662
  else if (e.type === 'base.moved')
661
663
  r.baseMoves[e.payload.by] += 1;
664
+ else if (e.type === 'joint.budget-reset')
665
+ r.jointResets[e.payload.by] += 1;
662
666
  // Окно начинается раньше записи: в нём есть попытки или события до неё.
663
667
  const before = (ms) => ms < recordedFrom;
664
668
  if (gapInWindow.size > 0 ||
@@ -109,7 +109,7 @@ export function reportBlocks(r) {
109
109
  ? `Accepted tasks that needed no human action: ${formatMeasureRatio(a.withoutAction)}. With a recorded human action (operator retry, cancellation or recovery decision): ${formatMeasureRatio(a.withAction)}.`
110
110
  : `Accepted tasks that needed no human action: not measurable yet (retries, resets and base moves have no recorded actor). Accepted tasks with an operator recovery decision: ${a.withAction.value ?? 0} of ${a.withAction.n}.`,
111
111
  rec
112
- ? `Human actions: operator recovery decisions ${a.actions.operatorDecisions}, operator retries ${ge}${rec.retries.operator} (resets ${ge}${rec.resets.operator}), operator cancellations ${ge}${rec.cancellations.operator}, operator base moves ≥ ${rec.baseMoves.operator}. Automatic: recovery retries ${ge}${rec.retries.recovery}, controller base moves ≥ ${rec.baseMoves.controller}, cancellations by a new graph revision ${ge}${rec.cancellations.graph}. By the host without a named actor: retries ${ge}${rec.retries.host}, cancellations ${ge}${rec.cancellations.host}, base moves ≥ ${rec.baseMoves.host}. Tasks cancelled without an active attempt: ${ge}${rec.cancelledWithoutAttempt}; cancelled attempts ${a.actions.cancelledAttempts}. Without a recorded actor: holds ${a.actions.holds} (held tasks count as unknown). Recorded from ${rec.from}.`
112
+ ? `Human actions: operator recovery decisions ${a.actions.operatorDecisions}, operator retries ${ge}${rec.retries.operator} (resets ${ge}${rec.resets.operator}), operator cancellations ${ge}${rec.cancellations.operator}, operator base moves ≥ ${rec.baseMoves.operator}. Automatic: recovery retries ${ge}${rec.retries.recovery}, controller base moves ≥ ${rec.baseMoves.controller}, cancellations by a new graph revision ${ge}${rec.cancellations.graph}. By the host without a named actor: retries ${ge}${rec.retries.host}, cancellations ${ge}${rec.cancellations.host}, base moves ≥ ${rec.baseMoves.host}. Joint verification budget resets: operator ${rec.jointResets?.operator ?? 0}, host ${rec.jointResets?.host ?? 0}. Tasks cancelled without an active attempt: ${ge}${rec.cancelledWithoutAttempt}; cancelled attempts ${a.actions.cancelledAttempts}. Without a recorded actor: holds ${a.actions.holds} (held tasks count as unknown). Recorded from ${rec.from}.`
113
113
  : `Human actions with a recorded actor: operator recovery decisions ${a.actions.operatorDecisions}. Without a recorded actor (not counted as human): holds ${a.actions.holds}, cancelled attempts ${a.actions.cancelledAttempts}. ${actionsLine([
114
114
  ['retries', a.actions.retries],
115
115
  ['resets', a.actions.resets],
@@ -478,7 +478,7 @@ export declare class DocumentView {
478
478
  evidence: {
479
479
  id: string;
480
480
  runId: string;
481
- kind: "review" | "test";
481
+ kind: "review" | "test" | "not-applicable";
482
482
  phase: "candidate" | "integration";
483
483
  sha: string;
484
484
  gate: string;
@@ -634,6 +634,18 @@ export declare class DocumentView {
634
634
  skippedMore?: number | undefined;
635
635
  } | undefined;
636
636
  checks?: string | undefined;
637
+ gateBasis?: string | undefined;
638
+ notApplicable?: {
639
+ gateDigest: string;
640
+ patterns: string[];
641
+ ranges: {
642
+ from: string;
643
+ to: string;
644
+ }[];
645
+ count: number;
646
+ files: string[];
647
+ pathsDigest: string;
648
+ } | undefined;
637
649
  alreadySatisfied?: {
638
650
  gates: string[];
639
651
  evidence: string;
@@ -838,7 +850,7 @@ export declare class DocumentView {
838
850
  evidence: {
839
851
  id: string;
840
852
  runId: string;
841
- kind: "review" | "test";
853
+ kind: "review" | "test" | "not-applicable";
842
854
  phase: "candidate" | "integration";
843
855
  sha: string;
844
856
  gate: string;
@@ -994,6 +1006,18 @@ export declare class DocumentView {
994
1006
  skippedMore?: number | undefined;
995
1007
  } | undefined;
996
1008
  checks?: string | undefined;
1009
+ gateBasis?: string | undefined;
1010
+ notApplicable?: {
1011
+ gateDigest: string;
1012
+ patterns: string[];
1013
+ ranges: {
1014
+ from: string;
1015
+ to: string;
1016
+ }[];
1017
+ count: number;
1018
+ files: string[];
1019
+ pathsDigest: string;
1020
+ } | undefined;
997
1021
  alreadySatisfied?: {
998
1022
  gates: string[];
999
1023
  evidence: string;
@@ -1280,6 +1304,7 @@ export declare class DocumentView {
1280
1304
  tree: string;
1281
1305
  }> | undefined;
1282
1306
  manifestDigest?: string | undefined;
1307
+ interrupted?: true | undefined;
1283
1308
  impact?: {
1284
1309
  changed: string[];
1285
1310
  affected: string[];
@@ -1443,6 +1468,7 @@ export declare class DocumentView {
1443
1468
  tree: string;
1444
1469
  }> | undefined;
1445
1470
  manifestDigest?: string | undefined;
1471
+ interrupted?: true | undefined;
1446
1472
  impact?: {
1447
1473
  changed: string[];
1448
1474
  affected: string[];
@@ -1,4 +1,4 @@
1
- import { type ExecutionStore, type InputRequest } from '../contracts/index.ts';
1
+ import { type ExecutionStore, type InputRequest, type JointVerificationState } from '../contracts/index.ts';
2
2
  /**
3
3
  * Запрос исполнителя (`input-requests`) для проверок адаптера: вопрос с
4
4
  * вариантами, основание исходной попытки, без ответов (`pending`).
@@ -12,4 +12,10 @@ export declare function answeredInputRequest(request: InputRequest, text?: strin
12
12
  * повторный вызов с тем же каталогом — то же хранилище другим экземпляром.
13
13
  * Регистрация тестов — через переданную `test` (node:test).
14
14
  */
15
- export declare function executionStoreContract(name: string, test: (title: string, fn: () => void | Promise<void>) => unknown, open: (dir: string) => ExecutionStore, tempDir: () => string): void;
15
+ export declare function executionStoreContract(name: string, test: (title: string, fn: () => void | Promise<void>) => unknown, open: (dir: string) => ExecutionStore, tempDir: () => string, options?: {
16
+ /**
17
+ * Как хост заводит новую совместную проверку (у DevContour — операцией
18
+ * ChangeSet). По умолчанию — `putVerification` в транзакции начала.
19
+ */
20
+ startVerification?: (store: ExecutionStore, verification: JointVerificationState) => void;
21
+ }): void;
@@ -75,7 +75,7 @@ export function answeredInputRequest(request, text = 'ISO 8601') {
75
75
  * повторный вызов с тем же каталогом — то же хранилище другим экземпляром.
76
76
  * Регистрация тестов — через переданную `test` (node:test).
77
77
  */
78
- export function executionStoreContract(name, test, open, tempDir) {
78
+ export function executionStoreContract(name, test, open, tempDir, options = {}) {
79
79
  const work = (id, status = 'ready') => ({
80
80
  id,
81
81
  graphId: 'g',
@@ -237,6 +237,61 @@ export function executionStoreContract(name, test, open, tempDir) {
237
237
  assert.equal(b.read((v) => v.local('input-requests', 'app', inputRequestId('run-1', 0))), undefined);
238
238
  b.close();
239
239
  });
240
+ test(`${name}: прерванная совместная проверка сохраняет interrupted и виден другому экземпляру`, () => {
241
+ const dir = tempDir();
242
+ const a = open(dir);
243
+ a.transact('run.phase', (tx) => {
244
+ tx.putWork(work('w1', 'done'));
245
+ tx.putWork(work('w2', 'done'));
246
+ });
247
+ const active = {
248
+ apiVersion: 'devcontour-harness/v1alpha1',
249
+ id: 'jv-interrupted',
250
+ token: 'token-'.padEnd(32, 'x'),
251
+ leaseUntil: 1,
252
+ startedAt: '2026-01-01T00:00:00.000Z',
253
+ status: 'active',
254
+ policyDigest: digestOf('policy'),
255
+ specDigest: digestOf('spec'),
256
+ workIds: ['w1', 'w2'],
257
+ evidence: [],
258
+ };
259
+ if (options.startVerification)
260
+ options.startVerification(a, active);
261
+ else
262
+ a.transact('workspace.verification.started', (tx) => tx.putVerification(active));
263
+ a.transact('workspace.failed', (tx) => tx.putVerification({
264
+ ...active,
265
+ status: 'failed',
266
+ error: 'Совместная проверка отменена',
267
+ finishedAt: '2026-01-01T00:01:00.000Z',
268
+ interrupted: true,
269
+ }));
270
+ a.close();
271
+ const b = open(dir);
272
+ const stored = b.read((v) => v.verification(active.id));
273
+ assert.equal(stored?.status, 'failed');
274
+ assert.equal(stored?.status === 'failed' ? stored.interrupted : undefined, true, 'отметка прерывания не теряется: без неё прерванная проверка тратит предел набора');
275
+ b.close();
276
+ });
277
+ test(`${name}: сброс бюджета совместных проверок хранится у @workspace и виден другому экземпляру`, () => {
278
+ const dir = tempDir();
279
+ const a = open(dir);
280
+ assert.deepEqual(a.read((v) => v.locals('joint-budget-resets', WORKSPACE_OWNER)), []);
281
+ const reset = {
282
+ id: 'reset-1',
283
+ at: '2026-01-01T00:00:00.000Z',
284
+ workIds: ['a', 'b'],
285
+ reason: 'lease lost on host stop',
286
+ actor: 'operator',
287
+ settledVerificationIds: ['jv-1', 'jv-2'],
288
+ };
289
+ a.transact('workspace.budget-reset', (tx) => tx.putLocal('joint-budget-resets', WORKSPACE_OWNER, reset.id, reset));
290
+ a.close();
291
+ const b = open(dir);
292
+ assert.deepEqual(b.read((v) => v.locals('joint-budget-resets', WORKSPACE_OWNER)), [{ owner: WORKSPACE_OWNER, key: reset.id, value: reset }]);
293
+ b.close();
294
+ });
240
295
  test(`${name}: запрос исполнителя хранится у владельца, версия видна другому экземпляру`, () => {
241
296
  const dir = tempDir();
242
297
  const a = open(dir);
@@ -210,6 +210,18 @@ export declare const receiptTrust: {
210
210
  readonly 'evidence[].summary': readonly ["informative", "описание записи"];
211
211
  readonly 'evidence[].consumer': readonly ["expected", "объявленный потребитель"];
212
212
  readonly 'evidence[].checks': readonly ["expected", "версия проверок, вычисленная получателем, у каждой записи"];
213
+ readonly 'evidence[].notApplicable': readonly ["consistency", "только у записи not-applicable: обычный gate с when, не доказательство и не предпосылка исполненного"];
214
+ readonly 'evidence[].notApplicable.gateDigest': readonly ["expected", "digest определения gate у получателя"];
215
+ readonly 'evidence[].notApplicable.patterns': readonly ["informative", "пути when; их задаёт определение gate"];
216
+ readonly 'evidence[].notApplicable.patterns[]': readonly ["informative", "пути when; их задаёт определение gate"];
217
+ readonly 'evidence[].notApplicable.ranges': readonly ["informative", "diff фазы — наблюдение Git исполнителя"];
218
+ readonly 'evidence[].notApplicable.ranges[]': readonly ["informative", "diff фазы — наблюдение Git исполнителя"];
219
+ readonly 'evidence[].notApplicable.ranges[].from': readonly ["informative", "diff фазы — наблюдение Git исполнителя"];
220
+ readonly 'evidence[].notApplicable.ranges[].to': readonly ["informative", "diff фазы — наблюдение Git исполнителя"];
221
+ readonly 'evidence[].notApplicable.count': readonly ["informative", "diff фазы — наблюдение Git исполнителя"];
222
+ readonly 'evidence[].notApplicable.files': readonly ["informative", "diff фазы — наблюдение Git исполнителя"];
223
+ readonly 'evidence[].notApplicable.files[]': readonly ["informative", "diff фазы — наблюдение Git исполнителя"];
224
+ readonly 'evidence[].notApplicable.pathsDigest': readonly ["informative", "diff фазы — наблюдение Git исполнителя"];
213
225
  readonly 'evidence[].tests': readonly ["expected", "доказательство названного testcase решающей записью"];
214
226
  readonly 'evidence[].tests[]': readonly ["expected", "элемент названного testcase; прочие элементы — сведения"];
215
227
  readonly 'evidence[].tests[].id': readonly ["expected", "ID названного testcase"];
@@ -3,6 +3,7 @@ import { corpusBindingHolds, effectiveChecks, obligationOf, orderCheckManifest,
3
3
  import { manifestDigest } from "./property.js";
4
4
  import { unprovenReason } from "./proof.js";
5
5
  import { REQUIREMENT_GATE } from "./requirements.js";
6
+ import { notApplicableProblem, proofGates } from "./applicability.js";
6
7
  /** Решающая запись gate на фазе: последняя запись этой фазы, SHA и версии. */
7
8
  function decisive(input, phase, gate) {
8
9
  const sha = phase === 'candidate' ? input.candidateSha : input.resultSha;
@@ -236,6 +237,24 @@ export const receiptTrust = {
236
237
  'evidence[].summary': ['informative', 'описание записи'],
237
238
  'evidence[].consumer': ['expected', 'объявленный потребитель'],
238
239
  'evidence[].checks': ['expected', 'версия проверок, вычисленная получателем, у каждой записи'],
240
+ 'evidence[].notApplicable': [
241
+ 'consistency',
242
+ 'только у записи not-applicable: обычный gate с when, не доказательство и не предпосылка исполненного',
243
+ ],
244
+ 'evidence[].notApplicable.gateDigest': ['expected', 'digest определения gate у получателя'],
245
+ 'evidence[].notApplicable.patterns': ['informative', 'пути when; их задаёт определение gate'],
246
+ 'evidence[].notApplicable.patterns[]': ['informative', 'пути when; их задаёт определение gate'],
247
+ 'evidence[].notApplicable.ranges': ['informative', 'diff фазы — наблюдение Git исполнителя'],
248
+ 'evidence[].notApplicable.ranges[]': ['informative', 'diff фазы — наблюдение Git исполнителя'],
249
+ 'evidence[].notApplicable.ranges[].from': [
250
+ 'informative',
251
+ 'diff фазы — наблюдение Git исполнителя',
252
+ ],
253
+ 'evidence[].notApplicable.ranges[].to': ['informative', 'diff фазы — наблюдение Git исполнителя'],
254
+ 'evidence[].notApplicable.count': ['informative', 'diff фазы — наблюдение Git исполнителя'],
255
+ 'evidence[].notApplicable.files': ['informative', 'diff фазы — наблюдение Git исполнителя'],
256
+ 'evidence[].notApplicable.files[]': ['informative', 'diff фазы — наблюдение Git исполнителя'],
257
+ 'evidence[].notApplicable.pathsDigest': ['informative', 'diff фазы — наблюдение Git исполнителя'],
239
258
  'evidence[].tests': ['expected', 'доказательство названного testcase решающей записью'],
240
259
  'evidence[].tests[]': ['expected', 'элемент названного testcase; прочие элементы — сведения'],
241
260
  'evidence[].tests[].id': ['expected', 'ID названного testcase'],
@@ -415,13 +434,25 @@ export function resultProblems(result, context) {
415
434
  integrity.push(`запись ${e.id}: сведения о свойствах недопустимы у записи вида ${e.kind}`);
416
435
  if ((e.reviewer !== undefined) !== (e.kind === 'review'))
417
436
  integrity.push(`запись ${e.id}: сведения о reviewer не согласованы с видом записи`);
437
+ if ((e.notApplicable !== undefined) !== (e.kind === 'not-applicable'))
438
+ integrity.push(`запись ${e.id}: сведения о неприменимости не согласованы с видом записи`);
439
+ if (e.kind === 'not-applicable' && (e.passed || e.consumer !== undefined))
440
+ integrity.push(`запись ${e.id}: неприменимый gate не бывает PASS или проверкой потребителя`);
418
441
  }
419
442
  if (integrity.length)
420
443
  return integrity;
421
444
  const evidence = result.evidence
422
- .filter((e) => e.kind === 'test' || e.kind === 'review' || e.kind === 'consumer')
445
+ .filter((e) => e.kind === 'test' ||
446
+ e.kind === 'review' ||
447
+ e.kind === 'consumer' ||
448
+ e.kind === 'not-applicable')
423
449
  .map((e) => ({
424
- kind: e.kind === 'review' ? 'review' : 'test',
450
+ kind: e.kind === 'review'
451
+ ? 'review'
452
+ : e.kind === 'not-applicable'
453
+ ? 'not-applicable'
454
+ : 'test',
455
+ ...(e.notApplicable ? { notApplicable: e.notApplicable } : {}),
425
456
  phase: e.phase,
426
457
  gate: e.gate,
427
458
  sha: e.sha,
@@ -432,7 +463,7 @@ export function resultProblems(result, context) {
432
463
  tests: e.tests,
433
464
  testsTruncated: e.testsTruncated,
434
465
  }));
435
- const last = (kind, phase, gate, consumer) => evidence.findLast((e) => e.kind === kind &&
466
+ const last = (kind, phase, gate, consumer) => evidence.findLast((e) => (typeof kind === 'string' ? e.kind === kind : kind.includes(e.kind)) &&
436
467
  e.phase === phase &&
437
468
  e.gate === gate &&
438
469
  e.sha === sha(phase) &&
@@ -457,13 +488,37 @@ export function resultProblems(result, context) {
457
488
  if (declared && !sameSet(declared, own))
458
489
  problems.push(`область результата [${declared.join(', ')}] — ожидалась ровно [${own.join(', ')}]`);
459
490
  const required = [...new Set([...own, ...(gates.byGate?.keys() ?? [])])];
491
+ // Обычный gate с `when` закрывается и записью неприменимости
492
+ // (`notApplicableProblem` по политике получателя); доказательства
493
+ // требований и договоров — только PASS.
494
+ const named = proofGates(order, context.contracts);
460
495
  const decisiveAll = ['candidate', 'integration'].flatMap((phase) => [
461
- ...required.map((gate) => ({ phase, gate, check: last('test', phase, gate) })),
496
+ ...required.map((gate) => ({
497
+ phase,
498
+ gate,
499
+ // Исход исполнения решает всегда; неприменимость — только без него.
500
+ check: last('test', phase, gate) ??
501
+ (named.has(gate) ? undefined : last(['not-applicable'], phase, gate)),
502
+ })),
462
503
  { phase, gate: 'independent-review', check: last('review', phase, 'independent-review') },
463
504
  ]);
464
- for (const { phase, gate, check } of decisiveAll)
465
- if (!check?.passed)
466
- problems.push(`Нет PASS: ${phase}/${gate}`);
505
+ for (const { phase, gate, check } of decisiveAll) {
506
+ if (check?.passed)
507
+ continue;
508
+ const problem = check?.kind === 'not-applicable'
509
+ ? notApplicableProblem({
510
+ gates: repo.gates,
511
+ gate,
512
+ record: check,
513
+ proof: named,
514
+ ran: decisiveAll
515
+ .filter((d) => d.phase === phase && d.check?.kind === 'test')
516
+ .map((d) => d.gate),
517
+ })
518
+ : 'нет записи';
519
+ if (problem)
520
+ problems.push(`Нет PASS: ${phase}/${gate}` + (check?.kind === 'not-applicable' ? ': ' + problem : ''));
521
+ }
467
522
  // Ревью: writer — роли поручения в политике получателя; reviewer решающих
468
523
  // записей обеих фаз — тот, кого политика назначает этому writer, и правило
469
524
  // вендора соблюдено (тот же вендор — только явным разрешением). Для