taskquoin 0.0.0-stage → 2026.12.0

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 (160) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/LICENSE +55 -0
  3. package/README.md +227 -2
  4. package/SECURITY.md +26 -0
  5. package/adapters/git/src/git.js +250 -0
  6. package/adapters/git/src/index.js +1 -0
  7. package/adapters/hooks-claude/src/canonical.js +45 -0
  8. package/adapters/hooks-claude/src/index.js +2 -0
  9. package/adapters/hooks-claude/src/main.js +58 -0
  10. package/adapters/hooks-claude/src/payload.js +40 -0
  11. package/adapters/host-probe/src/index.js +2 -0
  12. package/adapters/host-probe/src/ollama.js +18 -0
  13. package/adapters/host-probe/src/probe.js +107 -0
  14. package/adapters/local-tool/src/fingerprint.js +56 -0
  15. package/adapters/local-tool/src/index.js +4 -0
  16. package/adapters/local-tool/src/local-tool.js +22 -0
  17. package/adapters/local-tool/src/sandboxed.js +105 -0
  18. package/adapters/local-tool/src/scan.js +52 -0
  19. package/adapters/memory-claude-mem/src/claude-mem.js +115 -0
  20. package/adapters/memory-claude-mem/src/index.js +1 -0
  21. package/adapters/process-runner/src/index.js +1 -0
  22. package/adapters/process-runner/src/runner.js +123 -0
  23. package/adapters/runtime-api/src/capabilities.json +116 -0
  24. package/adapters/runtime-api/src/executor.js +131 -0
  25. package/adapters/runtime-api/src/index.js +1 -0
  26. package/adapters/runtime-claude/src/capabilities.json +375 -0
  27. package/adapters/runtime-claude/src/command.js +34 -0
  28. package/adapters/runtime-claude/src/executor.js +162 -0
  29. package/adapters/runtime-claude/src/index.js +4 -0
  30. package/adapters/runtime-claude/src/permissions.js +76 -0
  31. package/adapters/runtime-claude/src/stream.js +60 -0
  32. package/adapters/runtime-codex/src/capabilities.json +192 -0
  33. package/adapters/runtime-codex/src/command.js +36 -0
  34. package/adapters/runtime-codex/src/executor.js +83 -0
  35. package/adapters/runtime-codex/src/index.js +4 -0
  36. package/adapters/runtime-codex/src/scratch.js +32 -0
  37. package/adapters/runtime-codex/src/stream.js +39 -0
  38. package/adapters/runtime-opencode/src/capabilities.json +149 -0
  39. package/adapters/runtime-opencode/src/config.js +33 -0
  40. package/adapters/runtime-opencode/src/credentials.js +130 -0
  41. package/adapters/runtime-opencode/src/executor.js +127 -0
  42. package/adapters/runtime-opencode/src/facts.js +43 -0
  43. package/adapters/runtime-opencode/src/hosts.js +16 -0
  44. package/adapters/runtime-opencode/src/hosts.json +3 -0
  45. package/adapters/runtime-opencode/src/index.js +6 -0
  46. package/adapters/runtime-opencode/src/mounts.js +58 -0
  47. package/adapters/runtime-opencode/src/stream.js +63 -0
  48. package/adapters/skill-store/src/index.js +1 -0
  49. package/adapters/skill-store/src/skill-store.js +162 -0
  50. package/adapters/store-fs/src/index.js +2 -0
  51. package/adapters/store-fs/src/store.js +201 -0
  52. package/adapters/store-fs/src/trusted-dir.js +37 -0
  53. package/apps/cli/src/console.js +432 -0
  54. package/apps/cli/src/dashboard-approve.js +259 -0
  55. package/apps/cli/src/dashboard-data.js +424 -0
  56. package/apps/cli/src/dashboard.js +500 -0
  57. package/apps/cli/src/history.js +35 -0
  58. package/apps/cli/src/home.js +18 -0
  59. package/apps/cli/src/i18n/en.js +527 -0
  60. package/apps/cli/src/i18n/index.js +90 -0
  61. package/apps/cli/src/i18n/languages.js +25 -0
  62. package/apps/cli/src/i18n/locales/ar.json +526 -0
  63. package/apps/cli/src/i18n/locales/de.json +505 -0
  64. package/apps/cli/src/i18n/locales/es.json +505 -0
  65. package/apps/cli/src/i18n/locales/fa.json +505 -0
  66. package/apps/cli/src/i18n/locales/fr.json +505 -0
  67. package/apps/cli/src/i18n/locales/he.json +505 -0
  68. package/apps/cli/src/i18n/locales/hi.json +505 -0
  69. package/apps/cli/src/i18n/locales/id.json +491 -0
  70. package/apps/cli/src/i18n/locales/it.json +505 -0
  71. package/apps/cli/src/i18n/locales/ja.json +491 -0
  72. package/apps/cli/src/i18n/locales/ko.json +491 -0
  73. package/apps/cli/src/i18n/locales/nl.json +505 -0
  74. package/apps/cli/src/i18n/locales/pl.json +512 -0
  75. package/apps/cli/src/i18n/locales/pt-BR.json +505 -0
  76. package/apps/cli/src/i18n/locales/ru.json +512 -0
  77. package/apps/cli/src/i18n/locales/th.json +491 -0
  78. package/apps/cli/src/i18n/locales/tr.json +505 -0
  79. package/apps/cli/src/i18n/locales/uk.json +512 -0
  80. package/apps/cli/src/i18n/locales/vi.json +491 -0
  81. package/apps/cli/src/i18n/locales/zh-CN.json +491 -0
  82. package/apps/cli/src/i18n/locales/zh-TW.json +491 -0
  83. package/apps/cli/src/i18n/width.js +40 -0
  84. package/apps/cli/src/layout.js +18 -0
  85. package/apps/cli/src/main.js +830 -0
  86. package/apps/cli/src/preferences.js +46 -0
  87. package/apps/cli/src/runtime-notices.js +41 -0
  88. package/apps/cli/src/safe-text.js +3 -0
  89. package/apps/cli/src/shortcut.js +82 -0
  90. package/apps/cli/src/skills-cli.js +112 -0
  91. package/apps/cli/src/tui/caps.js +31 -0
  92. package/apps/cli/src/tui/components/agent-list.js +58 -0
  93. package/apps/cli/src/tui/components/approval-center.js +145 -0
  94. package/apps/cli/src/tui/components/approval.js +95 -0
  95. package/apps/cli/src/tui/components/dashboard-frame.js +293 -0
  96. package/apps/cli/src/tui/components/diff-viewer.js +549 -0
  97. package/apps/cli/src/tui/components/event-viewer.js +46 -0
  98. package/apps/cli/src/tui/components/help-panel.js +59 -0
  99. package/apps/cli/src/tui/components/home.js +185 -0
  100. package/apps/cli/src/tui/components/logo.js +67 -0
  101. package/apps/cli/src/tui/components/panel.js +70 -0
  102. package/apps/cli/src/tui/components/status-bar.js +96 -0
  103. package/apps/cli/src/tui/components/timeline.js +120 -0
  104. package/apps/cli/src/tui/keys.js +139 -0
  105. package/apps/cli/src/tui/neutral.js +68 -0
  106. package/apps/cli/src/tui/screen.js +111 -0
  107. package/apps/cli/src/tui/text.js +165 -0
  108. package/apps/cli/src/tui/tokens.js +89 -0
  109. package/apps/cli/src/tui/view.js +64 -0
  110. package/apps/cli/src/upgrade-check.js +86 -0
  111. package/apps/cli/src/upgrade-cli.js +168 -0
  112. package/apps/cli/src/workflow-cli.js +674 -0
  113. package/package.json +29 -4
  114. package/packages/application/src/index.js +8 -0
  115. package/packages/application/src/lib/digest.js +7 -0
  116. package/packages/application/src/ports/memory.js +1 -0
  117. package/packages/application/src/ports/runtime-executor.js +1 -0
  118. package/packages/application/src/projection/run-view.js +194 -0
  119. package/packages/application/src/projection/squad-view.js +33 -0
  120. package/packages/application/src/use-cases/prepare-run.js +68 -0
  121. package/packages/application/src/workflow/feature-governed.js +420 -0
  122. package/packages/application/src/workflow/gate-signals.js +40 -0
  123. package/packages/application/src/workflow/prompts.js +81 -0
  124. package/packages/config/src/config.js +372 -0
  125. package/packages/config/src/index.js +1 -0
  126. package/packages/domain/src/capabilities.js +13 -0
  127. package/packages/domain/src/capability-matrix.js +63 -0
  128. package/packages/domain/src/enforcement.js +95 -0
  129. package/packages/domain/src/index.js +4 -0
  130. package/packages/domain/src/policy.js +32 -0
  131. package/packages/rules/src/glob.js +47 -0
  132. package/packages/rules/src/index.js +5 -0
  133. package/packages/rules/src/inherit.js +19 -0
  134. package/packages/rules/src/lists.js +41 -0
  135. package/packages/rules/src/rules.js +79 -0
  136. package/packages/rules/src/shell.js +83 -0
  137. package/packages/skills/src/index.js +1 -0
  138. package/packages/skills/src/skills.js +108 -0
  139. package/skills/code-review/SKILL.md +51 -0
  140. package/skills/egm-design/LICENSE +202 -0
  141. package/skills/egm-design/SKILL.md +68 -0
  142. package/skills/egm-design/references/feature-spec-standard.md +39 -0
  143. package/skills/egm-implementation-readiness/LICENSE +202 -0
  144. package/skills/egm-implementation-readiness/SKILL.md +67 -0
  145. package/skills/egm-implementation-readiness/references/implementation-readiness-standard.md +37 -0
  146. package/skills/first-party.lock.json +10 -0
  147. package/skills/planning-contract/SKILL.md +51 -0
  148. package/skills/ponytail/LICENSE +21 -0
  149. package/skills/ponytail/SKILL.md +56 -0
  150. package/skills/security-review/SKILL.md +58 -0
  151. package/skills/tdd/SKILL.md +52 -0
  152. package/skills/unslop/LICENSE +396 -0
  153. package/skills/unslop/SKILL.md +239 -0
  154. package/skills/unslop/references/cjk.md +34 -0
  155. package/skills/unslop/references/effects.md +113 -0
  156. package/skills/unslop/references/refs.md +17 -0
  157. package/skills/unslop/references/rtl.md +111 -0
  158. package/skills/unslop/references/signs.md +122 -0
  159. package/skills/unslop/references/tokens.md +139 -0
  160. package/skills/unslop/references/visuals.md +84 -0
