@aiwg/cli 2026.11.7 → 2026.11.8

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 (44) hide show
  1. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +3 -2
  2. package/agentic/code/providers/model-capabilities.v1.json +22 -21
  3. package/agentic/code/providers/model-catalog.v1.json +11 -10
  4. package/dist/src/cli/handlers/refresh-managed-deployment.js +13 -3
  5. package/dist/src/cli/handlers/refresh-user-hooks.js +102 -0
  6. package/dist/src/cli/handlers/refresh.js +2 -0
  7. package/dist/src/config/worker-guidance-warning.js +8 -0
  8. package/dist/src/extensions/user-hook-diagnostics.js +16 -1
  9. package/dist/src/extensions/verified-hook-command.js +7 -0
  10. package/dist/src/models/cursor-models.js +92 -0
  11. package/dist/src/models/model-capabilities.v1.json +22 -21
  12. package/dist/src/models/model-catalog.v1.json +11 -10
  13. package/dist/src/models/model-discovery.js +4 -3
  14. package/dist/src/models/provider-policy.js +1 -1
  15. package/dist/src/models/worker-health-readiness.js +4 -0
  16. package/dist/src/models/worker-installation.d.mts +2 -0
  17. package/dist/src/models/worker-installation.mjs +8 -2
  18. package/dist/src/models/worker-invocation-policy.js +21 -1
  19. package/dist/src/models/worker-plan.js +3 -1
  20. package/dist/src/models/worker-wiring-diagnostics.js +25 -0
  21. package/dist/src/providers/provider-context-contracts.js +3 -0
  22. package/dist/src/providers/provider-seeds-1.js +1 -1
  23. package/dist/src/smiths/context-pipeline/muse-bridge.js +7 -4
  24. package/dist/src/smiths/context-pipeline/workspace-audit.js +37 -6
  25. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +3 -1
  26. package/dist/src/smiths/context-pipeline/workspace-doctor.js +16 -4
  27. package/dist/src/smiths/context-pipeline/workspace-document.js +4 -2
  28. package/dist/src/smiths/hook-bridge/codex-trust.js +56 -7
  29. package/dist/src/smiths/hook-bridge/cursor-translator.js +89 -0
  30. package/dist/src/smiths/hook-bridge/index.js +4 -1
  31. package/dist/src/writing/contextual-diagnostics.js +2 -1
  32. package/dist/src/writing/current-patterns.catalogue.json +4 -4
  33. package/dist/src/writing/current-patterns.js +2 -2
  34. package/dist/src/writing/structural-patterns.js +23 -6
  35. package/package.json +1 -1
  36. package/tools/agents/providers/cursor-prompt-discovery.mjs +13 -0
  37. package/tools/agents/providers/cursor.mjs +2 -0
  38. package/tools/agents/providers/openclaw-context.mjs +6 -0
  39. package/tools/agents/providers/openclaw.mjs +14 -12
  40. package/tools/agents/providers/rule-delivery-surface.mjs +1 -1
  41. package/tools/agents/providers/rule-deployment-prepare.mjs +1 -0
  42. package/tools/agents/providers/rule-presentation.mjs +1 -1
  43. package/tools/agents/providers/rule-startup.mjs +3 -1
  44. package/vscode-extension/schemas/aiwg.config.v1.json +13 -0
@@ -1,12 +1,18 @@
1
- // Read Codex project trust without granting trust or inventing hook-review storage.
1
+ // Read Codex trust and deduplicate trusted-project advice without granting hook approval.
2
+ import { execFile } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
2
4
  import { promises as fs } from 'node:fs';
3
5
  import { homedir } from 'node:os';
4
6
  import * as path from 'node:path';
7
+ import { promisify } from 'node:util';
5
8
  import { getStaticTOMLValue, parseTOML } from 'toml-eslint-parser';
9
+ import { getUserStateDir } from '../../config/user-state.js';
10
+ import { workerVersionProbeEnvironment } from '../../models/worker-installation.mjs';
11
+ const execFileAsync = promisify(execFile);
6
12
  // Printed after deploy: one line that fits an 80-column terminal.
7
13
  export const CODEX_HOOK_TRUST_NEXT_STEP = 'Trust this project in Codex and approve its AIWG hook; codex exec needs both.';
8
14
  // Full explanation for doctor and docs (#4035).
9
- export const CODEX_EXEC_HOOK_TRUST_DETAIL = 'Codex 0.167 requires saved folder and hook trust for codex exec; a per-run -c project trust override '
15
+ export const CODEX_EXEC_HOOK_TRUST_DETAIL = 'Codex requires saved folder and hook trust for codex exec; a per-run -c project trust override '
10
16
  + 'does not enable project hooks, even with --dangerously-bypass-hook-trust. '
11
17
  + 'Review and save trust interactively for each worker worktree before automation; AIWG never grants trust.';
