@aiwg/cli 2026.10.16 → 2026.10.18

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 (128) hide show
  1. package/dist/src/artifacts/corpus-tools/resolve.js +21 -4
  2. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  3. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  4. package/dist/src/artifacts/query-engine-discover.js +285 -0
  5. package/dist/src/artifacts/query-engine-entries.js +188 -0
  6. package/dist/src/artifacts/query-engine-index.js +249 -0
  7. package/dist/src/artifacts/query-engine-matching.js +143 -0
  8. package/dist/src/artifacts/query-engine-options.js +2 -0
  9. package/dist/src/artifacts/query-engine-rules.js +202 -0
  10. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  11. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  12. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  13. package/dist/src/artifacts/query-engine-show.js +300 -0
  14. package/dist/src/artifacts/query-engine.js +7 -2576
  15. package/dist/src/cli/handlers/mc-agents.js +111 -0
  16. package/dist/src/cli/handlers/mc-args.js +54 -0
  17. package/dist/src/cli/handlers/mc-control.js +227 -0
  18. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  19. package/dist/src/cli/handlers/mc-help.js +171 -0
  20. package/dist/src/cli/handlers/mc-run.js +343 -0
  21. package/dist/src/cli/handlers/mc-session.js +138 -0
  22. package/dist/src/cli/handlers/mc-status.js +258 -0
  23. package/dist/src/cli/handlers/mc-summary.js +43 -0
  24. package/dist/src/cli/handlers/mc-types.js +3 -0
  25. package/dist/src/cli/handlers/mc-worker.js +205 -0
  26. package/dist/src/cli/handlers/mc.js +12 -1665
  27. package/dist/src/cli/handlers/models-refusal.js +13 -0
  28. package/dist/src/cli/handlers/models.js +2 -1
  29. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  30. package/dist/src/cli/handlers/remove-options.js +31 -0
  31. package/dist/src/cli/handlers/remove-user.js +174 -0
  32. package/dist/src/cli/handlers/remove.js +201 -0
  33. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  34. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  35. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  36. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  37. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  38. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  39. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  40. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  41. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  42. package/dist/src/cli/handlers/subcommands.js +18 -1984
  43. package/dist/src/cli/scope-resolver.js +1 -142
  44. package/dist/src/cli/user-scope-mirror.js +173 -0
  45. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  46. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  47. package/dist/src/config/host-resource-report.d.mts +5 -0
  48. package/dist/src/config/host-resource-report.mjs +36 -6
  49. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  50. package/dist/src/config/host-resource-runtime.mjs +9 -6
  51. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  52. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  53. package/dist/src/decision/ensemble-study/gates.js +78 -0
  54. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  55. package/dist/src/decision/ensemble-study/score.js +3 -2
  56. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  57. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  58. package/dist/src/decision/sensitivity/comparative.js +18 -41
  59. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  60. package/dist/src/gates/evaluate.js +2 -358
  61. package/dist/src/gates/observations.js +363 -0
  62. package/dist/src/gates/pack-composition.js +270 -0
  63. package/dist/src/gates/pack-tightening.js +197 -0
  64. package/dist/src/gates/pack-validation.js +262 -0
  65. package/dist/src/gates/registry-error.js +5 -0
  66. package/dist/src/gates/registry.js +13 -685
  67. package/dist/src/mcp/json-document.mjs +29 -0
  68. package/dist/src/mcp/muse-native-config.mjs +1 -28
  69. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  70. package/dist/src/models/worker-plan.js +5 -5
  71. package/dist/src/plugin/command-ownership.js +34 -0
  72. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  73. package/dist/src/plugin/skill-command-translator.js +6 -232
  74. package/dist/src/providers/context-output-ownership.js +26 -0
  75. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  76. package/dist/src/providers/deployment-ownership.mjs +226 -0
  77. package/dist/src/providers/deployment-removal.js +200 -0
  78. package/dist/src/providers/removal-transaction.js +86 -0
  79. package/dist/src/providers/settings-document.d.mts +3 -0
  80. package/dist/src/providers/settings-document.mjs +47 -0
  81. package/dist/src/providers/settings-removal.js +190 -0
  82. package/dist/src/providers/skill-ownership.d.mts +19 -2
  83. package/dist/src/providers/skill-ownership.mjs +12 -4
  84. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  85. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  86. package/dist/src/providers/transformation-receipt-source.js +194 -0
  87. package/dist/src/research/identity.js +8 -2
  88. package/dist/src/research/reference-match.js +42 -7
  89. package/dist/src/rules/activation.mjs +15 -6
  90. package/dist/src/rules/core-startup.mjs +2 -2
  91. package/dist/src/serve/mission-conductor.js +4 -0
  92. package/dist/src/serve/mission-summary.js +56 -0
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  94. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  95. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  96. package/dist/src/smiths/hook-bridge/index.js +9 -0
  97. package/package.json +4 -1
  98. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  99. package/tools/agents/deploy-agents.mjs +16 -677
  100. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  101. package/tools/agents/deploy-options.mjs +258 -0
  102. package/tools/agents/deploy-support.mjs +165 -0
  103. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  104. package/tools/agents/providers/base-behaviors.mjs +168 -0
  105. package/tools/agents/providers/base-context.mjs +205 -0
  106. package/tools/agents/providers/base-contract.mjs +116 -0
  107. package/tools/agents/providers/base-files.mjs +252 -0
  108. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  109. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  110. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  111. package/tools/agents/providers/base-inventory.mjs +269 -0
  112. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  113. package/tools/agents/providers/base-migrations.mjs +258 -0
  114. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  115. package/tools/agents/providers/base-rule-index.mjs +450 -0
  116. package/tools/agents/providers/base-runtime.mjs +60 -0
  117. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  118. package/tools/agents/providers/base.mjs +16 -3364
  119. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  120. package/tools/agents/providers/hermes-startup.mjs +0 -5
  121. package/tools/agents/providers/muse.mjs +7 -2
  122. package/tools/agents/providers/rule-delivery-surface.mjs +31 -4
  123. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  124. package/tools/agents/providers/rule-deployment-prepare.mjs +11 -2
  125. package/tools/agents/providers/rule-projection.mjs +3 -0
  126. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  127. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  128. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -10,6 +10,7 @@
