ensemble-review 1.0.35 → 1.0.36

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 (129) hide show
  1. package/package.json +5 -2
  2. package/dist/ai/check-tool.js +0 -6
  3. package/dist/api/routes/auth.js +0 -194
  4. package/dist/api/routes/billing.js +0 -209
  5. package/dist/api/routes/claude-review.js +0 -522
  6. package/dist/api/routes/contact.js +0 -318
  7. package/dist/api/routes/feed.js +0 -21
  8. package/dist/api/routes/inbox.js +0 -45
  9. package/dist/api/routes/mentions.js +0 -22
  10. package/dist/api/routes/teams.js +0 -150
  11. package/dist/api/routes/webhooks.js +0 -181
  12. package/dist/coding/activity.js +0 -80
  13. package/dist/coding/agent.js +0 -147
  14. package/dist/coding/ai-fix/checks-preview.js +0 -58
  15. package/dist/coding/ai-fix/comment-seed.js +0 -519
  16. package/dist/coding/ai-fix/prompts.js +0 -283
  17. package/dist/coding/ai-resolve/prompt.js +0 -161
  18. package/dist/coding/ai-resolve/routes.js +0 -97
  19. package/dist/coding/ai-resolve/run.js +0 -343
  20. package/dist/coding/ai-resolve/schema.js +0 -26
  21. package/dist/coding/ai-resolve/validate.js +0 -136
  22. package/dist/coding/checks/deny-scan.js +0 -75
  23. package/dist/coding/checks/discover.js +0 -541
  24. package/dist/coding/checks/docker.js +0 -38
  25. package/dist/coding/checks/env.js +0 -88
  26. package/dist/coding/checks/hooks.js +0 -91
  27. package/dist/coding/checks/index.js +0 -8
  28. package/dist/coding/checks/local.js +0 -40
  29. package/dist/coding/checks/sandbox.js +0 -206
  30. package/dist/coding/checks/session.js +0 -518
  31. package/dist/coding/checks/spawn.js +0 -123
  32. package/dist/coding/checks/spec.js +0 -140
  33. package/dist/coding/checks/types.js +0 -6
  34. package/dist/coding/partial-spend.js +0 -19
  35. package/dist/coding/safe-path.js +0 -75
  36. package/dist/coding/story-build/build-prompts.js +0 -178
  37. package/dist/coding/story-build/build.js +0 -332
  38. package/dist/coding/story-build/checkouts.js +0 -66
  39. package/dist/coding/story-build/docs-runner.js +0 -178
  40. package/dist/coding/story-build/docs.js +0 -334
  41. package/dist/coding/story-build/manager.js +0 -999
  42. package/dist/coding/story-build/plan-agent.js +0 -190
  43. package/dist/coding/story-build/plan.js +0 -338
  44. package/dist/coding/story-build/prompts.js +0 -147
  45. package/dist/coding/story-build/routes-docs.js +0 -113
  46. package/dist/coding/story-build/routes.js +0 -295
  47. package/dist/coding/story-build/schema.js +0 -53
  48. package/dist/db/automation-output.js +0 -349
  49. package/dist/db/credits.js +0 -79
  50. package/dist/db/schema.js +0 -321
  51. package/dist/db/schema.pg.js +0 -2197
  52. package/dist/db/sprint-repo-suggest.js +0 -257
  53. package/dist/db/sprint-stories.js +0 -42
  54. package/dist/db/sprint-story.js +0 -505
  55. package/dist/db/sprint-ticket-repos.js +0 -195
  56. package/dist/db/story-selection.js +0 -270
  57. package/dist/db/team-comparison.js +0 -124
  58. package/dist/db/workspace-comparison.js +0 -98
  59. package/dist/feed/fyi-provider.js +0 -10
  60. package/dist/github/local-user.js +0 -92
  61. package/dist/github/repo-files.js +0 -26
  62. package/dist/ml/worker.js +0 -31
  63. package/dist/platform/advisor/discovery/tier2.js +0 -88
  64. package/dist/platform/advisor/discovery/tier3.js +0 -57
  65. package/dist/platform/advisor/emitters/adapter.js +0 -5
  66. package/dist/platform/advisor/emitters/coderabbit.js +0 -175
  67. package/dist/platform/advisor/emitters/copilot-prose.js +0 -118
  68. package/dist/platform/advisor/emitters/greptile.js +0 -176
  69. package/dist/platform/advisor/emitters/lint.js +0 -37
  70. package/dist/platform/advisor/emitters/manifest.js +0 -239
  71. package/dist/platform/advisor/emitters/prose.js +0 -183
  72. package/dist/platform/advisor/emitters/registry.js +0 -20
  73. package/dist/platform/advisor/emitters/yaml-doc.js +0 -95
  74. package/dist/platform/advisor/evidence.js +0 -79
  75. package/dist/platform/advisor/findings.js +0 -15
  76. package/dist/platform/advisor/intents.js +0 -269
  77. package/dist/platform/advisor/measure/effect.js +0 -18
  78. package/dist/platform/advisor/outputs/brief.js +0 -68
  79. package/dist/platform/advisor/outputs/config-pr.js +0 -156
  80. package/dist/platform/advisor/refine/diff-guard.js +0 -38
  81. package/dist/platform/advisor/refine/refine.js +0 -35
  82. package/dist/platform/advisor/retro-check.js +0 -98
  83. package/dist/platform/advisor/routes.js +0 -648
  84. package/dist/platform/advisor/store.js +0 -321
  85. package/dist/platform/advisor/taxonomy.js +0 -67
  86. package/dist/platform/annotations/prompts.js +0 -84
  87. package/dist/platform/annotations/routes.js +0 -86
  88. package/dist/platform/annotations/runner.js +0 -234
  89. package/dist/platform/annotations/targets.js +0 -203
  90. package/dist/platform/insights/grounded-figures.js +0 -162
  91. package/dist/platform/insights/period-questions.js +0 -235
  92. package/dist/platform/work-plan/hash.js +0 -99
  93. package/dist/platform/work-plan/prompt.js +0 -209
  94. package/dist/platform/work-plan/routes.js +0 -350
  95. package/dist/pro/bind.js +0 -309
  96. package/dist/pro/contract.js +0 -36
  97. package/dist/pro/event-hooks.js +0 -37
  98. package/dist/pro/migrate.js +0 -64
  99. package/dist/review/events.js +0 -24
  100. package/dist/review/local-settings.js +0 -78
  101. package/dist/review/memory/capture.js +0 -0
  102. package/dist/review/memory/retrieval.js +0 -272
  103. package/dist/review/memory/routes.js +0 -78
  104. package/dist/review/persist.js +0 -203
  105. package/dist/review/plugin-providers.js +0 -12
  106. package/dist/review/prompt.js +0 -264
  107. package/dist/review/review-manager.js +0 -259
  108. package/dist/review/routing.js +0 -164
  109. package/dist/review/sprint-assess/agent.js +0 -145
  110. package/dist/review/sprint-assess/manager.js +0 -382
  111. package/dist/review/sprint-assess/prompts.js +0 -99
  112. package/dist/review/sprint-assess/routes.js +0 -109
  113. package/dist/review/sprint-assess/schema.js +0 -70
  114. package/dist/review/sprint-assess/validate.js +0 -180
  115. package/dist/review/sprint-story/manager.js +0 -98
  116. package/dist/review/sprint-story/prompt.js +0 -45
  117. package/dist/review/sprint-story/validate.js +0 -127
  118. package/dist/review/story-docs/build-prompts.js +0 -153
  119. package/dist/review/story-docs/build-validate.js +0 -162
  120. package/dist/review/story-report/agent.js +0 -203
  121. package/dist/review/story-report/fingerprint.js +0 -45
  122. package/dist/review/story-report/manager.js +0 -287
  123. package/dist/review/story-report/routes.js +0 -154
  124. package/dist/review/story-report/story-detail.js +0 -148
  125. package/dist/review/story-report/validate.js +0 -105
  126. package/dist/review/ticket-review/sweep-waits.js +0 -20
  127. package/dist/review/write-deny.js +0 -170
  128. package/dist/shared/conflict-ai.js +0 -24
  129. package/dist/sync/benchmark-rollup.js +0 -50