12
18
  export function codexHookTrustNextStep(trust) {
@@ -28,7 +34,7 @@ export async function readCodexHookTrust(projectPath) {
28
34
  // Missing/broken installations are handled by deployment drift checks.
29
35
  return null;
30
36
  }
31
- // Codex 0.167 has no documented offline file signal for hook review.
37
+ // A notice marker is not evidence of Codex hook approval; keep that state unknown.
32
38
  const trust = { project: 'unknown', hookReview: 'unknown' };
33
39
  const codexHome = process.env.CODEX_HOME || path.join(process.env.HOME || homedir(), '.codex');
34
40
  try {
@@ -42,14 +48,57 @@ export async function readCodexHookTrust(projectPath) {
42
48
  }
43
49
  return trust;
44
50
  }
51
+ async function codexHookAdvisoryAlreadyShown(projectPath) {
52
+ const root = path.resolve(projectPath);
53
+ try {
54
+ const codexHome = path.resolve(process.env.CODEX_HOME || path.join(process.env.HOME || homedir(), '.codex'));
55
+ const registration = await fs.readFile(path.join(root, '.codex/hooks.json'));
56
+ const script = await fs.readFile(path.join(root, '.codex/hooks/aiwg-prompt-discovery.cjs'));
57
+ const digest = createHash('sha256').update(JSON.stringify([root, codexHome,
58
+ registration.toString('base64'), script.toString('base64')])).digest('hex');
59
+ // Empty host-local markers record only that advice was shown, never trust.
60
+ const directory = path.join(getUserStateDir(), 'codex-hook-advisories');
61
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
62
+ try {
63
+ await fs.writeFile(path.join(directory, digest), '', { flag: 'wx', mode: 0o600 });
64
+ }
65
+ catch (error) {
66
+ if (error.code === 'EEXIST')
67
+ return true;
68
+ throw error;
69
+ }
70
+ }
71
+ catch {
72
+ // A missing/unwritable state directory must never silence the diagnostic.
73
+ }
74
+ return false;
75
+ }
76
+ async function detectedCodexVersion(projectPath) {
77
+ try {
78
+ // Cleared environment: the probe needs only PATH, never setup inputs or credentials.
79
+ const { stdout } = await execFileAsync('codex', ['--version'], {
80
+ cwd: path.resolve(projectPath), env: workerVersionProbeEnvironment(), timeout: 2000, maxBuffer: 4096, windowsHide: true,
81
+ });
82
+ return /^codex-cli (\d+\.\d+\.\d+(?:[-+][\w.-]+)?)\s*$/.exec(stdout.trim())?.[1] ?? 'unknown';
83
+ }
84
+ catch {
85
+ return 'unknown';
86
+ }
87
+ }
45
88
  export async function diagnoseCodexHookTrust(projectPath) {
46
89
  const trust = await readCodexHookTrust(projectPath);
47
90
  const nextStep = codexHookTrustNextStep(trust);
48
- return trust && nextStep ? {
49
- // Review state is never observable offline, so a trusted project is only advisory.
91
+ if (!trust || !nextStep)
92
+ return null;
93
+ if (trust.project === 'trusted' && await codexHookAdvisoryAlreadyShown(projectPath))
94
+ return null;
95
+ const version = await detectedCodexVersion(projectPath);
96
+ return {
50
97
  severity: trust.project === 'trusted' ? 'info' : 'warning', code: 'codex-prompt-discovery-trust', path: '.codex/hooks.json',
51
98
  message: 'Codex prompt-discovery hook installed but inactive or unverified (untrusted project or unreviewed hook). '
52
- + `Project trust: ${trust.project}; hook review: ${trust.hookReview}. ${nextStep} ${CODEX_EXEC_HOOK_TRUST_DETAIL}`,
53
- } : null;
99
+ + `Project trust: ${trust.project}; hook review: ${trust.hookReview}. Detected Codex version: ${version}. `
100
+ + `${nextStep} ${CODEX_EXEC_HOOK_TRUST_DETAIL} `
101
+ + 'For trusted projects, this advisory is shown once per hook digest; changes to the script or registration re-raise it.',
102
+ };
54
103
  }
55
104
  //# sourceMappingURL=codex-trust.js.map
@@ -0,0 +1,89 @@
1
+ // Deploy canonical prompt discovery through Cursor's flat beforeSubmitPrompt command array.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { loadHookSources } from './loader.js';
6
+ import { verifiedHookCommand } from '../../extensions/verified-hook-command.js';
7
+ import { managedHookScriptState } from '../../extensions/managed-hook-script-state.js';
8
+ import { captureDeploymentOutputs, recordDeploymentOutputs } from '../../providers/deployment-ownership.mjs';
9
+ export const CURSOR_PROMPT_SCRIPT = '.cursor/hooks/aiwg-prompt-discovery.cjs';
10
+ export function managedCursorPromptHook(root, bytes) {
11
+ return { type: 'command', command: verifiedHookCommand(root, CURSOR_PROMPT_SCRIPT, bytes), timeout: 2,
12
+ _aiwg_managed: true, _aiwg_id: 'aiwg-prompt-discovery' };
13
+ }
14
+ export async function translateForCursor(source, options) {
15
+ const result = { provider: 'cursor', emittedPaths: [], warnings: [], skipped: false };
16
+ if (source.degradeOn?.includes('cursor'))
17
+ return { ...result, skipped: true, skipReason: 'degrade-on declared cursor' };
18
+ if (source.id !== 'aiwg-prompt-discovery' || !source.events.includes('UserPromptSubmit')) {
19
+ return { ...result, skipped: true, skipReason: 'no Cursor-mapped prompt discovery event' };
20
+ }
21
+ if (!source.args?.[0])
22
+ throw new Error('Missing shared prompt discovery script');
23
+ const directory = path.join(options.projectPath, '.cursor');
24
+ const script = path.join(options.projectPath, CURSOR_PROMPT_SCRIPT);
25
+ const config = path.join(directory, 'hooks.json');
26
+ if (options.dryRun)
27
+ return { ...result, emittedPaths: [config, script].map(file => file + ' (dry-run)') };
28
+ for (const file of [directory, config, path.dirname(script), script]) {
29
+ try {
30
+ if ((await fs.lstat(file)).isSymbolicLink())
31
+ throw new Error(`Refusing symlinked Cursor hook target: ${file}`);
32
+ }
33
+ catch (error) {
34
+ if (error.code !== 'ENOENT')
35
+ throw error;
36
+ }
37
+ }
38
+ let existing = '';
39
+ try {
40
+ existing = await fs.readFile(config, 'utf8');
41
+ }
42
+ catch (error) {
43
+ if (error.code !== 'ENOENT')
44
+ throw error;
45
+ }
46
+ const doc = existing ? JSON.parse(existing) : { version: 1, hooks: {} };
47
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc) || !Number.isInteger(doc.version) || doc.version < 1
48
+ || !doc.hooks || typeof doc.hooks !== 'object' || Array.isArray(doc.hooks)
49
+ || Object.values(doc.hooks).some(entries => !Array.isArray(entries)
50
+ || entries.some(entry => !entry || typeof entry !== 'object' || Array.isArray(entry)))) {
51
+ throw new Error(`Invalid Cursor hooks object: ${config}`);
52
+ }
53
+ const before = captureDeploymentOutputs([directory]);
54
+ const bytes = await fs.readFile(source.args[0]);
55
+ const state = await managedHookScriptState(options.projectPath, CURSOR_PROMPT_SCRIPT, bytes);
56
+ if (state === 'operator-edited' || state === 'unreadable')
57
+ result.warnings.push(`${script}: kept (${state})`);
58
+ else {
59
+ await fs.mkdir(path.dirname(script), { recursive: true });
60
+ await fs.writeFile(script, bytes, { mode: 0o755 });
61
+ result.emittedPaths.push(script);
62
+ }
63
+ // Replace only our registration; flat operator entries and other events retain their order.
64
+ const hooks = doc.hooks.beforeSubmitPrompt ?? [];
65
+ doc.hooks.beforeSubmitPrompt = [...hooks.filter((hook) => !(hook._aiwg_managed === true && hook._aiwg_id === source.id)),
66
+ managedCursorPromptHook(options.commandRoot ?? options.projectPath, bytes)];
67
+ await fs.mkdir(directory, { recursive: true });
68
+ const temporary = `${config}.tmp.${randomUUID()}`;
69
+ try {
70
+ await fs.writeFile(temporary, JSON.stringify(doc, null, 2) + '\n', { flag: 'wx' });
71
+ await fs.rename(temporary, config);
72
+ }
73
+ finally {
74
+ await fs.rm(temporary, { force: true });
75
+ }
76
+ result.emittedPaths.push(config);
77
+ recordDeploymentOutputs(before, [directory], { frameworkSlug: 'aiwg-hooks', claimUnchangedSettings: false, writtenFiles: result.emittedPaths });
78
+ return result;
79
+ }
80
+ export async function installCursorPromptDiscovery(options) {
81
+ const { sources, errors } = await loadHookSources(options.frameworkRoot);
82
+ if (errors.length)
83
+ throw new Error(errors.join('\n'));
84
+ const source = sources.find(hook => hook.id === 'aiwg-prompt-discovery');
85
+ if (!source)
86
+ throw new Error('Missing canonical aiwg-prompt-discovery source');
87
+ return translateForCursor(source, options);
88
+ }
89
+ //# sourceMappingURL=cursor-translator.js.map
@@ -12,6 +12,7 @@
12
12
  import path from 'node:path';
