@aiwg/cli 2026.10.14 → 2026.10.15

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 (56) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/dist/src/artifacts/corpus-tools/cli.js +32 -0
  4. package/dist/src/artifacts/corpus-tools/discovery-log.js +1 -1
  5. package/dist/src/artifacts/corpus-tools/expand-cli.js +89 -0
  6. package/dist/src/artifacts/corpus-tools/expand-queue.js +38 -0
  7. package/dist/src/artifacts/corpus-tools/expand-state.js +40 -0
  8. package/dist/src/artifacts/corpus-tools/expand.js +125 -0
  9. package/dist/src/artifacts/corpus-tools/resolve-cli.js +91 -0
  10. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/resolve.js +105 -0
  12. package/dist/src/cli/handlers/doctor-args.js +40 -0
  13. package/dist/src/cli/handlers/doctor-help.js +4 -2
  14. package/dist/src/cli/handlers/utilities.js +5 -31
  15. package/dist/src/config/worker-context.js +33 -4
  16. package/dist/src/decision/heldout/collector.js +1 -1
  17. package/dist/src/features/catalog.js +1 -1
  18. package/dist/src/gates/evaluate.js +2 -2
  19. package/dist/src/gates/heldout.js +42 -0
  20. package/dist/src/gates/index.js +2 -1
  21. package/dist/src/models/worker-installation-store.mjs +228 -0
  22. package/dist/src/models/worker-installation.mjs +7 -162
  23. package/dist/src/providers/provider-definitions.js +10 -10
  24. package/dist/src/research/clients/arxiv.js +10 -4
  25. package/dist/src/research/clients/base.js +5 -4
  26. package/dist/src/research/clients/crossref.js +9 -1
  27. package/dist/src/research/clients/semantic-scholar.js +73 -44
  28. package/dist/src/research/identity.js +85 -0
  29. package/dist/src/research/index.js +1 -0
  30. package/dist/src/research/reference-match.js +89 -0
  31. package/dist/src/rules/core-startup.d.mts +2 -0
  32. package/dist/src/rules/core-startup.mjs +31 -0
  33. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  34. package/dist/src/smiths/context-pipeline/aiwg-md.js +3 -0
  35. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  36. package/dist/src/smiths/context-pipeline/generator.js +40 -104
  37. package/dist/src/smiths/context-pipeline/managed-hook.js +10 -0
  38. package/package.json +4 -2
  39. package/tools/agents/deploy-agents.mjs +2 -123
  40. package/tools/agents/providers/antigravity.mjs +1 -1
  41. package/tools/agents/providers/context-write.mjs +12 -0
  42. package/tools/agents/providers/grok-build.mjs +8 -5
  43. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  44. package/tools/agents/providers/hermes-startup.mjs +209 -0
  45. package/tools/agents/providers/hermes.mjs +9 -359
  46. package/tools/agents/providers/model-wrapper.mjs +5 -1
  47. package/tools/agents/providers/muse.mjs +3 -3
  48. package/tools/agents/providers/pi.mjs +1 -1
  49. package/tools/agents/providers/rule-delivery.mjs +23 -225
  50. package/tools/agents/providers/rule-presentation.mjs +13 -4
  51. package/tools/agents/providers/rule-projection.mjs +119 -0
  52. package/tools/agents/providers/rule-startup.mjs +70 -0
  53. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  54. package/tools/agents/providers/warp.mjs +2 -2
  55. package/tools/agents/providers/windsurf.mjs +11 -57
  56. package/tools/plugin/plugin-links.mjs +3 -0