10
10
  * project` are mutually exclusive; default is `project`.
11
11
  */
12
12
  import { resolveOmpPaths } from '../providers/omp-paths.mjs';
13
+ import { mirrorArtifactDir, assertGrokUserMirrorPaths } from './user-scope-mirror.js';
13
14
  import { homedir } from 'node:os';
14
15
  import * as path from 'node:path';
15
16
  import { resolveHermesHome, resolveHermesHomePath } from '../providers/hermes-home.js';
@@ -373,57 +374,6 @@ export async function mirrorToUserScope(provider, projectPaths) {
373
374
  ]);
374
375
  return { agents, skills, commands, rules, behaviors };
375
376
  }
376
- async function assertGrokUserMirrorPaths(projectPaths, userPaths) {
377
- const fs = await import('node:fs/promises');
378
- const statIfPresent = async (target) => {
379
- try {
380
- return await fs.lstat(target);
381
- }
382
- catch (error) {
383
- if (error.code === 'ENOENT')
384
- return null;
385
- throw error;
386
- }
387
- };
388
- const checkTarget = async (target) => {
389
- const stat = await statIfPresent(target);
390
- if (!stat)
391
- return;
392
- if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
393
- throw new Error(`Refusing unsafe Grok Build user mirror target: ${target}`);
394
- }
395
- if (stat.isDirectory()) {
396
- for (const name of await fs.readdir(target))
397
- await checkTarget(path.join(target, name));
398
- }
399
- };
400
- for (const [destination, sources] of [
401
- [userPaths.agents, [projectPaths.agents]],
402
- [userPaths.skills, [projectPaths.skills, projectPaths.kernelSkills ?? '']],
403
- ]) {
404
- if (!destination)
405
- continue;
406
- const rootStat = await statIfPresent(destination);
407
- if (rootStat && (rootStat.isSymbolicLink() || !rootStat.isDirectory())) {
408
- throw new Error(`Refusing unsafe Grok Build user mirror root: ${destination}`);
409
- }
410
- for (const source of sources) {
411
- if (!source)
412
- continue;
413
- let names;
414
- try {
415
- names = await fs.readdir(source);
416
- }
417
- catch (error) {
418
- if (error.code === 'ENOENT')
419
- continue;
420
- throw error;
421
- }
422
- for (const name of names)
423
- await checkTarget(path.join(destination, name));
424
- }
425
- }
426
- }
427
377
  /**
428
378
  * Merge standard and kernel skill directories into one user-discoverable
429
379
  * target. Provider deployments intentionally keep those source surfaces
@@ -444,97 +394,6 @@ export async function mirrorSkillDirsToUserScope(sourceDirs, targetDir) {
444
394
  entries: [...entries],
445
395
  };
446
396
  }
447
- /**
448
- * Copy every directory or file under `src` into `dst` (creating `dst` if
449
- * needed). Returns the count of top-level entries successfully copied and
450
- * the entry names themselves — the names are needed by callers that record
451
- * a per-framework manifest at user scope so `aiwg remove --scope user` can
452
- * delete only what this deploy created.
453
- *
454
- * Used by the user-scope mirror to cover both directory-style artifacts
455
- * (skills, agents) and file-style artifacts (commands, rules in some
456
- * providers). Failures on individual entries are swallowed so a single bad
457
- * entry doesn't fail the whole mirror.
458
- */
459
- async function mirrorArtifactDir(src, dst, ownedThisCall = new Set()) {
460
- if (!src || !dst)
461
- return { count: 0, targetDir: dst, entries: [] };
462
- const fs = await import('node:fs/promises');
463
- let dirents;
464
- try {
465
- dirents = await fs.readdir(src, { withFileTypes: true });
466
- }
467
- catch {
468
- return { count: 0, targetDir: dst, entries: [] };
469
- }
470
- // Some providers already deploy kernel skills to an absolute user-level
471
- // path. Inventory that source for registry accounting instead of trying to
472
- // recursively copy each entry onto itself.
473
- if (path.resolve(src) === path.resolve(dst)) {
474
- const entries = [];
475
- for (const entry of dirents) {
476
- if ((entry.isDirectory() || entry.isFile()) && await isAiwgManagedEntry(path.join(dst, entry.name), entry.isDirectory())) {
477
- entries.push(entry.name);
478
- }
479
- }
480
- return { count: entries.length, targetDir: dst, entries };
481
- }
482
- await fs.mkdir(dst, { recursive: true });
483
- let count = 0;
484
- const entries = [];
485
- for (const entry of dirents) {
486
- const s = path.join(src, entry.name);
487
- const d = path.join(dst, entry.name);
488
- try {
489
- // User-scope directories are shared with operator-created artifacts.
490
- // A same-named unmanaged entry belongs to the operator, even when a
491
- // project has an AIWG-managed source with that name.
492
- try {
493
- const existing = await fs.lstat(d);
494
- if (!ownedThisCall.has(entry.name) && !await isAiwgManagedEntry(d, existing.isDirectory()))
495
- continue;
496
- }
497
- catch (error) {
498
- if (error.code !== 'ENOENT')
499
- continue;
500
- }
501
- if (entry.isDirectory()) {
502
- await fs.cp(s, d, { recursive: true, force: true });
503
- }
504
- else if (entry.isFile()) {
505
- await fs.copyFile(s, d);
506
- }
507
- else {
508
- continue;
509
- }
510
- count++;
511
- entries.push(entry.name);
512
- }
513
- catch {
514
- // ignore individual failures
515
- }
516
- }
517
- return { count, targetDir: dst, entries };
518
- }
519
- async function isAiwgManagedEntry(target, directory) {
520
- const fs = await import('node:fs/promises');
521
- if (directory) {
522
- try {
523
- const marker = await fs.readFile(path.join(target, '.aiwg-managed'), 'utf8');
524
- if (marker.trim() === 'aiwg')
525
- return true;
526
- }
527
- catch { /* legacy deployed skill may use an inline marker */ }
528
- }
529
- const markerFile = directory ? path.join(target, 'SKILL.md') : target;
530
- try {
531
- const text = await fs.readFile(markerFile, 'utf8');
532
- return /(?:#|<!--) aiwg:managed v[^\s]+ [^\r\n]+/.test(text.slice(0, 2048));
533
- }
534
- catch {
535
- return false;
536
- }
537
- }
538
397
  /**
539
398
  * #1156 Phase 1 — some app providers are exclusively user-scope. `--scope