13
13
  import { homedir } from 'node:os';
14
14
  import { captureDeploymentOutputs, recordDeploymentOutputs } from '../../providers/deployment-ownership.mjs';
15
+ import { translateForCursor } from './cursor-translator.js';
15
16
  import { translateForCodex } from './codex-translator.js';
16
17
  import { translateForCopilot } from './copilot-translator.js';
17
18
  import { translateForFactory } from './factory-translator.js';
@@ -22,6 +23,7 @@ import { resolveHermesHomePath } from '../../providers/hermes-home.js';
22
23
  export { AIWG_ENV_VARS, NATIVE_ENV_VAR_MAP } from './types.js';
23
24
  export { substituteEnvVars, generateShimBash, EXIT_CODE_MAP } from './shim.js';
24
25
  export { translateForCodex, renderCodexHookToml, injectHookBlock as injectCodexHookBlock } from './codex-translator.js';
26
+ export { translateForCursor, installCursorPromptDiscovery } from './cursor-translator.js';
25
27
  export { translateForCopilot } from './copilot-translator.js';
26
28
  export { translateForFactory, installFactoryPromptDiscovery } from './factory-translator.js';
27
29
  export { translateForHermes } from './hermes-translator.js';
@@ -37,6 +39,7 @@ export { loadHookSources } from './loader.js';
37
39
  */