@@ -0,0 +1,105 @@
1
+ // Resolve partial paper references through audited client attempts and conservative scoring.
2
+ import { ArxivClient } from '../../research/clients/arxiv.js';
3
+ import { CrossRefClient } from '../../research/clients/crossref.js';
4
+ import { SemanticScholarClient } from '../../research/clients/semantic-scholar.js';
5
+ import { normalizeIdentity, normalizeTitle } from '../../research/identity.js';
6
+ import { classifyCandidates, mergePapers, parsePartialReference, scorePaper } from '../../research/reference-match.js';
7
+ import { ResearchError, ResearchErrorCode } from '../../research/types.js';
8
+ import { findInCorpus } from './resolve-corpus.js';
9
+ export function createResolverClients() {
10
+ return { arxiv: new ArxivClient(), s2: new SemanticScholarClient(), crossref: new CrossRefClient() };
11
+ }
12
+ function canonicalPaper(paper) {
13
+ const identity = normalizeIdentity(paper);
14
+ return { ...paper, ...Object.fromEntries(Object.entries(identity).filter(([key, value]) => key !== 'title' && value !== undefined)) };
15
+ }
16
+ function s2Identifier(identifier) {
17
+ switch (identifier.kind) {
18
+ case 'arxiv': return `ARXIV:${identifier.id}`;
19
+ case 'doi': return `DOI:${identifier.id}`;
20
+ case 'acl': return `ACL:${identifier.id}`;
21
+ case 'openreview': return `URL:https://openreview.net/forum?id=${identifier.id}`;
22
+ case 's2': return identifier.id;
23
+ }
24
+ }
25
+ export async function resolveReference(input, root, year, clients = createResolverClients()) {
26
+ const reference = parsePartialReference(input, year);
27
+ const paths = [];
28
+ const findings = [];
29
+ const papers = [];
30
+ const verified = new Set();
31
+ const identifier = reference.identifier;
32
+ async function attempt(source, method, query, run, byId = false) {
33
+ try {
34
+ const returned = (await run()).slice(0, 5).map(canonicalPaper);
35
+ if (returned.some(paper => !paper.id || !normalizeTitle(paper.title))) {
36
+ throw new ResearchError(ResearchErrorCode.RF_301, 'Response lacks a paper identity or title');
37
+ }
38
+ paths.push({ source, method, query, status: returned.length ? 'returned' : 'empty', returned });
39
+ for (const paper of returned) {
40
+ if (byId && identifier) {
41
+ const key = { arxiv: 'arxivId', doi: 'doi', acl: 'aclId', openreview: 'openReviewId', s2: 's2PaperId' }[identifier.kind];
42
+ const actual = paper[key];
43
+ if (actual && identifier.kind !== 's2' && String(actual).toLowerCase() !== identifier.id.toLowerCase()) {
44
+ findings.push({ type: 'identifier_mismatch', supplied: identifier.id, returned: String(actual), candidate: paper.id });
45
+ continue;
46
+ }
47
+ if (identifier.kind === 's2' && !identifier.id.startsWith('CorpusId:') && paper.s2PaperId?.toLowerCase() !== identifier.id.toLowerCase()) {
48
+ findings.push({ type: 'identifier_mismatch', supplied: identifier.id, returned: paper.s2PaperId ?? paper.id, candidate: paper.id });
49
+ continue;
50
+ }
51
+ // A direct lookup establishes the requested ID when the API omits that externalId.
52
+ if (identifier.kind !== 's2')
53
+ Object.assign(paper, { [key]: identifier.id });
54
+ verified.add(paper.id);
55
+ }
56
+ papers.push(paper);
57
+ }
58
+ }
59
+ catch (error) {
60
+ const missing = error instanceof ResearchError && error.code === ResearchErrorCode.RF_300;
61
+ paths.push({ source, method, query, status: missing ? 'empty' : 'error', returned: [],
62
+ ...(missing ? {} : { error: error instanceof Error ? error.message : String(error) }) });
63
+ }
64
+ }
65
+ if (identifier) {
66
+ if (identifier.kind === 'arxiv') {
67
+ await attempt('arxiv', 'id', identifier.id, async () => [await clients.arxiv.getPaperById(identifier.id)], true);
68
+ }
69
+ else if (identifier.kind === 'doi') {
70
+ await attempt('crossref', 'id', identifier.id, async () => [await clients.crossref.getPaperByDoi(identifier.id)], true);
71
+ }
72
+ const id = s2Identifier(identifier);
73
+ await attempt('semantic-scholar', 'id', id, async () => [await clients.s2.getPaperById(id)], true);
74
+ }
75
+ const identifierUnresolved = Boolean(identifier && verified.size === 0);
76
+ if (identifierUnresolved && identifier) {
77
+ const idPaths = paths.filter(path => path.method === 'id');
78
+ findings.push({ type: 'identifier_unresolved', supplied: identifier.id, paths: idPaths,
79
+ returned: idPaths.map(path => {
80
+ const detail = path.error ?? path.returned.map(paper => JSON.stringify(normalizeIdentity(paper))).join(', ');
81
+ const outcome = path.returned.length ? 'returned (identifier mismatch)' : path.status;
82
+ return `${path.source}/${path.method} (${path.query}): ${outcome}${detail ? `: ${detail}` : ''}`;
83
+ }).join('; ') });
84
+ }
85
+ if (reference.title && (!identifier || papers.length === 0)) {
86
+ await attempt('semantic-scholar', 'title-match', reference.title, () => clients.s2.matchTitle(reference.title));
87
+ const query = `ti:"${normalizeTitle(reference.title)}"`;
88
+ await attempt('arxiv', 'title', query, async () => (await clients.arxiv.search(query, { limit: 5 })).papers);
89
+ await attempt('crossref', 'bibliographic', input, async () => (await clients.crossref.searchBibliographic(input, { limit: 5 })).papers);
90
+ }
91
+ const candidates = mergePapers(papers).map(paper => scorePaper(reference, paper, verified.has(paper.id)))
92
+ .sort((a, b) => b.score - a.score || a.paper.id.localeCompare(b.paper.id)).slice(0, 5);
93
+ for (const candidate of candidates) {
94
+ if (reference.title && normalizeTitle(reference.title) !== normalizeTitle(candidate.paper.title)) {
95
+ findings.push({ type: 'title_mismatch', supplied: reference.title, returned: candidate.paper.title, candidate: candidate.paper.id });
96
+ }
97
+ }
98
+ const classified = classifyCandidates(candidates);
99
+ const status = identifierUnresolved && classified === 'resolved' ? 'ambiguous' : classified;
100
+ const paper = status === 'resolved' ? candidates[0].paper : undefined;
101
+ const corpusMatches = paper ? findInCorpus(root, paper) : [];
102
+ return { input, reference, status, incomplete: paths.some(path => path.status === 'error'), candidates,
103
+ ...(paper ? { paper } : {}), findings, paths_tried: paths, already_in_corpus: corpusMatches.length > 0, corpus_matches: corpusMatches };
104
+ }
105
+ //# sourceMappingURL=resolve.js.map
@@ -0,0 +1,40 @@
1
+ // Validate public doctor flags before routing early-return modes.
2
+ import { argsTerminatorIndex, hasPositionalOrSwitch, requireFlagValue, valueTokenIndexes } from '../flag-parsing.js';
3
+ export function parsePublicDoctorFlags(args) {
4
+ const valueFlags = ['--provider', '--bundle', '--scope', '--context-baseline', '--context-budget-tokens', '--cli', '--forget-approval'];
5
+ const knownFlags = new Set([
6
+ ...valueFlags, '--list-approvals', '--all-providers', '--probe-workers', '--qualify', '--yes', '--dry-run', '--no-budget-check', '--strict-context', '--json',
7
+ '--decision-offload', '--deployment', '--user', '--verbose', '-v', '--project-local', '--quiet', '--help', '-h',
8
+ ]);
9
+ const hasSwitch = (name) => hasPositionalOrSwitch(args, name, valueFlags);
10
+ const values = new Map();
11
+ for (const flag of valueFlags) {
12
+ values.set(flag, requireFlagValue(args, { rejectEmpty: true, precedence: 'last' }, flag));
13
+ }
14
+ const consumed = valueTokenIndexes(args, valueFlags);
15
+ for (let i = 0; i < argsTerminatorIndex(args); i += 1) {
16
+ const token = args[i];
17
+ if (consumed.has(i) || !token.startsWith('-'))
18
+ continue;
19
+ const name = token.split('=')[0];
20
+ if (!knownFlags.has(name) || (token.includes('=') && !valueFlags.includes(name))) {
21
+ throw new Error(`Unknown flag: ${name}`);
22
+ }
23
+ }
24
+ if (hasSwitch('--decision-offload') && (hasSwitch('--probe-workers') || hasSwitch('--deployment') || hasSwitch('--user') || values.get('--scope') !== undefined)) {
25
+ throw new Error('--decision-offload is a separate offline mode; do not combine it with worker, deployment or user-scope checks');
26
+ }
27
+ if (['--list-approvals', '--forget-approval', '--qualify', '--cli', '--yes', '--dry-run'].some(flag => hasSwitch(flag) || values.get(flag)) && !hasSwitch('--probe-workers')) {
28
+ throw new Error('--list-approvals, --forget-approval, --qualify, --cli, --yes and --dry-run require --probe-workers');
29
+ }
30
+ if ((hasSwitch('--list-approvals') || values.get('--forget-approval')) && ((hasSwitch('--list-approvals') && values.get('--forget-approval')) || ['--qualify', '--dry-run', '--decision-offload', '--deployment', '--user'].some(hasSwitch) || values.get('--scope') !== undefined)) {
31
+ throw new Error('Approval management must run separately from other doctor modes');
32
+ }
33
+ if (values.get('--forget-approval') && !hasSwitch('--yes'))
34
+ throw new Error('--forget-approval requires --yes');
35
+ if (hasSwitch('--json') && !hasSwitch('--probe-workers') && !hasSwitch('--deployment') && !hasSwitch('--decision-offload')) {
36
+ throw new Error('--json requires --probe-workers or --deployment or --decision-offload');
37
+ }
38
+ return { hasSwitch, values };
39
+ }
40
+ //# sourceMappingURL=doctor-args.js.map
@@ -13,9 +13,11 @@ Options:
13
13
  --scope <scope> Verification scope: project or user
