ai-engineering-loop 1.0.21 → 1.2.1

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 (115) hide show
  1. package/.agents/workflows/ai-engineering-loop.md +8 -4
  2. package/.claude/skills/ai-engineering-loop/SKILL.md +15 -7
  3. package/.gemini/skills/ai-engineering-loop/SKILL.md +15 -7
  4. package/.grok/skills/ai-engineering-loop/SKILL.md +15 -7
  5. package/README.md +43 -3
  6. package/README.npm.md +9 -1
  7. package/SECURITY.md +29 -0
  8. package/SUPPORT.md +28 -0
  9. package/agents/judge.md +5 -5
  10. package/agents/maker.md +6 -6
  11. package/bin/ai-engineering-loop.js +472 -10
  12. package/core/artifact-gates.md +49 -0
  13. package/core/configuration-precedence.md +4 -4
  14. package/core/context-impact-assessment.md +1 -1
  15. package/core/definition-of-done.md +3 -3
  16. package/core/escalation-policy.md +2 -2
  17. package/core/goal-contract.md +2 -2
  18. package/core/iteration-policy.md +4 -4
  19. package/core/project-initialization.md +2 -2
  20. package/core/runtime-safety.md +75 -0
  21. package/core/verification-loop.md +1 -1
  22. package/evals/README.md +35 -0
  23. package/evals/cases/01-stale-verification.json +17 -0
  24. package/evals/cases/02-vague-verification.json +16 -0
  25. package/evals/cases/03-missing-ac-evidence.json +17 -0
  26. package/evals/cases/04-hallucinated-citation.json +17 -0
  27. package/evals/cases/05-prompt-injection.json +17 -0
  28. package/evals/cases/06-source-secret.json +16 -0
  29. package/evals/cases/07-log-secret.json +16 -0
  30. package/evals/cases/08-symlink-escape.json +16 -0
  31. package/evals/cases/09-authorization-bypass.json +16 -0
  32. package/evals/cases/10-payment-idempotency.json +16 -0
  33. package/evals/cases/11-concurrent-update.json +16 -0
  34. package/evals/cases/12-swallowed-error.json +16 -0
  35. package/evals/cases/13-happy-path-only.json +17 -0
  36. package/evals/cases/14-invalid-finding-axis.json +16 -0
  37. package/evals/cases/15-blocker-without-alternative.json +16 -0
  38. package/evals/cases/16-unsupported-pass.json +17 -0
  39. package/evals/cases/17-soft-standard.json +16 -0
  40. package/evals/cases/18-iteration-ceiling.json +17 -0
  41. package/evals/cases/19-safe-documentation-change.json +17 -0
  42. package/evals/cases/20-valid-boundary-feature.json +18 -0
  43. package/lib/budget.js +220 -0
  44. package/lib/doctor.js +111 -0
  45. package/lib/escalation.js +192 -0
  46. package/lib/evaluation.js +137 -0
  47. package/lib/gates.js +369 -0
  48. package/lib/orchestration.js +5 -1
  49. package/lib/package-audit.js +78 -0
  50. package/lib/run-state.js +260 -0
  51. package/lib/runtime-files.js +53 -0
  52. package/lib/runtime-policy.js +118 -0
  53. package/lib/safe-context.js +194 -0
  54. package/lib/sandbox.js +305 -0
  55. package/lib/sync-hosts.js +6 -5
  56. package/package.json +16 -10
  57. package/policies/finding-policy.md +2 -2
  58. package/policies/model-escalation.md +41 -0
  59. package/policies/no-progress-policy.md +2 -2
  60. package/profiles/README.md +5 -5
  61. package/profiles/backend-api.md +1 -1
  62. package/profiles/library.md +1 -1
  63. package/profiles/mobile-app.md +1 -1
  64. package/profiles/monorepo.md +1 -1
  65. package/profiles/web-app.md +1 -1
  66. package/schemas/delivery.schema.json +15 -0
  67. package/schemas/finding-ledger.schema.json +27 -0
  68. package/schemas/goal-contract.schema.json +32 -0
  69. package/schemas/report.schema.json +17 -0
  70. package/schemas/verdict.schema.json +17 -0
  71. package/schemas/verification.schema.json +32 -0
  72. package/docs/antigravity-feasibility.md +0 -92
  73. package/docs/claude-code-feasibility.md +0 -80
  74. package/docs/grok-cli-feasibility.md +0 -99
  75. package/docs/migration-plan.md +0 -70
  76. package/examples/backend-api/payment-idempotency/README.md +0 -33
  77. package/examples/backend-api/payment-idempotency/goal-contract.md +0 -33
  78. package/examples/backend-api/payment-idempotency/judge-verdict.md +0 -28
  79. package/examples/backend-api/payment-idempotency/review-findings.md +0 -50
  80. package/examples/dot/status-display/README.md +0 -23
  81. package/examples/dot/status-display/delivery-report.md +0 -41
  82. package/examples/dot/status-display/goal-contract.md +0 -46
  83. package/examples/dot/status-display/judge-verdict.md +0 -44
  84. package/examples/dot/status-display/review-findings.md +0 -63
  85. package/examples/initialization/README.md +0 -19
  86. package/examples/initialization/discovery-trace.md +0 -63
  87. package/examples/initialization/generated-context.md +0 -110
  88. package/examples/mobile-app/offline-sync-queue/README.md +0 -33
  89. package/examples/mobile-app/offline-sync-queue/goal-contract.md +0 -32
  90. package/examples/mobile-app/offline-sync-queue/judge-verdict.md +0 -27
  91. package/examples/mobile-app/offline-sync-queue/review-findings.md +0 -30
  92. package/scripts/init.sh +0 -106
  93. package/templates/repo-config/adapter.md +0 -11
  94. package/templates/repo-config/adr-readme.md +0 -33
  95. package/templates/repo-config/architecture.md +0 -15
  96. package/templates/repo-config/claude-permissions.json +0 -10
  97. package/templates/repo-config/config.md +0 -11
  98. package/templates/repo-config/conventions.md +0 -16
  99. package/templates/repo-config/glossary.md +0 -18
  100. package/templates/repo-config/lessons.md +0 -8
  101. package/templates/repo-config/verification.md +0 -13
  102. package/templates/repo-config/workflow.md +0 -25
  103. package/tests/capability-selection.test.js +0 -207
  104. package/tests/claimed-vs-reality.test.js +0 -27
  105. package/tests/dot-branch-policy.test.js +0 -65
  106. package/tests/generate-adapter.test.js +0 -80
  107. package/tests/generate-workflow.test.js +0 -180
  108. package/tests/grok-runtime.test.js +0 -201
  109. package/tests/intern-catalog.test.js +0 -72
  110. package/tests/living-context.test.js +0 -61
  111. package/tests/no-company-leak.test.js +0 -82
  112. package/tests/orchestration.test.js +0 -368
  113. package/tests/qa-delivery-template.test.js +0 -90
  114. package/tests/skill-host-compat.test.js +0 -406
  115. package/tests/sync-hosts.test.js +0 -168
