@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,85 @@
1
+ const ARXIV = '(?:\\d{4}\\.\\d{4,5}|[a-z][a-z.-]*(?:\\.[A-Z]{2})?/\\d{7})(?:v\\d+)?';
2
+ /** Parse abs/pdf/html URLs, arXiv DOIs, new/old IDs and an optional version. */
3
+ export function parseArxivId(input) {
4
+ const text = input.trim().replace(/\.pdf(?:[?#].*)?$/i, '').replace(/[?#].*$/, '');
5
+ const match = text.match(new RegExp(`^(?:(?:https?://(?:export\\.)?arxiv\\.org/(?:abs|pdf|html)/)|(?:https?://(?:dx\\.)?doi\\.org/)?10\\.48550/arxiv\\.|arxiv:\\s*)?(${ARXIV})$`, 'i'));
6
+ if (!match)
7
+ return undefined;
8
+ const version = match[1].match(/v(\d+)$/i);
9
+ return { id: match[1].replace(/v\d+$/i, '').toLowerCase(), ...(version ? { version: Number(version[1]) } : {}) };
10
+ }
11
+ /** Canonical DOI spelling, including DOI URLs; trailing citation punctuation is ignored. */
12
+ export function normalizeDoi(input) {
13
+ let text = input.trim().replace(/^(?:https?:\/\/(?:dx\.)?doi\.org\/|doi:\s*)/i, '');
14
+ try {
15
+ text = decodeURIComponent(text);
16
+ }
17
+ catch { /* Keep a literal DOI on malformed escapes. */ }
18
+ text = text.replace(/[.,;]+$/, '');
19
+ while (text.endsWith(')') && (text.match(/\)/g)?.length ?? 0) > (text.match(/\(/g)?.length ?? 0))
20
+ text = text.slice(0, -1);
21
+ return /^10\.\d{4,9}\/\S+$/i.test(text) ? text.toLowerCase() : undefined;
22
+ }
23
+ /** Parse a recognized identifier even when embedded in a bibliography line. */
24
+ export function parseResearchIdentifier(input) {
25
+ const arxiv = input.match(new RegExp(`(?:https?://(?:export\\.)?arxiv\\.org/(?:abs|pdf|html)/|(?:https?://(?:dx\\.)?doi\\.org/)?10\\.48550/arxiv\\.|arxiv:\\s*)${ARXIV}(?:\\.pdf)?(?:[?#][^\\s<>]*)?|(?<![\\w./])${ARXIV}(?![\\w.])`, 'i'));
26
+ if (arxiv) {
27
+ const parsed = parseArxivId(arxiv[0]);
28
+ if (parsed)
29
+ return { kind: 'arxiv', ...parsed, matched: arxiv[0] };
30
+ }
31
+ const doi = input.match(/(?:https?:\/\/(?:dx\.)?doi\.org\/|doi:\s*)?10\.\d{4,9}\/[^\s<>"\]]+/i);
32
+ if (doi) {
33
+ const id = normalizeDoi(doi[0]);
34
+ if (id)
35
+ return { kind: 'doi', id, matched: doi[0] };
36
+ }
37
+ const review = input.match(/https?:\/\/(?:www\.)?openreview\.net\/(?:forum|pdf)\?[^\s<>]*/i);
38
+ if (review) {
39
+ const id = new URL(review[0]).searchParams.get('id');
40
+ if (id)
41
+ return { kind: 'openreview', id, matched: review[0] };
42
+ }
43
+ const reviewId = input.match(/\bopenreview:\s*([\w-]+)/i);
44
+ if (reviewId)
45
+ return { kind: 'openreview', id: reviewId[1], matched: reviewId[0] };
46
+ const acl = input.match(/https?:\/\/(?:www\.)?aclanthology\.org\/([\w.-]+)\/?(?:[?#][^\s<>]*)?|\bacl:\s*([\w.-]+)|\b((?:\d{4}\.[a-z][\w-]*\.\d+|[A-Z]\d{2}-\d{4}))\b/i);
47
+ if (acl)
48
+ return { kind: 'acl', id: (acl[1] ?? acl[2] ?? acl[3]).replace(/\.pdf$/i, ''), matched: acl[0] };
49
+ const s2 = input.match(/https?:\/\/(?:www\.)?semanticscholar\.org\/paper\/(?:[^\s/]+\/)?([a-f\d]{40})\b|\b(?:s2|semanticscholar):\s*([a-f\d]{40})\b|\b(CorpusId:\d+)\b/i);
50
+ if (s2)
51
+ return { kind: 's2', id: (s2[1] ?? s2[2] ?? s2[3]).toLowerCase().replace(/^corpusid:/, 'CorpusId:'), matched: s2[0] };
52
+ return undefined;
53
+ }
54
+ /** Remove LaTeX formatting while retaining its text, then normalize Unicode and punctuation. */
55
+ export function normalizeTitle(input) {
56
+ return input.normalize('NFKC')
57
+ .replace(/\\(?:begin|end)\{[^}]*\}/g, ' ')
58
+ .replace(/\\[a-zA-Z]+\*?/g, '')
59
+ .replace(/\\([^a-zA-Z])/g, '$1')
60
+ .toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, ' ')
61
+ .replace(/\s+/g, ' ').trim();
62
+ }
63
+ /** Accept both corpus frontmatter spellings and canonical client metadata. */
64
+ export function normalizeIdentity(value) {
65
+ const fields = value;
66
+ const str = (...keys) => keys.map(k => fields[k])
67
+ .map(v => typeof v === 'number' && Number.isFinite(v) ? String(v) : v)
68
+ .find(v => typeof v === 'string' && v.trim());
69
+ const arxiv = parseArxivId(str('arxivId', 'arxiv_id', 'arxiv') ?? '') ?? parseArxivId(str('doi') ?? '');
70
+ return {
71
+ ...(arxiv ? { arxivId: arxiv.id, arxivVersion: arxiv.version ?? (typeof fields.arxivVersion === 'number' ? fields.arxivVersion : undefined) } : {}),
72
+ doi: normalizeDoi(str('doi', 'DOI') ?? ''),
73
+ s2PaperId: str('s2PaperId', 's2_paper_id', 'paperId')?.toLowerCase(),
74
+ openReviewId: str('openReviewId', 'openreview_id'),
75
+ aclId: str('aclId', 'acl_id'),
76
+ title: str('title') ? normalizeTitle(str('title')) : undefined,
77
+ };
78
+ }
79
+ /** Stable keys for matching any identifier or a normalized title across corpus sources. */
80
+ export function identityKeys(value) {
81
+ const identity = normalizeIdentity(value);
82
+ return ['arxivId', 'doi', 's2PaperId', 'openReviewId', 'aclId', 'title']
83
+ .flatMap(key => identity[key] ? [`${key}:${identity[key]}`] : []);
84
+ }
85
+ //# sourceMappingURL=identity.js.map
@@ -4,6 +4,7 @@
4
4
  * @module research
5
5
  */
6
6
  export * from './types.js';
7
+ export * from './identity.js';
7
8
  export * from './clients/base.js';
8
9
  export * from './clients/semantic-scholar.js';
9
10
  export * from './clients/crossref.js';
@@ -0,0 +1,89 @@
1
+ // Parse partial citations and score distinct candidate identities without choosing close matches.
2
+ import { normalizeIdentity, normalizeTitle, parseResearchIdentifier } from './identity.js';
3
+ /** Common quoted, APA-style and title-plus-year citations; retain the untouched input. */
4
+ export function parsePartialReference(input, year) {
5
+ const identifier = parseResearchIdentifier(input);
6
+ let rest = identifier ? input.replace(identifier.matched, '') : input;
7
+ rest = rest.replace(/^\s*\[\d+\]\s*/, '').trim();
8
+ const quoted = rest.match(/["“]([^"”]+)["”]/);
9
+ const apa = rest.match(/^(.+?)\s*\(((?:18|19|20|21)\d{2})\)\.?\s+(.+)$/);
10
+ const authorYear = rest.match(/^(.+?(?:et al\.|,\s*[A-Z]\.))\s*((?:18|19|20|21)\d{2})\.?\s+(.+)$/);
11
+ const bibliography = apa ?? authorYear;
12
+ // A number inside a title is not publication metadata; require citation cues.
13
+ const date = (quoted ? rest.replace(quoted[0], '') : rest).match(/\(((?:18|19|20|21)\d{2})\)/);
14
+ const inferredYear = bibliography?.[2] ?? date?.[1];
15
+ const firstAuthor = bibliography?.[1].split(/,|\s+et al\.|\s+and\s+|\s+&\s+/)[0].trim();
16
+ if (quoted)
17
+ rest = quoted[1];
18
+ else if (bibliography)
19
+ rest = bibliography[3].split(/\.\s+/)[0];
20
+ else if (date)
21
+ rest = rest.replace(date[0], '');
22
+ rest = rest.replace(/^[\s.,;:()[\]{}"']+|[\s.,;:()[\]{}"']+$/g, '').trim();
23
+ return { input, identifier, title: normalizeTitle(rest) ? rest : undefined, year: year ?? (inferredYear ? Number(inferredYear) : undefined), firstAuthor };
24
+ }
25
+ /** Jaccard token-set similarity avoids substring matches scoring as exact titles. */
26
+ export function titleSimilarity(left, right) {
27
+ const a = new Set(normalizeTitle(left).split(' ').filter(Boolean));
28
+ const b = new Set(normalizeTitle(right).split(' ').filter(Boolean));
29
+ const union = new Set([...a, ...b]).size;
30
+ return union ? [...a].filter(token => b.has(token)).length / union : 0;
31
+ }
32
+ function surname(name) {
33
+ return normalizeTitle(name.includes(',') ? name.split(',')[0] : name.trim().split(/\s+/).at(-1) ?? '');
34
+ }
35
+ /** Title weight .9; supplied year and first author each add .05, then renormalize. */
36
+ export function scorePaper(reference, paper, verifiedId = false) {
37
+ const title = reference.title ? titleSimilarity(reference.title, paper.title) : (verifiedId ? 1 : 0);
38
+ const parts = { title };
39
+ let sum = 0.9 * title;
40
+ let weight = 0.9;
41
+ if (reference.year !== undefined) {
42
+ parts.year = paper.year === reference.year ? 1 : 0;
43
+ sum += 0.05 * parts.year;
44
+ weight += 0.05;
45
+ }
46
+ if (reference.firstAuthor) {
47
+ parts.first_author = surname(reference.firstAuthor) === surname(paper.authors[0]?.name ?? '') ? 1 : 0;
48
+ sum += 0.05 * parts.first_author;
49
+ weight += 0.05;
50
+ }
51
+ if (verifiedId)
52
+ parts.identifier = 1;
53
+ return { paper, score: sum / weight, score_parts: parts };
54
+ }
55
+ /** Apply inclusive approved boundaries; epsilon only compensates floating-point subtraction. */
56
+ export function classifyCandidates(candidates) {
57
+ const best = candidates[0]?.score ?? 0;
58
+ if (best + 1e-12 < 0.6)
59
+ return 'unresolved';
60
+ const margin = best - (candidates[1]?.score ?? 0);
61
+ return best + 1e-12 >= 0.92 && margin + 1e-12 >= 0.05 ? 'resolved' : 'ambiguous';
62
+ }
63
+ /** Merge only corroborated identifiers; title equality alone does not establish identity. */
64
+ export function mergePapers(papers) {
65
+ const merged = [];
66
+ for (const paper of papers) {
67
+ const identity = normalizeIdentity(paper);
68
+ const previous = merged.find(existing => {
69
+ const other = normalizeIdentity(existing);
70
+ const ids = ['arxivId', 'doi', 's2PaperId', 'openReviewId', 'aclId'];
71
+ if (ids.some(key => identity[key] && other[key] && identity[key] !== other[key]))
72
+ return false;
73
+ return ids.some(key => identity[key] && identity[key] === other[key]);
74
+ });
75
+ if (!previous) {
76
+ merged.push({ ...paper });
77
+ continue;
78
+ }
79
+ // Source order determines metadata precedence; later sources only fill missing fields.
80
+ for (const [key, value] of Object.entries(paper)) {
81
+ if (value !== undefined && (!previous[key] ||
82
+ (Array.isArray(previous[key]) && previous[key].length === 0))) {
83
+ previous[key] = value;
84
+ }
85
+ }
86
+ }
87
+ return merged;
88
+ }
89
+ //# sourceMappingURL=reference-match.js.map
@@ -0,0 +1,2 @@
1
+ export function renderCoreStartup(rules: Array<{ name: string; coreBody?: string }>): string;
2
+ export function ensureCoreStartup(content: string): string;
@@ -0,0 +1,31 @@
1
+ /** Share compact core rendering between provider deployment and fresh regeneration. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { findPackageRoot } from '../cli/find-package-root.js';
6
+ import { parseRuleFrontmatter, readCoreBody, validateCoreSet } from './activation.mjs';
7
+
8
+ export function renderCoreStartup(rules) {
9
+ const cores = [...new Map(rules.filter(rule => rule.coreBody !== undefined).map(rule => [rule.name, rule])).values()];
10
+ const errors = validateCoreSet(cores.map(rule => ({ name: rule.name, text: rule.coreBody })));
11
+ if (errors.length) throw new Error(errors.join('; '));
12
+ return cores.length ? `<!-- AIWG:rule-core:start -->\n## Core rules\n\n${cores.map(rule => rule.coreBody).join('\n\n')}\n<!-- AIWG:rule-core:end -->\n` : '';
13
+ }
14
+
15
+ export function ensureCoreStartup(content) {
16
+ // Deployment has already selected and validated the project's core set.
17
+ if (content.includes('<!-- AIWG:rule-core:start -->')) return content;
18
+ const root = findPackageRoot(path.dirname(fileURLToPath(import.meta.url)));
19
+ if (!root) throw new Error('AIWG package unavailable; run aiwg use before regenerating context.');
20
+ const dir = path.join(root, 'agentic/code/addons/aiwg-utils/rules');
21
+ if (!fs.existsSync(dir)) throw new Error('Core rule sources unavailable; run aiwg use before regenerating context.');
22
+ const rules = fs.readdirSync(dir).filter(name => name.endsWith('.md') && !name.endsWith('.core.md')).flatMap(name => {
23
+ const file = path.join(dir, name);
24
+ const parsed = parseRuleFrontmatter(fs.readFileSync(file, 'utf8'));
25
+ if (!parsed.valid) throw new Error(`Invalid core rule source ${file}; run aiwg use after repairing it.`);
26
+ return parsed.rule.activation === 'core' ? [{ name: parsed.data.name || path.basename(file, '.md'), coreBody: readCoreBody(file) }] : [];
27
+ });
28
+ const block = renderCoreStartup(rules);
29
+ if (!block) throw new Error('No core rule sources found; run aiwg use before regenerating context.');
30
+ return `${content}${content.endsWith('\n') ? '\n' : '\n\n'}${block}`;
31
+ }
@@ -0,0 +1,34 @@
1
+ import { buildProviderBootstrapBlock } from './workspace-context.js';
2
+ const AIWG_SIGNATURE_COMMENT = '<!-- aiwg-managed -->';
3
+ /**
4
+ * Build the full AGENTS.md content (in-memory; does not write).
5
+ *
6
+ * Per operator direction (#1239): AGENTS.md is a thin pointer to AIWG.md at
7
+ * project root. AIWG.md mirrors CLAUDE.md (ADR-1 §0.5) and contains the full
8
+ * framework guidance — including the kernel-skill discovery pattern
9
+ * (`aiwg discover` / `aiwg show`). Inlining a full link-index here pushed the
10
+ * file past Codex's 32KB cap on real deploys, triggered auto-split, and ran
11
+ * every artifact description through the sanitizer (rejecting any with
12
+ * backticks). The thin-pointer body sidesteps all of that: zero warnings on
13
+ * any provider, regardless of how many artifacts are deployed.
14
+ *
15
+ * `opts.sections` is accepted for backwards compatibility with callers that
16
+ * still aggregate a link-index (no internal use). `splitOccurred` is always
17
+ * false; `spilloverContent` is always empty. The `partitionForOverflow` /
18
+ * spillover utilities remain exported for any external consumer.
19
+ */
20
+ export async function buildAgentsMd(opts) {
21
+ const warnings = [];
22
+ const parts = [];
23
+ parts.push('# AGENTS.md');
24
+ parts.push(`${AIWG_SIGNATURE_COMMENT}`);
25
+ parts.push('<!-- Generated by AIWG. Edit AGENTS.override.md for operator additions. -->');
26
+ parts.push('');
27
+ parts.push(buildProviderBootstrapBlock(opts.provider));
28
+ parts.push('');
29
+ if (opts.projectContext && opts.projectContext.trim().length > 0) {
30
+ warnings.push('projectContext is no longer inlined in provider startup files; place it in the protected WORKSPACE.md operator section.');
31
+ }
32
+ return { content: parts.join('\n'), warnings, spilloverContent: '', splitOccurred: false };
33
+ }
34
+ //# sourceMappingURL=agents-md.js.map
@@ -62,6 +62,9 @@ export async function buildAiwgMdContent(projectPath, stagedClaudeMdContent) {
62
62
  // that managed block here too so legacy duplicate policy never reaches
63
63
  // AIWG.md, even on the first refresh. Operator content stays untouched.
64
64
  claudeMdContent = dedupeProviderBootstrap(claudeMdContent);
65
+ // Each provider startup owns core and hooks; mirroring them would load a
66
+ // second copy through the shared framework companion.
67
+ claudeMdContent = claudeMdContent.replace(/<!-- AIWG:(rule-core|rule-startup|rule-hook-[\w-]+):start -->[\s\S]*?<!-- AIWG:\1:end -->\r?\n?/g, '');
65
68
  const start = claudeMdContent.indexOf(CLAUDE_HOOK_START);
66
69
  const end = claudeMdContent.indexOf(CLAUDE_HOOK_END, start);
67
70
  if (start >= 0 && end >= start) {
@@ -0,0 +1,50 @@
1
+ // Migrate startup ownership without nesting markers or discarding operator text.
2
+ export const AGENTS_HEADER = '# AGENTS.md\n<!-- aiwg-managed -->\n<!-- Generated by AIWG. Edit AGENTS.override.md for operator additions. -->\n';
3
+ const bootstrapBlock = /<!-- AIWG:provider-bootstrap:start -->[\s\S]*?<!-- AIWG:provider-bootstrap:end -->/g;
4
+ export const hasRuleStartup = (content) => /<!-- AIWG:rule-hook-[\w-]+:start -->/.test(content);
5
+ export function retireLegacyBridge(content) {
6
+ return content.replace(/\n\n---\n\n<!-- BEGIN AIWG-managed \(auto-generated;[^\n]*-->[\s\S]*?<!-- END AIWG-managed -->\n?/g, '\n')
7
+ .replace(/<!-- BEGIN AIWG-managed \(auto-generated;[^\n]*-->[\s\S]*?<!-- END AIWG-managed -->\n?/g, '');
8
+ }
9
+ export function normalizeRuleStartup(content, bootstrap, agentsHeader = false, retireLegacy = true) {
10
+ if (retireLegacy)
11
+ content = retireLegacyBridge(content);
12
+ // Retire context-hook's generated body; retain agents-md's enclosed content.
13
+ content = content.replace(/<!-- AIWG:context-hook:start -->[\s\S]*?<!-- AIWG:context-hook:end -->\r?\n?/g, '')
14
+ .replace(/<!-- AIWG:agents-md:(?:start|end) -->\r?\n?/g, '')
15
+ .replace(/\n## For Hermes Sessions\n\nHermes does not auto-load AIWG\.md\. Browse AIWG capabilities with:\n\n- `artifact-read AIWG\.md` through AIWG MCP\.\n- `aiwg discover "<intent>"` and `aiwg show <type> <name>`\.\n- `delegate_task` through the AIWG-orchestrate skill\.\n/, '');
16
+ if (retireLegacy)
17
+ content = content.replace(/## Framework Context\r?\n[\s\S]*?\*See `AGENTS.override.md` for operator-authored additions\.\*\r?\n?/g, '');
18
+ if (content.includes('<!-- AIWG:rule-core:start -->')) {
19
+ content = content.replace(/<!-- AIWG:core-rules:(?:start|end) -->\r?\n?/g, '');
20
+ }
21
+ let installed = false;
22
+ content = content.replace(bootstrapBlock, () => {
23
+ if (installed)
24
+ return '';
25
+ installed = true;
26
+ return bootstrap;
27
+ });
28
+ if (!installed)
29
+ content = `${content}${content.endsWith('\n') ? '\n' : '\n\n'}${bootstrap}\n`;
30
+ if (agentsHeader && !content.startsWith(AGENTS_HEADER)) {
31
+ content = content.replace(/^# AGENTS\.md\r?\n/gm, '')
32
+ .replace(/^<!-- (?:aiwg-managed|Generated by AIWG\.[^\n]*) -->\r?\n?/gm, '');
33
+ // Round 3 left the old generated Framework Context separator at the top.
34
+ content = content.replace(/^(?:[ \t]*\r?\n)*---[ \t]*\r?\n/, '').replace(/^\s+/, '');
35
+ content = `${AGENTS_HEADER}\n${content}`;
36
+ }
37
+ return content;
38
+ }
39
+ export function preserveBridgeOperatorText(existing, generated) {
40
+ if (!generated.startsWith(AGENTS_HEADER) || !existing)
41
+ return generated;
42
+ const fallback = generated.match(bootstrapBlock)?.[0];
43
+ if (!fallback)
44
+ return generated;
45
+ // Rule deployment owns the bootstrap when its hooks are present. Standalone
46
+ // regeneration supplies it only for files without an installed rule startup.
47
+ const bootstrap = hasRuleStartup(existing) ? existing.match(bootstrapBlock)?.[0] || fallback : fallback;
48
+ return normalizeRuleStartup(existing, bootstrap, true);
49
+ }
50
+ //# sourceMappingURL=bridge-ownership.js.map
@@ -1,17 +1,9 @@
1
- /**
2
- * Canonical WORKSPACE.md context graph and provider adapter generator.
3
- *
4
- * WORKSPACE.md owns provider-neutral project/operator context; AIWG.md owns
5
- * generated discovery detail; provider startup files are minimal adapters.
6
- *
7
- * This file contains the public generator API. Callers are expected to have already
8
- * deployed artifacts and to pass pre-aggregated `AgentsMdSection[]` describing what
9
- * was deployed. The generator does not walk the filesystem to discover artifacts;
10
- * that's the caller's responsibility (per ADR-1 §7 generator-runs-after-deploy
11
- * invariant — the caller knows what landed).
12
- */
1
+ // Generate canonical workspace context and provider adapters after artifact deployment.
2
+ import { ensureCoreStartup } from '../../rules/core-startup.mjs';
3
+ import { preserveBridgeOperatorText } from './bridge-ownership.js';
13
4
  import { promises as fs } from 'node:fs';
14
5
  import * as path from 'node:path';
6
+ import { readdirSync, readFileSync } from 'node:fs';
15
7
  import { sanitizeDescription, sanitizeTags } from './sanitizer.js';
16
8
  import { checkPathAllowed } from './allowlist.js';
17
9
  import { generateAiwgMd } from './aiwg-md.js';
@@ -21,8 +13,19 @@ import { shouldEmitAgentsMd, shouldEmitAiwgMd, shouldEmitClaudeMdHook } from './
21
13
  import { ensureClaudeMdHook } from './claude-hook.js';
22
14
  import { ensureManagedHook } from './managed-hook.js';
23
15
  import { assertSafeContextFile, writeContextFileSync } from './context-file-safety.js';
24
- import { buildProviderBootstrapBlock, ensureWorkspaceContext, registerProviderContext, } from './workspace-context.js';
25
- import { projectControlPath } from '../../config/project-artifacts.js';
16
+ import { ensureWorkspaceContext, registerProviderContext, } from './workspace-context.js';
17
+ import { buildAgentsMd } from './agents-md.js';
18
+ /** True when deployed native Claude rules already carry the compact core set. */
19
+ function hasNativeClaudeCore(projectDir) {
20
+ try {
21
+ return readdirSync(path.join(projectDir, '.claude', 'rules'))
22
+ .some(name => /^core-.+\.md$/.test(name) && /aiwg:managed/.test(readFileSync(path.join(projectDir, '.claude', 'rules', name), 'utf8')));
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ export { buildAgentsMd } from './agents-md.js';
26
29
  const SECTION_TITLES = {
27
30
  agents: 'Agents',
28
31
  rules: 'Rules',
@@ -108,54 +111,6 @@ export function renderSection(section) {
108
111
  warnings,
109
112
  };
110
113
  }
111
- /**
112
- * Build the full AGENTS.md content (in-memory; does not write).
113
- *
114
- * Per operator direction (#1239): AGENTS.md is a thin pointer to AIWG.md at
115
- * project root. AIWG.md mirrors CLAUDE.md (ADR-1 §0.5) and contains the full
116
- * framework guidance — including the kernel-skill discovery pattern
117
- * (`aiwg discover` / `aiwg show`). Inlining a full link-index here pushed the
118
- * file past Codex's 32KB cap on real deploys, triggered auto-split, and ran
119
- * every artifact description through the sanitizer (rejecting any with
120
- * backticks). The thin-pointer body sidesteps all of that: zero warnings on
121
- * any provider, regardless of how many artifacts are deployed.
122
- *
123
- * `opts.sections` is accepted for backwards compatibility with callers that
124
- * still aggregate a link-index (no internal use). `splitOccurred` is always
125
- * false; `spilloverContent` is always empty. The `partitionForOverflow` /
126
- * spillover utilities remain exported for any external consumer.
127
- */
128
- export async function buildAgentsMd(opts) {
129
- const warnings = [];
130
- const parts = [];
131
- parts.push('# AGENTS.md');
132
- parts.push(`${AIWG_SIGNATURE_COMMENT}`);
133
- parts.push('<!-- Generated by AIWG. Edit AGENTS.override.md for operator additions. -->');
134
- parts.push('');
135
- parts.push(buildProviderBootstrapBlock(opts.provider));
136
- parts.push('');
137
- parts.push('## Framework Context');
138
- parts.push('');
139
- parts.push('See [AIWG.md](./AIWG.md) for the full AIWG framework context');
140
- parts.push('(active frameworks, addons, agents, behaviors, rules).');
141
- const configRelative = path.relative(opts.projectPath, projectControlPath(opts.projectPath, 'aiwg.config')).replace(/\\/g, '/');
142
- const configLink = configRelative.startsWith('.') ? configRelative : `./${configRelative}`;
143
- parts.push(`Tracker and delivery source of truth: [${configRelative}](${configLink}).`);
144
- parts.push('');
145
- parts.push('Deployed artifacts live under your provider\'s native directory');
146
- parts.push('(for example `.codex/agents/`, `.warp/agents/`, `.github/agents/`).');
147
- parts.push('Use `aiwg discover "<intent>"` and `aiwg show <type> <name>` to browse');
148
- parts.push('skills, agents, rules, and commands across the installation.');
149
- parts.push('');
150
- if (opts.projectContext && opts.projectContext.trim().length > 0) {
151
- warnings.push('projectContext is no longer inlined in provider startup files; place it in the protected WORKSPACE.md operator section.');
152
- }
153
- parts.push('---');
154
- parts.push('');
155
- parts.push('*See `AGENTS.override.md` for operator-authored additions.*');
156
- parts.push('');
157
- return { content: parts.join('\n'), warnings, spilloverContent: '', splitOccurred: false };
158
- }
159
114
  /**
160
115
  * Detect whether a pre-existing file at `filePath` carries the AIWG signature.
161
116
  *
@@ -172,6 +127,14 @@ export async function isOverwriteSafe(filePath) {
172
127
  return true;
173
128
  if (/Generated by\s+(AIWG|aiwg)/i.test(head))
174
129
  return true;
130
+ // Provider templates use a different ownership marker. Adopt only wholly
131
+ // generated files; text outside managed blocks still belongs to the operator.
132
+ if (content.includes('<!-- BEGIN AIWG-managed (auto-generated;')) {
133
+ const remainder = content
134
+ .replace(/<!-- BEGIN AIWG-managed \(auto-generated;[^\n]*-->[\s\S]*?<!-- END AIWG-managed -->/g, '')
135
+ .replace(/<!-- AIWG:([\w-]+):start -->[\s\S]*?<!-- AIWG:\1:end -->/g, '');
136
+ return remainder.trim().length === 0;
137
+ }
175
138
  // Backwards-compatibility scan: pre-ADR-1 emitters wrote AGENTS.md /
176
139
  // WARP.md / .hermes.md without the canonical signature. Those files
177
140
  // typically include AIWG-specific markers somewhere in the first ~50
@@ -202,13 +165,21 @@ async function atomicWrite(filePath, content, provider) {
202
165
  // Rule delivery owns this block. Context regeneration runs after deployment
203
166
  // and must retain the selected kernel even when rebuilding the adapter.
204
167
  const existing = await fs.readFile(filePath, 'utf8').catch(() => '');
205
- for (const owner of ['rule-startup', 'hermes-context', 'hermes-routing', 'warp-context']) {
168
+ content = preserveBridgeOperatorText(existing, content);
169
+ for (const owner of ['rule-startup', 'rule-core', ...[...existing.matchAll(/<!-- AIWG:(rule-hook-[\w-]+):start -->/g)].map(match => match[1]), 'hermes-context', 'hermes-routing', 'warp-context']) {
206
170
  if (content.includes(`<!-- AIWG:${owner}:start -->`))
207
171
  continue;
208
172
  const managed = existing.match(new RegExp(`<!-- AIWG:${owner}:start -->[\\s\\S]*?<!-- AIWG:${owner}:end -->`));
209
173
  if (managed)
210
174
  content = `${content.trimEnd()}\n\n${managed[0]}\n`;
211
175
  }
176
+ // Claude loads core natively from .claude/rules/core-*.md once deployed; inject into CLAUDE.md
177
+ // only when those native files are absent (for example a regenerate before any `aiwg use`).
178
+ const nativeCore = provider === 'claude' && hasNativeClaudeCore(path.dirname(filePath));
179
+ if (provider && !nativeCore)
180
+ content = ensureCoreStartup(content);
181
+ else if (nativeCore)
182
+ content = content.replace(/\n*<!-- AIWG:rule-core:start -->[\s\S]*?<!-- AIWG:rule-core:end -->\n?/, '\n');
212
183
  const bytes = Buffer.byteLength(content, 'utf8');
213
184
  if (provider === 'codex' && path.basename(filePath) === 'AGENTS.md' && bytes >= 32768) {
214
185
  throw new Error('Codex AGENTS.md exceeds its 32 KB hard cap');
@@ -224,54 +195,16 @@ async function atomicWrite(filePath, content, provider) {
224
195
  *
225
196
  * Hermes scans `.hermes.md` first (priority 1) and falls back to AGENTS.md.
226
197
  * Warp prefers AGENTS.md but tooling expects `WARP.md` to exist. Both are
227
- * written with the same content as AGENTS.md, except Hermes — see
228
- * `applyTwinSuffix` below for the Hermes-specific MCP guidance suffix
229
- * (#1242).
198
+ * written with the same minimal bootstrap content as AGENTS.md.
230
199
  */
231
200
  const TWIN_FILES_BY_PROVIDER = {
232
201
  copilot: ['.github/copilot-instructions.md'],
233
202
  hermes: ['.hermes.md'],
234
203
  warp: ['WARP.md'],
235
204
  };
236
- /**
237
- * Hermes-specific suffix appended to `.hermes.md` (#1242).
238
- *
239
- * The cross-platform AGENTS.md thin pointer (#1239) says *"See [AIWG.md] for
240
- * the full AIWG framework context."* From inside a Hermes turn that link is
241
- * a dead end — Hermes auto-loads AGENTS.md and CLAUDE.md but not AIWG.md.
242
- * The twin file gets a Hermes-correct alternative path so a model running
243
- * inside Hermes knows to call `artifact-read` over MCP rather than chase the
244
- * AIWG.md link.
245
- *
246
- * Suffix is ~390 chars (~95 tokens) — keeps the .hermes.md twin total under
247
- * Hermes's <1,000-char turn-budget target on top of the 579-byte primary.
248
- */
249
- const HERMES_TWIN_SUFFIX = [
250
- '',
251
- '## For Hermes Sessions',
252
- '',
253
- 'Hermes does not auto-load AIWG.md. Browse AIWG capabilities with:',
254
- '',
255
- '- `artifact-read AIWG.md` through AIWG MCP.',
256
- '- `aiwg discover "<intent>"` and `aiwg show <type> <name>`.',
257
- '- `delegate_task` through the AIWG-orchestrate skill.',
258
- '',
259
- ].join('\n');
260
- /**
261
- * Apply provider-specific transformations to twin-file content.
262
- *
263
- * Currently used only for Hermes (#1242). Extend by adding more
264
- * provider-keyed branches as new twin formats need divergence.
265
- */
266
- function applyTwinSuffix(provider, baseContent) {
267
- if (provider === 'hermes') {
268
- return `${baseContent}${HERMES_TWIN_SUFFIX}`;
269
- }
270
- return baseContent;
271
- }
272
205
  /**
273
206
  * Write per-provider twin files (.hermes.md, WARP.md). Twin content is the
274
- * AGENTS.md body plus any provider-specific suffix from `applyTwinSuffix`.
207
+ * same minimal AGENTS.md bootstrap body.
275
208
  * Operator-claimed twin files are not overwritten unless --force is set,
276
209
  * matching the AGENTS.md guard.
277
210
  */
@@ -279,7 +212,7 @@ async function writeTwinFiles(provider, projectPath, agentsMdContent, opts, resu
279
212
  const twinNames = TWIN_FILES_BY_PROVIDER[provider];
280
213
  if (!twinNames || twinNames.length === 0)
281
214
  return;
282
- const twinContent = applyTwinSuffix(provider, agentsMdContent);
215
+ const twinContent = agentsMdContent;
283
216
  for (const twinName of twinNames) {
284
217
  const twinPath = path.join(projectPath, twinName);
285
218
  if (opts.detectExistingFiles && !opts.force) {
@@ -291,6 +224,7 @@ async function writeTwinFiles(provider, projectPath, agentsMdContent, opts, resu
291
224
  result.warnings.push(hook.action === 'unchanged'
292
225
  ? `${twinName} is operator-owned and already loads WORKSPACE.md then AIWG.md — left as-is.`
293
226
  : `${twinName} is operator-owned; ${hook.action} the WORKSPACE.md → AIWG.md hook additively (existing content preserved). Pass --force to replace the whole file.`);
227
+ await atomicWrite(twinPath, await fs.readFile(twinPath, 'utf8'), provider);
294
228
  result.twinPaths.push(twinPath);
295
229
  continue;
296
230
  }
@@ -426,6 +360,7 @@ export async function generate(opts) {
426
360
  // canonical graph hook (preserve operator content; no --force needed) so Codex/
427
361
  // fallback consumers load the generated AIWG.md.
428
362
  const hook = await ensureManagedHook(agentsMdPath, { provider: opts.provider });
363
+ result.agentsMdBytes = await atomicWrite(agentsMdPath, await fs.readFile(agentsMdPath, 'utf8'), opts.provider);
429
364
  result.agentsMdPath = agentsMdPath;
430
365
  result.warnings.push(hook.action === 'unchanged'
431
366
  ? `AGENTS.md is operator-owned and already loads WORKSPACE.md then AIWG.md — left as-is.`
@@ -476,6 +411,7 @@ export async function generate(opts) {
476
411
  force: opts.force,
477
412
  detectExistingFiles: opts.detectExistingFiles,
478
413
  });
414
+ await atomicWrite(hookResult.claudeMdPath, await fs.readFile(hookResult.claudeMdPath, 'utf8'), opts.provider);
479
415
  result.claudeMdHookPath = hookResult.claudeMdPath;
480
416
  result.claudeMdHookAction = hookResult.action;
481
417
  if (hookResult.backupPath) {
@@ -16,6 +16,7 @@ import * as path from 'path';
16
16
  import { buildProviderBootstrapBlock } from './workspace-context.js';
17
17
  import { dominantLineEnding, withLineEnding } from './line-endings.js';
18
18
  import { assertSafeContextFile, writeContextFileSync } from './context-file-safety.js';
19
+ import { hasRuleStartup, normalizeRuleStartup } from './bridge-ownership.js';
19
20
  export const CONTEXT_HOOK_START = '<!-- AIWG:context-hook:start -->';
20
21
  export const CONTEXT_HOOK_END = '<!-- AIWG:context-hook:end -->';
21
22
  /** The managed block — loads canonical workspace context before framework context. */
@@ -61,6 +62,15 @@ export async function ensureManagedHook(filePath, opts = {}) {
61
62
  }
62
63
  const lineEnding = dominantLineEnding(existing);
63
64
  block = withLineEnding(block, lineEnding);
65
+ if (hasRuleStartup(existing)) {
66
+ const bootstrap = existing.match(/<!-- AIWG:provider-bootstrap:start -->[\s\S]*?<!-- AIWG:provider-bootstrap:end -->/)?.[0]
67
+ || buildProviderBootstrapBlock(opts.provider || 'codex');
68
+ const normalized = normalizeRuleStartup(existing, bootstrap, false, false);
69
+ result.action = normalized === existing ? 'unchanged' : 'updated';
70
+ if (normalized !== existing)
71
+ writeContextFileSync(filePath, normalized, 'utf8');
72
+ return result;
73
+ }
64
74
  // Already has both bare includes (operator wired them by hand) — nothing to do.
65
75
  if (!existing.includes(CONTEXT_HOOK_START) && /^[ \t]*@WORKSPACE\.md[ \t]*$/m.test(existing) && /^[ \t]*@AIWG\.md[ \t]*$/m.test(existing)) {
66
76
  result.action = 'unchanged';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwg/cli",
3
- "version": "2026.10.14",
3
+ "version": "2026.10.15",
4
4
  "description": "Lightweight AIWG CLI for signed, versioned web-backed resources.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,6 +27,8 @@
27
27
  "THIRD_PARTY_NOTICES.md",
28
28
  "bin/",
29
29
  "agentic/code/providers/",
30
+ "agentic/code/addons/aiwg-utils/rules/anti-laziness.md",
31
+ "agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md",
30
32
  "agentic/code/addons/composition-engine/lib/runtime.mjs",
31
33
  "agentic/code/addons/composition-engine/lib/validator.mjs",
32
34
  "agentic/code/addons/composition-engine/schemas/flow-graph.schema.json",
@@ -137,7 +139,7 @@
137
139
  "zod": "^4.6.6"
138
140
  },
139
141
  "optionalDependencies": {
140
- "@hono/node-server": "2.0.11",
142
+ "@hono/node-server": "2.1.5",
141
143
  "@sigstore/bundle": "4.0.0",
142
144
  "@sigstore/protobuf-specs": "0.5.0",
143
145
  "@sigstore/verify": "3.1.1",