14
14
  --user Alias for --scope user
15
15
  --qualify With --probe-workers, record installation and configured model/role approval
16
- --yes Confirm worker qualification without a terminal
16
+ --list-approvals With --probe-workers, list recorded approvals offline (supports --json)
17
+ --forget-approval PATH With --probe-workers --yes, remove approvals for this workspace
18
+ --yes Confirm worker qualification or approval removal
17
19
  --dry-run With --probe-workers, preview qualification without writes
18
- --cli NAME Limit worker probes/qualification to one configured CLI
20
+ --cli NAME Limit worker probes, qualification, or approvals to one CLI
19
21
  --decision-offload Show offline advisory decision readiness and adoption report
20
22
  --probe-workers Run bounded worker CLI version probes (default: config-only, no subprocess)
21
23
  --project-local Include project-local artifact diagnostics
@@ -1,3 +1,4 @@
1
+ import { parsePublicDoctorFlags } from './doctor-args.js';
1
2
  /**
2
3
  * Utility Command Handlers
3
4
  *
@@ -18,7 +19,6 @@ import { getFrameworkRoot } from '../../channel/manager.mjs';
18
19
  import { updateInstallation } from '../../update/service.mjs';
19
20
  import { useHandler as useFrameworkHandler } from './use.js';
20
21
  import { projectAiwgPath } from '../../config/project-artifacts.js';
21
- import { argsTerminatorIndex, hasPositionalOrSwitch, requireFlagValue, valueTokenIndexes } from '../flag-parsing.js';
22
22
  import { checkCollisions, } from '../../smiths/skillsmith/collision-detector.js';
23
23
  import { renderUseDeploymentResult, verifyConfiguredDeployments, } from '../services/deployment-verification.js';
24
24
  /**
@@ -519,40 +519,14 @@ export const doctorHandler = {
519
519
  async execute(ctx) {
520
520
  // Validate before any early-return mode: deployment and user-scope doctor
521
521
  // never invoke doctor.mjs, so they must enforce the same flag contract.
522
- const valueFlags = ['--provider', '--bundle', '--scope', '--context-baseline', '--context-budget-tokens', '--cli'];
523
- const knownFlags = new Set([
524
- ...valueFlags, '--all-providers', '--probe-workers', '--qualify', '--yes', '--dry-run', '--no-budget-check', '--strict-context', '--json',
525
- '--decision-offload', '--deployment', '--user', '--verbose', '-v', '--project-local', '--quiet', '--help', '-h',
526
- ]);
527
- const hasSwitch = (name) => hasPositionalOrSwitch(ctx.args, name, valueFlags);
528
- const values = new Map();
522
+ let flags;
529
523
  try {
530
- for (const flag of valueFlags) {
531
- values.set(flag, requireFlagValue(ctx.args, { rejectEmpty: true, precedence: 'last' }, flag));
532
- }
533
- const consumed = valueTokenIndexes(ctx.args, valueFlags);
534
- for (let i = 0; i < argsTerminatorIndex(ctx.args); i += 1) {
535
- const token = ctx.args[i];
536
- if (consumed.has(i) || !token.startsWith('-'))
537
- continue;
538
- const name = token.split('=')[0];
539
- if (!knownFlags.has(name) || (token.includes('=') && !valueFlags.includes(name))) {
540
- throw new Error(`Unknown flag: ${name}`);
541
- }
542
- }
543
- if (hasSwitch('--decision-offload') && (hasSwitch('--probe-workers') || hasSwitch('--deployment') || hasSwitch('--user') || values.get('--scope') !== undefined)) {
544
- throw new Error('--decision-offload is a separate offline mode; do not combine it with worker, deployment or user-scope checks');
545
- }
546
- if (['--qualify', '--cli', '--yes', '--dry-run'].some(flag => hasSwitch(flag) || values.get(flag)) && !hasSwitch('--probe-workers')) {
547
- throw new Error('--qualify, --cli, --yes and --dry-run require --probe-workers');
548
- }
549
- if (hasSwitch('--json') && !hasSwitch('--probe-workers') && !hasSwitch('--deployment') && !hasSwitch('--decision-offload')) {
550
- throw new Error('--json requires --probe-workers or --deployment or --decision-offload');
551
- }
524
+ flags = parsePublicDoctorFlags(ctx.args);
552
525
  }
553
526
  catch (error) {
554
527
  return { exitCode: 2, message: `${error instanceof Error ? error.message : String(error)}. See 'aiwg doctor --help'.` };
555
528
  }
529
+ const { hasSwitch, values } = flags;
556
530
  if (hasSwitch('--help') || hasSwitch('-h')) {
557
531
  return { exitCode: 0, message: DOCTOR_HELP, rawOutput: true };
558
532
  }
@@ -593,7 +567,7 @@ export const doctorHandler = {
593
567
  // printed exactly one JSON document (or a usage error) on its own
594
568
  // stdio — every section below writes human-readable text, so returning
595
569
  // here keeps stdout to the JSON document alone.
596
- if (hasSwitch('--decision-offload') || hasSwitch('--json') || hasSwitch('--qualify') || hasSwitch('--cli') || hasSwitch('--dry-run') || result.exitCode === 2)
570
+ if (hasSwitch('--list-approvals') || values.get('--forget-approval') || hasSwitch('--decision-offload') || hasSwitch('--json') || hasSwitch('--qualify') || hasSwitch('--cli') || hasSwitch('--dry-run') || result.exitCode === 2)
597
571
  return result;
598
572
  let agentSkillsFailure = false;
599
573
  try {
@@ -125,8 +125,35 @@ export function resolveWorkerContextProvidersFromConfig(config) {
125
125
  }
126
126
  return { providers, skipped };
127
127
  }
128
- /** AIWG-managed rule-section markers written into a deployed AGENTS.md. */
129
- const WORKER_CONTEXT_RULE_MARKER = /<!--\s*AIWG:[A-Za-z0-9_-]+:(start|end)\s*-->/;
128
+ /** Complete managed sections are required; a bootstrap marker alone is insufficient. */
129
+ function ruleSection(content, owner) {
130
+ return content.match(new RegExp(`<!--\\s*AIWG:${owner}:start\\s*-->([\\s\\S]*?)<!--\\s*AIWG:${owner}:end\\s*-->`))?.[1].trim() ?? '';
131
+ }
132
+ function readNonempty(file) {
133
+ try {
134
+ return readFileSync(file, 'utf8').trim();
135
+ }
136
+ catch {
137
+ return '';
138
+ }
139
+ }
140
+ function hasRuleBootstrap(content, workdir, provider, rulesDir) {
141
+ // Older complete inline deployments remain usable during migration.
142
+ if (ruleSection(content, 'rule-startup'))
143
+ return true;
144
+ const hook = ruleSection(content, `rule-hook-${provider}`);
145
+ if (!ruleSection(content, 'rule-core') || !rulesDir)
146
+ return false;
147
+ const entry = path.join(rulesDir, 'RULES-INDEX.md');
148
+ if (!hook.includes(`\`${entry.replaceAll('\\', '/')}\``))
149
+ return false;
150
+ const indexFile = path.resolve(workdir, entry);
151
+ const index = readNonempty(indexFile);
152
+ if (!index)
153
+ return false;
154
+ return [...index.matchAll(/\]\(\.\/([^)]*\.md)\)/g)]
155
+ .every(match => Boolean(readNonempty(path.resolve(path.dirname(indexFile), match[1]))));
156
+ }
130
157
  /**
131
158
  * Check that a worker workdir already carries one provider's bootstrap:
132
159
  * the kernel artifact dirs (`use all` writes kernel skills, rules,
@@ -157,8 +184,10 @@ export function workerContextBootstrapStatus({ workdir, provider }) {
157
184
  catch {
158
185
  entries = null;
159
186
  }
160
- if (!entries || entries.length === 0)
187
+ if (!entries || entries.length === 0 || (dir === paths?.rules &&
188
+ !entries.some(name => /\.(md|mdc)$/.test(name) && readNonempty(path.join(absolute, name))))) {
161
189
  missing.push(`provider dir '${dir}'`);
190
+ }
162
191
  }
163
192
  if ((definition.context?.bootstrapTargets ?? []).includes('AGENTS.md')) {
164
193
  let content = null;
@@ -168,7 +197,7 @@ export function workerContextBootstrapStatus({ workdir, provider }) {
168
197
  catch {
169
198
  content = null;
170
199
  }
171
- if (!content || !WORKER_CONTEXT_RULE_MARKER.test(content)) {
200
+ if (!content || !hasRuleBootstrap(content, workdir, definition.id, paths?.rules ?? null)) {
172
201
  missing.push('AGENTS.md rule sections');
173
202
  }
174
203
  }
@@ -408,7 +408,7 @@ export async function scoreHeldoutStudy(input) {
408
408
  const approvedCalibration = structuredClone(approval.calibration);
409
409
  const calibrated = approvedCalibration.mode === 'uncalibrated-diagnostic'
410
410
  || approvedCalibration.mode === 'staged' && approvedCalibration.phase === 'calibration' ? false : null;
411
- const diagnostics = await input.module.score({ corpus: { ...corpus, rows }, preregistration, attempts, gold: input.gold,
411
+ const diagnostics = await input.module.score({ frozen, corpus: { ...corpus, rows }, preregistration, attempts, gold: input.gold,
412
412
  integrity: structuredClone(input.integrity), approvedCalibration: structuredClone(approvedCalibration), calibrated });
413
413
  if (calibrated === false && (!diagnostics || typeof diagnostics !== 'object'
414
414
  || diagnostics.calibrated !== false
@@ -72,7 +72,7 @@ export const FEATURE_CATALOG = [
72
72
  packages: ['hono', '@hono/node-server', 'ws'],
73
73
  packageSpecs: {
74
74
  hono: '4.12.31',
75
- '@hono/node-server': '2.0.11',
75
+ '@hono/node-server': '2.1.5',
76
76
  ws: '8.21.1',
77
77
  },
78
78
  enables: [
@@ -37,8 +37,8 @@ export function sealUpstream(metadata) {
37
37
  * `frozen.digest === heldoutDigest(frozen.bundle)`): a spread-copied or edited
38
38
  * record is refused. The seal is an unkeyed integrity digest, not an
39
39
  * authenticity proof, so the holdout inputs are trusted caller inputs built from
40
- * verified HeldoutFrozen and access records (verification of the frozen record
41
- * itself is tracked in #2833). `frozenDigest` is the binding digest in the frozen record.
40
+ * verified HeldoutFrozen and access records via `sealGateHoldoutFromFrozen`
41
+ * in `./heldout.js`. `frozenDigest` is the binding digest pinned by that record.
42
42
  */