@@ -0,0 +1,372 @@
1
+ import YAML from 'yaml';
2
+ import { CAPABILITIES, isCapability } from '../../domain/src/index.js';
3
+ /** The judges of a project: `workflow`, or today's single `challenger` for both steps. */
4
+ export function workflowOf(c) { return c.workflow ?? { challengers: ['challenger'], reviewers: ['challenger'] }; }
5
+ /** `DEEPSEEK_API_KEY` for `key: env:DEEPSEEK_API_KEY`; undefined when the provider needs no key (e.g. local Ollama). */
6
+ export function keyEnvName(p) { return p.key?.slice('env:'.length); }
7
+ const STACKS = ['node', 'php', 'python', 'go', 'java-maven', 'java-gradle', 'unknown'];
8
+ /** First entry = the full suite (Taskquoin's Verify runs it); the others let the agent run ONE test (pilot 1: RED/GREEN
9
+ * could not be observed through the full, truncated output). */
10
+ const TEST_CMDS = {
11
+ node: ['npm test', 'npm test -- *', 'node --test *'], php: ['vendor/bin/phpunit', 'vendor/bin/phpunit *'], python: ['pytest', 'pytest *'],
12
+ go: ['go test ./...', 'go test *'], 'java-maven': ['mvn -q test', 'mvn -q test *'], 'java-gradle': ['./gradlew test', './gradlew test *'], unknown: [],
13
+ };
14
+ /** Ignored dependency directories carried into Verify per stack (go/maven/gradle caches live in HOME, hidden anyway). */
15
+ const INHERIT_DEFAULTS = {
16
+ node: ['**/node_modules'], php: ['vendor'], python: ['.venv', 'venv'], go: [], 'java-maven': [], 'java-gradle': [], unknown: [],
17
+ };
18
+ /** Effective inherited paths: the stack's defaults plus the owner's `verify.inherit`. */
19
+ /** The command Verify (and the RED proof) runs: `verify.command`, else the implementer's first `shell.run` (today's configs). */
20
+ export function testCommand(c) { return c.verify?.command ?? c.agents.implementer?.capabilities['shell.run']?.[0]; }
21
+ /** OpenCode agents (project B, step 1) read and write files of the repository — nothing else. */
22
+ export const OPENCODE_CAPABILITIES = ['fs.read', 'fs.write'];
23
+ /** `openai/gpt-6-astra` → `openai` (OpenCode's model ids are `<provider>/<model>`; the model part may contain `/`). */
24
+ export function providerOf(model) { return model.slice(0, model.indexOf('/')); }
25
+ const OPENCODE_MODEL_RE = /^[a-z0-9][a-z0-9._-]*\/\S+$/;
26
+ export function inheritGlobs(c) { return [...new Set([...INHERIT_DEFAULTS[c.stack], ...(c.verify?.inherit ?? [])])]; }
27
+ export const DEFAULT_MANDATORY = ['fs.write', 'net.egress', 'config.modify', 'connector.write', 'vcs.commit', 'vcs.push'];
28
+ /** Suggested by init for an all-OpenCode project: a model a ChatGPT sign-in accepts (measured — opencode-interface-1.19.5.md). */
29
+ export const OPENCODE_DEFAULT_MODEL = 'openai/gpt-6-astra';
30
+ export function defaultConfig(stack, tools = { claude: true, codex: true }) {
31
+ const tests = TEST_CMDS[stack];
32
+ // Claude Code only: the challenger is a read-only Claude agent (the same model family as the implementer — doctor says so).
33
+ const challengerRuntime = tools.claude && !tools.codex ? 'claude' : 'codex';
34
+ const c = {
35
+ version: 1,
36
+ stack,
37
+ agents: {
38
+ planner: {
39
+ runtime: 'claude',
40
+ description: 'Read-only planner: turns a request into a minimal, test-first implementation plan.',
41
+ prompt: 'You plan; you never modify files. Read the repository, then produce the plan requested.',
42
+ capabilities: { 'fs.read': ['**'] },
43
+ maxTurns: 30,
44
+ skills: ['planning-contract'],
45
+ },
46
+ implementer: {
47
+ runtime: 'claude',
48
+ description: 'Implements an approved task with strict TDD (RED → GREEN → REFACTOR).',
49
+ prompt: 'You implement exactly the approved task. Write a failing test first, make it pass with the simplest change, then refactor. Never commit: Taskquoin verifies and commits.',
50
+ // fs.write "**": per-glob scope is not enforceable for subprocesses (measured R2.1); protected config stays denied.
51
+ capabilities: { 'fs.read': ['**'], 'fs.write': ['**'], ...(tests.length ? { 'shell.run': tests } : {}) },
52
+ maxTurns: 40,
53
+ skills: ['tdd'],
54
+ },
55
+ challenger: {
56
+ runtime: challengerRuntime,
57
+ description: 'Independent, read-only adversarial reviewer of plans and diffs.',
58
+ prompt: 'You are an independent reviewer. Challenge the plan or diff: correctness, security, missing tests, over-engineering. Report blocking and non-blocking findings with file:line. Do not modify files.',
59
+ capabilities: { 'fs.read': ['**'] },
60
+ skills: ['code-review'],
61
+ },
62
+ },
63
+ policy: { mandatory: [...DEFAULT_MANDATORY] },
64
+ connectors: {},
65
+ memory: { claudeMem: { enabled: true } },
66
+ };
67
+ // OpenCode only (project B step 1): every role on OpenCode, the implementer without commands — Taskquoin runs the tests.
68
+ if (tools.claude || !tools.opencode)
69
+ return c;
70
+ for (const a of Object.values(c.agents)) {
71
+ a.runtime = 'opencode';
72
+ a.model = OPENCODE_DEFAULT_MODEL;
73
+ delete a.capabilities['shell.run'];
74
+ }
75
+ return { ...c, ...(tests[0] ? { verify: { inherit: [], command: tests[0] } } : {}) };
76
+ }
77
+ /** Providers `init` can suggest when their key variable is present (models are examples: check them at the provider). */
78
+ const KNOWN_PROVIDERS = [
79
+ { env: 'DEEPSEEK_API_KEY', id: 'deepseek', url: 'https://api.deepseek.com/v1', model: 'deepseek-chat' },
80
+ { env: 'MISTRAL_API_KEY', id: 'mistral', url: 'https://api.mistral.ai/v1', model: 'mistral-large-latest' },
81
+ { env: 'OPENROUTER_API_KEY', id: 'openrouter', url: 'https://openrouter.ai/api/v1', model: 'deepseek/deepseek-chat' },
82
+ { env: 'GEMINI_API_KEY', id: 'gemini', url: 'https://generativelanguage.googleapis.com/v1beta/openai', model: 'gemini-2.5-flash' },
83
+ { env: 'OPENAI_API_KEY', id: 'openai', url: 'https://api.openai.com/v1', model: 'gpt-5', tokenField: 'max_completion_tokens' },
84
+ { env: 'ANTHROPIC_API_KEY', id: 'anthropic', url: 'https://api.anthropic.com/v1', model: 'claude-sonnet-5-5' },
85
+ ];
86
+ /** The environment variables `init` looks at (their values are never read into the file). */
87
+ export const KNOWN_KEY_VARS = KNOWN_PROVIDERS.map(p => p.env);
88
+ const commentOut = (yaml, indent = '') => yaml.trimEnd().split('\n').map(l => `${indent}# ${l}`).join('\n');
89
+ /** Bundled third-party skills (skills/<name>) proposed to the implementer, commented out: uncommenting one is the owner's choice. */
90
+ const PROPOSED_SKILLS = [
91
+ ['ponytail', 'the smallest complete change (bundled with Taskquoin, MIT, DietrichGebert/ponytail)'],
92
+ ['unslop', 'UI that stops looking AI-generated, for screens and pages (bundled with Taskquoin, CC BY 4.0, Damir Sokolovsky, heydamir/unslop)'],
93
+ ];
94
+ function proposeSkills(c, text) {
95
+ const skills = c.agents.implementer?.skills;
96
+ const todo = PROPOSED_SKILLS.filter(([n]) => !skills?.includes(n));
97
+ if (!skills?.length || !todo.length)
98
+ return text;
99
+ const lines = text.split('\n');
100
+ let end = lines.indexOf(' skills:', lines.indexOf(' implementer:')) + 1;
101
+ while (lines[end]?.startsWith(' - '))
102
+ end++;
103
+ lines.splice(end, 0, ...todo.flatMap(([n, note]) => [` ## proposed: ${n}, ${note}; uncomment to use it`, ` # - ${n}`]));
104
+ return lines.join('\n');
105
+ }
106
+ /** Goldfish plan reviewers from Google's Elephant-Goldfish Model (skills/egm-*, Apache-2.0): fresh, read-only, on the challenger's runtime. */
107
+ const GOLDFISH = [
108
+ ['goldfish-design', 'egm-design', 'architecture, scale and unmitigated risks of the plan'],
109
+ ['goldfish-readiness', 'egm-implementation-readiness', 'can the plan be coded with no design decision left to the implementer'],
110
+ ];
111
+ function proposeGoldfish(c, text) {
112
+ const ch = c.agents.challenger;
113
+ if (!ch || ch.runtime === 'api' || GOLDFISH.some(([id]) => c.agents[id]))
114
+ return text;
115
+ const agents = Object.fromEntries(GOLDFISH.map(([id, skill, what]) => [id, { runtime: ch.runtime, ...(ch.model ? { model: ch.model } : {}),
116
+ description: `Goldfish reviewer (Google's Elephant-Goldfish Model): ${what}`,
117
+ prompt: 'Mode: REVIEW. Your target document is the plan in your task, all of it; your Target Standard is the reference file of your skill. Read it as a newcomer with no history of the project.',
118
+ capabilities: { 'fs.read': ['**'] }, skills: [skill] }]));
119
+ const lines = text.split('\n');
120
+ const at = lines.indexOf('agents:');
121
+ lines.splice(lines.findIndex((l, i) => i > at && /^\S/.test(l)), 0, " ## ── proposed: two Goldfish reviewers of the plan from Google's Elephant-Goldfish Model (skills egm-*, bundled with Taskquoin, Apache-2.0), fresh and read-only.", ' ## ── Uncomment them, then list them in workflow.challengers, e.g. challengers: [challenger, goldfish-design, goldfish-readiness]', commentOut(YAML.stringify(agents, { lineWidth: 0 }), ' '));
122
+ return lines.join('\n');
123
+ }
124
+ /**
125
+ * taskquoin.yaml text. With `detected` AIs, adds them as COMMENTED suggestions (providers, a `security` judge inside
126
+ * `agents`, a `workflow`): uncommenting them is the project's consent to send its code there (multi-LLM A).
127
+ */
128
+ export function renderConfig(c, detected) {
129
+ const text = proposeGoldfish(c, proposeSkills(c, '# Taskquoin project configuration — see docs/architecture.md. Protected: agents can never edit this file.\n' +
130
+ YAML.stringify(c, { lineWidth: 0 })));
131
+ const remote = KNOWN_PROVIDERS.filter(p => detected?.env.includes(p.env));
132
+ const local = detected?.ollamaModels[0];
133
+ if (!remote.length && !local)
134
+ return text;
135
+ const providers = {};
136
+ // Reasoning models spend output tokens on reasoning first: give them room, or the verdict is cut (final review).
137
+ for (const p of remote)
138
+ providers[p.id] = { url: p.url, model: p.model, key: `env:${p.env}`, ...(p.tokenField ? { tokenField: p.tokenField, maxOutputTokens: 16000 } : {}) };
139
+ if (local)
140
+ providers.local = { url: 'http://localhost:11434/v1', model: local };
141
+ const judge = { security: { runtime: 'api', provider: remote[0]?.id ?? 'local', description: 'Revue de sécurité indépendante du diff',
142
+ prompt: 'You are an independent security reviewer of the diff. Report every security defect with file:line and a fix.', capabilities: {}, skills: ['security-review'] } };
143
+ const agentBlock = ` ## ── juge de sécurité suggéré : décommentez-le AVEC providers et workflow (en bas du fichier)\n${commentOut(YAML.stringify(judge, { lineWidth: 0 }), ' ')}`;
144
+ const lines = text.split('\n');
145
+ const agentsAt = lines.indexOf('agents:');
146
+ const next = lines.findIndex((l, i) => i > agentsAt && /^\S/.test(l));
147
+ lines.splice(next, 0, agentBlock);
148
+ // Notes start with "## ": an editor's comment toggle on the whole block leaves them comments (final review).
149
+ const tail = ['## ── IA détectées sur cette machine. Les décommenter, c\'est accepter de leur envoyer le code de ce projet.',
150
+ '## ── Les noms de modèles sont des exemples : vérifiez-les chez le fournisseur. Les clés restent dans votre environnement.',
151
+ commentOut(YAML.stringify({ providers }, { lineWidth: 0 })), commentOut(YAML.stringify({ workflow: { challengers: ['challenger'], reviewers: ['challenger', 'security'] } }, { lineWidth: 0 }))];
152
+ return lines.join('\n').replace(/\n*$/, '\n') + tail.join('\n') + '\n';
153
+ }
154
+ // ── validation ────────────────────────────────────────────────────────────────────────────────────────────────────
155
+ const isObj = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
156
+ function fail(path, msg) { throw new Error(`config${path}: ${msg}`); }
157
+ function keys(o, path, allowed, required = allowed) {
158
+ for (const k of Object.keys(o))
159
+ if (!allowed.includes(k))
160
+ fail(`${path}.${k}`, `unknown key (allowed: ${allowed.join(', ')})`);
161
+ for (const k of required)
162
+ if (!(k in o))
163
+ fail(`${path}.${k}`, 'required');
164
+ }
165
+ const str = (x, path, nonEmpty = true) => { if (typeof x !== 'string' || (nonEmpty && !x.trim()))
166
+ fail(path, 'expected a non-empty string'); return x; };
167
+ const strs = (x, path) => { if (!Array.isArray(x) || x.some(v => typeof v !== 'string'))
168
+ fail(path, 'expected a list of strings'); return x; };
169
+ const ID_RE = /^[a-z][a-z0-9-]{0,47}$/;
170
+ const HOST_RE = /^(?=.{1,253}$)[A-Za-z0-9-]{1,63}(\.[A-Za-z0-9-]{1,63})+$/;
171
+ function agent(raw, path) {
172
+ if (!isObj(raw))
173
+ fail(path, 'expected a mapping');
174
+ keys(raw, path, ['runtime', 'description', 'prompt', 'capabilities', 'model', 'maxTurns', 'skills', 'provider'], ['runtime', 'description', 'prompt', 'capabilities']);
175
+ if (raw.skills !== undefined && strs(raw.skills, `${path}.skills`).some(n => !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(n)))
176
+ fail(`${path}.skills`, 'skill names are lowercase letters, digits and single hyphens');
177
+ if (raw.runtime !== 'claude' && raw.runtime !== 'codex' && raw.runtime !== 'api' && raw.runtime !== 'opencode')
178
+ fail(`${path}.runtime`, `expected claude|codex|api|opencode, got ${JSON.stringify(raw.runtime)}`);
179
+ if (raw.runtime === 'opencode' && (typeof raw.model !== 'string' || !OPENCODE_MODEL_RE.test(raw.model)))
180
+ fail(`${path}.model`, 'required for runtime opencode, as <provider>/<model> (e.g. openai/gpt-6-astra)');
181
+ if (!isObj(raw.capabilities))
182
+ fail(`${path}.capabilities`, 'expected a mapping');
183
+ if (raw.runtime === 'api') {
184
+ // A text-only judge: text in, verdict out — it has no capability at all, and no agent loop to bound.
185
+ if (raw.provider === undefined)
186
+ fail(`${path}.provider`, 'required for runtime api (an id from providers)');
187
+ if (Object.keys(raw.capabilities).length)
188
+ fail(`${path}.capabilities`, 'an api judge has no capability (text in, text out): use {}');
189
+ if (raw.maxTurns !== undefined)
190
+ fail(`${path}.maxTurns`, 'not applicable to runtime api (one request, one answer)');
191
+ }
192
+ else if (raw.provider !== undefined)
193
+ fail(`${path}.provider`, 'only for runtime api');
194
+ const caps = {};
195
+ for (const [k, v] of Object.entries(raw.capabilities)) {
196
+ if (!isCapability(k))
197
+ fail(`${path}.capabilities.${k}`, `unknown capability (known: ${CAPABILITIES.join(', ')})`);
198
+ caps[k] = strs(v, `${path}.capabilities.${k}`);
199
+ if (raw.runtime === 'opencode' && !OPENCODE_CAPABILITIES.includes(k) && caps[k].length)
200
+ fail(`${path}.capabilities.${k}`, k === 'shell.run' ? 'no commands for OpenCode in this version: Taskquoin runs your tests with verify.command' : 'not available to OpenCode in this version (only fs.read and fs.write)');
201
+ }
202
+ if (raw.maxTurns !== undefined && (!Number.isInteger(raw.maxTurns) || raw.maxTurns < 1 || raw.maxTurns > 200))
203
+ fail(`${path}.maxTurns`, 'expected an integer 1..200');
204
+ return { runtime: raw.runtime, description: str(raw.description, `${path}.description`), prompt: str(raw.prompt, `${path}.prompt`), capabilities: caps,
205
+ ...(raw.model !== undefined ? { model: str(raw.model, `${path}.model`) } : {}), ...(raw.maxTurns !== undefined ? { maxTurns: raw.maxTurns } : {}),
206
+ ...(raw.skills !== undefined ? { skills: raw.skills } : {}), ...(raw.provider !== undefined ? { provider: str(raw.provider, `${path}.provider`) } : {}) };
207
+ }
208
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
209
+ const ENV_REF_RE = /^env:[A-Z_][A-Z0-9_]*$/;
210
+ function provider(raw, path) {
211
+ if (!isObj(raw))
212
+ fail(path, 'expected a mapping');
213
+ keys(raw, path, ['url', 'model', 'key', 'maxOutputTokens', 'timeoutSeconds', 'tokenField', 'maxInputChars'], ['url', 'model']);
214
+ const u = str(raw.url, `${path}.url`);
215
+ let url;
216
+ try {
217
+ url = new URL(u);
218
+ }
219
+ catch {
220
+ fail(`${path}.url`, 'expected an absolute URL');
221
+ }
222
+ if (url.username || url.password)
223
+ fail(`${path}.url`, 'no credentials in the URL (use key: env:NAME)');
224
+ if (u.includes('?') || u.includes('#'))
225
+ fail(`${path}.url`, 'no query string or fragment');
226
+ if (url.protocol === 'http:' && !LOOPBACK.has(url.hostname))
227
+ fail(`${path}.url`, 'https is required (http only for localhost, 127.0.0.1, [::1])');
228
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
229
+ fail(`${path}.url`, 'expected https://');
230
+ if (raw.key !== undefined && (typeof raw.key !== 'string' || !ENV_REF_RE.test(raw.key)))
231
+ fail(`${path}.key`, 'must reference an environment variable (env:NAME), never contain the key');
232
+ const int = (k, min, max, dflt) => {
233
+ if (raw[k] === undefined)
234
+ return dflt;
235
+ if (!Number.isInteger(raw[k]) || raw[k] < min || raw[k] > max)
236
+ fail(`${path}.${k}`, `expected an integer ${min}..${max}`);
237
+ return raw[k];
238
+ };
239
+ const tokenField = raw.tokenField ?? 'max_tokens';
240
+ if (tokenField !== 'max_tokens' && tokenField !== 'max_completion_tokens')
241
+ fail(`${path}.tokenField`, 'expected max_tokens|max_completion_tokens');
242
+ const maxInputChars = int('maxInputChars', 1000, 50_000_000);
243
+ return { url: u, model: str(raw.model, `${path}.model`), ...(raw.key !== undefined ? { key: raw.key } : {}),
244
+ maxOutputTokens: int('maxOutputTokens', 1, 1_000_000, 4000), timeoutSeconds: int('timeoutSeconds', 1, 3600, 300), tokenField,
245
+ ...(maxInputChars !== undefined ? { maxInputChars } : {}) };
246
+ }
247
+ /** Judges: listed agents exist, no duplicate, never empty (someone always challenges and reviews). */
248
+ function workflowSection(raw, agents) {
249
+ if (!isObj(raw))
250
+ fail('.workflow', 'expected a mapping');
251
+ keys(raw, '.workflow', ['challengers', 'reviewers']);
252
+ const list = (k) => {
253
+ const ids = strs(raw[k], `.workflow.${k}`);
254
+ if (!ids.length)
255
+ fail(`.workflow.${k}`, 'at least one agent');
256
+ ids.forEach((id, i) => {
257
+ if (ids.indexOf(id) !== i)
258
+ fail(`.workflow.${k}`, `duplicate agent "${id}"`);
259
+ if (!Object.hasOwn(agents, id))
260
+ fail(`.workflow.${k}`, `unknown agent "${id}"`);
261
+ });
262
+ return ids;
263
+ };
264
+ return { challengers: list('challengers'), reviewers: list('reviewers') };
265
+ }
266
+ function connector(raw, path) {
267
+ if (!isObj(raw))
268
+ fail(path, 'expected a mapping');
269
+ keys(raw, path, ['host', 'scope', 'read', 'write', 'credentialRef']);
270
+ const host = str(raw.host, `${path}.host`);
271
+ if (!HOST_RE.test(host))
272
+ fail(`${path}.host`, 'expected a plain hostname');
273
+ const credentialRef = str(raw.credentialRef, `${path}.credentialRef`);
274
+ if (!/^(env|keychain):[A-Za-z0-9_.-]+$/.test(credentialRef))
275
+ fail(`${path}.credentialRef`, 'must reference a secret (env:NAME or keychain:NAME), never contain it');
276
+ return { host, scope: str(raw.scope, `${path}.scope`), read: strs(raw.read, `${path}.read`), write: strs(raw.write, `${path}.write`), credentialRef };
277
+ }
278
+ /** Parse and validate taskquoin.yaml. Strict and fail-closed. */
279
+ export const MAX_CONFIG_BYTES = 256 * 1024;
280
+ export function parseConfig(text) {
281
+ if (Buffer.byteLength(text) > MAX_CONFIG_BYTES)
282
+ fail('', `file too large (> ${MAX_CONFIG_BYTES} bytes)`);
283
+ const doc = YAML.parseDocument(text, { uniqueKeys: true, prettyErrors: false });
284
+ if (doc.errors.length)
285
+ fail('', `invalid YAML: ${doc.errors[0].message}`);
286
+ let alias = false;
287
+ let anchor = false;
288
+ YAML.visit(doc, { Alias() { alias = true; return YAML.visit.BREAK; }, Node(_k, n) { if (n.anchor) {
289
+ anchor = true;
290
+ return YAML.visit.BREAK;
291
+ } return undefined; } });
292
+ if (alias || anchor)
293
+ fail('', 'YAML aliases/anchors are not allowed');
294
+ const raw = doc.toJS({ maxAliasCount: 0 });
295
+ if (!isObj(raw))
296
+ fail('', 'expected a mapping');
297
+ if (raw.version !== 1)
298
+ fail('.version', `expected 1, got ${JSON.stringify(raw.version)}`);
299
+ keys(raw, '', ['version', 'stack', 'agents', 'policy', 'connectors', 'memory', 'verify', 'providers', 'workflow'], ['version', 'stack', 'agents', 'policy', 'connectors', 'memory']);
300
+ if (!STACKS.includes(raw.stack))
301
+ fail('.stack', `expected one of ${STACKS.join(', ')}`);
302
+ if (!isObj(raw.agents) || Object.keys(raw.agents).length === 0)
303
+ fail('.agents', 'expected at least one agent');
304
+ const agents = {};
305
+ for (const [id, a] of Object.entries(raw.agents)) {
306
+ if (!ID_RE.test(id))
307
+ fail(`.agents.${id}`, 'invalid agent id');
308
+ Object.defineProperty(agents, id, { value: agent(a, `.agents.${id}`), enumerable: true, writable: true, configurable: true });
309
+ }
310
+ if (!isObj(raw.policy))
311
+ fail('.policy', 'expected a mapping');
312
+ if (Object.hasOwn(raw.policy, 'exceptions'))
313
+ fail('.policy.exceptions', 'risk acceptances are not read from the repository; record them with "taskquoin accept-risk" (stored in the control store, ADR-0012/Codex R3)');
314
+ keys(raw.policy, '.policy', ['mandatory']);
315
+ const mandatory = strs(raw.policy.mandatory, '.policy.mandatory').map((c, i) => { if (!isCapability(c))
316
+ fail(`.policy.mandatory[${i}]`, `unknown capability ${c}`); return c; });
317
+ if (!isObj(raw.connectors))
318
+ fail('.connectors', 'expected a mapping');
319
+ const connectors = {};
320
+ for (const [id, c] of Object.entries(raw.connectors)) {
321
+ if (!ID_RE.test(id))
322
+ fail(`.connectors.${id}`, 'invalid connector id');
323
+ connectors[id] = connector(c, `.connectors.${id}`);
324
+ }
325
+ if (!isObj(raw.memory) || !isObj(raw.memory.claudeMem) || typeof raw.memory.claudeMem.enabled !== 'boolean')
326
+ fail('.memory.claudeMem.enabled', 'expected a boolean');
327
+ keys(raw.memory, '.memory', ['claudeMem']);
328
+ keys(raw.memory.claudeMem, '.memory.claudeMem', ['enabled']);
329
+ let verify;
330
+ if (raw.verify !== undefined) {
331
+ if (!isObj(raw.verify))
332
+ fail('.verify', 'expected a mapping');
333
+ keys(raw.verify, '.verify', ['inherit', 'command'], []);
334
+ verify = { inherit: raw.verify.inherit === undefined ? [] : strs(raw.verify.inherit, '.verify.inherit').map((g, i) => inheritEntry(g, `.verify.inherit[${i}]`)),
335
+ ...(raw.verify.command !== undefined ? { command: str(raw.verify.command, '.verify.command') } : {}) };
336
+ }
337
+ let providers;
338
+ if (raw.providers !== undefined) {
339
+ if (!isObj(raw.providers))
340
+ fail('.providers', 'expected a mapping');
341
+ providers = {};
342
+ for (const [id, p] of Object.entries(raw.providers)) {
343
+ if (!ID_RE.test(id))
344
+ fail(`.providers.${id}`, 'invalid provider id');
345
+ providers[id] = provider(p, `.providers.${id}`);
346
+ }
347
+ }
348
+ for (const [id, a] of Object.entries(agents)) {
349
+ if (a.runtime !== 'api')
350
+ continue;
351
+ if (id === 'planner' || id === 'implementer')
352
+ fail(`.agents.${id}.runtime`, 'the planner reads the repository and the implementer writes code: they need claude|codex|opencode (an api judge has no tools)');
353
+ if (!providers || !Object.hasOwn(providers, a.provider))
354
+ fail(`.agents.${id}.provider`, `unknown provider "${a.provider}" (list it under providers)`);
355
+ }
356
+ if (agents.implementer?.runtime === 'opencode' && !verify?.command)
357
+ fail('.verify.command', 'required — the implementer runs no command, Taskquoin needs your test command (e.g. npm test)');
358
+ const workflow = raw.workflow !== undefined ? workflowSection(raw.workflow, agents) : undefined;
359
+ return { version: 1, stack: raw.stack, agents, policy: { mandatory }, connectors, memory: { claudeMem: { enabled: raw.memory.claudeMem.enabled } },
360
+ ...(verify ? { verify } : {}), ...(providers ? { providers } : {}), ...(workflow ? { workflow } : {}) };
361
+ }
362
+ /** A relative path or glob naming ignored files to carry into Verify — never everything, never outside, never .git. */
363
+ function inheritEntry(g, path) {
364
+ const segs = g.split('/');
365
+ if (!g || g.startsWith('/') || segs.includes('..') || segs.includes(''))
366
+ fail(path, 'expected a relative path inside the repository');
367
+ if (segs[0] === '.git')
368
+ fail(path, '.git is never inherited');
369
+ if (segs.every(x => x === '*' || x === '**'))
370
+ fail(path, 'inheriting everything would defeat the clean room (ADR-0014)');
371
+ return g;
372
+ }
@@ -0,0 +1 @@
1
+ export * from "./config.js";
@@ -0,0 +1,13 @@
1
+ /** Canonical capability vocabulary (architecture.md §4). Runtime-neutral by construction. */
2
+ export const CAPABILITIES = [
3
+ 'fs.read', 'fs.write', 'shell.run', 'net.egress',
4
+ 'vcs.commit', 'vcs.push', 'connector.read', 'connector.write', 'config.modify',
5
+ ];
6
+ export function isCapability(x) {
7
+ return CAPABILITIES.includes(x);
8
+ }
9
+ /** Machine-checkable preconditions, satisfied (or not) by HostFacts gathered by doctor/preflight. */
10
+ /** 'bash-sandbox' = Claude Code native OS sandbox usable (bubblewrap + socat on Linux), checked by doctor. */
11
+ /** 'landing-gate' = the run goes through the Taskquoin workflow, which never commits protected-config changes. */
12
+ /** 'file-sandbox' = Taskquoin's own bubblewrap profile is usable (OpenCode agents run in it), checked by doctor. */
13
+ export const PRECONDITIONS = ['hooks-trusted', 'container-profile', 'broker-available', 'bash-sandbox', 'landing-gate', 'file-sandbox'];
@@ -0,0 +1,63 @@
1
+ import { CAPABILITIES, PRECONDITIONS, isCapability, } from "./capabilities.js";
2
+ const CLASSES = ['ENFORCED', 'BROKERED', 'ADVISORY', 'UNSUPPORTED'];
3
+ const RUNTIMES = ['claude', 'codex', 'api', 'opencode'];
4
+ const EVIDENCE = ['measured', 'documented', 'inferred'];
5
+ function fail(path, msg) { throw new Error(`capabilities${path}: ${msg}`); }
6
+ const isObj = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
7
+ function variant(path, raw) {
8
+ if (!isObj(raw))
9
+ fail(path, 'expected object');
10
+ if (!CLASSES.includes(raw.class))
11
+ fail(`${path}.class`, `expected one of ${CLASSES.join('|')}, got ${JSON.stringify(raw.class)}`);
12
+ if (typeof raw.mechanism !== 'string' || raw.mechanism.length < 10)
13
+ fail(`${path}.mechanism`, 'required descriptive string');
14
+ if (!EVIDENCE.includes(raw.evidence))
15
+ fail(`${path}.evidence`, `expected one of ${EVIDENCE.join('|')}`);
16
+ if (raw.evidence === 'measured' && (typeof raw.evidenceRef !== 'string' || !raw.evidenceRef))
17
+ fail(`${path}.evidenceRef`, 'measured variants must cite their evidence');
18
+ if (raw.granularity !== undefined && raw.granularity !== 'workspace' && raw.granularity !== 'pattern')
19
+ fail(`${path}.granularity`, 'expected workspace|pattern');
20
+ if (raw.holdsFor !== undefined && (!Array.isArray(raw.holdsFor) || raw.holdsFor.length === 0 || raw.holdsFor.some(x => !['deny-all', 'scoped', 'workspace'].includes(x))))
21
+ fail(`${path}.holdsFor`, 'expected non-empty subset of deny-all|scoped|workspace');
22
+ if (raw.requires !== undefined && (!Array.isArray(raw.requires) || raw.requires.some(p => !PRECONDITIONS.includes(p))))
23
+ fail(`${path}.requires`, `expected subset of ${PRECONDITIONS.join('|')}`);
24
+ if (raw.when !== undefined) {
25
+ if (!isObj(raw.when))
26
+ fail(`${path}.when`, 'expected object');
27
+ const w = raw.when;
28
+ if (w.sandbox !== undefined && w.sandbox !== 'read-only' && w.sandbox !== 'workspace-write')
29
+ fail(`${path}.when.sandbox`, 'expected read-only|workspace-write');
30
+ if (w.scope !== undefined && !['deny-all', 'scoped', 'workspace'].includes(w.scope))
31
+ fail(`${path}.when.scope`, 'expected deny-all|scoped|workspace');
32
+ if (w.granted !== undefined && (!Array.isArray(w.granted) || w.granted.some(c => !isCapability(String(c)))))
33
+ fail(`${path}.when.granted`, 'expected capability list');
34
+ if (w.absent !== undefined && (!Array.isArray(w.absent) || w.absent.some(c => !isCapability(String(c)))))
35
+ fail(`${path}.when.absent`, 'expected capability list');
36
+ }
37
+ return raw;
38
+ }
39
+ /** Validate an untrusted JSON object into a CapabilityMatrix. Throws with a path-precise message. */
40
+ export function validateCapabilityMatrix(raw) {
41
+ if (!isObj(raw))
42
+ fail('', 'expected object');
43
+ if (!RUNTIMES.includes(raw.runtime))
44
+ fail('.runtime', `expected one of ${RUNTIMES.join('|')}, got ${JSON.stringify(raw.runtime)}`);
45
+ if (typeof raw.runtimeVersion !== 'string' || !raw.runtimeVersion)
46
+ fail('.runtimeVersion', 'required string');
47
+ if (typeof raw.measuredOn !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(raw.measuredOn))
48
+ fail('.measuredOn', 'expected YYYY-MM-DD');
49
+ if (!isObj(raw.entries))
50
+ fail('.entries', 'required object');
51
+ const entries = {};
52
+ for (const [k, v] of Object.entries(raw.entries)) {
53
+ if (!isCapability(k))
54
+ fail(`.entries.${k}`, `unknown capability (known: ${CAPABILITIES.join(', ')})`);
55
+ if (!Array.isArray(v) || v.length === 0)
56
+ fail(`.entries.${k}`, 'expected non-empty array of variants');
57
+ entries[k] = v.map((x, i) => variant(`.entries.${k}[${i}]`, x));
58
+ const last = entries[k][entries[k].length - 1];
59
+ if (last.when)
60
+ fail(`.entries.${k}`, 'last variant must be unconditional (fallback)');
61
+ }
62
+ return { runtime: raw.runtime, runtimeVersion: raw.runtimeVersion, measuredOn: raw.measuredOn, entries };
63
+ }
@@ -0,0 +1,95 @@
1
+ import { CAPABILITIES, isCapability, } from "./capabilities.js";
2
+ /** Drop empty grants: an empty list grants nothing (Codex R1 N2). */
3
+ export function normalizeGrants(g) {
4
+ const out = {};
5
+ for (const [k, v] of Object.entries(g))
6
+ if (v && v.length > 0)
7
+ out[k] = [...v];
8
+ return out;
9
+ }
10
+ /** Globs that mean the whole workspace. NOT '*' (top-level entries only) — review H3. */
11
+ const WHOLE = new Set(['**', './**']);
12
+ /** What a restriction on `capability` must hold, derived from the grant alone. */
13
+ export function restrictionScope(capability, grants) {
14
+ const g = normalizeGrants(grants)[capability];
15
+ if (!g)
16
+ return 'deny-all';
17
+ if ((capability === 'fs.read' || capability === 'fs.write') && g.every(x => WHOLE.has(x)))
18
+ return 'workspace';
19
+ return 'scoped';
20
+ }
21
+ function matches(v, scope, grants, facts) {
22
+ const w = v.when;
23
+ if (!w)
24
+ return true;
25
+ if (w.sandbox && w.sandbox !== facts.sandbox)
26
+ return false;
27
+ if (w.scope && w.scope !== scope)
28
+ return false;
29
+ if (w.granted && !w.granted.every(c => (grants[c]?.length ?? 0) > 0))
30
+ return false;
31
+ if (w.absent && w.absent.some(c => (grants[c]?.length ?? 0) > 0))
32
+ return false;
33
+ return true;
34
+ }
35
+ /**
36
+ * Pure, deterministic, fail closed. A mandatory restriction is certified only by a measured
37
+ * ENFORCED/BROKERED mechanism, matching the run conditions, with all preconditions satisfied,
38
+ * from a matrix measured on the installed runtime version.
39
+ */
40
+ export function resolveEnforcement(restrictions, rawGrants, matrix, facts) {
41
+ const grants = normalizeGrants(rawGrants);
42
+ const resolved = [];
43
+ const failures = [];
44
+ const warnings = [];
45
+ const target = `${matrix.runtime} ${facts.runtimeVersion}`;
46
+ const versionOk = facts.runtimeVersion === matrix.runtimeVersion;
47
+ for (const r of restrictions) {
48
+ if (!isCapability(r.capability))
49
+ throw new Error(`unknown capability "${String(r.capability)}"; known: ${CAPABILITIES.join(', ')}`);
50
+ const scope = restrictionScope(r.capability, grants);
51
+ let cls;
52
+ let mechanism;
53
+ let problem;
54
+ const variant = versionOk ? (matrix.entries[r.capability] ?? []).find(v => matches(v, scope, grants, facts)) : undefined;
55
+ if (!versionOk) {
56
+ cls = 'UNSUPPORTED';
57
+ mechanism = 'no matrix for this version';
58
+ problem = `capability matrix measured for ${matrix.runtime} ${matrix.runtimeVersion}, installed ${facts.runtimeVersion}`;
59
+ }
60
+ else if (!variant) {
61
+ cls = 'UNSUPPORTED';
62
+ mechanism = `no measured mechanism on ${target}`;
63
+ problem = mechanism;
64
+ }
65
+ else {
66
+ cls = variant.class;
67
+ mechanism = variant.mechanism;
68
+ const holds = variant.holdsFor ?? (variant.granularity === 'workspace' ? ['workspace'] : ['deny-all', 'scoped', 'workspace']);
69
+ if (!holds.includes(scope) && (cls === 'ENFORCED' || cls === 'BROKERED')) {
70
+ cls = 'ADVISORY';
71
+ mechanism = `${mechanism} — mechanism holds for ${holds.join('/')} only, not for a ${scope} restriction`;
72
+ }
73
+ const missing = (variant.requires ?? []).filter(p => !facts.satisfied.includes(p));
74
+ if (missing.length > 0) {
75
+ cls = 'UNSUPPORTED';
76
+ problem = `unmet precondition(s): ${missing.join(', ')}`;
77
+ }
78
+ else if ((cls === 'ENFORCED' || cls === 'BROKERED') && variant.evidence !== 'measured')
79
+ problem = `claimed ${cls} but the mechanism is not measured (${variant.evidence})`;
80
+ else if (cls === 'ADVISORY' || cls === 'UNSUPPORTED')
81
+ problem = mechanism;
82
+ }
83
+ const certified = (cls === 'ENFORCED' || cls === 'BROKERED') && !problem;
84
+ resolved.push({ ...r, class: cls, scope, mechanism, certified });
85
+ if (certified)
86
+ continue;
87
+ const detail = problem && problem !== mechanism ? problem : `${cls} — ${mechanism}`;
88
+ const msg = `restriction "${r.capability}" (${scope}) on ${target}: ${detail}`;
89
+ if (r.mandatory)
90
+ failures.push({ capability: r.capability, class: cls, message: `mandatory ${msg}. Execution refused (ADR-0002).` });
91
+ else
92
+ warnings.push(msg);
93
+ }
94
+ return { ok: failures.length === 0, resolved, failures, warnings };
95
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./capabilities.js";
2
+ export * from "./enforcement.js";
3
+ export * from "./capability-matrix.js";
4
+ export * from "./policy.js";
@@ -0,0 +1,32 @@
1
+ const STRENGTH = { allow: 0, ask: 1, deny: 2 };
2
+ /**
3
+ * Merge layers: a lower-precedence layer may only tighten (allow→ask→deny).
4
+ * Any attempt to relax is ignored and recorded as a conflict. Pure.
5
+ */
6
+ export function mergePolicyLayers(layers) {
7
+ const rules = new Map();
8
+ const conflicts = [];
9
+ for (const layer of layers) {
10
+ for (const rule of layer.rules) {
11
+ const current = rules.get(rule.capability);
12
+ if (!current) {
13
+ rules.set(rule.capability, { decision: rule.decision, decidedBy: layer.name });
14
+ continue;
15
+ }
16
+ if (STRENGTH[rule.decision] > STRENGTH[current.decision]) {
17
+ rules.set(rule.capability, { decision: rule.decision, decidedBy: layer.name });
18
+ }
19
+ else if (STRENGTH[rule.decision] < STRENGTH[current.decision]) {
20
+ conflicts.push(`layer "${layer.name}" tried to set ${rule.capability}=${rule.decision} but cannot relax ${current.decision} set by "${current.decidedBy}"`);
21
+ }
22
+ }
23
+ }
24
+ return { rules, conflicts };
25
+ }
26
+ /** Fail closed: a capability with no rule is denied. */
27
+ export function evaluate(policy, capability) {
28
+ const r = policy.rules.get(capability);
29
+ if (!r)
30
+ return { decision: 'deny', decidedBy: 'default', reason: `no rule for ${capability}: fail closed` };
31
+ return { decision: r.decision, decidedBy: r.decidedBy, reason: `rule from layer "${r.decidedBy}"` };
32
+ }
@@ -0,0 +1,47 @@
1
+ /** Minimal glob → RegExp for policy paths: `**`, `*`, `?`, literals. Anchored, dotAll (names may contain newlines). Relative paths only. */
2
+ const cache = new Map();
3
+ const strip = (s) => s.replace(/^\.\//, '');
4
+ export function globToRegExp(glob) {
5
+ const g = strip(glob);
6
+ let re = cache.get(g);
7
+ if (re)
8
+ return re;
9
+ let out = '';
10
+ for (let i = 0; i < g.length; i++) {
11
+ const c = g[i];
12
+ if (c === '*' && g[i + 1] === '*') {
13
+ const before = i === 0 || g[i - 1] === '/';
14
+ const after = g[i + 2] === '/' || i + 2 === g.length;
15
+ if (before && g[i + 2] === '/') {
16
+ out += '(?:.*/)?';
17
+ i += 2;
18
+ continue;
19
+ } // "**/"
20
+ if (before && after && i > 0) {
21
+ out = out.replace(/\/$/, '');
22
+ out += '(?:/.*)?';
23
+ i += 1;
24
+ continue;
25
+ } // "/**" at end
26
+ out += '.*';
27
+ i += 1;
28
+ continue; // bare "**"
29
+ }
30
+ if (c === '*') {
31
+ out += '[^/]*';
32
+ continue;
33
+ }
34
+ if (c === '?') {
35
+ out += '[^/]';
36
+ continue;
37
+ }
38
+ out += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
39
+ }
40
+ // dotAll: `**` must span a newline inside a path name too, or such a path escapes every policy (Codex CR4).
41
+ re = new RegExp(`^${out}$`, 's');
42
+ cache.set(g, re);
43
+ return re;
44
+ }
45
+ export function matchGlob(glob, relPath) {
46
+ return globToRegExp(glob).test(strip(relPath));
47
+ }
@@ -0,0 +1,5 @@
1
+ export * from "./glob.js";
2
+ export * from "./lists.js";
3
+ export * from "./shell.js";
4
+ export * from "./rules.js";
5
+ export * from "./inherit.js";