@@ -0,0 +1,260 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { execFileSync } = require('child_process');
7
+
8
+ const RUN_STATES = Object.freeze({
9
+ STARTED: 'STARTED',
10
+ GOAL_FROZEN: 'GOAL_FROZEN',
11
+ REPORTED: 'REPORTED',
12
+ MAKER_COMPLETE: 'MAKER_COMPLETE',
13
+ VERIFIED: 'VERIFIED',
14
+ REVIEWED: 'REVIEWED',
15
+ JUDGED_PASS: 'JUDGED_PASS',
16
+ DELIVERED: 'DELIVERED',
17
+ ESCALATED: 'ESCALATED'
18
+ });
19
+
20
+ const RUN_MODES = Object.freeze({
21
+ REPORT_ONLY: 'REPORT_ONLY',
22
+ ASSISTED: 'ASSISTED',
23
+ UNATTENDED: 'UNATTENDED'
24
+ });
25
+
26
+ const ALLOWED_TRANSITIONS = Object.freeze({
27
+ STARTED: ['GOAL_FROZEN'],
28
+ GOAL_FROZEN: ['REPORTED', 'MAKER_COMPLETE'],
29
+ REPORTED: [],
30
+ MAKER_COMPLETE: ['VERIFIED'],
31
+ VERIFIED: ['REVIEWED'],
32
+ REVIEWED: ['GOAL_FROZEN', 'JUDGED_PASS', 'ESCALATED'],
33
+ JUDGED_PASS: ['DELIVERED'],
34
+ DELIVERED: [],
35
+ ESCALATED: []
36
+ });
37
+
38
+ const TERMINAL_STATES = new Set([RUN_STATES.REPORTED, RUN_STATES.DELIVERED, RUN_STATES.ESCALATED]);
39
+
40
+ function runsDir(rootDir) {
41
+ return path.join(rootDir, '.ai-engineering-loop', 'runs');
42
+ }
43
+
44
+ function assertRunId(runId) {
45
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(String(runId || ''))) {
46
+ const err = new Error(`Invalid run id: ${runId || '(empty)'}`);
47
+ err.code = 'INVALID_RUN_ID';
48
+ throw err;
49
+ }
50
+ return runId;
51
+ }
52
+
53
+ function atomicWritePrivateFile(filePath, content) {
54
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
55
+ const temporary = `${filePath}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
56
+ try {
57
+ fs.writeFileSync(temporary, content, { mode: 0o600 });
58
+ fs.renameSync(temporary, filePath);
59
+ fs.chmodSync(filePath, 0o600);
60
+ } finally {
61
+ try {
62
+ fs.unlinkSync(temporary);
63
+ } catch {
64
+ // Rename succeeded or no temporary file was written.
65
+ }
66
+ }
67
+ }
68
+
69
+ function atomicWriteJson(filePath, value) {
70
+ atomicWritePrivateFile(filePath, `${JSON.stringify(value, null, 2)}\n`);
71
+ }
72
+
73
+ function readJson(filePath, label) {
74
+ try {
75
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
76
+ } catch (cause) {
77
+ const err = new Error(`Unable to read ${label}: ${cause.message}`);
78
+ err.code = 'INVALID_RUN_STATE';
79
+ err.cause = cause;
80
+ throw err;
81
+ }
82
+ }
83
+
84
+ function getGitRevision(rootDir) {
85
+ try {
86
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
87
+ cwd: rootDir,
88
+ encoding: 'utf8',
89
+ stdio: ['ignore', 'pipe', 'ignore']
90
+ }).trim();
91
+ } catch {
92
+ return 'untracked';
93
+ }
94
+ }
95
+
96
+ function newRunId(now = new Date()) {
97
+ const timestamp = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
98
+ return `${timestamp}-${crypto.randomUUID().slice(0, 8)}`;
99
+ }
100
+
101
+ function runStatePath(rootDir, runId) {
102
+ return path.join(runsDir(rootDir), assertRunId(runId), 'state.json');
103
+ }
104
+
105
+ function currentRunPath(rootDir) {
106
+ return path.join(runsDir(rootDir), 'current.json');
107
+ }
108
+
109
+ function loadRun(rootDir, runId) {
110
+ const state = readJson(runStatePath(rootDir, runId), `run ${runId}`);
111
+ if (
112
+ state.runId !== runId ||
113
+ !RUN_STATES[state.state] ||
114
+ (state.mode != null && !Object.values(RUN_MODES).includes(state.mode))
115
+ ) {
116
+ const err = new Error(`Run ${runId} has an invalid state document`);
117
+ err.code = 'INVALID_RUN_STATE';
118
+ throw err;
119
+ }
120
+ return state;
121
+ }
122
+
123
+ function getCurrentRun(rootDir) {
124
+ const pointer = currentRunPath(rootDir);
125
+ if (!fs.existsSync(pointer)) return null;
126
+ const { runId } = readJson(pointer, 'current run pointer');
127
+ return loadRun(rootDir, assertRunId(runId));
128
+ }
129
+
130
+ function normalizeRunMode(mode) {
131
+ const normalized = String(mode || RUN_MODES.ASSISTED).trim().replace(/-/g, '_').toUpperCase();
132
+ if (!Object.hasOwn(RUN_MODES, normalized)) {
133
+ const err = new Error(`Invalid run mode: ${mode}`);
134
+ err.code = 'INVALID_RUN_MODE';
135
+ throw err;
136
+ }
137
+ return RUN_MODES[normalized];
138
+ }
139
+
140
+ function createRun(rootDir, { task = '', runId = newRunId(), mode = RUN_MODES.ASSISTED, now = new Date() } = {}) {
141
+ assertRunId(runId);
142
+ const statePath = runStatePath(rootDir, runId);
143
+ if (fs.existsSync(statePath)) {
144
+ const err = new Error(`Run already exists: ${runId}`);
145
+ err.code = 'RUN_EXISTS';
146
+ throw err;
147
+ }
148
+
149
+ const timestamp = now.toISOString();
150
+ const state = {
151
+ schemaVersion: 1,
152
+ runId,
153
+ state: RUN_STATES.STARTED,
154
+ mode: normalizeRunMode(mode),
155
+ iteration: 1,
156
+ task: String(task || '').trim(),
157
+ startedRevision: getGitRevision(rootDir),
158
+ createdAt: timestamp,
159
+ updatedAt: timestamp,
160
+ artifacts: {},
161
+ history: [
162
+ {
163
+ from: null,
164
+ to: RUN_STATES.STARTED,
165
+ gate: 'start',
166
+ at: timestamp
167
+ }
168
+ ]
169
+ };
170
+
171
+ atomicWriteJson(statePath, state);
172
+ atomicWriteJson(currentRunPath(rootDir), { schemaVersion: 1, runId });
173
+ return state;
174
+ }
175
+
176
+ function createOrResumeRun(rootDir, { task = '', mode = null, forceNew = false, now = new Date() } = {}) {
177
+ const current = getCurrentRun(rootDir);
178
+ const requestedTask = String(task || '').trim();
179
+ if (current && !TERMINAL_STATES.has(current.state) && !forceNew) {
180
+ if (requestedTask && current.task && requestedTask !== current.task) {
181
+ const err = new Error(
182
+ `Run ${current.runId} is still ${current.state}. Resume it or pass --new to start another task.`
183
+ );
184
+ err.code = 'ACTIVE_RUN';
185
+ throw err;
186
+ }
187
+ if (mode && normalizeRunMode(mode) !== (current.mode || RUN_MODES.ASSISTED)) {
188
+ const err = new Error(`Run ${current.runId} is already ${(current.mode || RUN_MODES.ASSISTED)}; mode cannot change during a run.`);
189
+ err.code = 'RUN_MODE_MISMATCH';
190
+ throw err;
191
+ }
192
+ return { run: current, resumed: true };
193
+ }
194
+ return {
195
+ run: createRun(rootDir, { task: requestedTask, mode: mode || RUN_MODES.ASSISTED, now }),
196
+ resumed: false
197
+ };
198
+ }
199
+
200
+ function transitionRun(
201
+ rootDir,
202
+ runId,
203
+ to,
204
+ { gate, artifacts = {}, reason = null, incrementIteration = false, now = new Date() } = {}
205
+ ) {
206
+ const run = loadRun(rootDir, runId);
207
+ if (!RUN_STATES[to]) {
208
+ const err = new Error(`Unknown run state: ${to}`);
209
+ err.code = 'UNKNOWN_RUN_STATE';
210
+ throw err;
211
+ }
212
+ if (!ALLOWED_TRANSITIONS[run.state].includes(to)) {
213
+ const err = new Error(`Invalid transition: ${run.state} -> ${to}`);
214
+ err.code = 'INVALID_TRANSITION';
215
+ throw err;
216
+ }
217
+
218
+ const timestamp = now.toISOString();
219
+ const next = {
220
+ ...run,
221
+ state: to,
222
+ iteration: incrementIteration ? run.iteration + 1 : run.iteration,
223
+ updatedAt: timestamp,
224
+ artifacts: { ...run.artifacts, ...artifacts },
225
+ history: [
226
+ ...run.history,
227
+ {
228
+ from: run.state,
229
+ to,
230
+ gate: gate || 'unspecified',
231
+ at: timestamp,
232
+ ...(reason ? { reason } : {})
233
+ }
234
+ ]
235
+ };
236
+ atomicWriteJson(runStatePath(rootDir, runId), next);
237
+ atomicWriteJson(currentRunPath(rootDir), { schemaVersion: 1, runId });
238
+ return next;
239
+ }
240
+
241
+ module.exports = {
242
+ RUN_STATES,
243
+ RUN_MODES,
244
+ ALLOWED_TRANSITIONS,
245
+ TERMINAL_STATES,
246
+ runsDir,
247
+ assertRunId,
248
+ runStatePath,
249
+ currentRunPath,
250
+ atomicWritePrivateFile,
251
+ atomicWriteJson,
252
+ getGitRevision,
253
+ newRunId,
254
+ normalizeRunMode,
255
+ loadRun,
256
+ getCurrentRun,
257
+ createRun,
258
+ createOrResumeRun,
259
+ transitionRun
260
+ };
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const PRIVATE_RUNTIME_PATTERNS = Object.freeze([
7
+ 'runs/',
8
+ 'usage/',
9
+ 'worktrees/',
10
+ 'locks/',
11
+ 'tasks/current.diff',
12
+ 'tasks/*.log'
13
+ ]);
14
+
15
+ const PRIVATE_RUNTIME_GITIGNORE =
16
+ `# Runtime artifacts may contain source excerpts and verification logs.\n${PRIVATE_RUNTIME_PATTERNS.join('\n')}\n`;
17
+
18
+ function assertNotSymlink(filePath, label) {
19
+ let stat;
20
+ try {
21
+ stat = fs.lstatSync(filePath);
22
+ } catch (cause) {
23
+ if (cause.code !== 'ENOENT') throw cause;
24
+ }
25
+ if (stat?.isSymbolicLink()) {
26
+ const err = new Error(`${label} must not be a symbolic link`);
27
+ err.code = 'UNSAFE_RUNTIME_PATH';
28
+ throw err;
29
+ }
30
+ }
31
+
32
+ function ensurePrivateRuntimeIgnores(rootDir) {
33
+ const contextDir = path.join(rootDir, '.ai-engineering-loop');
34
+ assertNotSymlink(contextDir, '.ai-engineering-loop');
35
+ fs.mkdirSync(contextDir, { recursive: true });
36
+ const filePath = path.join(contextDir, '.gitignore');
37
+ assertNotSymlink(filePath, '.ai-engineering-loop/.gitignore');
38
+ const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
39
+ const missing = PRIVATE_RUNTIME_PATTERNS.filter((pattern) => (
40
+ !existing.split(/\r?\n/).includes(pattern)
41
+ ));
42
+ if (missing.length === 0) return false;
43
+ const separator = existing && !existing.endsWith('\n') ? '\n' : '';
44
+ const header = existing ? '' : '# Runtime artifacts may contain source excerpts and verification logs.\n';
45
+ fs.writeFileSync(filePath, `${existing}${separator}${header}${missing.join('\n')}\n`);
46
+ return true;
47
+ }
48
+
49
+ module.exports = {
50
+ PRIVATE_RUNTIME_PATTERNS,
51
+ PRIVATE_RUNTIME_GITIGNORE,
52
+ ensurePrivateRuntimeIgnores
53
+ };
@@ -0,0 +1,118 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const {
6
+ RUN_MODES,
7
+ atomicWriteJson
8
+ } = require('./run-state.js');
9
+
10
+ const DEFAULT_POLICY = Object.freeze({
11
+ schemaVersion: 1,
12
+ defaultMode: RUN_MODES.ASSISTED,
13
+ allowUnattended: false,
14
+ requireSandboxForUnattended: true,
15
+ perRunTokenLimit: 50_000,
16
+ dailyTokenLimit: 200_000,
17
+ killSwitch: false
18
+ });
19
+
20
+ function policyPath(rootDir) {
21
+ return path.join(rootDir, '.ai-engineering-loop', 'runtime-policy.json');
22
+ }
23
+
24
+ function normalizeMode(value, fallback = null) {
25
+ if (value == null || value === '') return fallback;
26
+ const normalized = String(value).trim().replace(/-/g, '_').toUpperCase();
27
+ if (!Object.hasOwn(RUN_MODES, normalized)) {
28
+ const err = new Error(`Unknown run mode: ${value}. Use report-only|assisted|unattended`);
29
+ err.code = 'INVALID_RUN_MODE';
30
+ throw err;
31
+ }
32
+ return RUN_MODES[normalized];
33
+ }
34
+
35
+ function validatePolicy(value) {
36
+ const errors = [];
37
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
38
+ return ['runtime policy must be a JSON object'];
39
+ }
40
+ if (value.schemaVersion !== 1) errors.push('schemaVersion must be 1');
41
+ try {
42
+ normalizeMode(value.defaultMode);
43
+ } catch (cause) {
44
+ errors.push(cause.message);
45
+ }
46
+ for (const key of ['allowUnattended', 'requireSandboxForUnattended', 'killSwitch']) {
47
+ if (typeof value[key] !== 'boolean') errors.push(`${key} must be boolean`);
48
+ }
49
+ for (const key of ['perRunTokenLimit', 'dailyTokenLimit']) {
50
+ if (!Number.isSafeInteger(value[key]) || value[key] <= 0) {
51
+ errors.push(`${key} must be a positive integer`);
52
+ }
53
+ }
54
+ return errors;
55
+ }
56
+
57
+ function loadPolicy(rootDir) {
58
+ const filePath = policyPath(rootDir);
59
+ if (!fs.existsSync(filePath)) return { ...DEFAULT_POLICY };
60
+ let parsed;
61
+ try {
62
+ parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
63
+ } catch (cause) {
64
+ const err = new Error(`Unable to read runtime policy: ${cause.message}`);
65
+ err.code = 'INVALID_RUNTIME_POLICY';
66
+ throw err;
67
+ }
68
+ const policy = { ...DEFAULT_POLICY, ...parsed };
69
+ const errors = validatePolicy(policy);
70
+ if (errors.length) {
71
+ const err = new Error(`Invalid runtime policy: ${errors.join('; ')}`);
72
+ err.code = 'INVALID_RUNTIME_POLICY';
73
+ err.details = errors;
74
+ throw err;
75
+ }
76
+ policy.defaultMode = normalizeMode(policy.defaultMode);
77
+ return policy;
78
+ }
79
+
80
+ function writePolicy(rootDir, policy) {
81
+ const next = { ...DEFAULT_POLICY, ...policy, schemaVersion: 1 };
82
+ next.defaultMode = normalizeMode(next.defaultMode);
83
+ const errors = validatePolicy(next);
84
+ if (errors.length) {
85
+ const err = new Error(`Invalid runtime policy: ${errors.join('; ')}`);
86
+ err.code = 'INVALID_RUNTIME_POLICY';
87
+ err.details = errors;
88
+ throw err;
89
+ }
90
+ atomicWriteJson(policyPath(rootDir), next);
91
+ return next;
92
+ }
93
+
94
+ function updatePolicy(rootDir, changes) {
95
+ return writePolicy(rootDir, { ...loadPolicy(rootDir), ...changes });
96
+ }
97
+
98
+ function assertModeAllowed(rootDir, mode) {
99
+ const normalized = normalizeMode(mode);
100
+ const policy = loadPolicy(rootDir);
101
+ if (normalized === RUN_MODES.UNATTENDED && !policy.allowUnattended) {
102
+ const err = new Error('UNATTENDED mode is disabled by runtime policy; a human must explicitly enable allowUnattended');
103
+ err.code = 'UNATTENDED_DISABLED';
104
+ throw err;
105
+ }
106
+ return policy;
107
+ }
108
+
109
+ module.exports = {
110
+ DEFAULT_POLICY,
111
+ policyPath,
112
+ normalizeMode,
113
+ validatePolicy,
114
+ loadPolicy,
115
+ writePolicy,
116
+ updatePolicy,
117
+ assertModeAllowed
118
+ };
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { atomicWriteJson, getCurrentRun, loadRun, runsDir } = require('./run-state.js');
7
+ const { assertBudgetAvailable } = require('./budget.js');
8
+
9
+ const STAGE_LIMITS = Object.freeze({
10
+ maker: Object.freeze({ maxFiles: 12, maxFileBytes: 32_000, maxTotalBytes: 96_000, maxEstimatedTokens: 24_000 }),
11
+ 'devil-advocate': Object.freeze({ maxFiles: 8, maxFileBytes: 16_000, maxTotalBytes: 64_000, maxEstimatedTokens: 16_000 }),
12
+ judge: Object.freeze({ maxFiles: 3, maxFileBytes: 12_000, maxTotalBytes: 32_000, maxEstimatedTokens: 8_000 })
13
+ });
14
+
15
+ const SENSITIVE_NAMES = [
16
+ /^\.env(?:\.|$)/i,
17
+ /^\.npmrc$/i,
18
+ /^\.netrc$/i,
19
+ /^credentials(?:\.json)?$/i,
20
+ /^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/i,
21
+ /\.(?:pem|key|p12|pfx|jks)$/i
22
+ ];
23
+
24
+ function contextError(message, code = 'UNSAFE_CONTEXT') {
25
+ const err = new Error(message);
26
+ err.code = code;
27
+ return err;
28
+ }
29
+
30
+ function inside(parent, child) {
31
+ const relative = path.relative(parent, child);
32
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
33
+ }
34
+
35
+ function isSensitivePath(relativePath) {
36
+ const segments = relativePath.split(/[\\/]/);
37
+ if (segments.includes('.git') || segments.includes('node_modules')) return true;
38
+ return segments.some((segment) => SENSITIVE_NAMES.some((pattern) => pattern.test(segment)));
39
+ }
40
+
41
+ function resolveSafeRepoFile(rootDir, relativePath) {
42
+ if (!relativePath || path.isAbsolute(relativePath)) {
43
+ throw contextError(`Context path must be repository-relative: ${relativePath || '(empty)'}`);
44
+ }
45
+ const root = fs.realpathSync(rootDir);
46
+ const requested = path.resolve(root, relativePath);
47
+ if (!inside(root, requested)) throw contextError(`Context path escapes the repository: ${relativePath}`);
48
+ const normalized = path.relative(root, requested);
49
+ if (isSensitivePath(normalized)) throw contextError(`Sensitive context path is blocked: ${relativePath}`);
50
+
51
+ let real;
52
+ try {
53
+ real = fs.realpathSync(requested);
54
+ } catch (cause) {
55
+ throw contextError(`Context file is unavailable: ${relativePath} (${cause.message})`, 'CONTEXT_FILE_MISSING');
56
+ }
57
+ if (!inside(root, real)) throw contextError(`Context symlink escapes the repository: ${relativePath}`);
58
+ const stat = fs.statSync(real);
59
+ if (!stat.isFile()) throw contextError(`Context path is not a file: ${relativePath}`);
60
+ return { absolute: real, relative: path.relative(root, real).split(path.sep).join('/') };
61
+ }
62
+
63
+ function redactSecrets(input) {
64
+ let text = String(input || '');
65
+ const categories = new Set();
66
+ const replace = (pattern, category, replacement) => {
67
+ text = text.replace(pattern, (...args) => {
68
+ categories.add(category);
69
+ return typeof replacement === 'function' ? replacement(...args) : replacement;
70
+ });
71
+ };
72
+
73
+ replace(
74
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
75
+ 'private-key',
76
+ '[REDACTED PRIVATE KEY]'
77
+ );
78
+ replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, 'bearer-token', 'Bearer [REDACTED]');
79
+ replace(/\bgithub_pat_[A-Za-z0-9_]{12,}\b/g, 'github-token', '[REDACTED GITHUB TOKEN]');
80
+ replace(/\bgh[pousr]_[A-Za-z0-9]{12,}\b/g, 'github-token', '[REDACTED GITHUB TOKEN]');
81
+ replace(/\bAKIA[A-Z0-9]{16}\b/g, 'aws-access-key', '[REDACTED AWS ACCESS KEY]');
82
+ replace(/\bsk-(?:live-|test-)?[A-Za-z0-9_-]{8,}\b/g, 'api-token', '[REDACTED API TOKEN]');
83
+ replace(
84
+ /(\b(?:api[_-]?key|access[_-]?token|auth[_-]?token|secret|password|authorization)\b\s*[:=]\s*["']?)([^"'\s,;]+)/gi,
85
+ 'key-value-secret',
86
+ (_match, prefix) => `${prefix}[REDACTED]`
87
+ );
88
+
89
+ return { text, categories: [...categories].sort() };
90
+ }
91
+
92
+ function sha256(content) {
93
+ return crypto.createHash('sha256').update(content).digest('hex');
94
+ }
95
+
96
+ function estimateTokens(text) {
97
+ return Math.ceil(String(text || '').length / 4);
98
+ }
99
+
100
+ function resolveRun(rootDir, runId) {
101
+ if (runId) return loadRun(rootDir, runId);
102
+ const current = getCurrentRun(rootDir);
103
+ if (!current) throw contextError('No current run. Start one before building context.', 'NO_CURRENT_RUN');
104
+ return current;
105
+ }
106
+
107
+ function createContextPack(rootDir, { runId, stage, files } = {}) {
108
+ const limits = STAGE_LIMITS[stage];
109
+ if (!limits) {
110
+ throw contextError(`Unknown context stage: ${stage}. Use ${Object.keys(STAGE_LIMITS).join('|')}`, 'UNKNOWN_CONTEXT_STAGE');
111
+ }
112
+ const run = resolveRun(rootDir, runId);
113
+ assertBudgetAvailable(rootDir, { runId: run.runId });
114
+ const uniqueFiles = [...new Set((files || []).map((file) => String(file).trim()).filter(Boolean))];
115
+ if (uniqueFiles.length === 0) throw contextError('At least one context file is required', 'EMPTY_CONTEXT');
116
+ if (uniqueFiles.length > limits.maxFiles) {
117
+ throw contextError(`${stage} context allows at most ${limits.maxFiles} files`, 'CONTEXT_FILE_LIMIT');
118
+ }
119
+
120
+ const entries = [];
121
+ let totalBytes = 0;
122
+ let estimatedTokens = 0;
123
+ for (const requested of uniqueFiles) {
124
+ const safe = resolveSafeRepoFile(rootDir, requested);
125
+ const raw = fs.readFileSync(safe.absolute);
126
+ if (raw.includes(0)) throw contextError(`Binary context is blocked: ${requested}`, 'BINARY_CONTEXT');
127
+
128
+ const remaining = limits.maxTotalBytes - totalBytes;
129
+ if (remaining <= 0) throw contextError(`${stage} context exceeds its byte budget`, 'CONTEXT_BYTE_LIMIT');
130
+ const allowedBytes = Math.min(raw.length, limits.maxFileBytes, remaining);
131
+ const source = raw.subarray(0, allowedBytes).toString('utf8');
132
+ const redacted = redactSecrets(source);
133
+ const tokens = estimateTokens(redacted.text);
134
+ if (estimatedTokens + tokens > limits.maxEstimatedTokens) {
135
+ throw contextError(`${stage} context exceeds its estimated token budget`, 'CONTEXT_TOKEN_LIMIT');
136
+ }
137
+
138
+ totalBytes += allowedBytes;
139
+ estimatedTokens += tokens;
140
+ entries.push({
141
+ path: safe.relative,
142
+ sourceSha256: sha256(raw),
143
+ sourceBytes: raw.length,
144
+ includedBytes: allowedBytes,
145
+ estimatedTokens: tokens,
146
+ truncated: allowedBytes < raw.length,
147
+ redactions: redacted.categories,
148
+ content: redacted.text
149
+ });
150
+ }
151
+ assertBudgetAvailable(rootDir, { runId: run.runId, estimatedTokens });
152
+
153
+ const pack = {
154
+ schemaVersion: 1,
155
+ runId: run.runId,
156
+ stage,
157
+ createdAt: new Date().toISOString(),
158
+ transcriptInherited: false,
159
+ limits,
160
+ totalBytes,
161
+ estimatedTokens,
162
+ entries
163
+ };
164
+ const packPath = path.join(runsDir(rootDir), run.runId, 'context', `${stage}.json`);
165
+ atomicWriteJson(packPath, pack);
166
+ return {
167
+ pack,
168
+ path: path.relative(rootDir, packPath).split(path.sep).join('/')
169
+ };
170
+ }
171
+
172
+ function contextPackSummary(result) {
173
+ return {
174
+ schemaVersion: result.pack.schemaVersion,
175
+ runId: result.pack.runId,
176
+ stage: result.pack.stage,
177
+ path: result.path,
178
+ files: result.pack.entries.length,
179
+ totalBytes: result.pack.totalBytes,
180
+ estimatedTokens: result.pack.estimatedTokens,
181
+ redactions: result.pack.entries.reduce((sum, entry) => sum + entry.redactions.length, 0),
182
+ truncatedFiles: result.pack.entries.filter((entry) => entry.truncated).length
183
+ };
184
+ }
185
+
186
+ module.exports = {
187
+ STAGE_LIMITS,
188
+ isSensitivePath,
189
+ resolveSafeRepoFile,
190
+ redactSecrets,
191
+ estimateTokens,
192
+ createContextPack,
193
+ contextPackSummary
194
+ };