43
43
  export function sealGateHoldout(input) {
44
44
  const payload = { frozenDigest: input.frozenDigest, firstAccessedAt: input.firstAccessedAt };
@@ -0,0 +1,42 @@
1
+ // Verify the frozen bundle, its pinned analysis and the independently anchored first-access record.
2
+ import { heldoutDigest } from '../decision/heldout/contract.js';
3
+ import { artifactDigest } from '../decision/validate.js';
4
+ import { evaluateGates, GateEvaluationError, sealGateHoldout } from './evaluate.js';
5
+ /**
6
+ * Derive gate inputs from HeldoutFrozen without altering its historical bytes.
7
+ * The existing bundle contains only corpus, preregistration and approval, so
8
+ * its studyAnalysisDigest must first verify the supplied analysis containing
9
+ * the binding. The access record pins that same analysis (and hence binding).
10
+ * Its timestamp is covered by the independently trusted access digest.
11
+ * Neither an unkeyed digest nor the access record alone authenticates a clock:
12
+ * D29 access/v1 has no signature or frozen-bundle digest. The host must retain
13
+ * the access anchor independently, just as for the existing D29 scorer.
14
+ */
15
+ export function sealGateHoldoutFromFrozen(input) {
16
+ const { frozen, analysis, access, trustedAccessDigest } = input;
17
+ if (!frozen?.bundle || frozen.digest !== heldoutDigest(frozen.bundle)) {
18
+ throw new GateEvaluationError('frozen bundle digest does not match its content');
19
+ }
20
+ const analysisDigest = frozen.bundle.preregistration?.studyAnalysisDigest;
21
+ if (!analysis?.gateBinding || heldoutDigest(analysis) !== analysisDigest) {
22
+ throw new GateEvaluationError('analysis digest does not match the frozen record');
23
+ }
24
+ if (!access || typeof trustedAccessDigest !== 'string'
25
+ || heldoutDigest(access) !== trustedAccessDigest) {
26
+ throw new GateEvaluationError('first-access digest does not match its trusted pin');
27
+ }
28
+ if (access.analysisDigest !== analysisDigest) {
29
+ throw new GateEvaluationError('first-access record does not belong to the frozen analysis and binding');
30
+ }
31
+ if (typeof access.firstTestAccessAt !== 'string' || !Number.isFinite(Date.parse(access.firstTestAccessAt))) {
32
+ throw new GateEvaluationError('first-access timestamp is not a valid date-time');
33
+ }
34
+ const trustedBindingDigest = artifactDigest(analysis.gateBinding);
35
+ return { trustedBindingDigest,
36
+ holdout: sealGateHoldout({ frozenDigest: trustedBindingDigest, firstAccessedAt: access.firstTestAccessAt }) };
37
+ }
38
+ /** Evaluate with a binding pin and holdout seal derived exclusively from the verified records. */
39
+ export function evaluateGatesFromHeldoutFrozen(input) {
40
+ return evaluateGates({ ...input, ...sealGateHoldoutFromFrozen(input) });
41
+ }
42
+ //# sourceMappingURL=heldout.js.map
@@ -6,7 +6,8 @@ export { GATES_API_VERSION, qualifyGateParameter } from './types.js';
6
6
  export { GateSchemaError, validateGateDocument } from './schema.js';
7
7
  export { GateRegistryError, GATE_NAMESPACES, splitPackId, validateResolvedPack, resolveThresholdDefault, assertGateTightens, applyGateExtends, composeGatePack, resolveGateBinding, expandFloorPacks, enforceProjectFloors, authoredGatePacksOf, gateProvidersOf, GateRegistry, } from './registry.js';
8
8
  export { INTEGRITY_CEILING_FLOOR_PACK_ID, INTEGRITY_CEILING_FLOOR_PACK_VERSION, assertCeilingDefaults, projectCeilingSatisfied, resolveProjectFloors, validateGatesConfig, } from './floors.js';
9
- export { GateEvaluationError, maxOutcome, gateStatusOutcome, sealUpstream, sealGateHoldout, evaluateGates, } from './evaluate.js';
9
+ export { GateEvaluationError, maxOutcome, gateStatusOutcome, sealUpstream, evaluateGates, } from './evaluate.js';
10
+ export { sealGateHoldoutFromFrozen, evaluateGatesFromHeldoutFrozen } from './heldout.js';
10
11
  export { assertGateReportDecision, validateGateReport } from './report.js';
11
12
  export { createCoreProviderRegistry, evidenceProvider, pairedProvider, proportionProvider, scalarProvider, screeningProvider } from './providers/index.js';
12
13
  export { MetricProviderRegistry } from './providers/index.js';
@@ -0,0 +1,228 @@
1
+ // Own trusted approval-store I/O, locking, pruning, and explicit approval management.
2
+ import { constants } from 'node:fs';
3
+ import { open, realpath, lstat, stat, mkdir, rename, writeFile, unlink } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { homedir } from 'node:os';
6
+ import { createHash } from 'node:crypto';
7
+ const installedModuleMaxBytes = 5 * 1024 * 1024;
8
+
9
+ // Resolve existing ancestors too: a not-yet-created output can traverse a symlink.
10
+ export async function canonicalFuturePath(filename) {
11
+ try { return await realpath(filename); }
12
+ catch (error) {
13
+ if (error.code !== 'ENOENT') throw error;
14
+ // A dangling link is not a new output: following it may leave the scope.
15
+ try { if ((await lstat(filename)).isSymbolicLink()) throw new Error('Dangling worker path'); }
16
+ catch (statError) { if (statError.code !== 'ENOENT') throw statError; }
17
+ const parent = path.dirname(filename);
18
+ if (parent === filename) throw error;
19
+ return path.join(await canonicalFuturePath(parent), path.basename(filename));
20
+ }
21
+ }
22
+
23
+ export function inside(root, target) {
24
+ const relative = path.relative(root, target);
25
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
26
+ }
27
+
28
+ export async function readInstalledFile(filename) {
29
+ const file = await open(filename, 'r');
30
+ try {
31
+ const stat = await file.stat();
32
+ if (!stat.isFile()) throw new Error('Installed module inputs must be regular files');
33
+ if (stat.size > installedModuleMaxBytes) throw new Error('Installed module input exceeds maxBytes (5 MiB)');
34
+ // Bound the actual read too: an fstat size check alone allows concurrent growth.
35
+ const bytes = Buffer.alloc(installedModuleMaxBytes + 1);
36
+ let length = 0;
37
+ while (length < bytes.length) {
38
+ const { bytesRead } = await file.read(bytes, length, bytes.length - length, null);
39
+ if (!bytesRead) break;
40
+ length += bytesRead;
41
+ }
42
+ if (length > installedModuleMaxBytes) throw new Error('Installed module input exceeds maxBytes (5 MiB)');
43
+ return bytes.subarray(0, length);
44
+ } finally {
45
+ await file.close();
46
+ }
47
+ }
48
+
49
+ export function installationStorePath() {
50
+ const root = process.env.AIWG_CONFIG || path.join(homedir(), '.config/aiwg');
51
+ if (!path.isAbsolute(root)) throw new Error('Installation store must be absolute');
52
+ return path.join(root, 'worker-installations.json');
53
+ }
54
+
55
+ // HOME is the operator's trust boundary; custom stores outside it are checked
56
+ // back to /. O_NOFOLLOW on the store itself does not protect its ancestors.
57
+ export async function assertTrustedStoreAncestors(directory) {
58
+ const home = path.resolve(homedir());
59
+ const boundary = inside(home, directory) ? home : path.parse(directory).root;
60
+ // The store directory itself is checked by the caller.
61
+ if (directory === boundary) return;
62
+ const ancestors = [];
63
+ for (let target = path.dirname(directory); ; target = path.dirname(target)) {
64
+ ancestors.push(target);
65
+ if (target === boundary) break;
66
+ }
67
+ for (const target of ancestors.reverse()) {
68
+ const stat = await lstat(target);
69
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.mode & 0o022
70
+ || process.getuid && stat.uid !== 0 && stat.uid !== process.getuid()) {
71
+ throw new Error(`Untrusted installation store ancestor: ${target}`);
72
+ }
73
+ }
74
+ }
75
+
76
+ export async function assertTrustedStore(filename, writableRoots, repairDirectory = false, apply = false) {
77
+ const changes = [];
78
+ const canonical = await canonicalFuturePath(filename);
79
+ if (canonical !== filename) throw new Error('Symlinked installation store');
80
+ for (const root of writableRoots) {
81
+ if (inside(await realpath(root), canonical)) throw new Error('Worker-writable installation store');
82
+ }
83
+ for (const target of [path.dirname(filename), filename]) {
84
+ try {
85
+ const stat = await lstat(target);
86
+ if (process.getuid && stat.uid !== process.getuid()) throw new Error(`Installation store path is owned by another user: ${target}`);
87
+ if (stat.isSymbolicLink() || stat.isFile() && stat.nlink !== 1
88
+ || target === path.dirname(filename) && !stat.isDirectory()
89
+ || target === filename && !stat.isFile()) throw new Error(`Untrusted installation store permissions: ${target}`);
90
+ if (stat.mode & 0o022) {
91
+ if (!repairDirectory || target !== path.dirname(filename) || !process.getuid) {
92
+ throw new Error(`Untrusted installation store permissions: ${target}`);
93
+ }
94
+ await assertTrustedStoreAncestors(target);
95
+ changes.push({ path: target, action: 'chmod go-w' });
96
+ if (apply) {
97
+ const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
98
+ try {
99
+ const current = await handle.stat();
100
+ if (current.uid !== process.getuid() || current.ino !== stat.ino || current.dev !== stat.dev) {
101
+ throw new Error(`Installation store directory changed: ${target}`);
102
+ }
103
+ await handle.chmod(current.mode & ~0o022);
104
+ } finally { await handle.close(); }
105
+ }
106
+ }
107
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
108
+ }
109
+ return changes;
110
+ }
111
+
112
+ /** Qualification's confirmed write may secure its own directory; ordinary readers never repair. */
113
+ export async function prepareWorkerInstallationStore({ workerWritableRoots, apply = false }) {
114
+ return assertTrustedStore(installationStorePath(), workerWritableRoots, true, apply);
115
+ }
116
+
117
+ export async function readInstallationStore(filename, expectedDigest) {
118
+ try {
119
+ const bytes = await readInstalledFile(filename);
120
+ const digest = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
121
+ if (expectedDigest !== undefined && digest !== expectedDigest) throw new Error('Installation store binding changed');
122
+ const stored = JSON.parse(bytes.toString('utf8'));
123
+ if (stored.version !== 1 || !Array.isArray(stored.registrations) || stored.registrations.length > 128) {
124
+ throw new Error('Unsupported installation record');
125
+ }
126
+ return { stored, digest };
127
+ } catch (error) {
128
+ if (error.code === 'ENOENT' && expectedDigest === undefined) return { stored: { version: 1, registrations: [] }, digest: null };
129
+ throw error;
130
+ }
131
+ }
132
+
133
+ // Serialize readers and writers; a stale lock fails closed and is never stolen.
134
+ export async function withWorkerInstallationStore(writableRoots, operation) {
135
+ const filename = installationStorePath();
136
+ await assertTrustedStore(filename, writableRoots);
137
+ await mkdir(path.dirname(filename), { recursive: true, mode: 0o700 });
138
+ const lockPath = `${filename}.lock`;
139
+ let lock;
140
+ for (let attempt = 0; attempt < 100; attempt++) {
141
+ try { lock = await open(lockPath, 'wx', 0o600); break; }
142
+ catch (error) {
143
+ if (error.code !== 'EEXIST' || attempt === 99) throw error;
144
+ await new Promise(resolve => setTimeout(resolve, 20));
145
+ }
146
+ }
147
+ try {
148
+ await assertTrustedStore(filename, writableRoots);
149
+ const { stored } = await readInstallationStore(filename);
150
+ return await operation({ filename, stored });
151
+ } finally {
152
+ await lock.close();
153
+ await unlink(lockPath);
154
+ }
155
+ }
156
+
157
+ export async function writeWorkerInstallationStore(filename, stored, writableRoots) {
158
+ await assertTrustedStore(filename, writableRoots);
159
+ const temporary = `${filename}.${process.pid}.${createHash('sha256').update(String(Math.random())).digest('hex')}.tmp`;
160
+ try {
161
+ await writeFile(temporary, `${JSON.stringify(stored, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
162
+ await rename(temporary, filename);
163
+ } finally {
164
+ await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });
165
+ }
166
+ }
167
+
168
+ async function workspaceIdentity(workspace) {
169
+ if (typeof workspace !== 'string' || !path.isAbsolute(workspace)) return workspace;
170
+ try { return await realpath(workspace); }
171
+ catch (error) {
172
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
173
+ return path.resolve(workspace);
174
+ }
175
+ }
176
+
177
+ async function workspaceDeleted(workspace) {
178
+ if (typeof workspace !== 'string' || !path.isAbsolute(workspace)) return false;
179
+ try { return !(await stat(workspace)).isDirectory(); }
180
+ catch (error) {
181
+ // Permission and I/O failures do not establish that a workspace was deleted.
182
+ return error.code === 'ENOENT' || error.code === 'ENOTDIR';
183
+ }
184
+ }
185
+
186
+ export async function retainWorkerApprovals(registrations, record) {
187
+ const retained = [];
188
+ for (const entry of registrations) {
189
+ if (await workspaceDeleted(entry.installation?.cwd)) continue;
190
+ const workspace = await workspaceIdentity(entry.installation?.cwd).catch(() => entry.installation?.cwd);
191
+ if (entry.cli !== record.cli || workspace !== record.installation.cwd) retained.push(entry);
192
+ }
193
+ if (retained.length >= 128) throw new Error('Worker installation store is full (128 workspace approvals); run aiwg doctor --probe-workers --forget-approval <workspace-path> [--cli <name>] --yes before qualifying another workspace');
194
+ return [...retained, record];
195
+ }
196
+
197
+ /** Offline inventory of recorded authority; never load a driver or validate launch eligibility. */
198
+ export async function listWorkerApprovals({ cwd, cli }) {
199
+ return withWorkerInstallationStore([cwd], async ({ stored }) => {
200
+ const approvals = [];
201
+ for (const entry of stored.registrations) {
202
+ if (cli && entry.cli !== cli) continue;
203
+ approvals.push({ cli: entry.cli, workspace: entry.installation?.cwd ?? null,
204
+ workspaceExists: !(await workspaceDeleted(entry.installation?.cwd)) });
205
+ }
206
+ return approvals;
207
+ });
208
+ }
209
+
210
+ /** Explicit revocation by exact canonical workspace, including workspaces already deleted. */
211
+ export async function forgetWorkerApproval({ cwd, workspace, cli, yes }) {
212
+ if (yes !== true) throw new Error('Forgetting worker approvals requires --yes');
213
+ const target = await workspaceIdentity(path.resolve(cwd, workspace));
214
+ return withWorkerInstallationStore([cwd], async ({ filename, stored }) => {
215
+ const removed = [];
216
+ const retained = [];
217
+ for (const entry of stored.registrations) {
218
+ const identity = await workspaceIdentity(entry.installation?.cwd);
219
+ if (identity === target && (!cli || entry.cli === cli)) {
220
+ removed.push({ cli: entry.cli, workspace: entry.installation.cwd });
221
+ } else retained.push(entry);
222
+ }
223
+ if (!removed.length) throw new Error(`No worker approval found for ${target}${cli ? ` (CLI ${cli})` : ''}`);
224
+ stored.registrations = retained;
225
+ await writeWorkerInstallationStore(filename, stored, [cwd]);
226
+ return removed;
227
+ });
228
+ }