@@ -1,343 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { config } from '../../config.js';
3
- import { getAccessToken } from '../../auth/account.js';
4
- import { claudeModelChoice, expectedRanOn, getProvider, } from '../../ai/provider.js';
5
- import { activeProviderId } from '../../ai/provider-setting.js';
6
- import { claimSession, getSession, peekSession, subscribe, } from '../../conflict/session.js';
7
- import { acceptAiChoices, AI_CHOICE_REFUSAL_TEXT } from './validate.js';
8
- import { buildAiResolvePrompt } from './prompt.js';
9
- import { partialSpendOf } from '../partial-spend.js';
10
- import { providerName } from '../../ai/prompt-tools.js';
11
- import { withWorktreeOwner } from '../../review/worktree-owner.js';
12
- /**
13
- * "RESOLVE WITH CLAUDE" — the agentic half of the merge-conflict resolver (CORE, free, LOCAL ONLY:
14
- * registered by `registerAgenticRoutes`, which refuses in cloud and under LIMN_AI_DISABLED).
15
- *
16
- * One run = one conflict SESSION (built or reused), then one read-only agent run in a worktree at
17
- * the session's pinned head, answering with resolver decisions through `submit_resolution`. The
18
- * answer is stored ON THE SESSION (`rec.ai`) and the reader reviews it in the resolver.
19
- *
20
- * ⚠ NOTHING IS COMMITTED OR PUSHED HERE. The reader presses "Commit and push" through the
21
- * resolver's own gate and land path, exactly as for decisions they made by hand.
22
- *
23
- * ⚠ THE AGENT CAN ONLY READ. Read/Glob/Grep plus the submit tool; Bash, NotebookEdit and every
24
- * write tool are denied outright. It has no reason to write — its answer is decisions, validated by
25
- * `acceptAiChoices` — and the conflict text it reads is attacker-authored.
26
- *
27
- * ⚠ ONE RUN PER ACCOUNT, claimed SYNCHRONOUSLY (no `await` between the check and the write), the
28
- * AI in-flight-slot rule. A second click on another PR is told about the reader's own run.
29
- */
30
- const READ_TOOLS = ['Read', 'Glob', 'Grep', 'mcp__resolve__submit_resolution'];
31
- const DENIED_TOOLS = ['Bash', 'NotebookEdit', 'Write', 'Edit', 'MultiEdit'];
32
- /** Accounts with a run in flight. */
33
- const runningAccounts = new Set();
34
- function freshView(rec, model) {
35
- return {
36
- runId: randomUUID(),
37
- prId: rec.prId,
38
- sessionId: rec.sessionId,
39
- headSha: rec.model?.headSha ?? '',
40
- baseSha: rec.model?.baseSha ?? '',
41
- modelHash: rec.modelHash,
42
- baseRef: rec.model?.baseRef ?? '',
43
- status: rec.status === 'preparing' ? 'preparing' : 'running',
44
- error: null,
45
- // Labelled by the provider it is expected to run on; the run stamps its own when it starts.
46
- ...expectedRanOn(claudeModelChoice(model)),
47
- startedAt: new Date().toISOString(),
48
- finishedAt: null,
49
- choices: [],
50
- decidableTotal: 0,
51
- summary: null,
52
- costUsd: null,
53
- };
54
- }
55
- export async function startAiResolve(ctx, input) {
56
- const { accountId, prId } = input;
57
- const auth = ctx.llm.detectAuth('resolve');
58
- if (auth.status !== 'ok')
59
- return { status: 'no_auth', message: auth.message };
60
- // Local accounts are unmetered, so this never refuses there; it is here so the rule cannot be
61
- // forgotten if the feature ever leaves local.
62
- // ── THE SYNCHRONOUS CLAIM WINDOW. No `await` from here to `runningAccounts.add`. ──
63
- const live = peekSession(accountId, prId);
64
- if (live?.aiRunning && live.ai)
65
- return { status: 'running', resolution: live.ai.view };
66
- if (runningAccounts.has(accountId))
67
- return { status: 'busy_account' };
68
- // A CLEAN session is a fact about the base it was built against, and the base may have moved
69
- // since (nothing synced pins the base SHA). The entry is only offered while the synced verdict is
70
- // `conflicts`, so a clean session nobody is watching is rebuilt rather than believed — otherwise
71
- // every click 409s "no longer conflicts" until the session is reaped. One an overlay is showing
72
- // stays: tearing it down would close the reader's own "no conflicts" view.
73
- if (live && live.status === 'clean' && live.subscribers.size > 0) {
74
- return { status: 'no_conflicts', baseRef: live.model?.baseRef ?? 'the base branch' };
75
- }
76
- const staleClean = live != null && live.status === 'clean';
77
- // A failed build is not worth re-attaching to; a ready or preparing one is — unless it is pinned
78
- // to a head the PR has since moved off and nobody has it open.
79
- const stale = live != null &&
80
- live.status === 'ready' &&
81
- input.headSha != null &&
82
- live.model != null &&
83
- live.model.headSha !== input.headSha &&
84
- live.subscribers.size === 0;
85
- const claim = claimSession(accountId, prId, {
86
- restart: live != null && (live.status === 'failed' || stale || staleClean),
87
- autoApply: false,
88
- });
89
- if (claim.kind === 'busy') {
90
- if (claim.reason === 'account')
91
- return { status: 'busy_account' };
92
- if (claim.reason === 'pr')
93
- return { status: 'busy_pr' };
94
- return { status: 'busy_service' };
95
- }
96
- const rec = claim.session;
97
- const abort = new AbortController();
98
- rec.aiRunning = true;
99
- rec.ai = { view: freshView(rec, input.model), abort };
100
- runningAccounts.add(accountId);
101
- // ── end of the claim window ──
102
- void runJob(ctx, rec, claim.kind === 'created', input, abort);
103
- return { status: 'started', resolution: rec.ai.view };
104
- }
105
- /** Resolve once the session's build settles (ready, clean or failed), or it is dropped. */
106
- function waitForBuild(rec) {
107
- if (rec.status !== 'preparing')
108
- return Promise.resolve();
109
- return new Promise((resolve) => {
110
- const unsub = subscribe(rec, (e) => {
111
- if (e.type === 'ready' || e.type === 'failed' || e.type === 'done') {
112
- unsub();
113
- resolve();
114
- }
115
- });
116
- // Settled between the check above and the subscribe.
117
- if (rec.status !== 'preparing') {
118
- unsub();
119
- resolve();
120
- }
121
- });
122
- }
123
- function settle(rec, patch) {
124
- if (!rec.ai)
125
- return;
126
- const { recentActivity: _drop, ...rest } = rec.ai.view;
127
- rec.ai.view = { ...rest, ...patch, finishedAt: new Date().toISOString() };
128
- }
129
- /** NEVER REJECTS — fired with `void`. */
130
- async function runJob(ctx, rec, created, input, abort) {
131
- let worktree = null;
132
- // Declared out here so the catch can keep what an answer already got accepted (below).
133
- const accepted = new Map();
134
- let summary = null;
135
- // CODEX: its final answer IS the call, so the FIRST answer with refused choices says so
136
- // (`isError`) to earn the provider's one retry with the refusals as its reason. A second answer
137
- // is kept as it is — the regions it still gets wrong stay undecided for the reader, exactly as
138
- // on Claude when the model stops calling. Claude's replies are today's, byte for byte.
139
- let codexRetryAsked = false;
140
- // The provider the run used, for its failure sentence (null until picked).
141
- let runProvider = null;
142
- try {
143
- if (created)
144
- await input.runOpen(rec, input.log);
145
- else
146
- await waitForBuild(rec);
147
- if (rec.status === 'clean') {
148
- settle(rec, {
149
- status: 'failed',
150
- error: `This pull request no longer conflicts with ${rec.model?.baseRef ?? 'its base branch'}.`,
151
- });
152
- return;
153
- }
154
- const model = rec.model;
155
- if (rec.status !== 'ready' || !model) {
156
- settle(rec, {
157
- status: 'failed',
158
- error: rec.error?.message ?? 'Couldn’t work out the conflicts in this pull request.',
159
- });
160
- return;
161
- }
162
- // THE PROVIDER IS PICKED ONCE: the prompt is worded for it (ai/prompt-tools.ts) and the run uses it.
163
- const provider = activeProviderId();
164
- runProvider = provider;
165
- const built = buildAiResolvePrompt(model, undefined, provider);
166
- if (rec.ai) {
167
- rec.ai.view = {
168
- ...rec.ai.view,
169
- status: 'running',
170
- headSha: model.headSha,
171
- baseSha: model.baseSha,
172
- modelHash: rec.modelHash,
173
- baseRef: model.baseRef,
174
- sessionId: rec.sessionId,
175
- decidableTotal: built.decidableTotal,
176
- // What runs it: the provider the prompt was worded for, and its model id.
177
- provider,
178
- model: getProvider(provider).resolveModel(claudeModelChoice(input.model)),
179
- };
180
- }
181
- if (built.offered.size === 0) {
182
- settle(rec, {
183
- status: 'failed',
184
- error: 'None of the conflicting files can be resolved here. Resolve them on GitHub.',
185
- });
186
- return;
187
- }
188
- if (abort.signal.aborted) {
189
- settle(rec, { status: 'cancelled' });
190
- return;
191
- }
192
- const [{ runAgentInWorktree }, { prepWorktree }, { submitResolutionShape }] = await Promise.all([
193
- import('../agent.js'),
194
- import('../../review/clone-manager.js'),
195
- import('./schema.js'),
196
- ]);
197
- const token = await getAccessToken(rec.accountId);
198
- const prepared = await withWorktreeOwner({ kind: 'resolve', accountId: rec.accountId, prId: rec.prId }, () => prepWorktree(model.owner, model.name, model.number, model.headSha, token));
199
- worktree = { owner: model.owner, name: model.name, ...prepared };
200
- const shape = await submitResolutionShape();
201
- const tools = {
202
- server: 'resolve',
203
- tools: [
204
- {
205
- name: 'submit_resolution',
206
- description: 'Submit your decisions for the conflict regions. Call again with only the refused ones to fix them.',
207
- shape,
208
- handle: (a) => {
209
- const p = a;
210
- if (typeof p.summary === 'string' && p.summary.trim() !== '') {
211
- summary = p.summary.trim().slice(0, 2000);
212
- }
213
- const rejected = acceptAiChoices(rec, p.choices ?? [], built.offered, accepted);
214
- if (rec.ai)
215
- rec.ai.view = { ...rec.ai.view, choices: [...accepted.values()] };
216
- const text = rejected.length === 0
217
- ? `Recorded. ${accepted.size} region(s) decided so far.`
218
- : [
219
- `Recorded ${accepted.size} region(s). Refused:`,
220
- ...rejected.map((r) => `- file=${r.file} region=${r.region}: ${AI_CHOICE_REFUSAL_TEXT[r.refusal]}`),
221
- ].join('\n');
222
- if (provider === 'codex' && rejected.length > 0 && !codexRetryAsked) {
223
- codexRetryAsked = true;
224
- return { text, isError: true };
225
- }
226
- return { text };
227
- },
228
- },
229
- ],
230
- };
231
- const outcome = await runAgentInWorktree({
232
- worktreePath: worktree.worktreePath,
233
- model: input.model,
234
- systemPrompt: built.system,
235
- prompt: built.prompt,
236
- allowedTools: READ_TOOLS,
237
- disallowedTools: DENIED_TOOLS,
238
- kind: 'resolve',
239
- tools,
240
- writes: false,
241
- maxTurns: config.aiFixMaxTurns,
242
- maxBudgetUsd: config.aiFixBudgetUsd,
243
- abortController: abort,
244
- onActivity: (activity) => {
245
- if (rec.ai)
246
- rec.ai.view = { ...rec.ai.view, recentActivity: activity.slice(-8) };
247
- },
248
- provider,
249
- usageRecord: { accountId: rec.accountId, seam: 'agent', feature: 'ai_resolve', prId: rec.prId },
250
- ...(input.codex ? { codex: input.codex } : {}),
251
- });
252
- // A provider that records its own usage (Codex) already wrote this run's row: never a second.
253
- if (!outcome.usageRecorded && outcome.costUsd != null && outcome.costUsd > 0) {
254
- await ctx
255
- .recordAiUsage({
256
- accountId: rec.accountId,
257
- seam: 'agent',
258
- feature: 'ai_resolve',
259
- model: input.model,
260
- costUsd: outcome.costUsd,
261
- inputTokens: outcome.usage.inputTokens,
262
- outputTokens: outcome.usage.outputTokens,
263
- prId: rec.prId,
264
- })
265
- .catch(() => { });
266
- }
267
- if (outcome.aborted || abort.signal.aborted) {
268
- settle(rec, { status: 'cancelled', choices: [], costUsd: outcome.costUsd });
269
- return;
270
- }
271
- settle(rec, {
272
- status: 'succeeded',
273
- choices: [...accepted.values()],
274
- summary,
275
- costUsd: outcome.costUsd,
276
- });
277
- }
278
- catch (err) {
279
- if (abort.signal.aborted) {
280
- settle(rec, { status: 'cancelled', choices: [] });
281
- }
282
- else if (codexRetryAsked && accepted.size > 0) {
283
- // CODEX: the first answer was partly refused and its one retry then FAILED (bad shape, a
284
- // non-zero exit, a timeout). What the first answer validly decided stands — as on Claude, where
285
- // a model that stops calling keeps every accepted region; the rest stay undecided for the
286
- // reader. (`codexRetryAsked` is only ever set on Codex.) Codex wrote its own ledger row.
287
- input.log.warn({ err, prId: rec.prId }, 'ai-resolve: the Codex retry failed; keeping the accepted choices');
288
- settle(rec, {
289
- status: 'succeeded',
290
- choices: [...accepted.values()],
291
- summary,
292
- costUsd: partialSpendOf(err)?.costUsd ?? null,
293
- });
294
- }
295
- else {
296
- input.log.warn({ err, prId: rec.prId }, 'ai-resolve run failed');
297
- settle(rec, { status: 'failed', error: `${providerName(runProvider ?? undefined)} couldn’t finish resolving these conflicts.` });
298
- }
299
- }
300
- finally {
301
- rec.aiRunning = false;
302
- if (rec.ai)
303
- rec.ai.abort = null;
304
- runningAccounts.delete(rec.accountId);
305
- // Keep the session alive past the run: the reader opens the resolver next.
306
- getSession(rec.accountId, rec.prId, rec.sessionId);
307
- if (worktree) {
308
- const wt = worktree;
309
- const { removeWorktreeLocked, cleanupCloneCache } = await import('../../review/clone-manager.js');
310
- await removeWorktreeLocked(wt.owner, wt.name, wt.repoCloneDir, wt.worktreePath).catch(() => { });
311
- setImmediate(() => {
312
- try {
313
- cleanupCloneCache();
314
- }
315
- catch {
316
- /* advisory */
317
- }
318
- });
319
- }
320
- }
321
- }
322
- /** This account's latest answer for the PR, or null. Touches the session (a read is not idle). */
323
- export function getAiResolution(accountId, prId) {
324
- const live = peekSession(accountId, prId);
325
- if (!live?.ai)
326
- return null;
327
- getSession(accountId, prId, live.sessionId);
328
- return live.ai.view;
329
- }
330
- /** Cancel this account's run on the PR. True when there was one to cancel. */
331
- export function cancelAiResolve(accountId, prId) {
332
- const live = peekSession(accountId, prId);
333
- if (!live?.aiRunning || !live.ai?.abort)
334
- return false;
335
- live.ai.abort.abort();
336
- return true;
337
- }
338
- /** Test seam only. */
339
- export const __testing = {
340
- runningAccounts,
341
- reset: () => runningAccounts.clear(),
342
- };
343
- //# sourceMappingURL=run.js.map
@@ -1,26 +0,0 @@
1
- import { loadZod } from '../../ai/runtime.js';
2
- /**
3
- * The `submit_resolution` tool's input. Loose on purpose (strings, not enums): an out-of-range
4
- * value is REFUSED BY `acceptAiChoices` with a reason the agent can act on, rather than rejected
5
- * by the SDK's schema layer with an error it cannot read.
6
- */
7
- export function buildSubmitResolutionShape(z) {
8
- return {
9
- choices: z
10
- .array(z.object({
11
- file: z.number(),
12
- region: z.number(),
13
- fingerprint: z.string(),
14
- decision: z.string(),
15
- lines: z.array(z.string()).optional(),
16
- rationale: z.string().optional(),
17
- confidence: z.string().optional(),
18
- }))
19
- .max(2000),
20
- summary: z.string().optional(),
21
- };
22
- }
23
- export async function submitResolutionShape() {
24
- return buildSubmitResolutionShape(await loadZod());
25
- }
26
- //# sourceMappingURL=schema.js.map
@@ -1,136 +0,0 @@
1
- import { CONFLICT_AI_DECISIONS } from '../../shared/index.js';
2
- import { config } from '../../config.js';
3
- import { allowedDecisions } from '../../conflict/model.js';
4
- import { storeEdit } from '../../conflict/session.js';
5
- import { editShapeFor, validateConflictEdit } from '../../conflict/suggestion.js';
6
- /** What the agent is told about a refusal, so it can fix the choice and submit it again. */
7
- export const AI_CHOICE_REFUSAL_TEXT = {
8
- unknown_region: 'no such file/region in this session',
9
- not_decidable: 'that region is unchanged context and takes no decision',
10
- not_offered: 'that region was not shown to you; leave it for the person',
11
- moved: 'fingerprint does not match the region; copy it exactly',
12
- not_allowed: 'that decision is not offered for this region',
13
- no_lines: "an 'edited' decision needs `lines`",
14
- not_text: 'the lines contain characters that cannot be saved to a file',
15
- markers: 'the lines still contain conflict markers',
16
- too_long: `an edited region can be at most ${config.conflictSuggestMaxChars} characters`,
17
- too_many_edits: 'too much edited text in this session; prefer taking a side',
18
- };
19
- const RATIONALE_MAX = 280;
20
- /** One line, trimmed and clipped. Model prose is rendered as plain text, never markup. */
21
- export function clipRationale(raw) {
22
- const one = (raw ?? '').replace(/\s+/g, ' ').trim();
23
- return one.length > RATIONALE_MAX ? `${one.slice(0, RATIONALE_MAX - 1)}…` : one;
24
- }
25
- function confidenceOf(raw) {
26
- return raw === 'high' || raw === 'low' ? raw : 'medium';
27
- }
28
- /** `${file}:${region}` — the resolver's own region key. */
29
- export const choiceKey = (file, region) => `${file}:${region}`;
30
- /**
31
- * Validate a batch of choices against the session and fold the accepted ones into `accepted`
32
- * (keyed `${file}:${region}`, a later choice for the same region REPLACING an earlier one — the
33
- * agent may resubmit after a refusal).
34
- *
35
- * ⚠ MUTATES THE SESSION only through `storeEdit`, and only for a choice that passed every check:
36
- * a refusal mints nothing. A replaced edit's handle is never evicted (`storeEdit`'s rule).
37
- */
38
- export function acceptAiChoices(rec, items, offered, accepted) {
39
- const model = rec.model;
40
- const rejected = [];
41
- const refuse = (it, refusal) => {
42
- rejected.push({ file: Number(it.file), region: Number(it.region), refusal });
43
- };
44
- if (!model) {
45
- for (const it of items)
46
- refuse(it, 'unknown_region');
47
- return rejected;
48
- }
49
- for (const it of items) {
50
- const file = model.files.find((f) => f.index === it.file) ?? null;
51
- const region = file?.regions.find((r) => r.id === it.region) ?? null;
52
- if (!file || !region || file.unsupported !== null) {
53
- refuse(it, 'unknown_region');
54
- continue;
55
- }
56
- if (region.kind === 'unchanged') {
57
- refuse(it, 'not_decidable');
58
- continue;
59
- }
60
- const key = choiceKey(file.index, region.id);
61
- if (!offered.has(key)) {
62
- refuse(it, 'not_offered');
63
- continue;
64
- }
65
- if (region.fingerprint !== it.fingerprint) {
66
- refuse(it, 'moved');
67
- continue;
68
- }
69
- const decision = it.decision;
70
- if (!CONFLICT_AI_DECISIONS.includes(decision)) {
71
- refuse(it, 'not_allowed');
72
- continue;
73
- }
74
- const rationale = clipRationale(it.rationale);
75
- const confidence = confidenceOf(it.confidence);
76
- if (decision !== 'edited') {
77
- // ⚠ THE MODEL'S OWN `allowed`, never a looser list: `disjoint_merge` exists only where the
78
- // wand proved the two edits disjoint, and a one-sided region offers its side and `base`.
79
- if (!allowedDecisions(region).includes(decision)) {
80
- refuse(it, 'not_allowed');
81
- continue;
82
- }
83
- accepted.set(key, {
84
- fileIndex: file.index,
85
- regionId: region.id,
86
- decision,
87
- editId: null,
88
- lines: null,
89
- rationale,
90
- confidence,
91
- });
92
- continue;
93
- }
94
- if (!Array.isArray(it.lines) || it.lines.some((l) => typeof l !== 'string')) {
95
- refuse(it, 'no_lines');
96
- continue;
97
- }
98
- // A model may echo a `\r` it saw; the region's own ending is re-imposed by the shape.
99
- const cleaned = it.lines.map((l) => l.replace(/\r$/, ''));
100
- const text = cleaned.join('\n');
101
- const shape = editShapeFor([region.base, region.ours, region.theirs], file.regions[0]?.id === region.id);
102
- const checked = validateConflictEdit(text, config.conflictSuggestMaxChars, shape);
103
- if (!checked.ok) {
104
- refuse(it, checked.refusal);
105
- continue;
106
- }
107
- // ⚠ ONE BLANK LINE IS NOT ZERO LINES. The text round trip cannot tell `['']` from `[]` (the
108
- // edit route reads an empty box as "delete the hunk"), but Claude submits an ARRAY, so a single
109
- // empty string is one blank line — given the region's own ending and BOM like any other line.
110
- if (cleaned.length === 1 && cleaned[0] === '' && checked.lines.length === 0) {
111
- checked.lines.push(`${shape.leadingBom ? '\uFEFF' : ''}${shape.crlf ? '\r' : ''}`);
112
- }
113
- const editId = storeEdit(rec, {
114
- fileIndex: file.index,
115
- regionId: region.id,
116
- lines: checked.lines,
117
- // Fold rule 4, as the edit route sets it: the OURS side's terminator.
118
- endsWithNewline: file.terminators.ours,
119
- });
120
- if (editId == null) {
121
- refuse(it, 'too_many_edits');
122
- continue;
123
- }
124
- accepted.set(key, {
125
- fileIndex: file.index,
126
- regionId: region.id,
127
- decision: 'edited',
128
- editId,
129
- lines: checked.lines,
130
- rationale,
131
- confidence,
132
- });
133
- }
134
- return rejected;
135
- }
136
- //# sourceMappingURL=validate.js.map
@@ -1,75 +0,0 @@
1
- // THE DENY SCAN (docs/SECURITY.md § Sandboxed checks): a CONSERVATIVE read of a declared script's
2
- // text before Limn will offer it as a check. It is the SECOND line, not the boundary — the OS sandbox
3
- // (sandbox.ts) is what confines a check that slips past it. Its job is to refuse, up front and in plain
4
- // words, a script whose text plainly does something a check must never do: build or start containers,
5
- // pipe a download into a shell, escalate, delete outside the tree, publish or push.
6
- //
7
- // What it does NOT refuse: a script that merely TALKS to services on localhost (a test that expects a
8
- // database the reader started with Docker). Starting the containers is the reader's job, not a check's.
9
- //
10
- // Pure: text in, a reason out. Node built-ins only.
11
- // A word boundary that also treats `&&`, `;`, `|`, `(` and backticks as the start of a command.
12
- const CMD = String.raw `(?:^|[\s;&|(\x60]|\$\()`;
13
- export const DENY_RULES = [
14
- // Containers: building, running, starting, pulling or pushing images. Talking to a running service
15
- // on localhost is fine; creating one from a check is not (it needs the Docker socket, which the
16
- // sandbox does not give, and a container is a way out of it).
17
- {
18
- re: new RegExp(`${CMD}(?:docker|podman|nerdctl)\\s+(?:[\\w-]+\\s+)*?(?:build|buildx|run|create|exec|start|pull|push|load|import|compose\\s+(?:[\\w-]+\\s+)*?(?:up|run|start|create|build|pull|exec))\\b`, 'i'),
19
- reason: 'It starts or builds containers.',
20
- },
21
- { re: new RegExp(`${CMD}docker-compose\\s+(?:[\\w-]+\\s+)*?(?:up|run|start|create|build|pull|exec)\\b`, 'i'), reason: 'It starts or builds containers.' },
22
- // A download piped into an interpreter.
23
- {
24
- re: /\b(?:curl|wget|fetch)\b[^|;&]*\|\s*(?:sudo\s+)?(?:ba|z|da|k|fi)?sh\b|\b(?:curl|wget)\b[^|;&]*\|\s*(?:sudo\s+)?(?:python[\d.]*|node|perl|ruby)\b/i,
25
- reason: 'It pipes a download into a shell.',
26
- },
27
- { re: /(?:ba|z)?sh\s+(?:-c\s+)?["']?\$\(\s*(?:curl|wget)\b|(?:ba|z)?sh\s+<\(\s*(?:curl|wget)\b/i, reason: 'It runs a downloaded script.' },
28
- // Privilege escalation.
29
- { re: new RegExp(`${CMD}(?:sudo|doas|pkexec)\\b`, 'i'), reason: 'It uses sudo.' },
30
- { re: new RegExp(`${CMD}su\\s+(?:-|\\w)`, 'i'), reason: 'It switches user.' },
31
- // Recursive delete of anything that is not plainly inside the tree: an absolute path, the home
32
- // folder, a variable (its value is not known here) or a parent folder.
33
- {
34
- re: new RegExp(`${CMD}(?:rm\\s+(?:-[a-zA-Z]*\\s+)*-[a-zA-Z]*[rR][a-zA-Z]*(?:\\s+-[a-zA-Z]+)*|rimraf|del-cli|trash)\\s+(?:[^\\s;&|]+\\s+)*?["']?(?:/|~|\\$|\\.\\.(?:/|\\s|$|["']))`, 'i'),
35
- reason: 'It deletes files outside the project.',
36
- },
37
- // Publishing and pushing.
38
- {
39
- re: new RegExp(`${CMD}(?:npm|pnpm|yarn|bun)\\s+(?:[\\w-]+\\s+)*?(?:publish|npm\\s+publish|dist-tag|deprecate|unpublish|owner|token|adduser|login)\\b`, 'i'),
40
- reason: 'It publishes a package.',
41
- },
42
- { re: new RegExp(`${CMD}(?:cargo\\s+(?:publish|yank|login|owner)|twine\\s+upload|gem\\s+push|poetry\\s+publish|flit\\s+publish|hatch\\s+publish|uv\\s+publish|vsce\\s+publish|ovsx\\s+publish|changeset\\s+publish|lerna\\s+publish|semantic-release|np\\s)`, 'i'), reason: 'It publishes a package.' },
43
- { re: new RegExp(`${CMD}(?:mvn|mvnw|\\./mvnw)\\s+(?:[\\w:.=-]+\\s+)*?deploy\\b|${CMD}(?:gradle|gradlew|\\./gradlew)\\s+(?:[\\w:.=-]+\\s+)*?publish\\w*`, 'i'), reason: 'It publishes a package.' },
44
- { re: new RegExp(`${CMD}git\\s+(?:-[\\w.=-]+\\s+|-C\\s+\\S+\\s+)*(?:push|remote\\s+(?:add|set-url)|config\\s+(?:--global|--system)|credential)\\b`, 'i'), reason: 'It pushes to git or changes git settings.' },
45
- { re: new RegExp(`${CMD}gh\\s+(?:release|pr|repo|secret|auth|api|workflow|gist)\\b`, 'i'), reason: 'It talks to GitHub.' },
46
- // Remote shells and copies.
47
- { re: new RegExp(`${CMD}(?:ssh|scp|sftp|rsync\\s+[^;&|]*\\w@?[\\w.-]+:)`, 'i'), reason: 'It connects to another machine.' },
48
- // Machine settings, keychains, schedulers.
49
- {
50
- re: new RegExp(`${CMD}(?:security\\s+(?:find|dump|export|unlock)|launchctl|systemctl|crontab|osascript|defaults\\s+write|chown\\s|chmod\\s+[0-7]*[67][0-7]*\\s+/|mkfs|diskutil|dd\\s+if=|shutdown|reboot)`, 'i'),
51
- reason: 'It changes machine settings.',
52
- },
53
- // Writing into the home folder's secrets or shell start-up.
54
- { re: /(?:~|\$HOME|\$\{HOME\})\/\.(?:ssh|aws|gnupg|npmrc|netrc|config\/gh|docker|kube|bashrc|zshrc|profile|bash_profile)/i, reason: 'It reads or writes your home folder’s settings.' },
55
- // eval of a computed string: nothing above can see what it runs.
56
- { re: new RegExp(`${CMD}eval\\s+["']?\\$`, 'i'), reason: 'It runs a command built at run time.' },
57
- ];
58
- /** Line continuations joined and whitespace collapsed, so a rule cannot be dodged by a line break. */
59
- export function normaliseScript(text) {
60
- return text
61
- .replace(/\\\r?\n/g, ' ')
62
- .replace(/[ \t]+/g, ' ')
63
- .trim();
64
- }
65
- /** The first rule a script's text breaks, as a plain sentence, or null when none does. */
66
- export function denyReason(text) {
67
- const t = normaliseScript(text);
68
- for (const line of t.split(/\r?\n/)) {
69
- for (const rule of DENY_RULES)
70
- if (rule.re.test(line))
71
- return rule.reason;
72
- }
73
- return null;
74
- }
75
- //# sourceMappingURL=deny-scan.js.map