@mcoda/codali 0.1.135-codali.10 → 0.1.135-codali.11

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.
@@ -4,7 +4,7 @@ export function contractReviewFixture(request) {
4
4
  return undefined;
5
5
  const input = JSON.parse(request.messages[1].content);
6
6
  const checks = input.contractSources.filter(source => !input.targetSourceIds || input.targetSourceIds.includes(source.id))
7
- .map(source => ({ sourceId: source.id, quoteIndex: 0,
8
- expectedBehavior: source.excerpts[0] }));
7
+ .map(source => ({ sourceId: source.id, quoteIndex: source.excerpts[0].quoteIndex,
8
+ expectedBehavior: source.excerpts[0].text }));
9
9
  return { message: { role: "assistant", content: JSON.stringify({ checks }) }, usage: { inputTokens: 10, outputTokens: 10, totalTokens: 20 } };
10
10
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ConfiguredModelScope.d.ts","sourceRoot":"","sources":["../../src/providers/ConfiguredModelScope.ts"],"names":[],"mappings":"AACA,OAAO,EAAwD,KAAK,WAAW,EAAE,KAAK,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAC5J,OAAO,EAA4C,KAAK,kBAAkB,EAAE,KAAK,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAClI,OAAO,KAAK,EAAE,QAAQ,EAAqC,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAErG,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IACnF,SAAS,EAAE,OAAO,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;CAC1C;AACD,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAA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C,OAAO,EAAE,MAAM;;;;IACtB,QAAQ,IAAI,gBAAgB;IAC5B,KAAK,IAAI,IAAI;IAEb,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ;YAKrB,QAAQ;CAqDvB"}
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { effortBudget, pinOrchestrationConfig, resolveBinding } from "../config/OrchestrationConfig.js";
3
3
  import { ConfiguredProvider, normalizeModelCaller } from "./ConfiguredProvider.js";
4
+ import { ModelServiceError } from "./ModelServiceError.js";
4
5
  /** Invalid upstream accounting cannot lower a shared budget or turn it into NaN. */
5
6
  export const verifiedTokenUsage = (usage) => {
6
7
  const valid = (value) => Number.isSafeInteger(value) && value >= 0;
@@ -104,7 +105,18 @@ export class ConfiguredModelScope {
104
105
  catch (error) {
105
106
  // A submitted request is never replayed; an unknown bill keeps its reservation.
106
107
  if (invocation && this.pending.has(invocation.id)) {
107
- this.usage.estimated = true;
108
+ const configured = this.resolved.config.providers[this.resolved.config.models[invocation.modelId].provider];
109
+ const nativeRefusal = configured.adapter === "openai-compatible"
110
+ && ["127.0.0.1", "localhost", "[::1]"].includes(new URL(configured.baseUrl).hostname)
111
+ && error instanceof ModelServiceError && error.status === 400 && error.nativeContextRefused;
112
+ if (nativeRefusal) {
113
+ // This exact native response precedes generation. Settle only this
114
+ // reservation; earlier usage and uncertain concurrent calls survive.
115
+ this.usage.totalTokens -= this.pending.get(invocation.id);
116
+ this.pending.delete(invocation.id);
117
+ }
118
+ else
119
+ this.usage.estimated = true;
108
120
  await this.options.onEvent?.({ type: "receipt", id: invocation.id, binding, configHash: this.resolved.hash, route: invocation, status: "failed", usage: this.snapshot() });
109
121
  }
110
122
  throw error;
@@ -4,9 +4,10 @@ export declare class ModelServiceError extends Error {
4
4
  readonly code: ModelServiceErrorCode;
5
5
  readonly status: number;
6
6
  readonly retryAfterSeconds?: number | undefined;
7
+ readonly nativeContextRefused: boolean;
7
8
  /** Set by Runner, not inferred from an HTTP status or upstream payload. */
8
9
  completedModelCalls?: number;
9
- constructor(code: ModelServiceErrorCode, status: number, retryAfterSeconds?: number | undefined);
10
+ constructor(code: ModelServiceErrorCode, status: number, retryAfterSeconds?: number | undefined, nativeContextRefused?: boolean);
10
11
  /** A relay may already have sent HTTP 200 headers when the model fails. */
11
12
  static fromRelayError(error: unknown): ModelServiceError | undefined;
12
13
  static fromResponse(response: Response): Promise<ModelServiceError>;
@@ -1 +1 @@
1
- {"version":3,"file":"ModelServiceError.d.ts","sourceRoot":"","sources":["../../src/providers/ModelServiceError.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,uBAAuB,GAAG,qBAAqB,GAAG,iBAAiB,GAAG,cAAc,GAAG,qBAAqB,GAAG,mBAAmB,GAAG,iBAAiB,GAAG,kBAAkB,GAAG,yBAAyB,CAAC;AAU5O,oFAAoF;AACpF,qBAAa,iBAAkB,SAAQ,KAAK;IAG9B,QAAQ,CAAC,IAAI,EAAE,qBAAqB;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM;IAAE,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM;IAF9G,2EAA2E;IAC3E,mBAAmB,CAAC,EAAE,MAAM,CAAC;gBACR,IAAI,EAAE,qBAAqB,EAAW,MAAM,EAAE,MAAM,EAAW,iBAAiB,CAAC,EAAE,MAAM,YAAA;IAK9G,2EAA2E;IAC3E,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB,GAAG,SAAS;WAOvD,YAAY,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,iBAAiB,CAAC;CAyB1E"}
1
+ {"version":3,"file":"ModelServiceError.d.ts","sourceRoot":"","sources":["../../src/providers/ModelServiceError.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,uBAAuB,GAAG,qBAAqB,GAAG,iBAAiB,GAAG,cAAc,GAAG,qBAAqB,GAAG,mBAAmB,GAAG,iBAAiB,GAAG,kBAAkB,GAAG,yBAAyB,CAAC;AAU5O,oFAAoF;AACpF,qBAAa,iBAAkB,SAAQ,KAAK;IAG9B,QAAQ,CAAC,IAAI,EAAE,qBAAqB;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM;IAAE,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM;IAC5G,QAAQ,CAAC,oBAAoB;IAH/B,2EAA2E;IAC3E,mBAAmB,CAAC,EAAE,MAAM,CAAC;gBACR,IAAI,EAAE,qBAAqB,EAAW,MAAM,EAAE,MAAM,EAAW,iBAAiB,CAAC,EAAE,MAAM,YAAA,EACnG,oBAAoB,UAAQ;IAKvC,2EAA2E;IAC3E,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB,GAAG,SAAS;WAOvD,YAAY,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,iBAAiB,CAAC;CA0B1E"}
@@ -8,11 +8,12 @@ function nativeContextRefusal(error) {
8
8
  }
9
9
  /** Transport diagnostics contain stable classifications, never an upstream body. */
10
10
  export class ModelServiceError extends Error {
11
- constructor(code, status, retryAfterSeconds) {
11
+ constructor(code, status, retryAfterSeconds, nativeContextRefused = false) {
12
12
  super(`Model service HTTP ${status}: ${code}${code === "authentication_failed" ? "; authenticate with codali login" : code === "context_length_exceeded" ? "; checkpoint and reduce context before continuing" : ""}`);
13
13
  this.code = code;
14
14
  this.status = status;
15
15
  this.retryAfterSeconds = retryAfterSeconds;
16
+ this.nativeContextRefused = nativeContextRefused;
16
17
  this.name = "ModelServiceError";
17
18
  }
18
19
  /** A relay may already have sent HTTP 200 headers when the model fails. */
@@ -27,6 +28,7 @@ export class ModelServiceError extends Error {
27
28
  static async fromResponse(response) {
28
29
  let serverCode = "";
29
30
  let contextRefused = false;
31
+ let nativeRefused = false;
30
32
  if (response.body) {
31
33
  const reader = response.body.getReader();
32
34
  const chunks = [];
@@ -44,8 +46,8 @@ export class ModelServiceError extends Error {
44
46
  const payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
45
47
  if (typeof (payload.error?.code ?? payload.code) === "string")
46
48
  serverCode = String(payload.error?.code ?? payload.code);
47
- contextRefused = response.status === 400 && (serverCode === "context_length_exceeded"
48
- || !!payload.error && nativeContextRefusal(payload.error));
49
+ nativeRefused = response.status === 400 && !!payload.error && nativeContextRefusal(payload.error);
50
+ contextRefused = response.status === 400 && (serverCode === "context_length_exceeded" || nativeRefused);
49
51
  }
50
52
  catch { /* The status still supplies a safe classification. */ }
51
53
  finally {
@@ -62,6 +64,6 @@ export class ModelServiceError extends Error {
62
64
  : serverCode === "structured_output_failed" ? "invalid_response"
63
65
  : response.status >= 500 ? "service_unavailable" : "invalid_request";
64
66
  const retry = Number(response.headers.get("retry-after"));
65
- return new ModelServiceError(code, response.status, response.headers.has("retry-after") && Number.isFinite(retry) && retry >= 0 ? Math.min(retry, 3600) : undefined);
67
+ return new ModelServiceError(code, response.status, response.headers.has("retry-after") && Number.isFinite(retry) && retry >= 0 ? Math.min(retry, 3600) : undefined, nativeRefused);
66
68
  }
67
69
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ReviewContract.d.ts","sourceRoot":"","sources":["../../src/runtime/ReviewContract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAmB,MAAM,+BAA+B,CAAC;AAE/E,MAAM,WAAW,oBAAoB;IAAG,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE;AAClE,MAAM,WAAW,mBAAmB;IAAG,QAAQ,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,CAAA;CAAE;AAC1G,MAAM,MAAM,oBAAoB,GAAG;IAAE,MAAM,EAAE,mBAAmB,EAAE,CAAA;CAAE,GAAG;IAAE,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE9F,wBAAgB,qBAAqB,CAAC,OAAO,EAAE;IA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AW,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/B,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7B,GAAG,oBAAoB,EAAE,CAWzB;AAuDD;;0EAE0E;AAC1E,wBAAsB,qBAAqB,CAAC,OAAO,EAAE;IACnD,QAAQ,EAAE,QAAQ,CAAC;IACnB,OAAO,EAAE,SAAS,oBAAoB,EAAE,CAAC;IACzC,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA2ChC"}
@@ -10,7 +10,7 @@ export function reviewContractSources(context) {
10
10
  ...context.nonGoals.map((text, index) => ({ id: `nonGoal:${index}`, text })),
11
11
  ];
12
12
  }
13
- const instruction = 'Prepare independent contract checks before seeing implementation, tests, diffs or claimed results. Use only the supplied authoritative sources. This is verification after authorized task execution; distinguish obligations that apply only during earlier planning. Preserve explicit error types, exact messages, schema fields, defaults, boundaries, side-effect rules and temporal/conditional qualifications. Do not invent behavior or relax quoted literals into substring matches. Reply exactly JSON {"checks":[{"sourceId":string,"quoteIndex":integer,"expectedBehavior":string}]}. Each source contains an excerpts array: concatenating its strings in order reconstructs its complete original text without changes. Read them together; excerpt boundaries do not separate or qualify obligations. quoteIndex is the zero-based index of the supporting excerpt in that identified source. Select the index instead of copying or rewriting the quotation; the controller supplies the exact source bytes. When targetSourceIds is supplied, generate checks only for those sources; all supplied sources remain authoritative context for interpreting conditions and qualifications. Include at least one check for every targeted source (every source when no targets are given), and enough checks to cover its distinct obligations. Multiple checks may cite the same excerpt. Keep each expectedBehavior concise; avoid repeating the same obligation. expectedBehavior states a concrete observable check, not an approval. These checks are an aid, never a replacement for the complete original contract. No tools.';
13
+ const instruction = 'Prepare independent contract checks before seeing implementation, tests, diffs or claimed results. Use only the supplied authoritative sources. This is verification after authorized task execution; distinguish obligations that apply only during earlier planning. Preserve explicit error types, exact messages, schema fields, defaults, boundaries, side-effect rules and temporal/conditional qualifications. Do not invent behavior or relax quoted literals into substring matches. Reply exactly JSON {"checks":[{"sourceId":string,"quoteIndex":integer,"expectedBehavior":string}]}. Each source contains an excerpts array of {quoteIndex,text} objects: concatenating text in order reconstructs its complete original text without changes. Read them together; excerpt boundaries do not separate or qualify obligations. quoteIndex is the explicit numeric label on the supporting excerpt in that identified source. Copy that label; do not count excerpts or infer an index from another source. Select the index instead of copying or rewriting the quotation; the controller supplies the exact source bytes. When targetSourceIds is supplied, generate checks only for those sources; all supplied sources remain authoritative context for interpreting conditions and qualifications. Include at least one check for every targeted source (every source when no targets are given), and enough checks to cover its distinct obligations. Multiple checks may cite the same excerpt. Keep each expectedBehavior concise; avoid repeating the same obligation. expectedBehavior states a concrete observable check, not an approval. These checks are an aid, never a replacement for the complete original contract. No tools.';
14
14
  /** Lossless source slices; preserve whitespace and never split a surrogate pair. */
15
15
  function sourceExcerpts(text) {
16
16
  const excerpts = [];
@@ -94,7 +94,8 @@ export async function prepareReviewContract(options) {
94
94
  batches.push(batch);
95
95
  if (batches.length > 16)
96
96
  return reject("Contract preparation requires too many bounded batches. Split the task or select a larger compatible reviewer; acceptance is not established.");
97
- const contractSources = options.sources.map(source => ({ id: source.id, excerpts: sourceExcerpts(source.text) }));
97
+ const contractSources = options.sources.map(source => ({ id: source.id,
98
+ excerpts: sourceExcerpts(source.text).map((text, quoteIndex) => ({ quoteIndex, text })) }));
98
99
  const checks = [];
99
100
  for (const targets of batches) {
100
101
  const messages = [
@@ -1 +1 @@
1
- {"version":3,"file":"ReviewCoordinator.d.ts","sourceRoot":"","sources":["../../src/runtime/ReviewCoordinator.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAmB,MAAM,+BAA+B,CAAC;AAC/E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAExD,OAAO,EAAuB,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AACrF,O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AAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACnH,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,SAAS,oBAAoB,EAAE,CAAC;IAC9C,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IACjG,cAAc,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC5E,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3C,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAsF5B"}
@@ -13,6 +13,7 @@ const reviewInstructions = [
13
13
  { role: "system", content: 'A requirement descriptionReference points to its exact unchanged text in goal at offset/length; review that text as the requirement, not as a summary. reviewSnapshotHash identifies the controller-verified source snapshot. All sourceRoles paths remain available for hash-checked paging. Treat explicit error messages, literal values, schema fields and specified defaults as exact contracts; do not approve altered values merely because the supplied tests accept them. contractChecklist was derived before seeing source or tests. Compare each check directly with the implementation, preserving the complete original contract as authority if a generated expectedBehavior is mistaken. Tests and docstrings are implementation artifacts: a passing test that requires behavior incompatible with the user contract is itself a blocking defect. The checklist never removes an original obligation. Distinguish internal implementation helpers shared between source files from public API changes: identify the violated public entry-point contract rather than treating every internal export as a new public feature.' },
14
14
  { role: "system", content: "taskAssessments are controller-recorded successful reviews of the identified task criteria at this exact workspaceSnapshotHash during this verification. Their sourcePaths were reviewed in those task scopes and remain available for sourceRequests. Use these assessments for already-reviewed criteria in later scoped reviews as well as integration; inspect the source needed for this task's own behavior and cross-task interactions. For integration, check the complete original goal, global constraints, architecture, cross-task interactions and remaining deliverables using these fresh assessments plus the current evidence. Do not demand an already assessed module's entire source merely to repeat its scoped review; request the specific files needed to investigate an integration defect. An assessment never certifies a different criterion, snapshot or missing deliverable. Empty findings still require sufficient evidence for every obligation." },
15
15
  { role: "system", content: "contractChecklist.checks preserves every prepared check. Each check's quoteId refers to the exact sourceId and contractQuote in contractChecklist.quotes. Identical quotations from the same source are stored once; every expectedBehavior remains separate. Follow those references when comparing a check to its authoritative text." },
16
+ { role: "system", content: "When checklistBatch is present, this is one bounded portion of the prepared checklist, with the complete original contract and current evidence retained. Scrutinize every check in this portion and its interactions with the original contract. Other prepared checks are reviewed separately against this same snapshot; the controller requires every portion to pass. Your verdict covers this portion, never acceptance of an unreviewed portion. Do not reject solely because other checklist portions are absent; reject any actual defect or insufficient evidence for the checks you are reviewing. The complete original requirements remain authoritative in every portion." },
16
17
  ];
17
18
  /** Review one scope without loading every sibling's source into the prompt.
18
19
  * Assessments are created only by the controller after separate successful
@@ -41,41 +42,85 @@ export async function reviewTaskScope(options) {
41
42
  });
42
43
  const assessedPaths = new Set(assessments.flatMap(value => value.sourcePaths));
43
44
  const initialPaths = options.scope.reviewPaths.filter(file => !assessedPaths.has(file));
44
- const source = {};
45
- const truncated = new Set(initialPaths);
46
- const sourceNextOffsets = Object.fromEntries(initialPaths.map(file => [file, 0]));
45
+ const checklist = (selected) => ({
46
+ quotes: Object.fromEntries([...new Set(selected.map(check => check.quoteId))].map(id => [id, quotes[id]])),
47
+ checks: selected,
48
+ });
47
49
  const input = { ...reviewPromptContext(options.scope, options.hashes), workspaceSnapshotHash,
48
50
  ...(assessments.length ? { taskAssessments: assessments } : {}),
49
- contractChecklist: { quotes, checks }, task: options.task,
51
+ contractChecklist: checklist(checks), task: options.task,
52
+ checklistBatch: undefined,
50
53
  receipts: options.receipts.map(r => ({ id: r.id, tool: r.tool, args: r.args, status: r.status,
51
54
  output: r.output ? r.tool === "run_shell" ? validationOutputExcerpt(r.output, 2400) : r.output.slice(0, 2000) : undefined, taskId: r.taskId })),
52
55
  validatedInputCount: Object.keys(options.hashes).length, preExistingDirtyPaths: options.preExistingDirtyPaths,
53
- source, sourceTruncatedPaths: [...truncated], sourceNextOffsets,
56
+ source: {}, sourceTruncatedPaths: [...initialPaths],
57
+ sourceNextOffsets: Object.fromEntries(initialPaths.map(file => [file, 0])),
54
58
  diff: (await options.diff(options.scope.changedPaths.filter(file => !assessedPaths.has(file)))).slice(0, 12000),
55
59
  claimedSummary: options.summary };
56
60
  const messages = () => [...reviewInstructions, { role: "user", content: JSON.stringify(input) }];
57
- // Reserve room for missing source pages rather than exhausting the context
58
- // with the first source block. Every omitted path remains requestable.
59
- let remaining = Math.min(32000, Math.max(0, Math.floor((options.maxInputChars - JSON.stringify(messages()).length) * 0.6)));
60
- for (const file of initialPaths) {
61
- if (remaining <= 0)
62
- break;
63
- const evidence = await options.readSource(file, Math.min(8000, Math.floor(remaining / 2)));
64
- const addedChars = JSON.stringify({ [file]: evidence.content }).length + 32;
65
- if (addedChars > remaining)
66
- continue;
67
- source[file] = evidence.content;
68
- remaining -= addedChars;
69
- if (evidence.truncated)
70
- sourceNextOffsets[file] = evidence.content.length;
71
- else {
72
- truncated.delete(file);
73
- delete sourceNextOffsets[file];
61
+ // Bound generated aids independently of authoritative requirements. Every
62
+ // batch retains the full contract and requires its own successful verdict;
63
+ // a large checklist cannot crowd out all source or silently lose checks.
64
+ const checklistLimit = options.maxInputChars - Math.min(16000, Math.floor(options.maxInputChars / 4));
65
+ const batches = [];
66
+ if (JSON.stringify(messages()).length <= checklistLimit)
67
+ batches.push(checks);
68
+ else {
69
+ input.checklistBatch = { index: 15, count: 16, totalChecks: checks.length };
70
+ let batch = [];
71
+ for (const check of checks) {
72
+ input.contractChecklist = checklist([...batch, check]);
73
+ if (JSON.stringify(messages()).length > checklistLimit) {
74
+ if (batch.length) {
75
+ batches.push(batch);
76
+ batch = [];
77
+ }
78
+ input.contractChecklist = checklist([check]);
79
+ if (JSON.stringify(messages()).length > checklistLimit)
80
+ return { passed: false,
81
+ findings: ["Required review authority and one checklist item exceed the configured evidence budget. Split the task or select a larger compatible reviewer; acceptance is not established."] };
82
+ }
83
+ batch.push(check);
84
+ }
85
+ if (batch.length)
86
+ batches.push(batch);
87
+ if (batches.length > 16)
88
+ return { passed: false,
89
+ findings: ["Review requires too many bounded checklist batches. Split the task or select a larger compatible reviewer; acceptance is not established."] };
90
+ }
91
+ for (const [index, batch] of batches.entries()) {
92
+ options.signal?.throwIfAborted();
93
+ input.contractChecklist = checklist(batch);
94
+ input.checklistBatch = batches.length > 1 ? { index, count: batches.length, totalChecks: checks.length } : undefined;
95
+ input.source = {};
96
+ input.sourceNextOffsets = Object.fromEntries(initialPaths.map(file => [file, 0]));
97
+ const truncated = new Set(initialPaths);
98
+ input.sourceTruncatedPaths = [...truncated];
99
+ // Every omitted path remains available through hash-checked paging.
100
+ let remaining = Math.min(32000, Math.max(0, Math.floor((options.maxInputChars - JSON.stringify(messages()).length) * 0.6)));
101
+ for (const file of initialPaths) {
102
+ if (remaining <= 0)
103
+ break;
104
+ const evidence = await options.readSource(file, Math.min(8000, Math.floor(remaining / 2)));
105
+ const addedChars = JSON.stringify({ [file]: evidence.content }).length + 32;
106
+ if (addedChars > remaining)
107
+ continue;
108
+ input.source[file] = evidence.content;
109
+ remaining -= addedChars;
110
+ if (evidence.truncated)
111
+ input.sourceNextOffsets[file] = evidence.content.length;
112
+ else {
113
+ truncated.delete(file);
114
+ delete input.sourceNextOffsets[file];
115
+ }
74
116
  }
117
+ input.sourceTruncatedPaths = [...truncated];
118
+ const result = await runTaskReview({ provider: options.provider, allowedPaths: options.scope.reviewPaths,
119
+ initialSourceOffsets: input.sourceNextOffsets, readSourcePage: options.readSourcePage,
120
+ maxInputChars: options.maxInputChars, maxOutputTokens: options.maxOutputTokens,
121
+ messages: messages(), signal: options.signal });
122
+ if (!result.passed)
123
+ return result;
75
124
  }
76
- input.sourceTruncatedPaths = [...truncated];
77
- return runTaskReview({ provider: options.provider, allowedPaths: options.scope.reviewPaths,
78
- initialSourceOffsets: sourceNextOffsets, readSourcePage: options.readSourcePage,
79
- maxInputChars: options.maxInputChars, maxOutputTokens: options.maxOutputTokens,
80
- messages: messages(), signal: options.signal });
125
+ return { passed: true, findings: [] };
81
126
  }
package/package.json CHANGED
@@ -8,8 +8,8 @@
8
8
  "url": "https://github.com/bekirdag/mcoda/issues"
9
9
  },
10
10
  "dependencies": {
11
- "@mcoda/db": "0.1.135-codali.10",
12
- "@mcoda/shared": "0.1.135-codali.10",
11
+ "@mcoda/db": "0.1.135-codali.11",
12
+ "@mcoda/shared": "0.1.135-codali.11",
13
13
  "@modelcontextprotocol/sdk": "1.30.0",
14
14
  "zod": "4.5.2"
15
15
  },
@@ -45,5 +45,5 @@
45
45
  },
46
46
  "type": "module",
47
47
  "types": "dist/index.d.ts",
48
- "version": "0.1.135-codali.10"
48
+ "version": "0.1.135-codali.11"
49
49
  }