540
399
  * project` against them is meaningless because their paths are home-rooted;
@@ -0,0 +1,173 @@
1
+ // Mirror provider artifacts while retaining only evidenced native ownership.
2
+ import * as path from 'node:path';
3
+ const SIDECAR = '.aiwg-manifest.json';
4
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value)
5
+ ? value : {};
6
+ function receipt(bytes) {
7
+ try {
8
+ return object(JSON.parse(bytes?.toString() || '{}'));
9
+ }
10
+ catch {
11
+ return {};
12
+ }
13
+ }
14
+ export async function assertGrokUserMirrorPaths(projectPaths, userPaths) {
15
+ const fs = await import('node:fs/promises');
16
+ const statIfPresent = async (target) => {
17
+ try {
18
+ return await fs.lstat(target);
19
+ }
20
+ catch (error) {
21
+ if (error.code === 'ENOENT')
22
+ return null;
23
+ throw error;
24
+ }
25
+ };
26
+ const checkTarget = async (target) => {
27
+ const stat = await statIfPresent(target);
28
+ if (!stat)
29
+ return;
30
+ if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
31
+ throw new Error(`Refusing unsafe Grok Build user mirror target: ${target}`);
32
+ }
33
+ if (stat.isDirectory()) {
34
+ for (const name of await fs.readdir(target))
35
+ await checkTarget(path.join(target, name));
36
+ }
37
+ };
38
+ for (const [destination, sources] of [
39
+ [userPaths.agents, [projectPaths.agents]],
40
+ [userPaths.skills, [projectPaths.skills, projectPaths.kernelSkills ?? '']],
41
+ ]) {
42
+ if (!destination)
43
+ continue;
44
+ const rootStat = await statIfPresent(destination);
45
+ if (rootStat && (rootStat.isSymbolicLink() || !rootStat.isDirectory())) {
46
+ throw new Error(`Refusing unsafe Grok Build user mirror root: ${destination}`);
47
+ }
48
+ for (const source of sources) {
49
+ if (!source)
50
+ continue;
51
+ let names;
52
+ try {
53
+ names = await fs.readdir(source);
54
+ }
55
+ catch (error) {
56
+ if (error.code === 'ENOENT')
57
+ continue;
58
+ throw error;
59
+ }
60
+ for (const name of names)
61
+ await checkTarget(path.join(destination, name));
62
+ }
63
+ }
64
+ }
65
+ /**
66
+ * Copy every directory or file under `src` into `dst` (creating `dst` if
67
+ * needed). Returns the count of top-level entries successfully copied and
68
+ * the entry names themselves — the names are needed by callers that record
69
+ * a per-framework manifest at user scope so `aiwg remove --scope user` can
70
+ * delete only what this deploy created.
71
+ *
72
+ * Used by the user-scope mirror to cover both directory-style artifacts
73
+ * (skills, agents) and file-style artifacts (commands, rules in some
74
+ * providers). Failures on individual entries are swallowed so a single bad
75
+ * entry doesn't fail the whole mirror.
76
+ */
77
+ export async function mirrorArtifactDir(src, dst, ownedThisCall = new Set()) {
78
+ if (!src || !dst)
79
+ return { count: 0, targetDir: dst, entries: [] };
80
+ const fs = await import('node:fs/promises');
81
+ let dirents;
82
+ try {
83
+ dirents = await fs.readdir(src, { withFileTypes: true });
84
+ }
85
+ catch {
86
+ return { count: 0, targetDir: dst, entries: [] };
87
+ }
88
+ // Some providers already deploy kernel skills to an absolute user-level
89
+ // path. Inventory that source for registry accounting instead of trying to
90
+ // recursively copy each entry onto itself.
91
+ if (path.resolve(src) === path.resolve(dst)) {
92
+ const entries = [];
93
+ for (const entry of dirents) {
94
+ if ((entry.isDirectory() || entry.isFile()) && await isAiwgManagedEntry(path.join(dst, entry.name), entry.isDirectory())) {
95
+ entries.push(entry.name);
96
+ }
97
+ }
98
+ return { count: entries.length, targetDir: dst, entries };
99
+ }
100
+ const { captureDeploymentOutputs, recordDeploymentOutputs } = await import('../providers/deployment-ownership.mjs');
101
+ const before = captureDeploymentOutputs([dst]);
102
+ const sourceReceipt = receipt(await fs.readFile(path.join(src, SIDECAR)).catch(() => undefined));
103
+ const copiedRecords = {};
104
+ await fs.mkdir(dst, { recursive: true });
105
+ let count = 0;
106
+ const entries = [];
107
+ for (const entry of dirents) {
108
+ if (entry.name === SIDECAR)
109
+ continue;
110
+ const s = path.join(src, entry.name);
111
+ const d = path.join(dst, entry.name);
112
+ try {
113
+ // User-scope directories are shared with operator-created artifacts.
114
+ // A same-named unmanaged entry belongs to the operator, even when a
115
+ // project has an AIWG-managed source with that name.
116
+ try {
117
+ const existing = await fs.lstat(d);
118
+ if (!ownedThisCall.has(entry.name) && !await isAiwgManagedEntry(d, existing.isDirectory()))
119
+ continue;
120
+ }
121
+ catch (error) {
122
+ if (error.code !== 'ENOENT')
123
+ continue;
124
+ }
125
+ if (entry.isDirectory()) {
126
+ await fs.cp(s, d, { recursive: true, force: true });
127
+ }
128
+ else if (entry.isFile()) {
129
+ await fs.copyFile(s, d);
130
+ if (sourceReceipt.managed?.[entry.name])
131
+ copiedRecords[entry.name] = sourceReceipt.managed[entry.name];
132
+ }
133
+ else {
134
+ continue;
135
+ }
136
+ count++;
137
+ entries.push(entry.name);
138
+ }
139
+ catch {
140
+ // ignore individual failures
141
+ }
142
+ }
143
+ if (Object.keys(copiedRecords).length) {
144
+ const sidecarPath = path.resolve(dst, SIDECAR);
145
+ const prior = receipt(before.get(sidecarPath));
146
+ const next = { ...prior, managed: { ...object(prior.managed), ...copiedRecords } };
147
+ await fs.writeFile(sidecarPath, `${JSON.stringify(next, null, 2)}\n`);
148
+ }
149
+ // Copied skill sidecars retain their directory-local shape. The same merge
150
+ // handles flat files, and never adopts an unrecorded legacy/operator file.
151
+ recordDeploymentOutputs(before, [dst], { onlyDeclared: true });
152
+ return { count, targetDir: dst, entries };
153
+ }
154
+ async function isAiwgManagedEntry(target, directory) {
155
+ const fs = await import('node:fs/promises');
156
+ if (directory) {
157
+ try {
158
+ const marker = await fs.readFile(path.join(target, '.aiwg-managed'), 'utf8');
159
+ if (marker.trim() === 'aiwg')
160
+ return true;
161
+ }
162
+ catch { /* legacy deployed skill may use an inline marker */ }
163
+ }
164
+ const markerFile = directory ? path.join(target, 'SKILL.md') : target;
165
+ try {
166
+ const text = await fs.readFile(markerFile, 'utf8');
167
+ return /(?:#|<!--) aiwg:managed v[^\s]+ [^\r\n]+/.test(text.slice(0, 2048));
168
+ }
169
+ catch {
170
+ return false;
171
+ }
172
+ }
173
+ //# sourceMappingURL=user-scope-mirror.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=dispatch-host-thresholds.js.map
@@ -7,6 +7,7 @@ export const DEFAULT_DISPATCH_HOST_THRESHOLDS = Object.freeze({
7
7
  // 08 brief/evidence retention: stop new admissions when less than 2 GiB free remains.
8
8
  min_free_disk_gb: 2,
9
9
  max_workers: 5,
10
+ max_snapshot_age_seconds: 300,
10
11
  });
11
12
 
12
13
  /**
@@ -32,6 +33,9 @@ export function resolveDispatchHostThresholds(buildDispatch, admissionHostResour
32
33
  if (!Number.isFinite(value) || value < 0) {
33
34
  throw new Error(`OG_CONFIG_REFERENCE dispatch threshold ${key}: must be a non-negative number`);
34
35
  }
36
+ if (key === 'max_snapshot_age_seconds' && value <= 0) {
37
+ throw new Error('OG_CONFIG_REFERENCE dispatch threshold max_snapshot_age_seconds: must be a positive number');
38
+ }
35
39
  if (key === 'max_workers' && (!Number.isInteger(value) || value < 1)) {
36
40
  throw new Error('OG_CONFIG_REFERENCE dispatch threshold max_workers: must be an integer >= 1 when set');
37
41
  }
@@ -3,6 +3,10 @@ import type { HostResourceSample, HostResourceReaders } from './host-resource-ru
3
3
  export interface HostResourceCap { threshold: string; limit?: number | null; running?: number }
4
4
  export interface HostResourceReport {
5
5
  measured: HostResourceSample;
6
+ freshness: {
7
+ collectedAt: string | null; evaluatedAt: string | null; ageMs: number | null; maxAgeMs: number;
8
+ status: 'fresh' | 'stale' | 'unavailable'; reason?: string;
9
+ };
6
10
  thresholds: DispatchHostThresholds | null;
7
11
  origins: Record<string, string[]>;
8
12
  slots: number;
@@ -16,4 +20,5 @@ export interface HostResourceReport {
16
20
  export function hostResourceReport(input?: {
17
21
  group?: string; config?: AiwgConfig; live?: HostResourceSample; readers?: HostResourceReaders; paths?: string[];
18
22
  thresholdOverlay?: DispatchHostThresholds; caps?: HostResourceCap[];
23
+ now?: () => number;
19
24
  }): HostResourceReport;
@@ -1,10 +1,28 @@
1
1
  // Normalize host measurements, tighten-only thresholds and remaining worker capacity.
2
2
  import { getProviderParallelismDefaults } from './aiwg-config.js';
3
3
  import { expandWorkerGroupTemplates } from './worker-group-templates.js';
4
- import { resolveDispatchHostThresholds } from './dispatch-thresholds-runtime.mjs';
4
+ import { DEFAULT_DISPATCH_HOST_THRESHOLDS, resolveDispatchHostThresholds } from './dispatch-thresholds-runtime.mjs';
5
5
  import { evaluateDispatchGate, readLiveHostResources } from './host-resource-runtime.mjs';
6
6
 
7
- export function hostResourceReport({ config, live, readers, paths, thresholdOverlay, caps, group } = {}) {
7
+ // Re-evaluate persisted/remote collection times; never stamp them with the read time.
8
+ function snapshotFreshness(measured, evaluated, maxSnapshotAgeSeconds) {
9
+ const collected = Date.parse(measured.collectedAt);
10
+ const ageMs = evaluated - collected;
11
+ const maxAgeMs = maxSnapshotAgeSeconds * 1000;
12
+ const result = { collectedAt: Number.isFinite(collected) ? new Date(collected).toISOString() : null,
13
+ evaluatedAt: Number.isFinite(evaluated) ? new Date(evaluated).toISOString() : null,
14
+ ageMs: Number.isFinite(ageMs) ? ageMs : null, maxAgeMs, status: 'fresh' };
15
+ if (!Number.isFinite(ageMs)) {
16
+ result.status = 'unavailable'; result.reason = 'collection time or evaluation clock missing or invalid';
17
+ } else if (ageMs < 0) {
18
+ result.status = 'unavailable'; result.reason = 'collection time is in the future';
19
+ } else if (ageMs > maxAgeMs) {
20
+ result.status = 'stale'; result.reason = `resource snapshot age ${ageMs}ms exceeds ${maxAgeMs}ms`;
21
+ }
22
+ return result;
23
+ }
24
+
25
+ export function hostResourceReport({ config, live, readers, paths, thresholdOverlay, caps, group, now = readers?.now ?? Date.now } = {}) {
8
26
  const expansion = expandWorkerGroupTemplates(config?.parallelism);
9
27
  if (expansion.errors.length) throw new Error(expansion.errors.join('; '));
10
28
  const parallelism = expansion.parallelism;
@@ -12,21 +30,33 @@ export function hostResourceReport({ config, live, readers, paths, thresholdOver
12
30
  if (group !== undefined && !Object.hasOwn(configured, group)) {
13
31
  throw new Error(`Unknown group "${group}"; configured groups: ${Object.keys(configured).join(', ') || '(none)'}`);
14
32
  }
15
- const measured = live ?? readLiveHostResources({ ...readers, paths, groupNames: Object.keys(configured) });
33
+ // Local collection and evaluation share one clock; supplied snapshots retain their source time.
34
+ const measured = live ?? readLiveHostResources({ ...readers, now, paths, groupNames: Object.keys(configured) });
35
+ const evaluated = now();
16
36
  const origins = {};
17
37
  let thresholds;
18
38
  try {
19
39
  thresholds = resolveDispatchHostThresholds(config?.build?.resource_preflight?.dispatch,
20
40
  config?.parallelism?.admission?.hostResources, thresholdOverlay, origins);
21
41
  } catch (error) {
22
- return { measured, thresholds: null, origins, slots: 0, ok: false, limits: [], groups: [],
42
+ const snapshot = snapshotFreshness(measured, evaluated, DEFAULT_DISPATCH_HOST_THRESHOLDS.max_snapshot_age_seconds);
43
+ return { measured, freshness: snapshot, thresholds: null, origins, slots: 0, ok: false, limits: [], groups: [],
23
44
  failures: [{ signal: 'thresholds', reason: error.message }] };
24
45
  }
46
+ const snapshot = snapshotFreshness(measured, evaluated, thresholds.max_snapshot_age_seconds);
25
47
  const gate = evaluateDispatchGate(measured, thresholds);
48
+ if (!Number.isFinite(measured.load1) || !Number.isFinite(measured.cores) || measured.cores <= 0) {
49
+ gate.failures.push({ signal: 'load', reason: 'load headroom requires detectable load1 and positive cores' });
50
+ }
26
51
  const names = { 'avail-mem': 'min_avail_mem_gb', load: 'max_load_ratio',
27
52
  'mem-psi-avg10': 'max_mem_psi_avg10', 'mem-psi-avg60': 'max_mem_psi_avg60',
28
53
  'free-disk': 'min_free_disk_gb', workers: 'max_workers' };
29
- const failures = gate.failures.map(failure => ({ ...failure, signal: names[failure.signal] ?? failure.signal }));
54
+ const failures = gate.failures.map(failure => ({ ...failure, signal: names[failure.signal] ?? failure.signal,
55
+ reason: failure.actual === undefined ? `unavailable: ${failure.reason}` : failure.reason }));
56
+ if (snapshot.status !== 'fresh') failures.unshift({ signal: 'snapshot', reason: `${snapshot.status}: ${snapshot.reason}` });
57
+ else if (failures.some(failure => failure.reason.startsWith('unavailable:'))) {
58
+ snapshot.status = 'unavailable'; snapshot.reason = 'required host signals unavailable';
59
+ }
30
60
  const limits = [];
31
61
  const add = (threshold, available, reason) => {
32
62
  const slots = Number.isFinite(available) ? Math.max(0, Math.floor(available)) : 0;
@@ -73,7 +103,7 @@ export function hostResourceReport({ config, live, readers, paths, thresholdOver
73
103
  });
74
104
  const slots = failures.length ? 0 : Math.min(...limits.map(limit => limit.slots));
75
105
  const limitingThreshold = failures[0]?.signal ?? [...limits].sort((a, b) => a.slots - b.slots)[0]?.threshold;
76
- return { measured, thresholds, origins, slots, ok: slots > 0, limits, failures, groups, limitingThreshold,
106
+ return { measured, freshness: snapshot, thresholds, origins, slots, ok: slots > 0, limits, failures, groups, limitingThreshold,
77
107
  counting: 'current UID AIWG worker units plus distinct AIWG_WORKER_INVOCATION_ID markers outside those units; '
78
108
  + (measured.workerCountingSource === 'owned-process-fallback' ? 'systemd unavailable: owned-process fallback; ' : '')
79
109
  + 'hostCliProcesses: exact codex/muse/muse-bin comm, informational, not used for admission; group attribution uses unambiguous configured prefixes in existing invocation markers or unit names; unattributed workers count against every group; tuple caps without attribution use owned worker total' };
@@ -1,4 +1,6 @@
1
1
  export interface HostResourceSample {
2
+ /** Start of collection on the source host; absent on legacy/unavailable snapshots. */
3
+ collectedAt?: string;
2
4
  supported: boolean; reason?: string; availMemGb?: number; load1?: number; cores?: number;
3
5
  loadRatio?: number; memPsiAvg10?: number; memPsiAvg60?: number; memPsiAvg300?: number;
4
6
  workerGroups?: Record<string, number>;
@@ -11,6 +13,7 @@ export interface WorkerCensus {
11
13
  source?: HostResourceSample['workerCountingSource'];
12
14
  }
13
15
  export interface HostResourceReaders {
16
+ now?: () => number;
14
17
  readText?: (path: string) => string;
15
18
  readDir?: (path: string) => string[];
16
19
  uid?: number;
@@ -194,6 +194,8 @@ function sampleFreeDiskGb(readers) {
194
194
  }
195
195
 
196
196
  function readLiveHostResources(readers = {}) {
197
+ // Capture the start of collection, so slow readers cannot make old values newer.
198
+ const collectedAt = new Date((readers.now ?? Date.now)()).toISOString();
197
199
  const readText = readers.readText ?? (path => readFileSync(path, 'utf8'));
198
200
  const coreCount = readers.coreCount ?? (() => os.cpus().length);
199
201
  const countWorkers = readers.countWorkers ?? (() => countWorkerProcesses(readers));
@@ -203,7 +205,7 @@ function readLiveHostResources(readers = {}) {
203
205
  // (threaded through `checkWorkerDispatch({ paths })`); without them free
204
206
  // disk is unknown and the gate fails closed.
205
207
  if (process.platform !== 'linux' && readers.readText === undefined) {
206
- return { supported: false, reason: `live dispatch signals require Linux /proc (this host: ${process.platform})` };
208
+ return { collectedAt, supported: false, reason: `live dispatch signals require Linux /proc (this host: ${process.platform})` };
207
209
  }
208
210
  const readOptional = (path) => {
209
211
  try {
@@ -222,6 +224,7 @@ function readLiveHostResources(readers = {}) {
222
224
  workers = undefined;
223
225
  }
224
226
  return {
227
+ collectedAt,
225
228
  supported: true,
226
229
  availMemGb: parseMemAvailableGb(readOptional('/proc/meminfo') ?? ''),
227
230
  load1: load?.load1,
@@ -252,24 +255,24 @@ function evaluateDispatchGate(live, thresholds) {
252
255
  };
253
256
  }
254
257
  const breach = (signal, actual, threshold, reason) => failures.push({ signal, actual, threshold, reason });
255
- if (live.availMemGb === undefined) breach('avail-mem', undefined, thresholds.min_avail_mem_gb, 'MemAvailable not detectable on this host');
258
+ if (!Number.isFinite(live.availMemGb)) breach('avail-mem', undefined, thresholds.min_avail_mem_gb, 'MemAvailable not detectable on this host');
256
259
  else if (live.availMemGb < thresholds.min_avail_mem_gb) {
257
260
  breach('avail-mem', live.availMemGb, thresholds.min_avail_mem_gb, `available ${live.availMemGb.toFixed(1)}GB < ${thresholds.min_avail_mem_gb}GB`);
258
261
  }
259
- if (live.loadRatio === undefined) breach('load', undefined, thresholds.max_load_ratio, 'load average not detectable on this host');
262
+ if (!Number.isFinite(live.loadRatio)) breach('load', undefined, thresholds.max_load_ratio, 'load average not detectable on this host');
260
263
  else if (live.loadRatio > thresholds.max_load_ratio) {
261
264
  breach('load', live.loadRatio, thresholds.max_load_ratio, `load ratio ${live.loadRatio.toFixed(2)} > ${thresholds.max_load_ratio}`);
262
265
  }
263
- if (live.memPsiAvg10 === undefined) breach('mem-psi-avg10', undefined, thresholds.max_mem_psi_avg10, '/proc/pressure/memory not detectable on this host');
266
+ if (!Number.isFinite(live.memPsiAvg10)) breach('mem-psi-avg10', undefined, thresholds.max_mem_psi_avg10, '/proc/pressure/memory not detectable on this host');
264
267
  else if (live.memPsiAvg10 > thresholds.max_mem_psi_avg10) {
265
268
  breach('mem-psi-avg10', live.memPsiAvg10, thresholds.max_mem_psi_avg10, `memory PSI avg10 ${live.memPsiAvg10} > ${thresholds.max_mem_psi_avg10}`);
266
269
  }
267
- if (live.memPsiAvg60 === undefined) breach('mem-psi-avg60', undefined, thresholds.max_mem_psi_avg60, '/proc/pressure/memory not detectable on this host');
270
+ if (!Number.isFinite(live.memPsiAvg60)) breach('mem-psi-avg60', undefined, thresholds.max_mem_psi_avg60, '/proc/pressure/memory not detectable on this host');
268
271
  else if (live.memPsiAvg60 > thresholds.max_mem_psi_avg60) {
269
272
  breach('mem-psi-avg60', live.memPsiAvg60, thresholds.max_mem_psi_avg60, `memory PSI avg60 ${live.memPsiAvg60} > ${thresholds.max_mem_psi_avg60}`);
270
273
  }
271
274
  if (thresholds.max_workers !== undefined) {
272
- if (live.workers === undefined) breach('workers', undefined, thresholds.max_workers, 'worker count not detectable on this host');
275
+ if (!Number.isFinite(live.workers)) breach('workers', undefined, thresholds.max_workers, 'worker count not detectable on this host');
273
276
  else if (live.workers >= thresholds.max_workers) {
274
277
  breach('workers', live.workers, thresholds.max_workers, `${live.workers} running workers >= ${thresholds.max_workers}`);
275
278
  }
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'node:url';
5
5
  import Ajv2020 from 'ajv/dist/2020.js';
6
6
  import { admitEntry, DEFAULT_ENTRY_LIMITS } from '../entry.js';
7
7
  import { heldoutDigest } from '../heldout/contract.js';
8
+ import { D17_ANALYSIS, validateD17Analysis } from './protocol.js';
8
9
  const schemas = { analysis: 'D17StudyAnalysis', splits: 'D17StudySplits', gold: 'D17StudyGold',
9
10
  review: 'D17StudyReview', guide: 'D17StudyGuide', report: 'D17StudyReport',
10
11
  nativeTemplates: 'D17StudyNativeTemplates', dryRun: 'D17StudyDryRun',
@@ -33,6 +34,12 @@ export function validateD17Artifact(name, value) {
33
34
  admitEntry(value, name === 'report' || name === 'reportV2' ? reportLimits : limits);
34
35
  if (!validators[name]?.(value))
35
36
  throw new Error(`D17 invalid ${name} artifact`);
37
+ if (name === 'analysis' || name === 'analysisV2') {
38
+ validateD17Analysis(value.protocol);
39
+ }
40
+ if (name === 'nativeTemplates') {
41
+ validateD17Analysis({ ...D17_ANALYSIS, native: value.comparison.pairedMetrics });
42
+ }
36
43
  if (name === 'report' || name === 'reportV2') {
37
44
  const report = value;
38
45
  assertDecisionCeiling(report.decision, ceilingDecision('HOLD', report.integrity.release_gate.decision, report.integrity.compromise_labels.length ? 'ROLLBACK' : 'PROMOTE'));
@@ -0,0 +1,58 @@
1
+ import { scalarProvider } from '../../gates/providers/index.js';
2
+ export const D17_PACK_ID = 'project:d17-study';
3
+ export const D17_SLICES = ['direct-facts', 'multi-fact', 'negation', 'authority'];
4
+ const base = {
5
+ minimumPairs: 1200, minimumPerSlice: 300, maximumMissingPairs: 0,
6
+ nonInferiorityMarginBps: -300, benefitLowerExclusiveBps: 0,
7
+ maximumBrierUpperBps: 200, maximumAcceptedErrorUpperBps: 500,
8
+ minimumCoverageLowerBps: 6000, maximumAbstentionUpperBps: 500,
9
+ maximumP95LatencyIncreaseMs: 15000, maximumDisagreementBps: 1000,
10
+ minimumSuccessfulMembers: 3, highAgreementWarningBps: 100,
11
+ nativeRiskCoverage: 0.01, nativeLatency: 10000, nativeTokens: 8000, nativeCost: 800,
12
+ };
13
+ export const D17_NATIVE = [
14
+ { metric: 'quality', comparison: 'delta-at-least', param: 'nonInferiorityMarginBps', divisor: 10000 },
15
+ { metric: 'calibration', comparison: 'delta-at-most', param: 'maximumBrierUpperBps', divisor: 10000 },
16
+ { metric: 'risk-coverage', comparison: 'delta-at-most', param: 'nativeRiskCoverage', divisor: 1 },
17
+ { metric: 'abstention', comparison: 'delta-at-most', param: 'maximumAbstentionUpperBps', divisor: 10000 },
18
+ { metric: 'latency', comparison: 'delta-at-most', param: 'nativeLatency', divisor: 1 },
19
+ { metric: 'tokens', comparison: 'delta-at-most', param: 'nativeTokens', divisor: 1 },
20
+ { metric: 'cost', comparison: 'delta-at-most', param: 'nativeCost', divisor: 1 },
21
+ { metric: 'slice', comparison: 'delta-at-least', param: 'nonInferiorityMarginBps', divisor: 10000 },
22
+ ];
23
+ export const d17NativeParameter = (metric) => `native_${metric.replaceAll('-', '_')}`;
24
+ export const D17_NATIVE_BOUNDS = Object.fromEntries(D17_NATIVE.map(row => [d17NativeParameter(row.metric), base[row.param] / row.divisor]));
25
+ export const D17_GATE_PARAMETERS = { ...base, ...D17_NATIVE_BOUNDS };
26
+ /** Scalar targets are the historical rounded endpoints, not newly recomputed intervals. */
27
+ export function d17GatePack() {
28
+ const definitions = [
29
+ ['incomplete-pairs', 'minimumPairs', 'gte'], ['missing-pairs', 'maximumMissingPairs', 'lte'],
30
+ ...D17_SLICES.map(slice => [`slice-support-${slice}`, 'minimumPerSlice', 'gte']),
31
+ ['quality-ni', 'nonInferiorityMarginBps', 'gte'], ['brier-upper', 'maximumBrierUpperBps', 'lte'],
32
+ ['abstention-upper', 'maximumAbstentionUpperBps', 'lte'],
33
+ ['accepted-risk-upper', 'maximumAcceptedErrorUpperBps', 'lte'],
34
+ ['coverage-lower', 'minimumCoverageLowerBps', 'gte'],
35
+ ['latency-p95', 'maximumP95LatencyIncreaseMs', 'lte'],
36
+ ['benefit', 'benefitLowerExclusiveBps', 'gte'],
37
+ ...D17_NATIVE.map(row => [`native-${row.metric}`, d17NativeParameter(row.metric),
38
+ row.comparison === 'delta-at-least' ? 'gte' : 'lte']),
39
+ ];
40
+ const direction = (name) => name.startsWith('minimum') || name === 'nonInferiorityMarginBps'
41
+ || name === 'benefitLowerExclusiveBps' || name === 'native_quality' || name === 'native_slice' ? 'higher-is-stricter' : 'lower-is-stricter';
42
+ const gates = definitions.map(([id, param, op]) => {
43
+ const support = param === 'minimumPairs' || param === 'minimumPerSlice';
44
+ return { id, kind: support ? 'minimum-n' : 'value-threshold',
45
+ metric: { provider: scalarProvider.id, name: 'measurement' },
46
+ ...(support ? { minimumN: { param } } : { threshold: { op, param } }),
47
+ scope: { mode: 'listed', slices: [id] },
48
+ ...(id.startsWith('native-') ? { minimumN: { param: 'minimumPairs' } } : {}),
49
+ direction: op === 'gte' ? 'higher-is-stricter' : 'lower-is-stricter', onFail: 'HOLD' };
50
+ });
51
+ return { apiVersion: 'gates.aiwg.io/v1alpha1', kind: 'GatePack',
52
+ metadata: { id: D17_PACK_ID, version: '1.0.0', description: 'D17 historical diagnostic endpoints.' },
53
+ spec: { parameters: Object.fromEntries(Object.keys(D17_GATE_PARAMETERS).map(name => [name,
54
+ { type: name === 'minimumPairs' || name === 'minimumPerSlice' ? 'count' : 'value', direction: direction(name) }])),
55
+ metrics: { measurement: { provider: scalarProvider.id, kind: 'scalar' } }, gates,
56
+ combine: { rule: 'max-severity' } } };
57
+ }
58
+ //# sourceMappingURL=gate-policy.js.map