38
40
  export const TRANSLATORS = {
39
41
  codex: translateForCodex,
42
+ cursor: translateForCursor,
40
43
  copilot: translateForCopilot,
41
44
  factory: translateForFactory,
42
45
  hermes: translateForHermes,
@@ -67,7 +70,7 @@ export async function bridgeAll(sources, providers, options) {
67
70
  continue;
68
71
  }
69
72
  try {
70
- const roots = [path.join(options.projectPath, '.factory/hooks'), path.join(options.projectPath, '.factory/hooks.json'), path.join(options.projectPath, '.github/hooks'),
73
+ const roots = [path.join(options.projectPath, '.cursor/hooks.json'), path.join(options.projectPath, '.cursor/hooks'), path.join(options.projectPath, '.factory/hooks'), path.join(options.projectPath, '.factory/hooks.json'), path.join(options.projectPath, '.github/hooks'),
71
74
  path.join(options.projectPath, '.grok/hooks'), path.join(options.projectPath, '.codex/hooks.json'), path.join(options.projectPath, '.codex/hooks'),
72
75
  path.join(homedir(), '.hermes/plugins'), resolveHermesHomePath('config.yaml'), resolveHermesHomePath('agent-hooks'),
73
76
  resolveHermesHomePath('.aiwg-manifest.json')];
@@ -87,7 +87,8 @@ function diagnoseDocument(content, options, priorParagraphs = new Map(), documen
87
87
  explanation: rule.explanation, suggestion: rule.suggestion, authority: rule.authority,
88
88
  confidence: { kind: 'heuristic', calibrated: false }, resolution: exception ? 'retained' : 'review', ...(exception ? { reason: exception.reason } : {}), ...(rule.tier ? { tier: rule.tier } : {}) });
89
89
  };
90
- const current = language.split('-')[0] === 'en' ? scanCurrentPatterns(maskProse(content, contexts.filter(c => c.context !== 'prose').map(c => ({ ...c, context: 'code' })))) : [];
90
+ // The shared scanner masks automatic quotations; explicit caller contexts stay protected.
91
+ const current = language.split('-')[0] === 'en' ? scanCurrentPatterns(maskProse(content, contexts.filter(c => c.context !== 'prose' && (c.context !== 'quote' || options.contexts?.includes(c))).map(c => ({ ...c, context: 'code' })))) : [];
91
92
  for (const f of [...current, ...campaign]) {
92
93
  const override = rules.get(f.ruleId);
93
94
  if (override?.enabled === false)
@@ -27,7 +27,7 @@
27
27
  {
28
28
  "id": "negate-then-assert",
29
29
  "tier": "check",
30
- "pattern": "\\b(?:(?:is|are|was|were)\\s+not|isn't|aren't)\\s+(?:evidence|proof|a substitute|a replacement|the same|enough|just|only|about)\\b|\\b(?:it|this|that)\\s+does\\s+not\\s+(?:mean|prove|imply)\\b",
30
+ "pattern": "\\b(?:(?:is|are|was|were)\\s+not|isn't|aren't)\\s+(?:evidence|proof|a substitute|a replacement|the same|enough|just|only|about)\\b|\\b(?:it|this|that)\\s+does\\s+not\\s+(?:mean|prove|imply)\\b|\\bit\\s+(?:doesn't|does not)\\s+anymore\\b",
31
31
  "message": "Negated assertion frames the claim.",
32
32
  "fix": "State the positive claim, retaining negation when it corrects a misconception."
33
33
  },
@@ -55,9 +55,9 @@
55
55
  ],
56
56
  "structuralRules": [
57
57
  { "id": "mirrored-sentences", "tier": "cut", "scope": "file", "trigger": "Adjacent sentences share the first two tokens and aligned predicates; exactly one polarity flip or listed antonym supplies a real contrast. Different verbs with a negated opener are insufficient.", "fix": "Combine the useful claim; retain deliberate parallelism with a reason." },
58
- { "id": "aphorism-ending", "tier": "cut", "scope": "file", "trigger": "Paragraph-final explicit moral/lesson opener of 3–10 words; exclude numbers, identifiers and protected spans. Generic closers are not detected.", "fix": "End on the last useful fact or support the claim." },
59
- { "id": "colon-reveal", "tier": "watch", "scope": "file", "trigger": "Setup of 4–12 words ending in a withheld complement, then a sentence-final punchline of 2–10 words. Frequency never triggers a finding. Exclude lists/definitions, digits/citations and protected material.", "fix": "State the subject and consequence directly." },
60
- { "id": "fragment-run", "tier": "check", "scope": "file", "trigger": "At least four consecutive statements with 1–4 words in one prose paragraph; questions break runs and identical-sentence-only runs are excluded.", "fix": "Join fragments to explain the reason or result." },
58
+ { "id": "aphorism-ending", "tier": "cut", "scope": "file", "trigger": "Paragraph-final explicit moral/lesson opener of 3–10 words; allow quoted scenario names inside authored prose but exclude numbers, identifiers, code and wholly quoted statements. Generic closers are not detected.", "fix": "End on the last useful fact or support the claim." },
59
+ { "id": "colon-reveal", "tier": "watch", "scope": "file", "trigger": "Setup of 4–12 words ending in a withheld complement, then a sentence-final punchline of 2–10 words. Also detect a withheld defect followed by an if-clause and a short consequence (at most 16 words after the colon). Frequency never triggers a finding. Exclude lists/definitions, digits/citations and protected material.", "fix": "State the subject and consequence directly." },
60
+ { "id": "fragment-run", "tier": "check", "scope": "file", "trigger": "At least four consecutive statements with 1–4 words in one prose paragraph; questions break runs and identical-sentence-only runs are excluded. Also detect a short consequence, a one-word repair and a final explicit moral; the consequence may follow a conditional comma.", "fix": "Join fragments to explain the reason or result." },
61
61
  { "id": "repeated-sentence", "tier": "cut", "scope": "cross", "trigger": "At least six words repeated within an explicit campaign; case and punctuation are ignored, numbers are retained.", "fix": "Write each channel from its relevant facts." },
62
62
  { "id": "repeated-phrase", "tier": "check", "scope": "cross", "trigger": "An eight-word run inside one sentence shared by at least three distinct documents; overlapping runs merge, affected sentences receive one phrase finding, repeated sentences are excluded.", "fix": "Rewrite the shared run for the reader and channel." },
63
63
  { "id": "shared-skeleton", "tier": "check", "scope": "cross", "trigger": "First or last three words of the first or last prose sentence shared by three distinct documents, including a content word; numbers and versions normalize to num.", "fix": "Lead or close with the useful change for this channel." }
@@ -1,6 +1,6 @@
1
1
  // Local editorial pattern matching shared by validation and contextual diagnostics.
2
2
  import { createRequire } from 'node:module';
3
- import { maskProse } from './prose-mask.js';
3
+ import { maskProse, protectedRegions } from './prose-mask.js';
4
4
  import { structuralPatterns } from './structural-patterns.js';
5
5
  const require = createRequire(import.meta.url);
6
6
  // Package-local copy of the writing-quality addon catalogue (the addon file stays canonical for the
@@ -79,7 +79,7 @@ export function scanCurrentPatterns(content) {
79
79
  }
80
80
  }
81
81
  }
82
- findings.push(...structuralPatterns(prose, catalogue.antonyms));
82
+ findings.push(...structuralPatterns(prose, catalogue.antonyms, maskProse(content, protectedRegions(content).filter(r => r.context !== 'quote'))));
83
83
  return findings.sort((a, b) => a.start - b.start || a.ruleId.localeCompare(b.ruleId));
84
84
  }
85
85
  /** Adapt local findings to the existing validation issue contract. */
@@ -40,7 +40,7 @@ export function proseParagraphs(prose) {
40
40
  }
41
41
  return paragraphs;
42
42
  }
43
- export function structuralPatterns(prose, antonyms) {
43
+ export function structuralPatterns(prose, antonyms, quotedProse = prose) {
44
44
  const out = [];
45
45
  const emit = (ruleId, tier, s, explanation, suggestion) => {
46
46
  out.push({ ruleId, tier, start: s.start, end: s.end, explanation, suggestion });
@@ -79,7 +79,7 @@ export function structuralPatterns(prose, antonyms) {
79
79
  // A reveal withholds its complement, then supplies a short final punchline.
80
80
  // Mere colon frequency, another diagnostic, or a technical definition is insufficient.
81
81
  const colon = s.text.indexOf(':');
82
- if (colon < 0 || colon !== s.text.lastIndexOf(':') || /[\d\u0001`\[\]{};,]/.test(s.text) || !/[.!]$/.test(s.text))
82
+ if (colon < 0 || colon !== s.text.lastIndexOf(':') || /[\d\u0001`\[\]{};]/.test(s.text) || !/[.!]$/.test(s.text))
83
83
  continue;
84
84
  const before = s.text.slice(0, colon), after = s.text.slice(colon + 1).trim();
85
85
  const setup = words(before), punchline = words(after);
@@ -91,18 +91,35 @@ export function structuralPatterns(prose, antonyms) {
91
91
  const predicate = punchline[subject + 1] ?? '';
92
92
  const clause = (subject === 1 || /^(?:it|this|that|we|you|they|he|she|nothing|everything)$/.test(punchline[0]))
93
93
  && /^(?:is|are|was|were|can|will|must|has|had|does|[a-z]+(?:s|ed))$/.test(predicate);
94
- if (clause && setup.length >= 4 && setup.length <= 12 && punchline.length >= 2 && punchline.length <= 10
94
+ const conditional = /^if\b[^,;:]+,\s*(?:nothing|everything|it|this|that|the [a-z]+)\s+(?:[a-z]+(?:s|ed)|is|was|can|will)\b/i.test(after)
95
+ && !/\b(?:and|or)\b|[?!]/i.test(after) && punchline.length <= 16;
96
+ if (conditional && /\b(?:bug|defect|flaw|failure|problem)$/i.test(before.trim()) && setup.length >= 4 && setup.length <= 12 && withheld) {
97
+ emit('colon-reveal', 'watch', { start: s.start + colon, end: s.start + colon + 1 }, 'A short setup reveals its defect through a conditional consequence.', 'State the defect and consequence together.');
98
+ }
99
+ if (clause && !after.includes(',') && setup.length >= 4 && setup.length <= 12 && punchline.length >= 2 && punchline.length <= 10
95
100
  && withheld && !/^(?:["“]|[-*+]|\u0001)/.test(after) && !/\b(?:and|or)\b|:|[?!]/i.test(after)) {
96
101
  emit('colon-reveal', 'watch', { start: s.start + colon, end: s.start + colon + 1 }, 'A short setup withholds a complement until a sentence-final punchline.', 'State the subject and consequence directly; retain real lists, labels and code introductions.');
97
102
  }
98
103
  }
99
104
  flush();
100
105
  const last = sentences.at(-1);
101
- if (!last || last.tokens.length < 3 || last.tokens.length > 10 || /[\d\u0001@/]|[?:]$/.test(last.text))
106
+ if (!last)
107
+ continue;
108
+ // Quoted scenario names may sit inside an authored moral; code stays masked.
109
+ const ending = quotedProse.slice(last.start, last.end).replace(/[‘’]/g, "'");
110
+ if (words(ending).length < 3 || words(ending).length > 10 || /[\d\u0001@/]|[?:]$/.test(ending))
102
111
  continue;
103
- const moral = /^(?:(?:always|never|remember)\b|the (?:point|lesson|moral)\b|(?:that's|that is|it's|it is|this is) the (?:point|lesson|moral)\b)/i.test(last.text);
104
- if (moral)
112
+ const moral = /^(?:(?:always|never|remember)\b|the (?:point|lesson|moral)\b|(?:that's|that is|it's|it is|this is) the (?:point|lesson|moral)\b)/i.test(ending);
113
+ if (moral) {
105
114
  emit('aphorism-ending', 'cut', last, 'A short paragraph-final sentence opens with an explicit moral or lesson.', 'End on the last useful fact, or develop the claim with supported detail.');
115
+ const [consequence, repair] = sentences.slice(-3, -1);
116
+ if (sentences.length >= 3 && !out.some(f => f.ruleId === 'fragment-run' && f.end === last.end) && /^(?:fixed|patched|repaired|resolved)[.!]$/i.test(repair.text)) {
117
+ const tail = consequence.text.split(',').at(-1).trimStart();
118
+ if (words(tail).length >= 1 && words(tail).length <= 4 && !/[?:\u0001]/.test(tail)) {
119
+ emit('fragment-run', 'check', { start: consequence.end - tail.length, end: last.end }, 'A short consequence and one-word repair lead into a moral ending.', 'Join the consequence, repair and test into a supported explanation.');
120
+ }
121
+ }
122
+ }
106
123
  }
107
124
  return out;
108
125
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwg/cli",
3
- "version": "2026.11.7",
3
+ "version": "2026.11.8",
4
4
  "description": "Lightweight AIWG CLI for signed, versioned web-backed resources.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,13 @@
1
+ // Install package-owned prompt discovery for full Cursor project deployments.
2
+ import { fileURLToPath } from 'node:url';
3
+ import { importImpl } from '../../_resolve-impl.mjs';
4
+
5
+ export async function deployCursorPromptDiscovery(targetDir, opts) {
6
+ const fullDeploy = !opts.commandsOnly && !opts.rulesOnly && (!opts.skillsOnly || opts.kernelOnly === true);
7
+ if (!fullDeploy || opts.hooks === false || opts.scope === 'user') return;
8
+ const { installCursorPromptDiscovery } = await importImpl(import.meta.url, 'smiths/hook-bridge/cursor-translator.js');
9
+ const result = await installCursorPromptDiscovery({ projectPath: targetDir,
10
+ commandRoot: opts.logicalOutputPath?.(targetDir), frameworkRoot: fileURLToPath(new URL('../../../', import.meta.url)),
11
+ dryRun: opts.dryRun });
12
+ for (const warning of result.warnings) console.warn(warning);
13
+ }
@@ -1,3 +1,4 @@
1
+ import { deployCursorPromptDiscovery } from './cursor-prompt-discovery.mjs';
1
2
  import { withModelWrapper } from './model-wrapper.mjs';
2
3
  /**
3
4
  * Cursor IDE Provider
@@ -410,6 +411,7 @@ export function deployCursorConfigTemplates(targetDir, srcRoot, opts) {
410
411
 
411
412
  export async function postDeploy(targetDir, opts) {
412
413
  initializeFrameworkWorkspace(targetDir, opts.mode, opts.dryRun, opts.srcRoot);
414
+ await deployCursorPromptDiscovery(targetDir, opts);
413
415
 
414
416
  if (opts.createAgentsMd) {
415
417
  if (opts.contextFiles !== false) createAgentsMd(targetDir, opts.srcRoot, opts.dryRun);
@@ -0,0 +1,6 @@
1
+ // Select OpenClaw startup destinations for default sessions and agent exec --cwd.
2
+ import path from 'node:path';
3
+
4
+ export function openClawContextWorkspaces(opts, workspace) {
5
+ return [...new Set([workspace, ...(opts.contextFiles === false ? [] : [opts.target])].map(dir => path.resolve(dir)))];
6
+ }
@@ -25,6 +25,7 @@ let fs;
25
25
  try { const gfs = _require('graceful-fs'); gfs.gracefulify(realFs); fs = realFs; } catch { fs = realFs; }
26
26
  import path from 'path';
27
27
  import os from 'os';
28
+ import { openClawContextWorkspaces } from './openclaw-context.mjs';
28
29
  import {
29
30
  withRuleDeployment,
30
31
  ensureDir,
@@ -553,19 +554,20 @@ async function deploySelected(opts) {
553
554
  srcRoot, 'agentic', 'code', 'frameworks', 'sdlc-complete', 'templates', 'openclaw', 'AGENTS.md.aiwg-template',
554
555
  );
555
556
  if (fs.existsSync(templatePath)) {
556
- const workspace = opts.activeWorkspace || resolveOpenClawWorkspace();
557
- ensureDir(workspace, dryRun);
558
- if (verbose || !opts.quiet) {
559
- console.log(`\nBridging AIWG context into ${path.join(workspace, 'AGENTS.md')} + SOUL.md (#1562/#1572)...`);
557
+ for (const workspace of openClawContextWorkspaces(opts, opts.activeWorkspace || resolveOpenClawWorkspace())) {
558
+ ensureDir(workspace, dryRun);
559
+ if (verbose || !opts.quiet) {
560
+ console.log(`\nBridging AIWG context into ${path.join(workspace, 'AGENTS.md')} + SOUL.md (#1562/#1572)...`);
561
+ }
562
+ // AGENTS.md = methodology/rules; SOUL.md = the AIWG Steward identity (the
563
+ // discover-first reflex baked in as *who the agent is*, which a weak model
564
+ // adopts far more reliably than a rules appendix). Both update in place.
565
+ createAgentsMdFromTemplate(workspace, srcRoot, 'openclaw/AGENTS.md.aiwg-template', dryRun);
566
+ createManagedMdFromTemplate(workspace, 'SOUL.md', srcRoot, 'openclaw/SOUL.md.aiwg-template', dryRun, {
567
+ sectionMarker: '<!-- AIWG Steward Identity -->',
568
+ legacyHeading: '## AIWG Steward',
569
+ });
560
570
  }
561
- // AGENTS.md = methodology/rules; SOUL.md = the AIWG Steward identity (the
562
- // discover-first reflex baked in as *who the agent is*, which a weak model
563
- // adopts far more reliably than a rules appendix). Both update in place.
564
- createAgentsMdFromTemplate(workspace, srcRoot, 'openclaw/AGENTS.md.aiwg-template', dryRun);
565
- createManagedMdFromTemplate(workspace, 'SOUL.md', srcRoot, 'openclaw/SOUL.md.aiwg-template', dryRun, {
566
- sectionMarker: '<!-- AIWG Steward Identity -->',
567
- legacyHeading: '## AIWG Steward',
568
- });
569
571
  }
570
572
  }
571
573
 
@@ -354,7 +354,7 @@ export function warpRuleContent(content) {
354
354
  }
355
355
 
356
356
  export function startupFiles(opts, provider) {
357
- const bridgeNames = { claude: ['CLAUDE.md'], cursor: ['AGENTS.md'], codex: ['AGENTS.md'], hermes: ['AGENTS.md', '.hermes.md'], pi: ['AGENTS.md'], warp: ['WARP.md'], openclaw: [] };
357
+ const bridgeNames = { claude: ['CLAUDE.md'], cursor: ['AGENTS.md'], codex: ['AGENTS.md'], hermes: ['AGENTS.md', '.hermes.md'], pi: ['AGENTS.md'], warp: ['WARP.md'], openclaw: ['AGENTS.md'] };
358
358
  const paths = ['AIWG.md', 'WORKSPACE.md', ...(bridgeNames[provider.name] || ['AGENTS.md']), inlineStartup[provider.name]].filter(Boolean).map(name => path.join(opts.target, name));
359
359
  if (opts.activeWorkspace) paths.push(path.join(opts.activeWorkspace, 'AGENTS.md'));
360
360
  {
@@ -233,6 +233,7 @@ async function prepareWithInputs(original, provider, deploy) {
233
233
  fs.mkdirSync(path.join(stage, '.aiwg'), { recursive: true });
234
234
  if (fs.existsSync(projectSnapshot)) materializeInput(projectSnapshot, path.join(stage, '.aiwg', 'aiwg.config'));
235
235
  const rootNames = ['opencode.json', ...GENERATED_CONTEXT_NAMES, ...OPERATOR_CONTEXT_NAMES, '.aiwg/frameworks/registry.json'];
236
+ if (provider.name === 'openclaw' && original.contextFiles !== false) rootNames.push('SOUL.md');
236
237
  if (provider.deploymentFiles) rootNames.push(...provider.deploymentFiles(target));
237
238
  if (provider.name === 'windsurf') rootNames.push('.windsurfrules');
238
239
  for (const framework of getFrameworksForMode(original.srcRoot, original.mode)) {
@@ -29,7 +29,7 @@ export function renderRuleKernelIndex(rules, nativePaths = false, perRuleFetch =
29
29
  // RULES-INDEX receipts are parsed by deployment accounting; retain their command format.
30
30
  // #3900: "fetch before governed work" made Muse read every rule before discovery; fetch on need.
31
31
  if (!perRuleFetch) lines.push("Fetch a rule's full body when a task or discovered component needs it: `aiwg show rule <name> --body`.", '');
32
- if (kernelFile && kernels.length) lines.push("Kernel rules bind every task and subagent task. On a new task, first run discovery for the request (`aiwg discover --stdin <<'AIWG_REQUEST'`, the request, then `AIWG_REQUEST`) before reading any file below; then read a kernel file before work its subject covers.", '');
32
+ if (kernelFile && kernels.length) lines.push("Kernel rules bind every task and subagent task. On a new task, first run discovery for the request (`aiwg discover --stdin <<'AIWG_REQUEST'`, the request, then `AIWG_REQUEST`) before reading any file below; then read a kernel file before work its subject covers. For AIWG lookup, never open `.agents/skills/**` or `agentic/code/**`, including a discovered skill's mirror file or a template. After discover, use `aiwg show <type> <name>` and its drill-ins (`--section`, `--rules --with-rule-bodies`, `--body`); read required rules before governed work.", '');
33
33
  for (const rule of kernels) lines.push(kernelFile
34
34
  ? `- ${rule.name} — ${rule.summary || 'Binding kernel rule.'} Full rule: [${kernelFile(rule)}](./${kernelFile(rule)}).`
35
35
  : perRuleFetch
@@ -50,13 +50,15 @@ export function projectStartup(opts, provider, coreSection, indexFile) {
50
50
  const file = provider.name === 'openclaw' ? path.join(opts.activeWorkspace, 'AGENTS.md')
51
51
  : path.join(opts.target, owner || 'AGENTS.md');
52
52
  retireInlineStartup(opts, provider, file);
53
- const files = provider.name === 'hermes' ? [file, path.join(opts.target, '.hermes.md')] : [file];
53
+ const files = provider.name === 'hermes' ? [file, path.join(opts.target, '.hermes.md')]
54
+ : provider.name === 'openclaw' ? [...new Set([file, path.join(opts.target, 'AGENTS.md')])] : [file];
54
55
  for (const startup of files) {
55
56
  let content = provider.name === 'flue' ? read(startup) : normalizeRuleStartup(read(startup), bootstrap, path.basename(startup) === 'AGENTS.md');
56
57
  if (provider.name !== 'flue' || coreSection) content = section(content, 'rule-core', coreSection.replace(/<!-- AIWG:(?:core-rules|rule-core):(?:start|end) -->\n?/g, '').trimEnd());
57
58
  const logical = opts.logicalOutputPath || (file => file);
58
59
  const location = path.relative(logical(opts.target), logical(indexFile)).replaceAll('\\', '/');
59
60
  let hook = `${provider.name}: Before every task and subagent task, read and follow \`${location}\`; read every listed kernel file and fetch matching full rules before governed work.`;
61
+ if (['codex', 'muse'].includes(provider.name)) hook = `${provider.name}: On every new directive, including subagent tasks, run \`aiwg discover\` as the first information-gathering call, before tool-based context reads. After discovery, read and follow \`${location}\`; read every listed kernel file and fetch matching full rules before governed work.`;
60
62
  if (CONTEXT_CONTRACTS[provider.name]?.promptDiscovery?.delivery === 'bootstrap-rule') {
61
63
  hook += " Before any other tool call or answer on every new request, run `aiwg discover --stdin <<'AIWG_REQUEST'` "
62
64
  + "with the request text on the next lines and `AIWG_REQUEST` alone on the last line; never put request text in quotes on a command line. "
@@ -1398,6 +1398,19 @@
1398
1398
  "minLength": 1,
1399
1399
  "format": "uri"
1400
1400
  },
1401
+ "modelLimits": {
1402
+ "type": "object",
1403
+ "propertyNames": { "type": "string", "minLength": 1 },
1404
+ "description": "Operator-declared per-selector limits for CLI model discovery; overrides provider display-name limits.",
1405
+ "additionalProperties": {
1406
+ "type": "object", "additionalProperties": false,
1407
+ "required": ["contextTokens"],
1408
+ "properties": {
1409
+ "contextTokens": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 },
1410
+ "maxOutputTokens": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }
1411
+ }
1412
+ }
1413
+ },
1401
1414
  "localModels": {
1402
1415
  "type": "object",
1403
1416
  "additionalProperties": false,