@engineeros/connector 0.15.2 → 0.15.3

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.
package/src/runner.mjs CHANGED
@@ -1,2121 +1,2113 @@
1
- import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import {
4
- lstat,
5
- mkdir,
6
- readFile,
7
- readdir,
8
- stat,
9
- writeFile,
10
- } from "node:fs/promises";
11
- import os from "node:os";
12
- import path from "node:path";
13
- import { promisify } from "node:util";
14
- import { deflateRaw, gzip } from "node:zlib";
15
- import { inspectAcpExecutionProfiles, launchAcpAgent } from "./acp-client.mjs";
16
- import {
17
- inspectCodexExecutionProfiles,
18
- launchCodexAppServer,
19
- } from "./codex-app-server.mjs";
20
- import {
21
- buildAgentHarnessPrompt,
22
- normalizeAgentStructuredOutput,
23
- } from "./agent-harness.mjs";
24
-
25
- const deflate = promisify(deflateRaw);
26
- const gzipBuffer = promisify(gzip);
27
- const MAX_ARCHIVE_BYTES = 25_000_000;
28
- const MAX_EVIDENCE_BYTES = 24_000_000;
29
- const MAX_SHAREABLE_FILE_BYTES = 5 * 1024 * 1024;
30
- const MAX_EVIDENCE_FILES = 5_000;
31
- const MAX_INVENTORY_FILES = 100_000;
32
- const MAX_COMPRESSED_INVENTORY_BYTES = 10_000_000;
33
- const EVIDENCE_POLICY_VERSION = "workspace-evidence-v1";
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import {
4
+ lstat,
5
+ mkdir,
6
+ readFile,
7
+ readdir,
8
+ stat,
9
+ writeFile,
10
+ } from "node:fs/promises";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { promisify } from "node:util";
14
+ import { deflateRaw, gzip } from "node:zlib";
15
+ import { inspectAcpExecutionProfiles, launchAcpAgent } from "./acp-client.mjs";
16
+ import {
17
+ inspectCodexExecutionProfiles,
18
+ launchCodexAppServer,
19
+ } from "./codex-app-server.mjs";
20
+ import {
21
+ buildAgentHarnessPrompt,
22
+ normalizeAgentStructuredOutput,
23
+ } from "./agent-harness.mjs";
24
+
25
+ const deflate = promisify(deflateRaw);
26
+ const gzipBuffer = promisify(gzip);
27
+ const MAX_ARCHIVE_BYTES = 25_000_000;
28
+ const MAX_EVIDENCE_BYTES = 24_000_000;
29
+ const MAX_SHAREABLE_FILE_BYTES = 5 * 1024 * 1024;
30
+ const MAX_EVIDENCE_FILES = 5_000;
31
+ const MAX_INVENTORY_FILES = 100_000;
32
+ const MAX_COMPRESSED_INVENTORY_BYTES = 10_000_000;
33
+ const EVIDENCE_POLICY_VERSION = "workspace-evidence-v1";
34
34
  export const ASSESSMENT_INACTIVITY_TIMEOUT_MS = 10 * 60 * 1_000;
35
35
  export const ASSESSMENT_RESULT_TIMEOUT_MS = 120_000;
36
36
  export const MAX_REPEATED_ASSESSMENT_VALIDATION_FAILURES = 3;
37
- export const MAX_ASSESSMENT_WORKERS = 32;
38
- export const MAX_AUTOMATIC_ASSESSMENT_WORKERS = 8;
39
- const EXCLUDED_DIRECTORIES = new Set([
40
- ".agents",
41
- ".claude",
42
- ".codex",
43
- ".engineeros",
44
- ".forge",
45
- ".gemini",
46
- ".git",
47
- ".next",
48
- ".pytest_cache",
49
- ".ruff_cache",
50
- ".venv",
51
- "__pycache__",
52
- "build",
53
- "coverage",
54
- "dist",
55
- "node_modules",
56
- "target",
57
- "vendor",
58
- ]);
59
- const EXCLUDED_PATH_PREFIXES = [".github/skills/"];
60
- const EXCLUDED_FILE_EXTENSIONS = new Set([
61
- ".7z",
62
- ".a",
63
- ".bin",
64
- ".class",
65
- ".dll",
66
- ".dylib",
67
- ".exe",
68
- ".gz",
69
- ".jar",
70
- ".lib",
71
- ".o",
72
- ".obj",
73
- ".pyc",
74
- ".pyo",
75
- ".rar",
76
- ".so",
77
- ".tar",
78
- ".tgz",
79
- ".war",
80
- ".zip",
81
- ]);
82
- const LOCK_FILE_NAMES = new Set([
83
- "cargo.lock",
84
- "composer.lock",
85
- "go.sum",
86
- "package-lock.json",
87
- "pnpm-lock.yaml",
88
- "poetry.lock",
89
- "uv.lock",
90
- "yarn.lock",
91
- ]);
92
- const ENTRYPOINT_NAMES = new Set([
93
- "app.py",
94
- "index.ts",
95
- "index.tsx",
96
- "main.py",
97
- "main.ts",
98
- "main.tsx",
99
- "manage.py",
100
- "server.py",
101
- ]);
102
- const REPOSITORY_CONFIGURATION_NAMES = new Set([
103
- ".dockerignore",
104
- ".editorconfig",
105
- ".gitattributes",
106
- ".gitignore",
107
- "lerna.json",
108
- "makefile",
109
- "nx.json",
110
- "turbo.json",
111
- ]);
112
- const CODE_EXTENSIONS = new Set([
113
- ".c",
114
- ".cpp",
115
- ".cs",
116
- ".go",
117
- ".h",
118
- ".java",
119
- ".js",
120
- ".jsx",
121
- ".mjs",
122
- ".php",
123
- ".py",
124
- ".rb",
125
- ".rs",
126
- ".sql",
127
- ".ts",
128
- ".tsx",
129
- ]);
130
- const CODE_MARKERS = new Set([
131
- "cargo.toml",
132
- "composer.json",
133
- "go.mod",
134
- "package.json",
135
- "pom.xml",
136
- "pyproject.toml",
137
- "requirements.txt",
138
- ]);
139
-
140
- export async function executeAssignment(assignment, config, callbacks) {
141
- const execution = connectorExecution(assignment);
142
- const runWorkspace = await prepareRunWorkspace(
143
- config.workspace,
144
- assignment.run_id,
145
- assignment.base_revision,
146
- );
147
- const controller = launchAgentProcess(
148
- runWorkspace,
149
- execution.prompt,
150
- execution.sandboxMode,
151
- config,
152
- callbacks,
153
- execution.profile,
154
- undefined,
155
- { runId: assignment.run_id },
156
- );
157
- callbacks.onProcess?.(controller.child);
158
- const implementation = await controller.completed;
159
- const changedFiles = await changedFilePaths(runWorkspace);
160
- if (!changedFiles.length)
161
- throw new Error("Agent completed without changing any files.");
162
- const committed = await commitRunChange(
163
- runWorkspace,
164
- assignment.base_revision,
165
- assignment.run_id,
166
- );
167
- const verificationHeading = "# Verification Report";
168
- const verifier = launchAgentProcess(
169
- runWorkspace,
170
- buildAgentHarnessPrompt({
171
- agentRole: "verification",
172
- prompt: verificationPrompt(
173
- assignment,
174
- committed.revision,
175
- committed.changedFiles,
176
- ),
177
- sandboxMode: "read-only",
178
- requiredOutputHeading: verificationHeading,
179
- }),
180
- "read-only",
181
- config,
182
- callbacks,
183
- execution.profile,
184
- );
185
- callbacks.onProcess?.(verifier.child);
186
- const verification = await verifier.completed;
187
- const verificationReport = normalizeAgentStructuredOutput(
188
- verification.finalMessage,
189
- verificationHeading,
190
- );
191
- const proofEvidence = parseVerificationReport(
192
- verificationReport,
193
- assignment.proof_checks,
194
- config.connector_id,
195
- assignment.run_id,
196
- );
197
- return {
198
- head_revision: committed.revision,
199
- repository_locator: assignment.repository_locator,
200
- external_reference: `connector:${config.connector_id}/run:${assignment.run_id}`,
201
- diff_patch: committed.diffPatch,
202
- changed_files: committed.changedFiles,
203
- proof_evidence: proofEvidence,
204
- verification_report: verificationReport,
205
- usage: [
206
- {
207
- request_type: "goal_implementation",
208
- model: implementation.model,
209
- ...implementation.usage,
210
- },
211
- {
212
- request_type: "goal_verification",
213
- model: verification.model,
214
- ...verification.usage,
215
- },
216
- ].filter((entry) => entry.total_tokens > 0),
217
- };
218
- }
219
-
220
- export async function applyAcceptedChange(
221
- workspace,
222
- baseRevision,
223
- headRevision,
224
- ) {
225
- const current = await run("git", ["rev-parse", "HEAD"], workspace, {
226
- allowFailure: true,
227
- });
228
- if (current.code !== 0) {
229
- return {
230
- applied: false,
231
- reason: "The connected workspace is not a Git repository.",
232
- };
233
- }
234
- const currentHead = current.stdout.trim();
235
- const alreadyApplied = await run(
236
- "git",
237
- ["merge-base", "--is-ancestor", headRevision, currentHead],
238
- workspace,
239
- { allowFailure: true },
240
- );
241
- if (alreadyApplied.code === 0)
242
- return { applied: true, revision: currentHead };
243
- const status = await run("git", ["status", "--porcelain"], workspace);
244
- if (status.stdout.trim()) {
245
- return {
246
- applied: false,
247
- reason: `The connected workspace has uncommitted changes. Apply accepted commit ${headRevision} after preserving them.`,
248
- };
249
- }
250
- if (currentHead !== baseRevision) {
251
- return {
252
- applied: false,
253
- reason: `The connected branch moved from frozen base ${baseRevision} to ${currentHead}. Apply accepted commit ${headRevision} with git cherry-pick.`,
254
- };
255
- }
256
- const applied = await run("git", ["cherry-pick", headRevision], workspace, {
257
- allowFailure: true,
258
- });
259
- if (applied.code !== 0) {
260
- await run("git", ["cherry-pick", "--abort"], workspace, {
261
- allowFailure: true,
262
- });
263
- return {
264
- applied: false,
265
- reason: `The accepted commit ${headRevision} could not be applied cleanly. Apply it manually with git cherry-pick.`,
266
- };
267
- }
268
- const integrated = await run("git", ["rev-parse", "HEAD"], workspace);
269
- return { applied: true, revision: integrated.stdout.trim() };
270
- }
271
-
272
- async function commitRunChange(workspace, baseRevision, runId) {
273
- await run("git", ["add", "-A"], workspace);
274
- await run(
275
- "git",
276
- [
277
- "-c",
278
- "user.name=EngineerOS Codex",
279
- "-c",
280
- "user.email=codex@engineeros.local",
281
- "commit",
282
- "-m",
283
- `EngineerOS Goal Run ${runId}`,
284
- ],
285
- workspace,
286
- );
287
- const head = await run("git", ["rev-parse", "HEAD"], workspace);
288
- const revision = head.stdout.trim();
289
- const diff = await run(
290
- "git",
291
- ["diff", "--binary", baseRevision, revision, "--"],
292
- workspace,
293
- );
294
- const paths = await run(
295
- "git",
296
- ["diff", "--name-only", "-z", baseRevision, revision, "--"],
297
- workspace,
298
- );
299
- return {
300
- revision,
301
- diffPatch: diff.stdout,
302
- changedFiles: gitPathList(paths.stdout).sort(),
303
- };
304
- }
305
-
306
- export function verificationPrompt(assignment, revision, changedFiles) {
307
- const checks = (assignment.proof_checks ?? [])
308
- .map(
309
- (proof, index) =>
310
- `## Proof ${index + 1}\n- Check: ${proof.check ?? ""}\n- Expected: ${proof.expected ?? ""}`,
311
- )
312
- .join("\n\n");
313
- return `# EngineerOS Connected Verification
314
-
315
- Independently verify the frozen Goal at Git commit \`${revision}\`. Do not modify files. Run the commands or inspections needed for every Proof item, and check the Goal boundaries and constraints in the supplied packet.
316
-
317
- Changed files:
318
- ${changedFiles.map((item) => `- \`${item}\``).join("\n")}
319
-
320
- ${checks}
321
-
322
- Return structured Markdown only, with exactly one section per Proof:
323
-
324
- ## Proof 1
325
- - Status: passed or failed
326
- - Exit code: integer or none
327
- - Evidence: concise observed output and command
328
-
329
- Do not claim a Proof passed unless you observed it directly.`;
330
- }
331
-
332
- export function parseVerificationReport(
333
- report,
334
- proofChecks,
335
- connectorId,
336
- runId,
337
- ) {
338
- if (!report?.trim())
339
- throw new Error("Codex returned no connected verification report.");
340
- return (proofChecks ?? []).map((_, index) => {
341
- const start = new RegExp(`^## Proof ${index + 1}\\s*$`, "im").exec(report);
342
- const tail = start ? report.slice(start.index + start[0].length) : "";
343
- const section = tail.split(/^## Proof \d+\s*$/im)[0] ?? "";
344
- const status =
345
- /^- Status:\s*(passed|failed)\s*$/im.exec(section)?.[1] ?? "failed";
346
- const exitValue =
347
- /^- Exit code:\s*(\d+|none)\s*$/im.exec(section)?.[1] ?? "none";
348
- const evidence = /^- Evidence:\s*(.+)$/im.exec(section)?.[1]?.trim();
349
- return {
350
- proof_index: index,
351
- status,
352
- verifier_type: "agent_reported",
353
- verifier_identity: "Connected Codex CLI verifier",
354
- locator: `connector:${connectorId}/run:${runId}#proof-${index + 1}`,
355
- output_excerpt:
356
- evidence ||
357
- "The connected verifier did not provide evidence for this Proof.",
358
- exit_code: exitValue === "none" ? null : Number(exitValue),
359
- };
360
- });
361
- }
362
-
363
- export async function executeWorkspaceAssessment(
364
- assignment,
365
- config,
366
- callbacks,
367
- ) {
368
- const execution = workspaceAssessmentExecution(assignment);
369
- const assessmentAcpContext =
370
- config.agent_protocol === "acp"
371
- ? {
372
- persistentAcp: true,
373
- sessionKey: `assessment:${assignment.assessment_id}:${assignment.stage}`,
374
- }
375
- : undefined;
376
- const launchAssessmentAgent = (turnPrompt, previousSessionId) => {
377
- const controller = launchAgentProcess(
378
- config.workspace,
379
- turnPrompt,
380
- execution.sandboxMode,
381
- config,
382
- callbacks,
383
- execution.profile,
384
- previousSessionId,
385
- assessmentAcpContext,
386
- );
387
- callbacks.onController?.(controller);
388
- callbacks.onProcess?.(controller.child);
389
- return controller;
390
- };
391
- const startingRevision = await run(
392
- "git",
393
- ["rev-parse", "HEAD"],
394
- config.workspace,
395
- { allowFailure: true },
396
- );
397
- const startingHead =
398
- startingRevision.code === 0
399
- ? startingRevision.stdout.trim().slice(0, 128)
400
- : null;
401
- if (
402
- assignment.target_head_revision &&
403
- startingHead !== assignment.target_head_revision
404
- ) {
405
- throw new Error(
406
- "This workspace is no longer at the commit inventoried by EngineerOS. Refresh the workspace inventory before assessing it.",
407
- );
408
- }
409
- const changeImpact =
410
- assignment.assessment_mode === "incremental"
411
- ? await workspaceChangeImpact(
412
- config.workspace,
413
- assignment.base_head_revision,
414
- assignment.target_head_revision,
415
- )
416
- : { changedFiles: [], markdown: null };
417
- const prompt = changeImpact.markdown
418
- ? execution.prompt.replace(
419
- "<!-- ENGINEEROS_CHANGE_IMPACT -->",
420
- changeImpact.markdown,
421
- )
422
- : execution.prompt;
423
- const controller = launchAssessmentAgent(prompt);
424
- let completed = await controller.completed;
425
- const recovered = await recoverAssessmentStageOutput({
426
- completed,
427
- prompt,
428
- requiredOutputHeading: execution.requiredOutputHeading,
429
- retry: async (correctionPrompt, previousSessionId) => {
430
- callbacks.onEvent?.({
431
- type: "assessment.output_correction",
432
- message: "The Agent is completing the required stage report structure",
433
- });
434
- const correction = launchAssessmentAgent(
435
- correctionPrompt,
436
- previousSessionId,
437
- );
438
- return correction.completed;
439
- },
440
- });
441
- completed = recovered.completed;
442
- const buildResult = async (turn, report) => {
443
- const endingRevision = await run(
444
- "git",
445
- ["rev-parse", "HEAD"],
446
- config.workspace,
447
- { allowFailure: true },
448
- );
449
- const endingHead =
450
- endingRevision.code === 0
451
- ? endingRevision.stdout.trim().slice(0, 128)
452
- : null;
453
- if (startingHead !== endingHead) {
454
- throw new Error(
455
- "The Git commit changed during assessment. Refresh the workspace inventory and assess the new commit.",
456
- );
457
- }
458
- return {
459
- stage: assignment.stage,
460
- report_markdown: report,
461
- observed_head_revision: endingHead,
462
- changed_files: changeImpact.changedFiles,
463
- change_impact_markdown: changeImpact.markdown,
464
- model: turn.model ?? config.agent_protocol ?? "coding-agent",
465
- usage: turn.usage ?? null,
466
- agent_session_id: turn.sessionId ?? null,
467
- };
468
- };
469
- const result = await buildResult(completed, recovered.report);
470
- attachAssessmentRejectionCorrection(result, assignment, config, callbacks, {
471
- previousSessionId: completed.sessionId,
472
- buildResult,
473
- });
474
- return result;
475
- }
476
-
477
- export function attachAssessmentRejectionCorrection(
478
- result,
479
- assignment,
480
- config,
481
- callbacks,
482
- { previousSessionId = result.agent_session_id, draftPath, buildResult } = {},
483
- ) {
484
- const execution = workspaceAssessmentExecution(assignment);
485
- const assessmentAcpContext =
486
- config.agent_protocol === "acp"
487
- ? {
488
- persistentAcp: true,
489
- sessionKey: `assessment:${assignment.assessment_id}:${assignment.stage}`,
490
- }
491
- : undefined;
492
- Object.defineProperty(result, "correctAfterRejection", {
493
- enumerable: false,
494
- value: async (validationMessage) => {
495
- callbacks.onEvent?.({
496
- type: "assessment.output_correction",
497
- message: "The Agent is correcting the rejected stage report",
498
- });
499
- const draftInstruction = draftPath
500
- ? [
501
- "",
502
- `The authoritative draft is stored at \`${draftPath}\`. Read that file before making the requested correction.`,
503
- ].join("\n")
504
- : "";
505
- const correctionPrompt = `${assessmentRejectionCorrectionPrompt(validationMessage, execution.requiredOutputHeading)}${draftInstruction}`;
506
- const launchCorrection = (prompt, sessionId) => {
507
- const controller = launchAgentProcess(
508
- config.workspace,
509
- prompt,
510
- execution.sandboxMode,
511
- config,
512
- callbacks,
513
- execution.profile,
514
- sessionId,
515
- assessmentAcpContext,
516
- );
517
- callbacks.onController?.(controller);
518
- callbacks.onProcess?.(controller.child);
519
- return controller;
520
- };
521
- let corrected = await launchCorrection(
522
- correctionPrompt,
523
- previousSessionId,
524
- ).completed;
525
- const recovered = await recoverAssessmentStageOutput({
526
- completed: corrected,
527
- prompt: correctionPrompt,
528
- requiredOutputHeading: execution.requiredOutputHeading,
529
- retry: async (formatPrompt, sessionId) => {
530
- callbacks.onEvent?.({
531
- type: "assessment.output_correction",
532
- message: "The Agent is formatting the corrected stage report",
533
- });
534
- return launchCorrection(formatPrompt, sessionId).completed;
535
- },
536
- });
537
- corrected = recovered.completed;
538
- const correctedReport = recovered.report;
539
- if (buildResult) {
540
- return buildResult(
541
- {
542
- ...corrected,
543
- usage: mergeTokenUsage(result.usage, corrected.usage),
544
- },
545
- correctedReport,
546
- );
547
- }
548
- const endingRevision = await run(
549
- "git",
550
- ["rev-parse", "HEAD"],
551
- config.workspace,
552
- { allowFailure: true },
553
- );
554
- const endingHead =
555
- endingRevision.code === 0
556
- ? endingRevision.stdout.trim().slice(0, 128)
557
- : null;
558
- if (
559
- assignment.target_head_revision &&
560
- endingHead !== assignment.target_head_revision
561
- ) {
562
- throw new Error(
563
- "The Git commit changed before assessment correction. Refresh the workspace inventory and assess the new commit.",
564
- );
565
- }
566
- return {
567
- ...result,
568
- report_markdown: correctedReport,
569
- observed_head_revision: endingHead,
570
- model: corrected.model ?? result.model,
571
- usage: mergeTokenUsage(result.usage, corrected.usage),
572
- agent_session_id: corrected.sessionId ?? previousSessionId ?? null,
573
- };
574
- },
575
- });
576
- return result;
577
- }
578
-
579
- export async function workspaceChangeImpact(
580
- workspace,
581
- baseRevision,
582
- targetRevision,
583
- ) {
584
- if (!baseRevision || !targetRevision) {
585
- throw new Error(
586
- "Incremental assessment requires both the previously assessed and current Git commits. Run a full assessment instead.",
587
- );
588
- }
589
- const range = `${baseRevision}..${targetRevision}`;
590
- const names = await run(
591
- "git",
592
- ["diff", "--name-status", "--find-renames", range],
593
- workspace,
594
- { allowFailure: true },
595
- );
596
- if (names.code !== 0) {
597
- throw new Error(
598
- "Codex could not compare the assessed and current commits. Fetch the missing Git history or run a full assessment.",
599
- );
600
- }
601
- const committedFiles = await run(
602
- "git",
603
- ["-c", "core.quotepath=false", "diff", "--name-only", range],
604
- workspace,
605
- { allowFailure: true },
606
- );
607
- const workingFiles = await run(
608
- "git",
609
- [
610
- "-c",
611
- "core.quotepath=false",
612
- "ls-files",
613
- "--others",
614
- "--modified",
615
- "--deleted",
616
- "--exclude-standard",
617
- ],
618
- workspace,
619
- { allowFailure: true },
620
- );
621
- const status = await run("git", ["status", "--short"], workspace, {
622
- allowFailure: true,
623
- });
624
- const stat = await run(
625
- "git",
626
- ["diff", "--stat", "--compact-summary", range],
627
- workspace,
628
- { allowFailure: true },
629
- );
630
- const allChangedFiles = [
631
- ...new Set([
632
- ...pathLines(committedFiles.stdout),
633
- ...pathLines(workingFiles.stdout),
634
- ]),
635
- ];
636
- if (allChangedFiles.length > 500) {
637
- throw new Error(
638
- `This change affects ${allChangedFiles.length} paths, above the 500-path incremental limit. Run a full reassessment instead.`,
639
- );
640
- }
641
- const changedFiles = allChangedFiles;
642
- if (!changedFiles.length) {
643
- throw new Error(
644
- "The inventoried repository changed but Git reports no assessable paths. Refresh inventory or run a full assessment.",
645
- );
646
- }
647
- const lines = [
648
- `Comparison: \`${range}\``,
649
- `Changed paths: ${changedFiles.length}`,
650
- "",
651
- "### Name status",
652
- "",
653
- "```text",
654
- boundedText(names.stdout, 12_000),
655
- "```",
656
- ];
657
- if (status.stdout.trim()) {
658
- lines.push(
659
- "",
660
- "### Working tree",
661
- "",
662
- "```text",
663
- boundedText(status.stdout, 6_000),
664
- "```",
665
- );
666
- }
667
- if (stat.stdout.trim()) {
668
- lines.push(
669
- "",
670
- "### Diff summary",
671
- "",
672
- "```text",
673
- boundedText(stat.stdout, 6_000),
674
- "```",
675
- );
676
- }
677
- return { changedFiles, markdown: lines.join("\n") };
678
- }
679
-
680
- function pathLines(output) {
681
- return String(output || "")
682
- .split(/\r?\n/)
683
- .map((line) => line.trim())
684
- .filter(Boolean)
685
- .map((line) => line.replace(/^"|"$/g, ""));
686
- }
687
-
688
- function boundedText(value, maximum) {
689
- const text = String(value || "").trim();
690
- return text.length <= maximum
691
- ? text
692
- : `${text.slice(0, maximum)}\n... truncated by EngineerOS`;
693
- }
694
-
695
- export async function executeConnectedPrompt(assignment, config, callbacks) {
696
- const execution = connectorExecution(assignment);
697
- const previousSessionId = config.sessions?.[execution.sessionKey];
698
- const controller = launchAgentProcess(
699
- config.workspace,
700
- execution.prompt,
701
- execution.sandboxMode,
702
- config,
703
- callbacks,
704
- execution.profile,
705
- previousSessionId,
706
- {
707
- persistentAcp: true,
708
- sessionKey: execution.sessionKey,
709
- },
710
- );
711
- callbacks.onController?.(controller);
712
- callbacks.onProcess?.(controller.child);
713
- const completed = await controller.completed;
714
- const content = sanitizeAgentResponse(completed.finalMessage).trim();
715
- if (!content) {
716
- throw new Error("Agent completed without returning a response.");
717
- }
718
- return {
719
- content,
720
- model: completed.model ?? config.agent_protocol ?? "coding-agent",
721
- sessionId: completed.sessionId,
722
- sessionKey: execution.sessionKey,
723
- usage: completed.usage ?? null,
724
- };
725
- }
726
-
727
- export async function inspectCodingAgent(config, workspace = process.cwd()) {
728
- if (config.agent_protocol === "acp") {
729
- if (!config.agent_command) {
730
- throw new Error(
731
- "ACP requires --agent-command when pairing the connector.",
732
- );
733
- }
734
- const executionProfiles = await inspectAcpExecutionProfiles(
735
- workspace,
736
- config,
737
- );
738
- return {
739
- protocol: "acp",
740
- name: config.agent_name || path.basename(config.agent_command),
741
- version: config.agent_version || "ACP v1",
742
- executionProfiles,
743
- };
744
- }
745
- const codex = await inspectCodexCli(workspace);
746
- const modelProfiles = await inspectCodexExecutionProfiles({
747
- workspace,
748
- command: codex.command,
749
- });
750
- return {
751
- protocol: "codex",
752
- name: "Codex CLI",
753
- version: codex.version,
754
- executionProfiles: {
755
- model_selection: modelProfiles.length > 0,
756
- model_profiles: modelProfiles,
757
- reasoning_efforts: [
758
- ...new Set(modelProfiles.flatMap((model) => model.reasoning_efforts)),
759
- ],
760
- },
761
- };
762
- }
763
-
764
- export async function inspectCodexCli(workspace = process.cwd()) {
765
- const command =
766
- process.env.CODEX_BIN ||
767
- (process.platform === "win32" ? "codex.cmd" : "codex");
768
- const result = await runCodexCommand(command, ["--version"], workspace);
769
- if (result.code !== 0) {
770
- throw new Error(
771
- "Codex CLI is unavailable. Install it with `npm install -g @openai/codex@latest`, run `codex login`, then restart this connector.",
772
- );
773
- }
774
- const version = result.stdout.trim().slice(0, 100);
775
- if (!version) {
776
- throw new Error(
777
- "Codex CLI returned no version. Reinstall @openai/codex, then restart this connector.",
778
- );
779
- }
780
- return { command, version };
781
- }
782
-
783
- export function codexFailureMessage(output, code) {
784
- if (/requires a newer version of Codex/i.test(output)) {
785
- return (
786
- "The configured model requires a newer Codex CLI. " +
787
- "Run `npm install -g @openai/codex@latest`, verify with `codex --version`, " +
788
- "then restart the EngineerOS connector and retry the assessment."
789
- );
790
- }
791
- if (/not logged in|login required|authentication required/i.test(output)) {
792
- return "Codex CLI is not authenticated. Run `codex login`, then restart the EngineerOS connector.";
793
- }
794
- return `Codex exited with code ${code}. ${output.slice(-1_000)}`;
795
- }
796
-
797
- export function assessmentProgressMessage(event) {
798
- if (!event || typeof event !== "object") return null;
799
- if (event.type === "assessment.output_correction")
800
- return "Completing the required stage report structure";
801
- if (event.type === "agent.connected")
802
- return "Connected agent is ready to inspect the workspace";
803
- if (event.type === "acp.plan")
804
- return "Organizing the repository assessment plan";
805
- if (event.type === "acp.agent_thought_chunk")
806
- return "Reasoning through the current implementation";
807
- if (event.type === "acp.agent_message_chunk")
808
- return "Drafting the stage report";
809
- if (event.type === "acp.tool_call" || event.type === "acp.tool_call_update") {
810
- return assessmentCommandMilestone(event.update?.title);
811
- }
812
- if (event.type === "turn.started")
813
- return "Reviewing repository structure and current Git state";
814
- if (event.type === "item.started") {
815
- if (event.item?.type === "command_execution") {
816
- return assessmentCommandMilestone(event.item.command);
817
- }
818
- if (event.item?.type === "mcp_tool_call")
819
- return "Tracing architecture and code relationships";
820
- if (event.item?.type === "web_search")
821
- return "Checking an external technical reference";
822
- return null;
823
- }
824
- if (event.type === "item.completed" && event.item?.type === "agent_message") {
825
- return "Synthesizing findings and highest-return actions";
826
- }
827
- return null;
828
- }
829
-
830
- export function assessmentInactivityFailure(stage, inactiveMs) {
831
- if (inactiveMs < ASSESSMENT_INACTIVITY_TIMEOUT_MS) return null;
832
- return (
833
- `The connected agent produced no activity for 10 minutes during ${stage}. ` +
834
- "The stage was stopped instead of waiting indefinitely. Retry it after checking the agent terminal."
835
- );
836
- }
837
-
838
- export function promptProgressMessage(event) {
839
- if (!event || typeof event !== "object") return null;
840
- if (event.type === "turn.started")
841
- return "Reviewing the request and workspace context";
842
- if (event.type === "item.started") {
843
- if (event.item?.type === "command_execution") {
844
- return assessmentCommandMilestone(event.item.command);
845
- }
846
- if (event.item?.type === "mcp_tool_call")
847
- return "Checking connected project evidence";
848
- if (event.item?.type === "web_search")
849
- return "Checking an external technical reference";
850
- return null;
851
- }
852
- if (event.type === "item.completed" && event.item?.type === "agent_message") {
853
- return "Preparing the response";
854
- }
855
- if (event.type === "agent.connected") return "Agent connected";
856
- if (event.type === "acp.tool_call" || event.type === "acp.tool_call_update") {
857
- return "Agent is inspecting the workspace";
858
- }
859
- if (event.type === "acp.agent_message_chunk") return "Preparing the response";
860
- return null;
861
- }
862
-
863
- export function promptStreamEvent(event) {
864
- if (!event || typeof event !== "object") return null;
865
- if (
866
- event.type === "codex.agent_message_delta" &&
867
- typeof event.delta === "string"
868
- ) {
869
- const delta = sanitizeAgentResponse(event.delta);
870
- return delta ? { kind: "message", delta } : null;
871
- }
872
- if (
873
- event.type === "acp.agent_message_chunk" &&
874
- event.update?.content?.type === "text"
875
- ) {
876
- const delta = sanitizeAgentResponse(event.update.content.text);
877
- return delta ? { kind: "message", delta } : null;
878
- }
879
- if (event.type === "acp.agent_thought_chunk") {
880
- return {
881
- kind: "thought",
882
- message: "Agent is reasoning through the request",
883
- };
884
- }
885
- if (event.type === "acp.permission") {
886
- return {
887
- kind: "permission",
888
- message: event.update?.title || "Agent requested workspace permission",
889
- status: event.update?.status,
890
- };
891
- }
892
- if (event.type === "codex.usage") {
893
- return { kind: "usage", message: "Agent usage updated" };
894
- }
895
- if (event.type === "acp.plan") {
896
- return { kind: "plan", message: "Agent updated the working plan" };
897
- }
898
- if (event.type === "acp.tool_call" || event.type === "acp.tool_call_update") {
899
- return {
900
- kind: "tool",
901
- message: event.update?.title || "Agent is inspecting the workspace",
902
- status: event.update?.status,
903
- };
904
- }
905
- if (event.type === "item.completed" && event.item?.type === "agent_message") {
906
- const delta = sanitizeAgentResponse(event.item.text);
907
- return delta ? { kind: "message", delta } : null;
908
- }
909
- const message = promptProgressMessage(event);
910
- return message ? { kind: "status", message } : null;
911
- }
912
-
913
- function assessmentCommandMilestone(command) {
914
- const value = Array.isArray(command)
915
- ? command.join(" ")
916
- : String(command || "");
917
- const normalized = value.replace(/\s+/g, " ").trim().toLowerCase();
918
- if (!normalized) return "Inspecting workspace source";
919
- if (/\bgit\s+(status|log|diff|show|rev-parse)\b/.test(normalized)) {
920
- return "Comparing Git history and workspace changes";
921
- }
922
- if (
923
- /\b(test|pytest|vitest|jest|ruff|eslint|tsc|build|lint)\b/.test(normalized)
924
- ) {
925
- return "Checking verification and delivery signals";
926
- }
927
- if (
928
- /\b(audit|dependency|dependencies|lockfile|package-lock|pnpm-lock|requirements)\b/.test(
929
- normalized,
930
- )
931
- ) {
932
- return "Reviewing dependencies and security signals";
933
- }
934
- return "Tracing architecture and code relationships";
935
- }
936
-
937
- export function workspaceAssessmentExecution(assignment) {
938
- const stage = assignment?.stage;
939
- const requiredOutputHeading = String(
940
- assignment?.required_output_heading || "",
941
- ).trim();
942
- if (!stage || !requiredOutputHeading.startsWith("# Assessment Stage: ")) {
943
- throw new Error(
944
- "EngineerOS assessment assignment has an unsupported stage.",
945
- );
946
- }
947
- return {
948
- ...connectorExecution(assignment, { requiredOutputHeading }),
949
- requiredOutputHeading,
950
- };
951
- }
952
-
953
- export async function recoverAssessmentStageOutput({
954
- completed,
955
- prompt,
956
- requiredOutputHeading,
957
- retry,
958
- }) {
959
- try {
960
- return {
961
- completed,
962
- correctionUsed: false,
963
- report: normalizeAgentStructuredOutput(
964
- completed.finalMessage,
965
- requiredOutputHeading,
966
- ),
967
- };
968
- } catch (error) {
969
- if (!recoverableStructuredOutputFailure(error)) throw error;
970
- }
971
-
972
- const corrected = await retry(
973
- assessmentStageCorrectionPrompt(prompt, requiredOutputHeading),
974
- completed.sessionId,
975
- );
976
- try {
977
- return {
978
- completed: {
979
- ...corrected,
980
- usage: mergeTokenUsage(completed.usage, corrected.usage),
981
- },
982
- correctionUsed: true,
983
- report: normalizeAgentStructuredOutput(
984
- corrected.finalMessage,
985
- requiredOutputHeading,
986
- ),
987
- };
988
- } catch (error) {
989
- throw new Error(
990
- `Agent did not return the required stage report after one automatic correction attempt. ${error.message}`,
991
- { cause: error },
992
- );
993
- }
994
- }
995
-
996
- export function assessmentRejectionCorrectionPrompt(
997
- validationMessage,
998
- requiredOutputHeading,
999
- ) {
1000
- return [
1001
- "## Rejected Stage Output Recovery",
1002
- "",
1003
- "EngineerOS rejected the previous stage report because it was incomplete or violated the structured Markdown contract:",
1004
- "",
1005
- String(validationMessage || "The stage report was rejected.").trim(),
1006
- "",
1007
- "Treat the previous stage report as the authoritative draft.",
1008
- "Copy every valid section and block unchanged; repair only the incomplete or invalid entries identified by EngineerOS validation.",
1009
- "Do not re-inspect the repository or replace valid evidence unless the validation error requires it.",
1010
- "Return the entire corrected structured Markdown stage report so EngineerOS can validate it atomically, not only the repaired fragment or missing tail.",
1011
- `The first non-whitespace line must be exactly: ${requiredOutputHeading}`,
1012
- "Do not return progress commentary, an explanation of the correction, or a code fence.",
1013
- ].join("\n");
1014
- }
1015
-
1016
- export function assessmentStageCorrectionPrompt(
1017
- originalPrompt,
1018
- requiredOutputHeading,
1019
- ) {
1020
- return [
1021
- String(originalPrompt || "").trim(),
1022
- "",
1023
- "## Incomplete Stage Output Recovery",
1024
- "",
1025
- "The previous turn ended without a complete stage deliverable. Return the entire structured Markdown stage report now.",
1026
- "Use repository context already inspected in the previous turn when it is available; inspect only what remains necessary.",
1027
- `The first non-whitespace line of the final answer must be exactly: ${requiredOutputHeading}`,
1028
- "Follow every section, inspection, and completeness rule in the Assignment.",
1029
- "Do not return progress commentary, an explanation of the correction, or a code fence.",
1030
- ].join("\n");
1031
- }
1032
-
1033
- function recoverableStructuredOutputFailure(error) {
1034
- const message = error instanceof Error ? error.message : "";
1035
- return (
1036
- message.startsWith("Agent completed") ||
1037
- message.startsWith("Agent response")
1038
- );
1039
- }
1040
-
1041
- function mergeTokenUsage(first, second) {
1042
- const usages = [first, second].filter(
1043
- (usage) => usage && typeof usage === "object",
1044
- );
1045
- if (!usages.length) return null;
1046
- return Object.fromEntries(
1047
- [
1048
- "input_tokens",
1049
- "output_tokens",
1050
- "cache_read_tokens",
1051
- "cache_write_tokens",
1052
- "reasoning_tokens",
1053
- "total_tokens",
1054
- ].map((field) => [
1055
- field,
1056
- usages.reduce(
1057
- (total, usage) =>
1058
- total + (Number.isFinite(usage[field]) ? usage[field] : 0),
1059
- 0,
1060
- ),
1061
- ]),
1062
- );
1063
- }
1064
-
1065
- export function enqueueWorkspaceAssessment(
1066
- queue,
1067
- activeAssessment,
1068
- assignment,
1069
- { front = false } = {},
1070
- ) {
1071
- const matches = (candidate) =>
1072
- candidate?.assessment_id === assignment?.assessment_id &&
1073
- candidate?.stage === assignment?.stage;
1074
- if (
1075
- activeAssessment?.kind === "assessment" &&
1076
- activeAssessment.runId === assignment?.assessment_id &&
1077
- activeAssessment.stage === assignment?.stage
1078
- ) {
1079
- activeAssessment.resumeAssignment = assignment;
1080
- return "deferred";
1081
- }
1082
- if (queue.some(matches)) return "duplicate";
1083
- if (front) queue.unshift(assignment);
1084
- else queue.push(assignment);
1085
- return "queued";
1086
- }
1087
-
37
+ export const MIN_ASSESSMENT_WORKERS = 3;
38
+ export const MAX_ASSESSMENT_WORKERS = 8;
39
+ export const DEFAULT_ASSESSMENT_WORKERS = MIN_ASSESSMENT_WORKERS;
40
+ const EXCLUDED_DIRECTORIES = new Set([
41
+ ".agents",
42
+ ".claude",
43
+ ".codex",
44
+ ".engineeros",
45
+ ".forge",
46
+ ".gemini",
47
+ ".git",
48
+ ".next",
49
+ ".pytest_cache",
50
+ ".ruff_cache",
51
+ ".venv",
52
+ "__pycache__",
53
+ "build",
54
+ "coverage",
55
+ "dist",
56
+ "node_modules",
57
+ "target",
58
+ "vendor",
59
+ ]);
60
+ const EXCLUDED_PATH_PREFIXES = [".github/skills/"];
61
+ const EXCLUDED_FILE_EXTENSIONS = new Set([
62
+ ".7z",
63
+ ".a",
64
+ ".bin",
65
+ ".class",
66
+ ".dll",
67
+ ".dylib",
68
+ ".exe",
69
+ ".gz",
70
+ ".jar",
71
+ ".lib",
72
+ ".o",
73
+ ".obj",
74
+ ".pyc",
75
+ ".pyo",
76
+ ".rar",
77
+ ".so",
78
+ ".tar",
79
+ ".tgz",
80
+ ".war",
81
+ ".zip",
82
+ ]);
83
+ const LOCK_FILE_NAMES = new Set([
84
+ "cargo.lock",
85
+ "composer.lock",
86
+ "go.sum",
87
+ "package-lock.json",
88
+ "pnpm-lock.yaml",
89
+ "poetry.lock",
90
+ "uv.lock",
91
+ "yarn.lock",
92
+ ]);
93
+ const ENTRYPOINT_NAMES = new Set([
94
+ "app.py",
95
+ "index.ts",
96
+ "index.tsx",
97
+ "main.py",
98
+ "main.ts",
99
+ "main.tsx",
100
+ "manage.py",
101
+ "server.py",
102
+ ]);
103
+ const REPOSITORY_CONFIGURATION_NAMES = new Set([
104
+ ".dockerignore",
105
+ ".editorconfig",
106
+ ".gitattributes",
107
+ ".gitignore",
108
+ "lerna.json",
109
+ "makefile",
110
+ "nx.json",
111
+ "turbo.json",
112
+ ]);
113
+ const CODE_EXTENSIONS = new Set([
114
+ ".c",
115
+ ".cpp",
116
+ ".cs",
117
+ ".go",
118
+ ".h",
119
+ ".java",
120
+ ".js",
121
+ ".jsx",
122
+ ".mjs",
123
+ ".php",
124
+ ".py",
125
+ ".rb",
126
+ ".rs",
127
+ ".sql",
128
+ ".ts",
129
+ ".tsx",
130
+ ]);
131
+ const CODE_MARKERS = new Set([
132
+ "cargo.toml",
133
+ "composer.json",
134
+ "go.mod",
135
+ "package.json",
136
+ "pom.xml",
137
+ "pyproject.toml",
138
+ "requirements.txt",
139
+ ]);
140
+
141
+ export async function executeAssignment(assignment, config, callbacks) {
142
+ const execution = connectorExecution(assignment);
143
+ const runWorkspace = await prepareRunWorkspace(
144
+ config.workspace,
145
+ assignment.run_id,
146
+ assignment.base_revision,
147
+ );
148
+ const controller = launchAgentProcess(
149
+ runWorkspace,
150
+ execution.prompt,
151
+ execution.sandboxMode,
152
+ config,
153
+ callbacks,
154
+ execution.profile,
155
+ undefined,
156
+ { runId: assignment.run_id },
157
+ );
158
+ callbacks.onProcess?.(controller.child);
159
+ const implementation = await controller.completed;
160
+ const changedFiles = await changedFilePaths(runWorkspace);
161
+ if (!changedFiles.length)
162
+ throw new Error("Agent completed without changing any files.");
163
+ const committed = await commitRunChange(
164
+ runWorkspace,
165
+ assignment.base_revision,
166
+ assignment.run_id,
167
+ );
168
+ const verificationHeading = "# Verification Report";
169
+ const verifier = launchAgentProcess(
170
+ runWorkspace,
171
+ buildAgentHarnessPrompt({
172
+ agentRole: "verification",
173
+ prompt: verificationPrompt(
174
+ assignment,
175
+ committed.revision,
176
+ committed.changedFiles,
177
+ ),
178
+ sandboxMode: "read-only",
179
+ requiredOutputHeading: verificationHeading,
180
+ }),
181
+ "read-only",
182
+ config,
183
+ callbacks,
184
+ execution.profile,
185
+ );
186
+ callbacks.onProcess?.(verifier.child);
187
+ const verification = await verifier.completed;
188
+ const verificationReport = normalizeAgentStructuredOutput(
189
+ verification.finalMessage,
190
+ verificationHeading,
191
+ );
192
+ const proofEvidence = parseVerificationReport(
193
+ verificationReport,
194
+ assignment.proof_checks,
195
+ config.connector_id,
196
+ assignment.run_id,
197
+ );
198
+ return {
199
+ head_revision: committed.revision,
200
+ repository_locator: assignment.repository_locator,
201
+ external_reference: `connector:${config.connector_id}/run:${assignment.run_id}`,
202
+ diff_patch: committed.diffPatch,
203
+ changed_files: committed.changedFiles,
204
+ proof_evidence: proofEvidence,
205
+ verification_report: verificationReport,
206
+ usage: [
207
+ {
208
+ request_type: "goal_implementation",
209
+ model: implementation.model,
210
+ ...implementation.usage,
211
+ },
212
+ {
213
+ request_type: "goal_verification",
214
+ model: verification.model,
215
+ ...verification.usage,
216
+ },
217
+ ].filter((entry) => entry.total_tokens > 0),
218
+ };
219
+ }
220
+
221
+ export async function applyAcceptedChange(
222
+ workspace,
223
+ baseRevision,
224
+ headRevision,
225
+ ) {
226
+ const current = await run("git", ["rev-parse", "HEAD"], workspace, {
227
+ allowFailure: true,
228
+ });
229
+ if (current.code !== 0) {
230
+ return {
231
+ applied: false,
232
+ reason: "The connected workspace is not a Git repository.",
233
+ };
234
+ }
235
+ const currentHead = current.stdout.trim();
236
+ const alreadyApplied = await run(
237
+ "git",
238
+ ["merge-base", "--is-ancestor", headRevision, currentHead],
239
+ workspace,
240
+ { allowFailure: true },
241
+ );
242
+ if (alreadyApplied.code === 0)
243
+ return { applied: true, revision: currentHead };
244
+ const status = await run("git", ["status", "--porcelain"], workspace);
245
+ if (status.stdout.trim()) {
246
+ return {
247
+ applied: false,
248
+ reason: `The connected workspace has uncommitted changes. Apply accepted commit ${headRevision} after preserving them.`,
249
+ };
250
+ }
251
+ if (currentHead !== baseRevision) {
252
+ return {
253
+ applied: false,
254
+ reason: `The connected branch moved from frozen base ${baseRevision} to ${currentHead}. Apply accepted commit ${headRevision} with git cherry-pick.`,
255
+ };
256
+ }
257
+ const applied = await run("git", ["cherry-pick", headRevision], workspace, {
258
+ allowFailure: true,
259
+ });
260
+ if (applied.code !== 0) {
261
+ await run("git", ["cherry-pick", "--abort"], workspace, {
262
+ allowFailure: true,
263
+ });
264
+ return {
265
+ applied: false,
266
+ reason: `The accepted commit ${headRevision} could not be applied cleanly. Apply it manually with git cherry-pick.`,
267
+ };
268
+ }
269
+ const integrated = await run("git", ["rev-parse", "HEAD"], workspace);
270
+ return { applied: true, revision: integrated.stdout.trim() };
271
+ }
272
+
273
+ async function commitRunChange(workspace, baseRevision, runId) {
274
+ await run("git", ["add", "-A"], workspace);
275
+ await run(
276
+ "git",
277
+ [
278
+ "-c",
279
+ "user.name=EngineerOS Codex",
280
+ "-c",
281
+ "user.email=codex@engineeros.local",
282
+ "commit",
283
+ "-m",
284
+ `EngineerOS Goal Run ${runId}`,
285
+ ],
286
+ workspace,
287
+ );
288
+ const head = await run("git", ["rev-parse", "HEAD"], workspace);
289
+ const revision = head.stdout.trim();
290
+ const diff = await run(
291
+ "git",
292
+ ["diff", "--binary", baseRevision, revision, "--"],
293
+ workspace,
294
+ );
295
+ const paths = await run(
296
+ "git",
297
+ ["diff", "--name-only", "-z", baseRevision, revision, "--"],
298
+ workspace,
299
+ );
300
+ return {
301
+ revision,
302
+ diffPatch: diff.stdout,
303
+ changedFiles: gitPathList(paths.stdout).sort(),
304
+ };
305
+ }
306
+
307
+ export function verificationPrompt(assignment, revision, changedFiles) {
308
+ const checks = (assignment.proof_checks ?? [])
309
+ .map(
310
+ (proof, index) =>
311
+ `## Proof ${index + 1}\n- Check: ${proof.check ?? ""}\n- Expected: ${proof.expected ?? ""}`,
312
+ )
313
+ .join("\n\n");
314
+ return `# EngineerOS Connected Verification
315
+
316
+ Independently verify the frozen Goal at Git commit \`${revision}\`. Do not modify files. Run the commands or inspections needed for every Proof item, and check the Goal boundaries and constraints in the supplied packet.
317
+
318
+ Changed files:
319
+ ${changedFiles.map((item) => `- \`${item}\``).join("\n")}
320
+
321
+ ${checks}
322
+
323
+ Return structured Markdown only, with exactly one section per Proof:
324
+
325
+ ## Proof 1
326
+ - Status: passed or failed
327
+ - Exit code: integer or none
328
+ - Evidence: concise observed output and command
329
+
330
+ Do not claim a Proof passed unless you observed it directly.`;
331
+ }
332
+
333
+ export function parseVerificationReport(
334
+ report,
335
+ proofChecks,
336
+ connectorId,
337
+ runId,
338
+ ) {
339
+ if (!report?.trim())
340
+ throw new Error("Codex returned no connected verification report.");
341
+ return (proofChecks ?? []).map((_, index) => {
342
+ const start = new RegExp(`^## Proof ${index + 1}\\s*$`, "im").exec(report);
343
+ const tail = start ? report.slice(start.index + start[0].length) : "";
344
+ const section = tail.split(/^## Proof \d+\s*$/im)[0] ?? "";
345
+ const status =
346
+ /^- Status:\s*(passed|failed)\s*$/im.exec(section)?.[1] ?? "failed";
347
+ const exitValue =
348
+ /^- Exit code:\s*(\d+|none)\s*$/im.exec(section)?.[1] ?? "none";
349
+ const evidence = /^- Evidence:\s*(.+)$/im.exec(section)?.[1]?.trim();
350
+ return {
351
+ proof_index: index,
352
+ status,
353
+ verifier_type: "agent_reported",
354
+ verifier_identity: "Connected Codex CLI verifier",
355
+ locator: `connector:${connectorId}/run:${runId}#proof-${index + 1}`,
356
+ output_excerpt:
357
+ evidence ||
358
+ "The connected verifier did not provide evidence for this Proof.",
359
+ exit_code: exitValue === "none" ? null : Number(exitValue),
360
+ };
361
+ });
362
+ }
363
+
364
+ export async function executeWorkspaceAssessment(
365
+ assignment,
366
+ config,
367
+ callbacks,
368
+ ) {
369
+ const execution = workspaceAssessmentExecution(assignment);
370
+ const assessmentAcpContext =
371
+ config.agent_protocol === "acp"
372
+ ? {
373
+ persistentAcp: true,
374
+ sessionKey: `assessment:${assignment.assessment_id}:${assignment.stage}`,
375
+ }
376
+ : undefined;
377
+ const launchAssessmentAgent = (turnPrompt, previousSessionId) => {
378
+ const controller = launchAgentProcess(
379
+ config.workspace,
380
+ turnPrompt,
381
+ execution.sandboxMode,
382
+ config,
383
+ callbacks,
384
+ execution.profile,
385
+ previousSessionId,
386
+ assessmentAcpContext,
387
+ );
388
+ callbacks.onController?.(controller);
389
+ callbacks.onProcess?.(controller.child);
390
+ return controller;
391
+ };
392
+ const startingRevision = await run(
393
+ "git",
394
+ ["rev-parse", "HEAD"],
395
+ config.workspace,
396
+ { allowFailure: true },
397
+ );
398
+ const startingHead =
399
+ startingRevision.code === 0
400
+ ? startingRevision.stdout.trim().slice(0, 128)
401
+ : null;
402
+ if (
403
+ assignment.target_head_revision &&
404
+ startingHead !== assignment.target_head_revision
405
+ ) {
406
+ throw new Error(
407
+ "This workspace is no longer at the commit inventoried by EngineerOS. Refresh the workspace inventory before assessing it.",
408
+ );
409
+ }
410
+ const changeImpact =
411
+ assignment.assessment_mode === "incremental"
412
+ ? await workspaceChangeImpact(
413
+ config.workspace,
414
+ assignment.base_head_revision,
415
+ assignment.target_head_revision,
416
+ )
417
+ : { changedFiles: [], markdown: null };
418
+ const prompt = changeImpact.markdown
419
+ ? execution.prompt.replace(
420
+ "<!-- ENGINEEROS_CHANGE_IMPACT -->",
421
+ changeImpact.markdown,
422
+ )
423
+ : execution.prompt;
424
+ const controller = launchAssessmentAgent(prompt);
425
+ let completed = await controller.completed;
426
+ const recovered = await recoverAssessmentStageOutput({
427
+ completed,
428
+ prompt,
429
+ requiredOutputHeading: execution.requiredOutputHeading,
430
+ retry: async (correctionPrompt, previousSessionId) => {
431
+ callbacks.onEvent?.({
432
+ type: "assessment.output_correction",
433
+ message: "The Agent is completing the required stage report structure",
434
+ });
435
+ const correction = launchAssessmentAgent(
436
+ correctionPrompt,
437
+ previousSessionId,
438
+ );
439
+ return correction.completed;
440
+ },
441
+ });
442
+ completed = recovered.completed;
443
+ const buildResult = async (turn, report) => {
444
+ const endingRevision = await run(
445
+ "git",
446
+ ["rev-parse", "HEAD"],
447
+ config.workspace,
448
+ { allowFailure: true },
449
+ );
450
+ const endingHead =
451
+ endingRevision.code === 0
452
+ ? endingRevision.stdout.trim().slice(0, 128)
453
+ : null;
454
+ if (startingHead !== endingHead) {
455
+ throw new Error(
456
+ "The Git commit changed during assessment. Refresh the workspace inventory and assess the new commit.",
457
+ );
458
+ }
459
+ return {
460
+ stage: assignment.stage,
461
+ report_markdown: report,
462
+ observed_head_revision: endingHead,
463
+ changed_files: changeImpact.changedFiles,
464
+ change_impact_markdown: changeImpact.markdown,
465
+ model: turn.model ?? config.agent_protocol ?? "coding-agent",
466
+ usage: turn.usage ?? null,
467
+ agent_session_id: turn.sessionId ?? null,
468
+ };
469
+ };
470
+ const result = await buildResult(completed, recovered.report);
471
+ attachAssessmentRejectionCorrection(result, assignment, config, callbacks, {
472
+ previousSessionId: completed.sessionId,
473
+ buildResult,
474
+ });
475
+ return result;
476
+ }
477
+
478
+ export function attachAssessmentRejectionCorrection(
479
+ result,
480
+ assignment,
481
+ config,
482
+ callbacks,
483
+ { previousSessionId = result.agent_session_id, draftPath, buildResult } = {},
484
+ ) {
485
+ const execution = workspaceAssessmentExecution(assignment);
486
+ const assessmentAcpContext =
487
+ config.agent_protocol === "acp"
488
+ ? {
489
+ persistentAcp: true,
490
+ sessionKey: `assessment:${assignment.assessment_id}:${assignment.stage}`,
491
+ }
492
+ : undefined;
493
+ Object.defineProperty(result, "correctAfterRejection", {
494
+ enumerable: false,
495
+ value: async (validationMessage) => {
496
+ callbacks.onEvent?.({
497
+ type: "assessment.output_correction",
498
+ message: "The Agent is correcting the rejected stage report",
499
+ });
500
+ const draftInstruction = draftPath
501
+ ? [
502
+ "",
503
+ `The authoritative draft is stored at \`${draftPath}\`. Read that file before making the requested correction.`,
504
+ ].join("\n")
505
+ : "";
506
+ const correctionPrompt = `${assessmentRejectionCorrectionPrompt(validationMessage, execution.requiredOutputHeading)}${draftInstruction}`;
507
+ const launchCorrection = (prompt, sessionId) => {
508
+ const controller = launchAgentProcess(
509
+ config.workspace,
510
+ prompt,
511
+ execution.sandboxMode,
512
+ config,
513
+ callbacks,
514
+ execution.profile,
515
+ sessionId,
516
+ assessmentAcpContext,
517
+ );
518
+ callbacks.onController?.(controller);
519
+ callbacks.onProcess?.(controller.child);
520
+ return controller;
521
+ };
522
+ let corrected = await launchCorrection(
523
+ correctionPrompt,
524
+ previousSessionId,
525
+ ).completed;
526
+ const recovered = await recoverAssessmentStageOutput({
527
+ completed: corrected,
528
+ prompt: correctionPrompt,
529
+ requiredOutputHeading: execution.requiredOutputHeading,
530
+ retry: async (formatPrompt, sessionId) => {
531
+ callbacks.onEvent?.({
532
+ type: "assessment.output_correction",
533
+ message: "The Agent is formatting the corrected stage report",
534
+ });
535
+ return launchCorrection(formatPrompt, sessionId).completed;
536
+ },
537
+ });
538
+ corrected = recovered.completed;
539
+ const correctedReport = recovered.report;
540
+ if (buildResult) {
541
+ return buildResult(
542
+ {
543
+ ...corrected,
544
+ usage: mergeTokenUsage(result.usage, corrected.usage),
545
+ },
546
+ correctedReport,
547
+ );
548
+ }
549
+ const endingRevision = await run(
550
+ "git",
551
+ ["rev-parse", "HEAD"],
552
+ config.workspace,
553
+ { allowFailure: true },
554
+ );
555
+ const endingHead =
556
+ endingRevision.code === 0
557
+ ? endingRevision.stdout.trim().slice(0, 128)
558
+ : null;
559
+ if (
560
+ assignment.target_head_revision &&
561
+ endingHead !== assignment.target_head_revision
562
+ ) {
563
+ throw new Error(
564
+ "The Git commit changed before assessment correction. Refresh the workspace inventory and assess the new commit.",
565
+ );
566
+ }
567
+ return {
568
+ ...result,
569
+ report_markdown: correctedReport,
570
+ observed_head_revision: endingHead,
571
+ model: corrected.model ?? result.model,
572
+ usage: mergeTokenUsage(result.usage, corrected.usage),
573
+ agent_session_id: corrected.sessionId ?? previousSessionId ?? null,
574
+ };
575
+ },
576
+ });
577
+ return result;
578
+ }
579
+
580
+ export async function workspaceChangeImpact(
581
+ workspace,
582
+ baseRevision,
583
+ targetRevision,
584
+ ) {
585
+ if (!baseRevision || !targetRevision) {
586
+ throw new Error(
587
+ "Incremental assessment requires both the previously assessed and current Git commits. Run a full assessment instead.",
588
+ );
589
+ }
590
+ const range = `${baseRevision}..${targetRevision}`;
591
+ const names = await run(
592
+ "git",
593
+ ["diff", "--name-status", "--find-renames", range],
594
+ workspace,
595
+ { allowFailure: true },
596
+ );
597
+ if (names.code !== 0) {
598
+ throw new Error(
599
+ "Codex could not compare the assessed and current commits. Fetch the missing Git history or run a full assessment.",
600
+ );
601
+ }
602
+ const committedFiles = await run(
603
+ "git",
604
+ ["-c", "core.quotepath=false", "diff", "--name-only", range],
605
+ workspace,
606
+ { allowFailure: true },
607
+ );
608
+ const workingFiles = await run(
609
+ "git",
610
+ [
611
+ "-c",
612
+ "core.quotepath=false",
613
+ "ls-files",
614
+ "--others",
615
+ "--modified",
616
+ "--deleted",
617
+ "--exclude-standard",
618
+ ],
619
+ workspace,
620
+ { allowFailure: true },
621
+ );
622
+ const status = await run("git", ["status", "--short"], workspace, {
623
+ allowFailure: true,
624
+ });
625
+ const stat = await run(
626
+ "git",
627
+ ["diff", "--stat", "--compact-summary", range],
628
+ workspace,
629
+ { allowFailure: true },
630
+ );
631
+ const allChangedFiles = [
632
+ ...new Set([
633
+ ...pathLines(committedFiles.stdout),
634
+ ...pathLines(workingFiles.stdout),
635
+ ]),
636
+ ];
637
+ if (allChangedFiles.length > 500) {
638
+ throw new Error(
639
+ `This change affects ${allChangedFiles.length} paths, above the 500-path incremental limit. Run a full reassessment instead.`,
640
+ );
641
+ }
642
+ const changedFiles = allChangedFiles;
643
+ if (!changedFiles.length) {
644
+ throw new Error(
645
+ "The inventoried repository changed but Git reports no assessable paths. Refresh inventory or run a full assessment.",
646
+ );
647
+ }
648
+ const lines = [
649
+ `Comparison: \`${range}\``,
650
+ `Changed paths: ${changedFiles.length}`,
651
+ "",
652
+ "### Name status",
653
+ "",
654
+ "```text",
655
+ boundedText(names.stdout, 12_000),
656
+ "```",
657
+ ];
658
+ if (status.stdout.trim()) {
659
+ lines.push(
660
+ "",
661
+ "### Working tree",
662
+ "",
663
+ "```text",
664
+ boundedText(status.stdout, 6_000),
665
+ "```",
666
+ );
667
+ }
668
+ if (stat.stdout.trim()) {
669
+ lines.push(
670
+ "",
671
+ "### Diff summary",
672
+ "",
673
+ "```text",
674
+ boundedText(stat.stdout, 6_000),
675
+ "```",
676
+ );
677
+ }
678
+ return { changedFiles, markdown: lines.join("\n") };
679
+ }
680
+
681
+ function pathLines(output) {
682
+ return String(output || "")
683
+ .split(/\r?\n/)
684
+ .map((line) => line.trim())
685
+ .filter(Boolean)
686
+ .map((line) => line.replace(/^"|"$/g, ""));
687
+ }
688
+
689
+ function boundedText(value, maximum) {
690
+ const text = String(value || "").trim();
691
+ return text.length <= maximum
692
+ ? text
693
+ : `${text.slice(0, maximum)}\n... truncated by EngineerOS`;
694
+ }
695
+
696
+ export async function executeConnectedPrompt(assignment, config, callbacks) {
697
+ const execution = connectorExecution(assignment);
698
+ const previousSessionId = config.sessions?.[execution.sessionKey];
699
+ const controller = launchAgentProcess(
700
+ config.workspace,
701
+ execution.prompt,
702
+ execution.sandboxMode,
703
+ config,
704
+ callbacks,
705
+ execution.profile,
706
+ previousSessionId,
707
+ {
708
+ persistentAcp: true,
709
+ sessionKey: execution.sessionKey,
710
+ },
711
+ );
712
+ callbacks.onController?.(controller);
713
+ callbacks.onProcess?.(controller.child);
714
+ const completed = await controller.completed;
715
+ const content = sanitizeAgentResponse(completed.finalMessage).trim();
716
+ if (!content) {
717
+ throw new Error("Agent completed without returning a response.");
718
+ }
719
+ return {
720
+ content,
721
+ model: completed.model ?? config.agent_protocol ?? "coding-agent",
722
+ sessionId: completed.sessionId,
723
+ sessionKey: execution.sessionKey,
724
+ usage: completed.usage ?? null,
725
+ };
726
+ }
727
+
728
+ export async function inspectCodingAgent(config, workspace = process.cwd()) {
729
+ if (config.agent_protocol === "acp") {
730
+ if (!config.agent_command) {
731
+ throw new Error(
732
+ "ACP requires --agent-command when pairing the connector.",
733
+ );
734
+ }
735
+ const executionProfiles = await inspectAcpExecutionProfiles(
736
+ workspace,
737
+ config,
738
+ );
739
+ return {
740
+ protocol: "acp",
741
+ name: config.agent_name || path.basename(config.agent_command),
742
+ version: config.agent_version || "ACP v1",
743
+ executionProfiles,
744
+ };
745
+ }
746
+ const codex = await inspectCodexCli(workspace);
747
+ const modelProfiles = await inspectCodexExecutionProfiles({
748
+ workspace,
749
+ command: codex.command,
750
+ });
751
+ return {
752
+ protocol: "codex",
753
+ name: "Codex CLI",
754
+ version: codex.version,
755
+ executionProfiles: {
756
+ model_selection: modelProfiles.length > 0,
757
+ model_profiles: modelProfiles,
758
+ reasoning_efforts: [
759
+ ...new Set(modelProfiles.flatMap((model) => model.reasoning_efforts)),
760
+ ],
761
+ },
762
+ };
763
+ }
764
+
765
+ export async function inspectCodexCli(workspace = process.cwd()) {
766
+ const command =
767
+ process.env.CODEX_BIN ||
768
+ (process.platform === "win32" ? "codex.cmd" : "codex");
769
+ const result = await runCodexCommand(command, ["--version"], workspace);
770
+ if (result.code !== 0) {
771
+ throw new Error(
772
+ "Codex CLI is unavailable. Install it with `npm install -g @openai/codex@latest`, run `codex login`, then restart this connector.",
773
+ );
774
+ }
775
+ const version = result.stdout.trim().slice(0, 100);
776
+ if (!version) {
777
+ throw new Error(
778
+ "Codex CLI returned no version. Reinstall @openai/codex, then restart this connector.",
779
+ );
780
+ }
781
+ return { command, version };
782
+ }
783
+
784
+ export function codexFailureMessage(output, code) {
785
+ if (/requires a newer version of Codex/i.test(output)) {
786
+ return (
787
+ "The configured model requires a newer Codex CLI. " +
788
+ "Run `npm install -g @openai/codex@latest`, verify with `codex --version`, " +
789
+ "then restart the EngineerOS connector and retry the assessment."
790
+ );
791
+ }
792
+ if (/not logged in|login required|authentication required/i.test(output)) {
793
+ return "Codex CLI is not authenticated. Run `codex login`, then restart the EngineerOS connector.";
794
+ }
795
+ return `Codex exited with code ${code}. ${output.slice(-1_000)}`;
796
+ }
797
+
798
+ export function assessmentProgressMessage(event) {
799
+ if (!event || typeof event !== "object") return null;
800
+ if (event.type === "assessment.output_correction")
801
+ return "Completing the required stage report structure";
802
+ if (event.type === "agent.connected")
803
+ return "Connected agent is ready to inspect the workspace";
804
+ if (event.type === "acp.plan")
805
+ return "Organizing the repository assessment plan";
806
+ if (event.type === "acp.agent_thought_chunk")
807
+ return "Reasoning through the current implementation";
808
+ if (event.type === "acp.agent_message_chunk")
809
+ return "Drafting the stage report";
810
+ if (event.type === "acp.tool_call" || event.type === "acp.tool_call_update") {
811
+ return assessmentCommandMilestone(event.update?.title);
812
+ }
813
+ if (event.type === "turn.started")
814
+ return "Reviewing repository structure and current Git state";
815
+ if (event.type === "item.started") {
816
+ if (event.item?.type === "command_execution") {
817
+ return assessmentCommandMilestone(event.item.command);
818
+ }
819
+ if (event.item?.type === "mcp_tool_call")
820
+ return "Tracing architecture and code relationships";
821
+ if (event.item?.type === "web_search")
822
+ return "Checking an external technical reference";
823
+ return null;
824
+ }
825
+ if (event.type === "item.completed" && event.item?.type === "agent_message") {
826
+ return "Synthesizing findings and highest-return actions";
827
+ }
828
+ return null;
829
+ }
830
+
831
+ export function assessmentInactivityFailure(stage, inactiveMs) {
832
+ if (inactiveMs < ASSESSMENT_INACTIVITY_TIMEOUT_MS) return null;
833
+ return (
834
+ `The connected agent produced no activity for 10 minutes during ${stage}. ` +
835
+ "The stage was stopped instead of waiting indefinitely. Retry it after checking the agent terminal."
836
+ );
837
+ }
838
+
839
+ export function promptProgressMessage(event) {
840
+ if (!event || typeof event !== "object") return null;
841
+ if (event.type === "turn.started")
842
+ return "Reviewing the request and workspace context";
843
+ if (event.type === "item.started") {
844
+ if (event.item?.type === "command_execution") {
845
+ return assessmentCommandMilestone(event.item.command);
846
+ }
847
+ if (event.item?.type === "mcp_tool_call")
848
+ return "Checking connected project evidence";
849
+ if (event.item?.type === "web_search")
850
+ return "Checking an external technical reference";
851
+ return null;
852
+ }
853
+ if (event.type === "item.completed" && event.item?.type === "agent_message") {
854
+ return "Preparing the response";
855
+ }
856
+ if (event.type === "agent.connected") return "Agent connected";
857
+ if (event.type === "acp.tool_call" || event.type === "acp.tool_call_update") {
858
+ return "Agent is inspecting the workspace";
859
+ }
860
+ if (event.type === "acp.agent_message_chunk") return "Preparing the response";
861
+ return null;
862
+ }
863
+
864
+ export function promptStreamEvent(event) {
865
+ if (!event || typeof event !== "object") return null;
866
+ if (
867
+ event.type === "codex.agent_message_delta" &&
868
+ typeof event.delta === "string"
869
+ ) {
870
+ const delta = sanitizeAgentResponse(event.delta);
871
+ return delta ? { kind: "message", delta } : null;
872
+ }
873
+ if (
874
+ event.type === "acp.agent_message_chunk" &&
875
+ event.update?.content?.type === "text"
876
+ ) {
877
+ const delta = sanitizeAgentResponse(event.update.content.text);
878
+ return delta ? { kind: "message", delta } : null;
879
+ }
880
+ if (event.type === "acp.agent_thought_chunk") {
881
+ return {
882
+ kind: "thought",
883
+ message: "Agent is reasoning through the request",
884
+ };
885
+ }
886
+ if (event.type === "acp.permission") {
887
+ return {
888
+ kind: "permission",
889
+ message: event.update?.title || "Agent requested workspace permission",
890
+ status: event.update?.status,
891
+ };
892
+ }
893
+ if (event.type === "codex.usage") {
894
+ return { kind: "usage", message: "Agent usage updated" };
895
+ }
896
+ if (event.type === "acp.plan") {
897
+ return { kind: "plan", message: "Agent updated the working plan" };
898
+ }
899
+ if (event.type === "acp.tool_call" || event.type === "acp.tool_call_update") {
900
+ return {
901
+ kind: "tool",
902
+ message: event.update?.title || "Agent is inspecting the workspace",
903
+ status: event.update?.status,
904
+ };
905
+ }
906
+ if (event.type === "item.completed" && event.item?.type === "agent_message") {
907
+ const delta = sanitizeAgentResponse(event.item.text);
908
+ return delta ? { kind: "message", delta } : null;
909
+ }
910
+ const message = promptProgressMessage(event);
911
+ return message ? { kind: "status", message } : null;
912
+ }
913
+
914
+ function assessmentCommandMilestone(command) {
915
+ const value = Array.isArray(command)
916
+ ? command.join(" ")
917
+ : String(command || "");
918
+ const normalized = value.replace(/\s+/g, " ").trim().toLowerCase();
919
+ if (!normalized) return "Inspecting workspace source";
920
+ if (/\bgit\s+(status|log|diff|show|rev-parse)\b/.test(normalized)) {
921
+ return "Comparing Git history and workspace changes";
922
+ }
923
+ if (
924
+ /\b(test|pytest|vitest|jest|ruff|eslint|tsc|build|lint)\b/.test(normalized)
925
+ ) {
926
+ return "Checking verification and delivery signals";
927
+ }
928
+ if (
929
+ /\b(audit|dependency|dependencies|lockfile|package-lock|pnpm-lock|requirements)\b/.test(
930
+ normalized,
931
+ )
932
+ ) {
933
+ return "Reviewing dependencies and security signals";
934
+ }
935
+ return "Tracing architecture and code relationships";
936
+ }
937
+
938
+ export function workspaceAssessmentExecution(assignment) {
939
+ const stage = assignment?.stage;
940
+ const requiredOutputHeading = String(
941
+ assignment?.required_output_heading || "",
942
+ ).trim();
943
+ if (!stage || !requiredOutputHeading.startsWith("# Assessment Stage: ")) {
944
+ throw new Error(
945
+ "EngineerOS assessment assignment has an unsupported stage.",
946
+ );
947
+ }
948
+ return {
949
+ ...connectorExecution(assignment, { requiredOutputHeading }),
950
+ requiredOutputHeading,
951
+ };
952
+ }
953
+
954
+ export async function recoverAssessmentStageOutput({
955
+ completed,
956
+ prompt,
957
+ requiredOutputHeading,
958
+ retry,
959
+ }) {
960
+ try {
961
+ return {
962
+ completed,
963
+ correctionUsed: false,
964
+ report: normalizeAgentStructuredOutput(
965
+ completed.finalMessage,
966
+ requiredOutputHeading,
967
+ ),
968
+ };
969
+ } catch (error) {
970
+ if (!recoverableStructuredOutputFailure(error)) throw error;
971
+ }
972
+
973
+ const corrected = await retry(
974
+ assessmentStageCorrectionPrompt(prompt, requiredOutputHeading),
975
+ completed.sessionId,
976
+ );
977
+ try {
978
+ return {
979
+ completed: {
980
+ ...corrected,
981
+ usage: mergeTokenUsage(completed.usage, corrected.usage),
982
+ },
983
+ correctionUsed: true,
984
+ report: normalizeAgentStructuredOutput(
985
+ corrected.finalMessage,
986
+ requiredOutputHeading,
987
+ ),
988
+ };
989
+ } catch (error) {
990
+ throw new Error(
991
+ `Agent did not return the required stage report after one automatic correction attempt. ${error.message}`,
992
+ { cause: error },
993
+ );
994
+ }
995
+ }
996
+
997
+ export function assessmentRejectionCorrectionPrompt(
998
+ validationMessage,
999
+ requiredOutputHeading,
1000
+ ) {
1001
+ return [
1002
+ "## Rejected Stage Output Recovery",
1003
+ "",
1004
+ "EngineerOS rejected the previous stage report because it was incomplete or violated the structured Markdown contract:",
1005
+ "",
1006
+ String(validationMessage || "The stage report was rejected.").trim(),
1007
+ "",
1008
+ "Treat the previous stage report as the authoritative draft.",
1009
+ "Copy every valid section and block unchanged; repair only the incomplete or invalid entries identified by EngineerOS validation.",
1010
+ "Do not re-inspect the repository or replace valid evidence unless the validation error requires it.",
1011
+ "Return the entire corrected structured Markdown stage report so EngineerOS can validate it atomically, not only the repaired fragment or missing tail.",
1012
+ `The first non-whitespace line must be exactly: ${requiredOutputHeading}`,
1013
+ "Do not return progress commentary, an explanation of the correction, or a code fence.",
1014
+ ].join("\n");
1015
+ }
1016
+
1017
+ export function assessmentStageCorrectionPrompt(
1018
+ originalPrompt,
1019
+ requiredOutputHeading,
1020
+ ) {
1021
+ return [
1022
+ String(originalPrompt || "").trim(),
1023
+ "",
1024
+ "## Incomplete Stage Output Recovery",
1025
+ "",
1026
+ "The previous turn ended without a complete stage deliverable. Return the entire structured Markdown stage report now.",
1027
+ "Use repository context already inspected in the previous turn when it is available; inspect only what remains necessary.",
1028
+ `The first non-whitespace line of the final answer must be exactly: ${requiredOutputHeading}`,
1029
+ "Follow every section, inspection, and completeness rule in the Assignment.",
1030
+ "Do not return progress commentary, an explanation of the correction, or a code fence.",
1031
+ ].join("\n");
1032
+ }
1033
+
1034
+ function recoverableStructuredOutputFailure(error) {
1035
+ const message = error instanceof Error ? error.message : "";
1036
+ return (
1037
+ message.startsWith("Agent completed") ||
1038
+ message.startsWith("Agent response")
1039
+ );
1040
+ }
1041
+
1042
+ function mergeTokenUsage(first, second) {
1043
+ const usages = [first, second].filter(
1044
+ (usage) => usage && typeof usage === "object",
1045
+ );
1046
+ if (!usages.length) return null;
1047
+ return Object.fromEntries(
1048
+ [
1049
+ "input_tokens",
1050
+ "output_tokens",
1051
+ "cache_read_tokens",
1052
+ "cache_write_tokens",
1053
+ "reasoning_tokens",
1054
+ "total_tokens",
1055
+ ].map((field) => [
1056
+ field,
1057
+ usages.reduce(
1058
+ (total, usage) =>
1059
+ total + (Number.isFinite(usage[field]) ? usage[field] : 0),
1060
+ 0,
1061
+ ),
1062
+ ]),
1063
+ );
1064
+ }
1065
+
1066
+ export function enqueueWorkspaceAssessment(
1067
+ queue,
1068
+ activeAssessment,
1069
+ assignment,
1070
+ { front = false } = {},
1071
+ ) {
1072
+ const matches = (candidate) =>
1073
+ candidate?.assessment_id === assignment?.assessment_id &&
1074
+ candidate?.stage === assignment?.stage;
1075
+ if (
1076
+ activeAssessment?.kind === "assessment" &&
1077
+ activeAssessment.runId === assignment?.assessment_id &&
1078
+ activeAssessment.stage === assignment?.stage
1079
+ ) {
1080
+ activeAssessment.resumeAssignment = assignment;
1081
+ return "deferred";
1082
+ }
1083
+ if (queue.some(matches)) return "duplicate";
1084
+ if (front) queue.unshift(assignment);
1085
+ else queue.push(assignment);
1086
+ return "queued";
1087
+ }
1088
+
1088
1089
  export function takeWorkspaceAssessmentWave(queue, activeCount, limit) {
1089
- const available = Math.max(0, limit - activeCount);
1090
- if (!available || !queue.length) return [];
1091
- if (queue[0]?.parallelizable !== true) {
1092
- return activeCount === 0 ? queue.splice(0, 1) : [];
1093
- }
1094
- const wave = [];
1095
- while (wave.length < available && queue[0]?.parallelizable === true) {
1096
- wave.push(queue.shift());
1097
- }
1098
- return wave;
1099
- }
1100
-
1101
- export function workspaceAssessmentWorkerLimit(
1102
- configuredLimit,
1103
- availableParallelism = os.availableParallelism(),
1104
- ) {
1105
- if (configuredLimit !== undefined && configuredLimit !== null) {
1106
- const parsed = Number(configuredLimit);
1107
- if (
1108
- !Number.isInteger(parsed) ||
1109
- parsed < 1 ||
1110
- parsed > MAX_ASSESSMENT_WORKERS
1111
- ) {
1112
- throw new Error(
1113
- `Assessment workers must be a whole number from 1 to ${MAX_ASSESSMENT_WORKERS}.`,
1114
- );
1115
- }
1116
- return parsed;
1117
- }
1118
- return Math.min(
1119
- MAX_AUTOMATIC_ASSESSMENT_WORKERS,
1120
- Math.max(1, Math.floor(Number(availableParallelism) / 2) || 1),
1121
- );
1090
+ const available = Math.max(0, limit - activeCount);
1091
+ if (!available || !queue.length) return [];
1092
+ if (queue[0]?.parallelizable !== true) {
1093
+ return activeCount === 0 ? queue.splice(0, 1) : [];
1094
+ }
1095
+ const wave = [];
1096
+ while (wave.length < available && queue[0]?.parallelizable === true) {
1097
+ wave.push(queue.shift());
1098
+ }
1099
+ return wave;
1122
1100
  }
1123
1101
 
1124
- export function assessmentWorkerSnapshots(activeAssessments) {
1125
- return [...activeAssessments.values()].map((state) => ({
1126
- assessment_id: String(state.runId),
1127
- stage: String(state.stage).slice(0, 96),
1128
- phase: state.phase,
1129
- progress_percent: Math.max(
1130
- 0,
1131
- Math.min(95, Number(state.progressPercent) || 0),
1132
- ),
1133
- message: String(state.lastMessage || "Assessment worker is starting").slice(
1134
- 0,
1135
- 500,
1136
- ),
1137
- started_at: new Date(state.startedAt).toISOString(),
1138
- last_activity_at: new Date(state.lastActivityAt).toISOString(),
1139
- event_count: Math.max(0, Number(state.eventCount) || 0),
1140
- }));
1141
- }
1142
-
1143
- export function requeueInterruptedAssessment(
1144
- queue,
1145
- assessmentState,
1146
- { accepted, failureReported },
1147
- ) {
1148
- if (accepted || failureReported || !assessmentState?.resumeAssignment) {
1149
- return false;
1150
- }
1151
- return (
1152
- enqueueWorkspaceAssessment(queue, null, assessmentState.resumeAssignment, {
1153
- front: true,
1154
- }) === "queued"
1155
- );
1156
- }
1157
-
1158
- export async function submitAssessmentResultWithRetry(
1159
- payload,
1160
- submit,
1161
- {
1162
- isActive = () => true,
1163
- onRetry = () => {},
1164
- wait = (milliseconds) =>
1165
- new Promise((resolve) => setTimeout(resolve, milliseconds)),
1166
- initialDelayMs = 1_000,
1167
- maxDelayMs = 30_000,
1168
- } = {},
1169
- ) {
1170
- let retryDelayMs = initialDelayMs;
1171
- while (isActive()) {
1172
- let retryFailure;
1173
- try {
1174
- const response = await submit(payload);
1175
- if (!isTransientAssessmentResultResponse(response)) return response;
1176
- await response.body?.cancel?.();
1177
- retryFailure = new Error(
1178
- `EngineerOS temporarily rejected the completed assessment result (${response.status}).`,
1179
- );
1180
- } catch (error) {
1181
- retryFailure = error;
1182
- }
1183
- if (!isActive()) break;
1184
- onRetry(retryFailure, retryDelayMs);
1185
- await wait(retryDelayMs);
1186
- retryDelayMs = Math.min(maxDelayMs, retryDelayMs * 2);
1187
- }
1188
- throw new Error(
1189
- "Assessment result delivery stopped before EngineerOS accepted it.",
1190
- );
1191
- }
1192
-
1193
- export async function submitAssessmentWithValidationRepair(
1194
- initialResult,
1195
- {
1196
- submit,
1197
- payloadFor,
1198
- rejectionFor,
1199
- correct,
1200
- onCorrected = async () => {},
1201
- maxRepeatedFailures = MAX_REPEATED_ASSESSMENT_VALIDATION_FAILURES,
1202
- },
1203
- ) {
1204
- let result = initialResult;
1205
- let response = await submit(await payloadFor(result));
1206
- const rejectionCounts = new Map();
1207
- while (response.status === 422) {
1208
- const rejection = await rejectionFor(response);
1209
- const rejectionCount = (rejectionCounts.get(rejection) || 0) + 1;
1210
- rejectionCounts.set(rejection, rejectionCount);
1211
- if (rejectionCount > maxRepeatedFailures) {
1212
- throw new Error(
1213
- `${rejection} The Agent repeated this unresolved validation failure ${maxRepeatedFailures} times; the connector retained the latest local report for retry.`,
1214
- );
1215
- }
1216
- result = await correct(result, rejection);
1217
- result = (await onCorrected(result, rejection)) || result;
1218
- response = await submit(await payloadFor(result));
1219
- }
1220
- return { result, response };
1221
- }
1222
-
1223
- function isTransientAssessmentResultResponse(response) {
1224
- return (
1225
- response.status === 408 ||
1226
- response.status === 425 ||
1227
- response.status === 429 ||
1228
- response.status >= 500
1229
- );
1230
- }
1231
-
1232
- export function connectorExecution(assignment, options = {}) {
1233
- const rawPrompt = assignment?.prompt_markdown;
1234
- if (typeof rawPrompt !== "string" || !rawPrompt.trim()) {
1235
- throw new Error("EngineerOS assignment is missing prompt_markdown.");
1236
- }
1237
- const sandboxMode = assignment?.sandbox_mode;
1238
- if (!new Set(["read-only", "workspace-write"]).has(sandboxMode)) {
1239
- throw new Error("EngineerOS assignment has an unsupported sandbox_mode.");
1240
- }
1241
- const rawProfile = assignment?.execution_profile ?? {};
1242
- const model =
1243
- typeof rawProfile.model === "string" ? rawProfile.model.trim() : "";
1244
- const reasoningEffort = rawProfile.reasoning_effort;
1102
+ export function workspaceAssessmentWorkerLimit(value) {
1103
+ const parsed = Number(value ?? DEFAULT_ASSESSMENT_WORKERS);
1245
1104
  if (
1246
- reasoningEffort &&
1247
- !new Set(["minimal", "low", "medium", "high", "xhigh", "max", "ultra"]).has(
1248
- reasoningEffort,
1249
- )
1105
+ !Number.isInteger(parsed) ||
1106
+ parsed < MIN_ASSESSMENT_WORKERS ||
1107
+ parsed > MAX_ASSESSMENT_WORKERS
1250
1108
  ) {
1251
1109
  throw new Error(
1252
- "EngineerOS assignment has an unsupported reasoning effort.",
1253
- );
1254
- }
1255
- const agentRole = assignment?.agent_role;
1256
- const prompt = buildAgentHarnessPrompt({
1257
- agentRole,
1258
- agentDefinition: assignment?.agent_definition,
1259
- prompt: rawPrompt,
1260
- sandboxMode,
1261
- requiredOutputHeading: options.requiredOutputHeading,
1262
- });
1263
- return {
1264
- prompt,
1265
- agentRole,
1266
- sandboxMode,
1267
- sessionKey:
1268
- typeof assignment.session_key === "string" &&
1269
- assignment.session_key.trim()
1270
- ? assignment.session_key.trim()
1271
- : `project-${String(agentRole)}-${String(
1272
- assignment.purpose || "general",
1273
- )
1274
- .toLowerCase()
1275
- .replace(/[^a-z0-9]+/g, "-")
1276
- .slice(0, 80)}`,
1277
- profile: {
1278
- ...(model ? { model } : {}),
1279
- ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
1280
- },
1281
- };
1282
- }
1283
-
1284
- export async function stopProcess(child) {
1285
- if (!child || child.exitCode !== null) return;
1286
- if (typeof child.engineerOsCancel === "function") {
1287
- await child.engineerOsCancel();
1288
- return;
1289
- }
1290
- if (process.platform === "win32") {
1291
- await run(
1292
- "taskkill",
1293
- ["/pid", String(child.pid), "/t", "/f"],
1294
- process.cwd(),
1295
- { allowFailure: true },
1296
- );
1297
- } else {
1298
- child.kill("SIGTERM");
1299
- }
1300
- }
1301
-
1302
- export async function workspaceSnapshot(workspace) {
1303
- const root = path.resolve(workspace);
1304
- const gitFiles = await run(
1305
- "git",
1306
- ["ls-files", "-z", "-co", "--exclude-standard"],
1307
- root,
1308
- { allowFailure: true },
1309
- );
1310
- const candidates =
1311
- gitFiles.code === 0
1312
- ? gitPathList(gitFiles.stdout)
1313
- : await workspaceFiles(root);
1314
- const ignoredFiles =
1315
- gitFiles.code === 0
1316
- ? gitPathList(
1317
- (
1318
- await run(
1319
- "git",
1320
- ["ls-files", "-z", "--others", "--ignored", "--exclude-standard"],
1321
- root,
1322
- { allowFailure: true },
1323
- )
1324
- ).stdout,
1325
- )
1326
- : [];
1327
- const trackedFiles =
1328
- gitFiles.code === 0
1329
- ? new Set(
1330
- gitPathList(
1331
- (
1332
- await run("git", ["ls-files", "-z", "--cached"], root, {
1333
- allowFailure: true,
1334
- })
1335
- ).stdout,
1336
- ),
1337
- )
1338
- : new Set();
1339
- const modifiedFiles =
1340
- gitFiles.code === 0
1341
- ? new Set(
1342
- gitPathList(
1343
- (
1344
- await run("git", ["diff", "--name-only", "-z", "--"], root, {
1345
- allowFailure: true,
1346
- })
1347
- ).stdout,
1348
- ),
1349
- )
1350
- : new Set();
1351
- const stagedFiles =
1352
- gitFiles.code === 0
1353
- ? new Set(
1354
- gitPathList(
1355
- (
1356
- await run(
1357
- "git",
1358
- ["diff", "--cached", "--name-only", "-z", "--"],
1359
- root,
1360
- { allowFailure: true },
1361
- )
1362
- ).stdout,
1363
- ),
1364
- )
1365
- : new Set();
1366
- const gitStatus =
1367
- gitFiles.code === 0
1368
- ? await run(
1369
- "git",
1370
- ["status", "--porcelain=v1", "-z", "--untracked-files=all"],
1371
- root,
1372
- { allowFailure: true },
1373
- )
1374
- : { stdout: "" };
1375
- const inventory = [];
1376
- let excludedFileCount = new Set(ignoredFiles).size;
1377
- const sortedCandidates = [...new Set(candidates)].sort();
1378
- for (let start = 0; start < sortedCandidates.length; start += 256) {
1379
- const batch = sortedCandidates.slice(start, start + 256);
1380
- const inspected = await Promise.all(
1381
- batch.map(async (relative) => ({
1382
- relative,
1383
- details: isShareablePath(relative)
1384
- ? await lstat(path.join(root, relative)).catch(() => null)
1385
- : null,
1386
- })),
1387
- );
1388
- for (const { relative, details } of inspected) {
1389
- if (!details?.isFile() || details.isSymbolicLink()) {
1390
- excludedFileCount += 1;
1391
- continue;
1392
- }
1393
- inventory.push({
1394
- path: relative,
1395
- size: details.size,
1396
- classification: evidenceClassification(relative),
1397
- git_state: inventoryGitState(
1398
- relative,
1399
- trackedFiles,
1400
- modifiedFiles,
1401
- stagedFiles,
1402
- ),
1403
- });
1404
- if (inventory.length > MAX_INVENTORY_FILES) {
1405
- throw new Error(
1406
- `Workspace contains more than ${MAX_INVENTORY_FILES.toLocaleString()} safe files. Configure repository exclusions for generated or data directories, then reconnect.`,
1407
- );
1408
- }
1409
- }
1410
- }
1411
- const representativeSources = representativeSourcePaths(inventory);
1412
- const evidenceCandidates = [...inventory].sort((left, right) => {
1413
- const priorityDifference =
1414
- evidencePriority(left, representativeSources) -
1415
- evidencePriority(right, representativeSources);
1416
- return priorityDifference || left.path.localeCompare(right.path);
1417
- });
1418
- const evidenceEntries = [];
1419
- let evidenceBytes = 0;
1420
- for (const entry of evidenceCandidates) {
1421
- if (
1422
- evidenceEntries.length >= MAX_EVIDENCE_FILES ||
1423
- entry.size > MAX_SHAREABLE_FILE_BYTES ||
1424
- evidenceBytes + entry.size > MAX_EVIDENCE_BYTES
1425
- ) {
1426
- continue;
1427
- }
1428
- evidenceEntries.push(entry);
1429
- evidenceBytes += entry.size;
1430
- }
1431
- const evidenceFiles = await readEvidenceFiles(root, evidenceEntries);
1432
- const archive = await createZip(evidenceFiles);
1433
- if (archive.length > MAX_ARCHIVE_BYTES) {
1434
- throw new Error(
1435
- "Prioritized workspace evidence exceeds the 25 MB archive limit. Configure repository exclusions for large source or data files, then reconnect.",
1436
- );
1437
- }
1438
- const inventoryJson = Buffer.from(
1439
- JSON.stringify({ version: 1, entries: inventory }),
1440
- "utf8",
1441
- );
1442
- const compressedInventory = await gzipBuffer(inventoryJson);
1443
- if (compressedInventory.length > MAX_COMPRESSED_INVENTORY_BYTES) {
1444
- throw new Error(
1445
- "Compressed workspace inventory exceeds 10 MB. Configure repository exclusions for generated or data directories, then reconnect.",
1446
- );
1447
- }
1448
- const head = await run("git", ["rev-parse", "HEAD"], root, {
1449
- allowFailure: true,
1450
- });
1451
- return {
1452
- inventory_base64: compressedInventory.toString("base64"),
1453
- evidence_archive_base64: archive.toString("base64"),
1454
- media_type: "application/zip",
1455
- workspace_name: path.basename(root),
1456
- workspace_kind: inventory.some(({ path: relative }) =>
1457
- isCodeBearing(relative),
1458
- )
1459
- ? "brownfield"
1460
- : "greenfield",
1461
- total_file_count: inventory.length,
1462
- evidence_file_count: evidenceFiles.length,
1463
- excluded_file_count: excludedFileCount,
1464
- omitted_evidence_file_count: inventory.length - evidenceFiles.length,
1465
- head_revision: head.code === 0 ? head.stdout.trim().slice(0, 128) : null,
1466
- working_tree_status_digest: sha256(gitStatus.stdout),
1467
- inventory_digest: sha256(inventoryJson),
1468
- evidence_policy_version: EVIDENCE_POLICY_VERSION,
1469
- };
1470
- }
1471
-
1472
- function evidenceClassification(relative) {
1473
- const normalized = normalizePath(relative).toLowerCase();
1474
- const name = path.posix.basename(normalized);
1475
- const extension = path.posix.extname(name);
1476
- if (CODE_MARKERS.has(name)) return "manifest";
1477
- if (LOCK_FILE_NAMES.has(name)) return "lockfile";
1478
- if (
1479
- normalized.startsWith(".github/workflows/") ||
1480
- [
1481
- ".gitlab-ci.yml",
1482
- "azure-pipelines.yml",
1483
- "docker-compose.yml",
1484
- "docker-compose.yaml",
1485
- "dockerfile",
1486
- "jenkinsfile",
1487
- ].includes(name)
1488
- ) {
1489
- return "workflow";
1490
- }
1491
- if (
1492
- /(^|\/)(tests|__tests__)\//.test(normalized) ||
1493
- name.startsWith("test_") ||
1494
- name.includes(".test.") ||
1495
- name.includes(".spec.") ||
1496
- /^(jest|vitest|pytest|playwright|cypress)(\.|$)/.test(name)
1497
- ) {
1498
- return "test";
1499
- }
1500
- if (/(^|\/)(security|compliance|policy|policies)(\/|\.|$)/.test(normalized)) {
1501
- return "security_configuration";
1502
- }
1503
- if (
1504
- REPOSITORY_CONFIGURATION_NAMES.has(name) ||
1505
- /(^|\/)(eslint|ruff|mypy|tsconfig|biome|prettier)/.test(normalized)
1506
- ) {
1507
- return "repository_configuration";
1508
- }
1509
- if (ENTRYPOINT_NAMES.has(name)) return "entrypoint";
1510
- if (
1511
- /(^|\/)(api|routes|controllers)\//.test(normalized) ||
1512
- name.endsWith(".d.ts") ||
1513
- name.includes("openapi") ||
1514
- name.includes("swagger")
1515
- ) {
1516
- return "public_api";
1517
- }
1518
- if (
1519
- extension === ".md" ||
1520
- normalized.startsWith("docs/") ||
1521
- /(^|\/)(architecture|operations|runbook|deployment)(\/|\.|$)/.test(
1522
- normalized,
1523
- )
1524
- ) {
1525
- return "documentation";
1526
- }
1527
- if (CODE_EXTENSIONS.has(extension)) return "source";
1528
- return "other";
1529
- }
1530
-
1531
- function inventoryGitState(relative, trackedFiles, modifiedFiles, stagedFiles) {
1532
- if (!trackedFiles.has(relative)) return "untracked";
1533
- const modified = modifiedFiles.has(relative);
1534
- const staged = stagedFiles.has(relative);
1535
- if (modified && staged) return "staged_and_modified";
1536
- if (modified) return "modified";
1537
- if (staged) return "staged";
1538
- return "clean";
1539
- }
1540
-
1541
- function representativeSourcePaths(inventory) {
1542
- const representatives = new Set();
1543
- const groups = new Set();
1544
- for (const entry of inventory) {
1545
- if (entry.classification !== "source") continue;
1546
- const parts = entry.path.split("/");
1547
- const moduleName = parts.length > 1 ? parts[0] : ".";
1548
- const extension = path.posix.extname(entry.path).toLowerCase();
1549
- const group = `${moduleName}:${extension}`;
1550
- if (groups.has(group)) continue;
1551
- groups.add(group);
1552
- representatives.add(entry.path);
1553
- }
1554
- return representatives;
1555
- }
1556
-
1557
- function evidencePriority(entry, representativeSources) {
1558
- const priorities = {
1559
- manifest: 0,
1560
- lockfile: 0,
1561
- workflow: 1,
1562
- security_configuration: 1,
1563
- repository_configuration: 1,
1564
- entrypoint: 2,
1565
- public_api: 2,
1566
- test: 3,
1567
- documentation: 4,
1568
- };
1569
- if (entry.classification in priorities)
1570
- return priorities[entry.classification];
1571
- if (
1572
- entry.classification === "source" &&
1573
- representativeSources.has(entry.path)
1574
- ) {
1575
- return 5;
1576
- }
1577
- return 6;
1578
- }
1579
-
1580
- function sha256(value) {
1581
- return createHash("sha256").update(value).digest("hex");
1582
- }
1583
-
1584
- async function readEvidenceFiles(root, entries) {
1585
- const files = [];
1586
- for (let start = 0; start < entries.length; start += 128) {
1587
- files.push(
1588
- ...(await Promise.all(
1589
- entries.slice(start, start + 128).map(async (entry) => ({
1590
- name: entry.path,
1591
- data: await readFile(path.join(root, entry.path)),
1592
- })),
1593
- )),
1594
- );
1595
- }
1596
- return files;
1597
- }
1598
-
1599
- async function prepareRunWorkspace(workspace, runId, baseRevision) {
1600
- const source = path.resolve(workspace);
1601
- const root = path.join(os.homedir(), ".engineeros", "runs");
1602
- const target = path.join(root, runId);
1603
- await mkdir(root, { recursive: true });
1604
- const isGit =
1605
- (
1606
- await run("git", ["rev-parse", "--is-inside-work-tree"], source, {
1607
- allowFailure: true,
1608
- })
1609
- ).code === 0;
1610
- if (isGit) {
1611
- const exists = await stat(target).then(
1612
- () => true,
1613
- () => false,
1614
- );
1615
- if (!exists) {
1616
- const base = await worktreeBase(source, baseRevision);
1617
- await run("git", ["worktree", "add", "--detach", target, base], source);
1618
- }
1619
- return target;
1620
- }
1621
- const exists = await stat(target).then(
1622
- () => true,
1623
- () => false,
1624
- );
1625
- if (!exists) {
1626
- await mkdir(target, { recursive: true });
1627
- await copyWorkspace(source, target);
1628
- await run("git", ["init"], target);
1629
- await run("git", ["config", "user.name", "EngineerOS Connector"], target);
1630
- await run(
1631
- "git",
1632
- ["config", "user.email", "connector@engineeros.local"],
1633
- target,
1634
- );
1635
- await run("git", ["add", "-A"], target);
1636
- await run(
1637
- "git",
1638
- ["commit", "--allow-empty", "-m", "EngineerOS run baseline"],
1639
- target,
1110
+ `Assessment worker limit must be a whole number from ${MIN_ASSESSMENT_WORKERS} to ${MAX_ASSESSMENT_WORKERS}.`,
1640
1111
  );
1641
1112
  }
1642
- return target;
1643
- }
1644
-
1645
- function launchCodexProcess(
1646
- workspace,
1647
- prompt,
1648
- sandbox,
1649
- callbacks,
1650
- profile = {},
1651
- previousSessionId,
1652
- skipGitRepoCheck = false,
1653
- mcpServer,
1654
- ) {
1655
- if (!mcpServer) {
1656
- return launchCodexAppServer({
1657
- workspace,
1658
- prompt,
1659
- sandbox,
1660
- profile,
1661
- previousSessionId,
1662
- callbacks,
1663
- });
1664
- }
1665
- const command =
1666
- process.env.CODEX_BIN ||
1667
- (process.platform === "win32" ? "codex.cmd" : "codex");
1668
- const args = codexExecutionArgs({
1669
- workspace,
1670
- sandbox,
1671
- profile,
1672
- previousSessionId,
1673
- skipGitRepoCheck,
1674
- mcpServer,
1675
- });
1676
- const child = spawn(command, args, {
1677
- cwd: workspace,
1678
- env: process.env,
1679
- shell: process.platform === "win32",
1680
- stdio: ["pipe", "pipe", "pipe"],
1681
- });
1682
- child.stdin.end(prompt);
1683
- let output = "";
1684
- let buffer = "";
1685
- let finalMessage = "";
1686
- let sessionId = previousSessionId || "";
1687
- child.stdout.setEncoding("utf8");
1688
- child.stdout.on("data", (chunk) => {
1689
- output += chunk;
1690
- buffer += chunk;
1691
- const lines = buffer.split(/\r?\n/);
1692
- buffer = lines.pop() ?? "";
1693
- for (const line of lines) {
1694
- if (!line.trim()) continue;
1695
- try {
1696
- const event = JSON.parse(line);
1697
- if (
1698
- event.type === "thread.started" &&
1699
- typeof event.thread_id === "string"
1700
- ) {
1701
- sessionId = event.thread_id;
1702
- }
1703
- if (
1704
- event.type === "item.completed" &&
1705
- event.item?.type === "agent_message" &&
1706
- typeof event.item.text === "string"
1707
- ) {
1708
- finalMessage = event.item.text;
1709
- }
1710
- callbacks.onEvent?.(event);
1711
- } catch {
1712
- callbacks.onEvent?.({
1713
- type: "agent.output",
1714
- message: line.slice(0, 500),
1715
- });
1716
- }
1717
- }
1718
- });
1719
- child.stderr.setEncoding("utf8");
1720
- child.stderr.on("data", (chunk) => {
1721
- output += chunk;
1722
- callbacks.onEvent?.({
1723
- type: "agent.stderr",
1724
- message: chunk.trim().slice(0, 500),
1725
- });
1726
- });
1727
- const completed = new Promise((resolve, reject) => {
1728
- child.once("error", reject);
1729
- child.once("close", (code) => {
1730
- if (code === 0 && sessionId)
1731
- resolve({ output: output.slice(-20_000), finalMessage, sessionId });
1732
- else if (code === 0)
1733
- reject(
1734
- new Error(
1735
- "Agent completed without announcing a resumable session id.",
1736
- ),
1737
- );
1738
- else reject(new Error(codexFailureMessage(output, code)));
1739
- });
1740
- });
1741
- return { child, completed };
1742
- }
1743
-
1744
- export function codexExecutionArgs({
1745
- workspace,
1746
- sandbox,
1747
- profile = {},
1748
- previousSessionId,
1749
- skipGitRepoCheck = false,
1750
- mcpServer,
1751
- }) {
1752
- const optionArgs = [
1753
- "--json",
1754
- "--config",
1755
- codexConfigArgument("skills.include_instructions=false"),
1756
- ];
1757
- if (skipGitRepoCheck) optionArgs.push("--skip-git-repo-check");
1758
- if (profile.model) optionArgs.push("--model", profile.model);
1759
- if (profile.reasoning_effort) {
1760
- optionArgs.push(
1761
- "--config",
1762
- codexConfigArgument(
1763
- `model_reasoning_effort=${tomlLiteralString(profile.reasoning_effort)}`,
1764
- ),
1765
- );
1766
- }
1767
- if (mcpServer) {
1768
- const mcpArgs = [
1769
- mcpServer.connectorBin,
1770
- "mcp",
1771
- "--workspace",
1772
- mcpServer.workspace,
1773
- "--run-id",
1774
- mcpServer.runId,
1775
- ];
1776
- optionArgs.push(
1777
- "--config",
1778
- codexConfigArgument(
1779
- `mcp_servers.engineeros.command=${tomlLiteralString(process.execPath)}`,
1780
- ),
1781
- "--config",
1782
- codexConfigArgument(
1783
- `mcp_servers.engineeros.args=[${mcpArgs.map(tomlLiteralString).join(",")}]`,
1784
- ),
1785
- );
1786
- }
1787
- return previousSessionId
1788
- ? ["exec", "resume", ...optionArgs, previousSessionId, "-"]
1789
- : ["exec", ...optionArgs, "--sandbox", sandbox, "-C", workspace, "-"];
1790
- }
1791
-
1792
- export function sanitizeAgentResponse(value) {
1793
- return String(value || "").replace(
1794
- /^Warning: Exceeded skills context budget(?: of \d+%)?\. All skill descriptions were removed and \d+ additional skills? (?:was|were) not included in the model-visible skills list\.\s*/i,
1795
- "",
1796
- );
1797
- }
1798
-
1799
- function tomlLiteralString(value) {
1800
- const text = String(value);
1801
- if (text.includes("'''")) {
1802
- throw new Error(
1803
- "Codex configuration values cannot contain three consecutive apostrophes.",
1804
- );
1805
- }
1806
- return `'''${text}'''`;
1807
- }
1808
-
1809
- function codexConfigArgument(override) {
1810
- return process.platform === "win32" ? `"${override}"` : override;
1811
- }
1812
-
1813
- function launchAgentProcess(
1814
- workspace,
1815
- prompt,
1816
- sandbox,
1817
- config,
1818
- callbacks,
1819
- profile = {},
1820
- previousSessionId,
1821
- mcpContext,
1822
- ) {
1823
- if (config.agent_protocol === "acp") {
1824
- return launchAcpAgent(workspace, prompt, config, callbacks, {
1825
- persistent: mcpContext?.persistentAcp === true,
1826
- sessionKey: mcpContext?.sessionKey,
1827
- previousSessionId,
1828
- sandbox,
1829
- profile,
1830
- });
1831
- }
1832
- return launchCodexProcess(
1833
- workspace,
1834
- prompt,
1835
- sandbox,
1836
- callbacks,
1837
- profile,
1838
- previousSessionId,
1839
- config.skip_git_repo_check === true,
1840
- mcpContext?.runId
1841
- ? {
1842
- connectorBin: process.argv[1],
1843
- workspace: config.workspace,
1844
- runId: mcpContext.runId,
1845
- }
1846
- : undefined,
1847
- );
1848
- }
1849
-
1850
- function runCodexCommand(command, args, cwd) {
1851
- return new Promise((resolve, reject) => {
1852
- const child = spawn(command, args, {
1853
- cwd,
1854
- env: process.env,
1855
- shell: process.platform === "win32",
1856
- windowsHide: true,
1857
- });
1858
- let stdout = "";
1859
- let stderr = "";
1860
- child.stdout.setEncoding("utf8");
1861
- child.stderr.setEncoding("utf8");
1862
- child.stdout.on("data", (chunk) => (stdout += chunk));
1863
- child.stderr.on("data", (chunk) => (stderr += chunk));
1864
- child.once("error", reject);
1865
- child.once("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
1866
- });
1867
- }
1868
-
1869
- async function changedFilePaths(workspace) {
1870
- const tracked = await run(
1871
- "git",
1872
- ["diff", "--name-only", "-z", "HEAD", "--"],
1873
- workspace,
1874
- );
1875
- const untracked = await run(
1876
- "git",
1877
- ["ls-files", "-z", "--others", "--exclude-standard"],
1878
- workspace,
1879
- );
1880
- return [
1881
- ...new Set([
1882
- ...gitPathList(tracked.stdout),
1883
- ...gitPathList(untracked.stdout),
1884
- ]),
1885
- ].sort();
1886
- }
1887
-
1888
- async function boundedDiff(workspace, changedFiles) {
1889
- const tracked = await run(
1890
- "git",
1891
- ["diff", "--binary", "HEAD", "--"],
1892
- workspace,
1893
- );
1894
- const untracked = new Set(
1895
- gitPathList(
1896
- (
1897
- await run(
1898
- "git",
1899
- ["ls-files", "-z", "--others", "--exclude-standard"],
1900
- workspace,
1901
- )
1902
- ).stdout,
1903
- ),
1904
- );
1905
- const parts = [tracked.stdout];
1906
- for (const relative of changedFiles.filter((item) => untracked.has(item))) {
1907
- const generated = await run(
1908
- "git",
1909
- ["diff", "--no-index", "--binary", "--", "/dev/null", relative],
1910
- workspace,
1911
- {
1912
- allowFailure: true,
1913
- },
1914
- );
1915
- parts.push(generated.stdout);
1916
- }
1917
- const diff = parts.filter(Boolean).join("\n");
1918
- if (!diff.trim()) throw new Error("The run produced no bounded diff.");
1919
- return diff;
1920
- }
1921
-
1922
- export async function repositoryArchive(workspace) {
1923
- const listed = await run(
1924
- "git",
1925
- ["ls-files", "-z", "-co", "--exclude-standard"],
1926
- workspace,
1927
- );
1928
- const files = [...new Set(gitPathList(listed.stdout))].sort();
1929
- return createZip(
1930
- await Promise.all(
1931
- files.map(async (relative) => ({
1932
- name: relative,
1933
- data: await readFile(path.join(workspace, relative)),
1934
- })),
1935
- ),
1936
- );
1937
- }
1938
-
1939
- async function workspaceFiles(root, current = root) {
1940
- const files = [];
1941
- for (const entry of await readdir(current, { withFileTypes: true })) {
1942
- const absolute = path.join(current, entry.name);
1943
- const relative = normalizePath(path.relative(root, absolute));
1944
- if (entry.isSymbolicLink()) continue;
1945
- if (entry.isDirectory()) {
1946
- files.push(...(await workspaceFiles(root, absolute)));
1947
- } else if (entry.isFile()) {
1948
- files.push(relative);
1949
- }
1950
- }
1951
- return files;
1952
- }
1953
-
1954
- function isShareablePath(relative) {
1955
- const normalized = normalizePath(relative);
1956
- if (
1957
- !normalized ||
1958
- normalized === ".." ||
1959
- normalized.startsWith("../") ||
1960
- path.isAbsolute(normalized)
1961
- ) {
1962
- return false;
1963
- }
1964
- const parts = normalized.split("/");
1965
- if (parts.some((part) => EXCLUDED_DIRECTORIES.has(part.toLowerCase()))) {
1966
- return false;
1967
- }
1968
- if (
1969
- EXCLUDED_PATH_PREFIXES.some((prefix) =>
1970
- normalized.toLowerCase().startsWith(prefix),
1971
- )
1972
- ) {
1973
- return false;
1974
- }
1975
- const name = parts.at(-1)?.toLowerCase() ?? "";
1976
- if (EXCLUDED_FILE_EXTENSIONS.has(path.posix.extname(name))) return false;
1977
- if (name === ".env.example" || name === ".env.sample") return true;
1978
- if (
1979
- name === ".env" ||
1980
- name.startsWith(".env.") ||
1981
- [".npmrc", ".netrc", "credentials", "credentials.json"].includes(name) ||
1982
- /\.(?:key|pem|p12|pfx)$/i.test(name)
1983
- ) {
1984
- return false;
1985
- }
1986
- return true;
1987
- }
1988
-
1989
- function isCodeBearing(relative) {
1990
- const name = path.posix.basename(relative).toLowerCase();
1991
- return (
1992
- CODE_MARKERS.has(name) || CODE_EXTENSIONS.has(path.posix.extname(name))
1993
- );
1994
- }
1995
-
1996
- async function worktreeBase(workspace, requested) {
1997
- if (!requested || requested.startsWith("greenfield:")) return "HEAD";
1998
- const exists = await run(
1999
- "git",
2000
- ["cat-file", "-e", `${requested}^{commit}`],
2001
- workspace,
2002
- { allowFailure: true },
2003
- );
2004
- if (exists.code !== 0) {
2005
- throw new Error(
2006
- `The frozen base revision ${requested} is not available in this repository.`,
2007
- );
2008
- }
2009
- return requested;
2010
- }
2011
-
2012
- export async function createZip(files) {
2013
- const localParts = [];
2014
- const centralParts = [];
2015
- let offset = 0;
2016
- let total = 0;
2017
- for (const file of files) {
2018
- const name = Buffer.from(normalizePath(file.name), "utf8");
2019
- const data = Buffer.from(file.data);
2020
- total += data.length;
2021
- if (total > MAX_ARCHIVE_BYTES)
2022
- throw new Error("Repository archive exceeds the 25 MB connector limit.");
2023
- const compressed = await deflate(data);
2024
- const crc = crc32(data);
2025
- const local = Buffer.alloc(30);
2026
- local.writeUInt32LE(0x04034b50, 0);
2027
- local.writeUInt16LE(20, 4);
2028
- local.writeUInt16LE(0x0800, 6);
2029
- local.writeUInt16LE(8, 8);
2030
- local.writeUInt32LE(crc, 14);
2031
- local.writeUInt32LE(compressed.length, 18);
2032
- local.writeUInt32LE(data.length, 22);
2033
- local.writeUInt16LE(name.length, 26);
2034
- localParts.push(local, name, compressed);
2035
-
2036
- const central = Buffer.alloc(46);
2037
- central.writeUInt32LE(0x02014b50, 0);
2038
- central.writeUInt16LE(20, 4);
2039
- central.writeUInt16LE(20, 6);
2040
- central.writeUInt16LE(0x0800, 8);
2041
- central.writeUInt16LE(8, 10);
2042
- central.writeUInt32LE(crc, 16);
2043
- central.writeUInt32LE(compressed.length, 20);
2044
- central.writeUInt32LE(data.length, 24);
2045
- central.writeUInt16LE(name.length, 28);
2046
- central.writeUInt32LE(offset, 42);
2047
- centralParts.push(central, name);
2048
- offset += local.length + name.length + compressed.length;
2049
- }
2050
- const central = Buffer.concat(centralParts);
2051
- const end = Buffer.alloc(22);
2052
- end.writeUInt32LE(0x06054b50, 0);
2053
- end.writeUInt16LE(files.length, 8);
2054
- end.writeUInt16LE(files.length, 10);
2055
- end.writeUInt32LE(central.length, 12);
2056
- end.writeUInt32LE(offset, 16);
2057
- return Buffer.concat([...localParts, central, end]);
2058
- }
2059
-
2060
- async function copyWorkspace(source, target) {
2061
- for (const entry of await readdir(source, { withFileTypes: true })) {
2062
- if ([".git", ".engineeros", "node_modules"].includes(entry.name)) continue;
2063
- const from = path.join(source, entry.name);
2064
- const to = path.join(target, entry.name);
2065
- if (entry.isDirectory()) {
2066
- await mkdir(to, { recursive: true });
2067
- await copyWorkspace(from, to);
2068
- } else if (entry.isFile()) {
2069
- await writeFile(to, await readFile(from));
2070
- }
2071
- }
2072
- }
2073
-
2074
- function normalizePath(value) {
2075
- return String(value ?? "")
2076
- .trim()
2077
- .replaceAll("\\", "/")
2078
- .replace(/^\.\//, "");
2079
- }
2080
-
2081
- function gitPathList(value) {
2082
- return String(value ?? "")
2083
- .split("\0")
2084
- .map(normalizePath)
2085
- .filter(Boolean);
2086
- }
2087
-
2088
- function run(command, args, cwd, options = {}) {
2089
- return new Promise((resolve, reject) => {
2090
- const child = spawn(command, args, {
2091
- cwd,
2092
- shell: false,
2093
- windowsHide: true,
2094
- });
2095
- let stdout = "";
2096
- let stderr = "";
2097
- child.stdout.setEncoding("utf8");
2098
- child.stderr.setEncoding("utf8");
2099
- child.stdout.on("data", (chunk) => (stdout += chunk));
2100
- child.stderr.on("data", (chunk) => (stderr += chunk));
2101
- child.once("error", reject);
2102
- child.once("close", (code) => {
2103
- const result = { code: code ?? 1, stdout, stderr };
2104
- if (code === 0 || options.allowFailure) resolve(result);
2105
- else
2106
- reject(
2107
- new Error(`${command} ${args.join(" ")} failed: ${stderr || stdout}`),
2108
- );
2109
- });
2110
- });
2111
- }
2112
-
2113
- function crc32(buffer) {
2114
- let crc = 0xffffffff;
2115
- for (const byte of buffer) {
2116
- crc ^= byte;
2117
- for (let bit = 0; bit < 8; bit += 1)
2118
- crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));
2119
- }
2120
- return (crc ^ 0xffffffff) >>> 0;
1113
+ return parsed;
2121
1114
  }
1115
+
1116
+ export function assessmentWorkerSnapshots(activeAssessments) {
1117
+ return [...activeAssessments.values()].map((state) => ({
1118
+ assessment_id: String(state.runId),
1119
+ stage: String(state.stage).slice(0, 96),
1120
+ phase: state.phase,
1121
+ progress_percent: Math.max(
1122
+ 0,
1123
+ Math.min(95, Number(state.progressPercent) || 0),
1124
+ ),
1125
+ message: String(state.lastMessage || "Assessment worker is starting").slice(
1126
+ 0,
1127
+ 500,
1128
+ ),
1129
+ started_at: new Date(state.startedAt).toISOString(),
1130
+ last_activity_at: new Date(state.lastActivityAt).toISOString(),
1131
+ event_count: Math.max(0, Number(state.eventCount) || 0),
1132
+ }));
1133
+ }
1134
+
1135
+ export function requeueInterruptedAssessment(
1136
+ queue,
1137
+ assessmentState,
1138
+ { accepted, failureReported },
1139
+ ) {
1140
+ if (accepted || failureReported || !assessmentState?.resumeAssignment) {
1141
+ return false;
1142
+ }
1143
+ return (
1144
+ enqueueWorkspaceAssessment(queue, null, assessmentState.resumeAssignment, {
1145
+ front: true,
1146
+ }) === "queued"
1147
+ );
1148
+ }
1149
+
1150
+ export async function submitAssessmentResultWithRetry(
1151
+ payload,
1152
+ submit,
1153
+ {
1154
+ isActive = () => true,
1155
+ onRetry = () => {},
1156
+ wait = (milliseconds) =>
1157
+ new Promise((resolve) => setTimeout(resolve, milliseconds)),
1158
+ initialDelayMs = 1_000,
1159
+ maxDelayMs = 30_000,
1160
+ } = {},
1161
+ ) {
1162
+ let retryDelayMs = initialDelayMs;
1163
+ while (isActive()) {
1164
+ let retryFailure;
1165
+ try {
1166
+ const response = await submit(payload);
1167
+ if (!isTransientAssessmentResultResponse(response)) return response;
1168
+ await response.body?.cancel?.();
1169
+ retryFailure = new Error(
1170
+ `EngineerOS temporarily rejected the completed assessment result (${response.status}).`,
1171
+ );
1172
+ } catch (error) {
1173
+ retryFailure = error;
1174
+ }
1175
+ if (!isActive()) break;
1176
+ onRetry(retryFailure, retryDelayMs);
1177
+ await wait(retryDelayMs);
1178
+ retryDelayMs = Math.min(maxDelayMs, retryDelayMs * 2);
1179
+ }
1180
+ throw new Error(
1181
+ "Assessment result delivery stopped before EngineerOS accepted it.",
1182
+ );
1183
+ }
1184
+
1185
+ export async function submitAssessmentWithValidationRepair(
1186
+ initialResult,
1187
+ {
1188
+ submit,
1189
+ payloadFor,
1190
+ rejectionFor,
1191
+ correct,
1192
+ onCorrected = async () => {},
1193
+ maxRepeatedFailures = MAX_REPEATED_ASSESSMENT_VALIDATION_FAILURES,
1194
+ },
1195
+ ) {
1196
+ let result = initialResult;
1197
+ let response = await submit(await payloadFor(result));
1198
+ const rejectionCounts = new Map();
1199
+ while (response.status === 422) {
1200
+ const rejection = await rejectionFor(response);
1201
+ const rejectionCount = (rejectionCounts.get(rejection) || 0) + 1;
1202
+ rejectionCounts.set(rejection, rejectionCount);
1203
+ if (rejectionCount > maxRepeatedFailures) {
1204
+ throw new Error(
1205
+ `${rejection} The Agent repeated this unresolved validation failure ${maxRepeatedFailures} times; the connector retained the latest local report for retry.`,
1206
+ );
1207
+ }
1208
+ result = await correct(result, rejection);
1209
+ result = (await onCorrected(result, rejection)) || result;
1210
+ response = await submit(await payloadFor(result));
1211
+ }
1212
+ return { result, response };
1213
+ }
1214
+
1215
+ function isTransientAssessmentResultResponse(response) {
1216
+ return (
1217
+ response.status === 408 ||
1218
+ response.status === 425 ||
1219
+ response.status === 429 ||
1220
+ response.status >= 500
1221
+ );
1222
+ }
1223
+
1224
+ export function connectorExecution(assignment, options = {}) {
1225
+ const rawPrompt = assignment?.prompt_markdown;
1226
+ if (typeof rawPrompt !== "string" || !rawPrompt.trim()) {
1227
+ throw new Error("EngineerOS assignment is missing prompt_markdown.");
1228
+ }
1229
+ const sandboxMode = assignment?.sandbox_mode;
1230
+ if (!new Set(["read-only", "workspace-write"]).has(sandboxMode)) {
1231
+ throw new Error("EngineerOS assignment has an unsupported sandbox_mode.");
1232
+ }
1233
+ const rawProfile = assignment?.execution_profile ?? {};
1234
+ const model =
1235
+ typeof rawProfile.model === "string" ? rawProfile.model.trim() : "";
1236
+ const reasoningEffort = rawProfile.reasoning_effort;
1237
+ if (
1238
+ reasoningEffort &&
1239
+ !new Set(["minimal", "low", "medium", "high", "xhigh", "max", "ultra"]).has(
1240
+ reasoningEffort,
1241
+ )
1242
+ ) {
1243
+ throw new Error(
1244
+ "EngineerOS assignment has an unsupported reasoning effort.",
1245
+ );
1246
+ }
1247
+ const agentRole = assignment?.agent_role;
1248
+ const prompt = buildAgentHarnessPrompt({
1249
+ agentRole,
1250
+ agentDefinition: assignment?.agent_definition,
1251
+ prompt: rawPrompt,
1252
+ sandboxMode,
1253
+ requiredOutputHeading: options.requiredOutputHeading,
1254
+ });
1255
+ return {
1256
+ prompt,
1257
+ agentRole,
1258
+ sandboxMode,
1259
+ sessionKey:
1260
+ typeof assignment.session_key === "string" &&
1261
+ assignment.session_key.trim()
1262
+ ? assignment.session_key.trim()
1263
+ : `project-${String(agentRole)}-${String(
1264
+ assignment.purpose || "general",
1265
+ )
1266
+ .toLowerCase()
1267
+ .replace(/[^a-z0-9]+/g, "-")
1268
+ .slice(0, 80)}`,
1269
+ profile: {
1270
+ ...(model ? { model } : {}),
1271
+ ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
1272
+ },
1273
+ };
1274
+ }
1275
+
1276
+ export async function stopProcess(child) {
1277
+ if (!child || child.exitCode !== null) return;
1278
+ if (typeof child.engineerOsCancel === "function") {
1279
+ await child.engineerOsCancel();
1280
+ return;
1281
+ }
1282
+ if (process.platform === "win32") {
1283
+ await run(
1284
+ "taskkill",
1285
+ ["/pid", String(child.pid), "/t", "/f"],
1286
+ process.cwd(),
1287
+ { allowFailure: true },
1288
+ );
1289
+ } else {
1290
+ child.kill("SIGTERM");
1291
+ }
1292
+ }
1293
+
1294
+ export async function workspaceSnapshot(workspace) {
1295
+ const root = path.resolve(workspace);
1296
+ const gitFiles = await run(
1297
+ "git",
1298
+ ["ls-files", "-z", "-co", "--exclude-standard"],
1299
+ root,
1300
+ { allowFailure: true },
1301
+ );
1302
+ const candidates =
1303
+ gitFiles.code === 0
1304
+ ? gitPathList(gitFiles.stdout)
1305
+ : await workspaceFiles(root);
1306
+ const ignoredFiles =
1307
+ gitFiles.code === 0
1308
+ ? gitPathList(
1309
+ (
1310
+ await run(
1311
+ "git",
1312
+ ["ls-files", "-z", "--others", "--ignored", "--exclude-standard"],
1313
+ root,
1314
+ { allowFailure: true },
1315
+ )
1316
+ ).stdout,
1317
+ )
1318
+ : [];
1319
+ const trackedFiles =
1320
+ gitFiles.code === 0
1321
+ ? new Set(
1322
+ gitPathList(
1323
+ (
1324
+ await run("git", ["ls-files", "-z", "--cached"], root, {
1325
+ allowFailure: true,
1326
+ })
1327
+ ).stdout,
1328
+ ),
1329
+ )
1330
+ : new Set();
1331
+ const modifiedFiles =
1332
+ gitFiles.code === 0
1333
+ ? new Set(
1334
+ gitPathList(
1335
+ (
1336
+ await run("git", ["diff", "--name-only", "-z", "--"], root, {
1337
+ allowFailure: true,
1338
+ })
1339
+ ).stdout,
1340
+ ),
1341
+ )
1342
+ : new Set();
1343
+ const stagedFiles =
1344
+ gitFiles.code === 0
1345
+ ? new Set(
1346
+ gitPathList(
1347
+ (
1348
+ await run(
1349
+ "git",
1350
+ ["diff", "--cached", "--name-only", "-z", "--"],
1351
+ root,
1352
+ { allowFailure: true },
1353
+ )
1354
+ ).stdout,
1355
+ ),
1356
+ )
1357
+ : new Set();
1358
+ const gitStatus =
1359
+ gitFiles.code === 0
1360
+ ? await run(
1361
+ "git",
1362
+ ["status", "--porcelain=v1", "-z", "--untracked-files=all"],
1363
+ root,
1364
+ { allowFailure: true },
1365
+ )
1366
+ : { stdout: "" };
1367
+ const inventory = [];
1368
+ let excludedFileCount = new Set(ignoredFiles).size;
1369
+ const sortedCandidates = [...new Set(candidates)].sort();
1370
+ for (let start = 0; start < sortedCandidates.length; start += 256) {
1371
+ const batch = sortedCandidates.slice(start, start + 256);
1372
+ const inspected = await Promise.all(
1373
+ batch.map(async (relative) => ({
1374
+ relative,
1375
+ details: isShareablePath(relative)
1376
+ ? await lstat(path.join(root, relative)).catch(() => null)
1377
+ : null,
1378
+ })),
1379
+ );
1380
+ for (const { relative, details } of inspected) {
1381
+ if (!details?.isFile() || details.isSymbolicLink()) {
1382
+ excludedFileCount += 1;
1383
+ continue;
1384
+ }
1385
+ inventory.push({
1386
+ path: relative,
1387
+ size: details.size,
1388
+ classification: evidenceClassification(relative),
1389
+ git_state: inventoryGitState(
1390
+ relative,
1391
+ trackedFiles,
1392
+ modifiedFiles,
1393
+ stagedFiles,
1394
+ ),
1395
+ });
1396
+ if (inventory.length > MAX_INVENTORY_FILES) {
1397
+ throw new Error(
1398
+ `Workspace contains more than ${MAX_INVENTORY_FILES.toLocaleString()} safe files. Configure repository exclusions for generated or data directories, then reconnect.`,
1399
+ );
1400
+ }
1401
+ }
1402
+ }
1403
+ const representativeSources = representativeSourcePaths(inventory);
1404
+ const evidenceCandidates = [...inventory].sort((left, right) => {
1405
+ const priorityDifference =
1406
+ evidencePriority(left, representativeSources) -
1407
+ evidencePriority(right, representativeSources);
1408
+ return priorityDifference || left.path.localeCompare(right.path);
1409
+ });
1410
+ const evidenceEntries = [];
1411
+ let evidenceBytes = 0;
1412
+ for (const entry of evidenceCandidates) {
1413
+ if (
1414
+ evidenceEntries.length >= MAX_EVIDENCE_FILES ||
1415
+ entry.size > MAX_SHAREABLE_FILE_BYTES ||
1416
+ evidenceBytes + entry.size > MAX_EVIDENCE_BYTES
1417
+ ) {
1418
+ continue;
1419
+ }
1420
+ evidenceEntries.push(entry);
1421
+ evidenceBytes += entry.size;
1422
+ }
1423
+ const evidenceFiles = await readEvidenceFiles(root, evidenceEntries);
1424
+ const archive = await createZip(evidenceFiles);
1425
+ if (archive.length > MAX_ARCHIVE_BYTES) {
1426
+ throw new Error(
1427
+ "Prioritized workspace evidence exceeds the 25 MB archive limit. Configure repository exclusions for large source or data files, then reconnect.",
1428
+ );
1429
+ }
1430
+ const inventoryJson = Buffer.from(
1431
+ JSON.stringify({ version: 1, entries: inventory }),
1432
+ "utf8",
1433
+ );
1434
+ const compressedInventory = await gzipBuffer(inventoryJson);
1435
+ if (compressedInventory.length > MAX_COMPRESSED_INVENTORY_BYTES) {
1436
+ throw new Error(
1437
+ "Compressed workspace inventory exceeds 10 MB. Configure repository exclusions for generated or data directories, then reconnect.",
1438
+ );
1439
+ }
1440
+ const head = await run("git", ["rev-parse", "HEAD"], root, {
1441
+ allowFailure: true,
1442
+ });
1443
+ return {
1444
+ inventory_base64: compressedInventory.toString("base64"),
1445
+ evidence_archive_base64: archive.toString("base64"),
1446
+ media_type: "application/zip",
1447
+ workspace_name: path.basename(root),
1448
+ workspace_kind: inventory.some(({ path: relative }) =>
1449
+ isCodeBearing(relative),
1450
+ )
1451
+ ? "brownfield"
1452
+ : "greenfield",
1453
+ total_file_count: inventory.length,
1454
+ evidence_file_count: evidenceFiles.length,
1455
+ excluded_file_count: excludedFileCount,
1456
+ omitted_evidence_file_count: inventory.length - evidenceFiles.length,
1457
+ head_revision: head.code === 0 ? head.stdout.trim().slice(0, 128) : null,
1458
+ working_tree_status_digest: sha256(gitStatus.stdout),
1459
+ inventory_digest: sha256(inventoryJson),
1460
+ evidence_policy_version: EVIDENCE_POLICY_VERSION,
1461
+ };
1462
+ }
1463
+
1464
+ function evidenceClassification(relative) {
1465
+ const normalized = normalizePath(relative).toLowerCase();
1466
+ const name = path.posix.basename(normalized);
1467
+ const extension = path.posix.extname(name);
1468
+ if (CODE_MARKERS.has(name)) return "manifest";
1469
+ if (LOCK_FILE_NAMES.has(name)) return "lockfile";
1470
+ if (
1471
+ normalized.startsWith(".github/workflows/") ||
1472
+ [
1473
+ ".gitlab-ci.yml",
1474
+ "azure-pipelines.yml",
1475
+ "docker-compose.yml",
1476
+ "docker-compose.yaml",
1477
+ "dockerfile",
1478
+ "jenkinsfile",
1479
+ ].includes(name)
1480
+ ) {
1481
+ return "workflow";
1482
+ }
1483
+ if (
1484
+ /(^|\/)(tests|__tests__)\//.test(normalized) ||
1485
+ name.startsWith("test_") ||
1486
+ name.includes(".test.") ||
1487
+ name.includes(".spec.") ||
1488
+ /^(jest|vitest|pytest|playwright|cypress)(\.|$)/.test(name)
1489
+ ) {
1490
+ return "test";
1491
+ }
1492
+ if (/(^|\/)(security|compliance|policy|policies)(\/|\.|$)/.test(normalized)) {
1493
+ return "security_configuration";
1494
+ }
1495
+ if (
1496
+ REPOSITORY_CONFIGURATION_NAMES.has(name) ||
1497
+ /(^|\/)(eslint|ruff|mypy|tsconfig|biome|prettier)/.test(normalized)
1498
+ ) {
1499
+ return "repository_configuration";
1500
+ }
1501
+ if (ENTRYPOINT_NAMES.has(name)) return "entrypoint";
1502
+ if (
1503
+ /(^|\/)(api|routes|controllers)\//.test(normalized) ||
1504
+ name.endsWith(".d.ts") ||
1505
+ name.includes("openapi") ||
1506
+ name.includes("swagger")
1507
+ ) {
1508
+ return "public_api";
1509
+ }
1510
+ if (
1511
+ extension === ".md" ||
1512
+ normalized.startsWith("docs/") ||
1513
+ /(^|\/)(architecture|operations|runbook|deployment)(\/|\.|$)/.test(
1514
+ normalized,
1515
+ )
1516
+ ) {
1517
+ return "documentation";
1518
+ }
1519
+ if (CODE_EXTENSIONS.has(extension)) return "source";
1520
+ return "other";
1521
+ }
1522
+
1523
+ function inventoryGitState(relative, trackedFiles, modifiedFiles, stagedFiles) {
1524
+ if (!trackedFiles.has(relative)) return "untracked";
1525
+ const modified = modifiedFiles.has(relative);
1526
+ const staged = stagedFiles.has(relative);
1527
+ if (modified && staged) return "staged_and_modified";
1528
+ if (modified) return "modified";
1529
+ if (staged) return "staged";
1530
+ return "clean";
1531
+ }
1532
+
1533
+ function representativeSourcePaths(inventory) {
1534
+ const representatives = new Set();
1535
+ const groups = new Set();
1536
+ for (const entry of inventory) {
1537
+ if (entry.classification !== "source") continue;
1538
+ const parts = entry.path.split("/");
1539
+ const moduleName = parts.length > 1 ? parts[0] : ".";
1540
+ const extension = path.posix.extname(entry.path).toLowerCase();
1541
+ const group = `${moduleName}:${extension}`;
1542
+ if (groups.has(group)) continue;
1543
+ groups.add(group);
1544
+ representatives.add(entry.path);
1545
+ }
1546
+ return representatives;
1547
+ }
1548
+
1549
+ function evidencePriority(entry, representativeSources) {
1550
+ const priorities = {
1551
+ manifest: 0,
1552
+ lockfile: 0,
1553
+ workflow: 1,
1554
+ security_configuration: 1,
1555
+ repository_configuration: 1,
1556
+ entrypoint: 2,
1557
+ public_api: 2,
1558
+ test: 3,
1559
+ documentation: 4,
1560
+ };
1561
+ if (entry.classification in priorities)
1562
+ return priorities[entry.classification];
1563
+ if (
1564
+ entry.classification === "source" &&
1565
+ representativeSources.has(entry.path)
1566
+ ) {
1567
+ return 5;
1568
+ }
1569
+ return 6;
1570
+ }
1571
+
1572
+ function sha256(value) {
1573
+ return createHash("sha256").update(value).digest("hex");
1574
+ }
1575
+
1576
+ async function readEvidenceFiles(root, entries) {
1577
+ const files = [];
1578
+ for (let start = 0; start < entries.length; start += 128) {
1579
+ files.push(
1580
+ ...(await Promise.all(
1581
+ entries.slice(start, start + 128).map(async (entry) => ({
1582
+ name: entry.path,
1583
+ data: await readFile(path.join(root, entry.path)),
1584
+ })),
1585
+ )),
1586
+ );
1587
+ }
1588
+ return files;
1589
+ }
1590
+
1591
+ async function prepareRunWorkspace(workspace, runId, baseRevision) {
1592
+ const source = path.resolve(workspace);
1593
+ const root = path.join(os.homedir(), ".engineeros", "runs");
1594
+ const target = path.join(root, runId);
1595
+ await mkdir(root, { recursive: true });
1596
+ const isGit =
1597
+ (
1598
+ await run("git", ["rev-parse", "--is-inside-work-tree"], source, {
1599
+ allowFailure: true,
1600
+ })
1601
+ ).code === 0;
1602
+ if (isGit) {
1603
+ const exists = await stat(target).then(
1604
+ () => true,
1605
+ () => false,
1606
+ );
1607
+ if (!exists) {
1608
+ const base = await worktreeBase(source, baseRevision);
1609
+ await run("git", ["worktree", "add", "--detach", target, base], source);
1610
+ }
1611
+ return target;
1612
+ }
1613
+ const exists = await stat(target).then(
1614
+ () => true,
1615
+ () => false,
1616
+ );
1617
+ if (!exists) {
1618
+ await mkdir(target, { recursive: true });
1619
+ await copyWorkspace(source, target);
1620
+ await run("git", ["init"], target);
1621
+ await run("git", ["config", "user.name", "EngineerOS Connector"], target);
1622
+ await run(
1623
+ "git",
1624
+ ["config", "user.email", "connector@engineeros.local"],
1625
+ target,
1626
+ );
1627
+ await run("git", ["add", "-A"], target);
1628
+ await run(
1629
+ "git",
1630
+ ["commit", "--allow-empty", "-m", "EngineerOS run baseline"],
1631
+ target,
1632
+ );
1633
+ }
1634
+ return target;
1635
+ }
1636
+
1637
+ function launchCodexProcess(
1638
+ workspace,
1639
+ prompt,
1640
+ sandbox,
1641
+ callbacks,
1642
+ profile = {},
1643
+ previousSessionId,
1644
+ skipGitRepoCheck = false,
1645
+ mcpServer,
1646
+ ) {
1647
+ if (!mcpServer) {
1648
+ return launchCodexAppServer({
1649
+ workspace,
1650
+ prompt,
1651
+ sandbox,
1652
+ profile,
1653
+ previousSessionId,
1654
+ callbacks,
1655
+ });
1656
+ }
1657
+ const command =
1658
+ process.env.CODEX_BIN ||
1659
+ (process.platform === "win32" ? "codex.cmd" : "codex");
1660
+ const args = codexExecutionArgs({
1661
+ workspace,
1662
+ sandbox,
1663
+ profile,
1664
+ previousSessionId,
1665
+ skipGitRepoCheck,
1666
+ mcpServer,
1667
+ });
1668
+ const child = spawn(command, args, {
1669
+ cwd: workspace,
1670
+ env: process.env,
1671
+ shell: process.platform === "win32",
1672
+ stdio: ["pipe", "pipe", "pipe"],
1673
+ });
1674
+ child.stdin.end(prompt);
1675
+ let output = "";
1676
+ let buffer = "";
1677
+ let finalMessage = "";
1678
+ let sessionId = previousSessionId || "";
1679
+ child.stdout.setEncoding("utf8");
1680
+ child.stdout.on("data", (chunk) => {
1681
+ output += chunk;
1682
+ buffer += chunk;
1683
+ const lines = buffer.split(/\r?\n/);
1684
+ buffer = lines.pop() ?? "";
1685
+ for (const line of lines) {
1686
+ if (!line.trim()) continue;
1687
+ try {
1688
+ const event = JSON.parse(line);
1689
+ if (
1690
+ event.type === "thread.started" &&
1691
+ typeof event.thread_id === "string"
1692
+ ) {
1693
+ sessionId = event.thread_id;
1694
+ }
1695
+ if (
1696
+ event.type === "item.completed" &&
1697
+ event.item?.type === "agent_message" &&
1698
+ typeof event.item.text === "string"
1699
+ ) {
1700
+ finalMessage = event.item.text;
1701
+ }
1702
+ callbacks.onEvent?.(event);
1703
+ } catch {
1704
+ callbacks.onEvent?.({
1705
+ type: "agent.output",
1706
+ message: line.slice(0, 500),
1707
+ });
1708
+ }
1709
+ }
1710
+ });
1711
+ child.stderr.setEncoding("utf8");
1712
+ child.stderr.on("data", (chunk) => {
1713
+ output += chunk;
1714
+ callbacks.onEvent?.({
1715
+ type: "agent.stderr",
1716
+ message: chunk.trim().slice(0, 500),
1717
+ });
1718
+ });
1719
+ const completed = new Promise((resolve, reject) => {
1720
+ child.once("error", reject);
1721
+ child.once("close", (code) => {
1722
+ if (code === 0 && sessionId)
1723
+ resolve({ output: output.slice(-20_000), finalMessage, sessionId });
1724
+ else if (code === 0)
1725
+ reject(
1726
+ new Error(
1727
+ "Agent completed without announcing a resumable session id.",
1728
+ ),
1729
+ );
1730
+ else reject(new Error(codexFailureMessage(output, code)));
1731
+ });
1732
+ });
1733
+ return { child, completed };
1734
+ }
1735
+
1736
+ export function codexExecutionArgs({
1737
+ workspace,
1738
+ sandbox,
1739
+ profile = {},
1740
+ previousSessionId,
1741
+ skipGitRepoCheck = false,
1742
+ mcpServer,
1743
+ }) {
1744
+ const optionArgs = [
1745
+ "--json",
1746
+ "--config",
1747
+ codexConfigArgument("skills.include_instructions=false"),
1748
+ ];
1749
+ if (skipGitRepoCheck) optionArgs.push("--skip-git-repo-check");
1750
+ if (profile.model) optionArgs.push("--model", profile.model);
1751
+ if (profile.reasoning_effort) {
1752
+ optionArgs.push(
1753
+ "--config",
1754
+ codexConfigArgument(
1755
+ `model_reasoning_effort=${tomlLiteralString(profile.reasoning_effort)}`,
1756
+ ),
1757
+ );
1758
+ }
1759
+ if (mcpServer) {
1760
+ const mcpArgs = [
1761
+ mcpServer.connectorBin,
1762
+ "mcp",
1763
+ "--workspace",
1764
+ mcpServer.workspace,
1765
+ "--run-id",
1766
+ mcpServer.runId,
1767
+ ];
1768
+ optionArgs.push(
1769
+ "--config",
1770
+ codexConfigArgument(
1771
+ `mcp_servers.engineeros.command=${tomlLiteralString(process.execPath)}`,
1772
+ ),
1773
+ "--config",
1774
+ codexConfigArgument(
1775
+ `mcp_servers.engineeros.args=[${mcpArgs.map(tomlLiteralString).join(",")}]`,
1776
+ ),
1777
+ );
1778
+ }
1779
+ return previousSessionId
1780
+ ? ["exec", "resume", ...optionArgs, previousSessionId, "-"]
1781
+ : ["exec", ...optionArgs, "--sandbox", sandbox, "-C", workspace, "-"];
1782
+ }
1783
+
1784
+ export function sanitizeAgentResponse(value) {
1785
+ return String(value || "").replace(
1786
+ /^Warning: Exceeded skills context budget(?: of \d+%)?\. All skill descriptions were removed and \d+ additional skills? (?:was|were) not included in the model-visible skills list\.\s*/i,
1787
+ "",
1788
+ );
1789
+ }
1790
+
1791
+ function tomlLiteralString(value) {
1792
+ const text = String(value);
1793
+ if (text.includes("'''")) {
1794
+ throw new Error(
1795
+ "Codex configuration values cannot contain three consecutive apostrophes.",
1796
+ );
1797
+ }
1798
+ return `'''${text}'''`;
1799
+ }
1800
+
1801
+ function codexConfigArgument(override) {
1802
+ return process.platform === "win32" ? `"${override}"` : override;
1803
+ }
1804
+
1805
+ function launchAgentProcess(
1806
+ workspace,
1807
+ prompt,
1808
+ sandbox,
1809
+ config,
1810
+ callbacks,
1811
+ profile = {},
1812
+ previousSessionId,
1813
+ mcpContext,
1814
+ ) {
1815
+ if (config.agent_protocol === "acp") {
1816
+ return launchAcpAgent(workspace, prompt, config, callbacks, {
1817
+ persistent: mcpContext?.persistentAcp === true,
1818
+ sessionKey: mcpContext?.sessionKey,
1819
+ previousSessionId,
1820
+ sandbox,
1821
+ profile,
1822
+ });
1823
+ }
1824
+ return launchCodexProcess(
1825
+ workspace,
1826
+ prompt,
1827
+ sandbox,
1828
+ callbacks,
1829
+ profile,
1830
+ previousSessionId,
1831
+ config.skip_git_repo_check === true,
1832
+ mcpContext?.runId
1833
+ ? {
1834
+ connectorBin: process.argv[1],
1835
+ workspace: config.workspace,
1836
+ runId: mcpContext.runId,
1837
+ }
1838
+ : undefined,
1839
+ );
1840
+ }
1841
+
1842
+ function runCodexCommand(command, args, cwd) {
1843
+ return new Promise((resolve, reject) => {
1844
+ const child = spawn(command, args, {
1845
+ cwd,
1846
+ env: process.env,
1847
+ shell: process.platform === "win32",
1848
+ windowsHide: true,
1849
+ });
1850
+ let stdout = "";
1851
+ let stderr = "";
1852
+ child.stdout.setEncoding("utf8");
1853
+ child.stderr.setEncoding("utf8");
1854
+ child.stdout.on("data", (chunk) => (stdout += chunk));
1855
+ child.stderr.on("data", (chunk) => (stderr += chunk));
1856
+ child.once("error", reject);
1857
+ child.once("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
1858
+ });
1859
+ }
1860
+
1861
+ async function changedFilePaths(workspace) {
1862
+ const tracked = await run(
1863
+ "git",
1864
+ ["diff", "--name-only", "-z", "HEAD", "--"],
1865
+ workspace,
1866
+ );
1867
+ const untracked = await run(
1868
+ "git",
1869
+ ["ls-files", "-z", "--others", "--exclude-standard"],
1870
+ workspace,
1871
+ );
1872
+ return [
1873
+ ...new Set([
1874
+ ...gitPathList(tracked.stdout),
1875
+ ...gitPathList(untracked.stdout),
1876
+ ]),
1877
+ ].sort();
1878
+ }
1879
+
1880
+ async function boundedDiff(workspace, changedFiles) {
1881
+ const tracked = await run(
1882
+ "git",
1883
+ ["diff", "--binary", "HEAD", "--"],
1884
+ workspace,
1885
+ );
1886
+ const untracked = new Set(
1887
+ gitPathList(
1888
+ (
1889
+ await run(
1890
+ "git",
1891
+ ["ls-files", "-z", "--others", "--exclude-standard"],
1892
+ workspace,
1893
+ )
1894
+ ).stdout,
1895
+ ),
1896
+ );
1897
+ const parts = [tracked.stdout];
1898
+ for (const relative of changedFiles.filter((item) => untracked.has(item))) {
1899
+ const generated = await run(
1900
+ "git",
1901
+ ["diff", "--no-index", "--binary", "--", "/dev/null", relative],
1902
+ workspace,
1903
+ {
1904
+ allowFailure: true,
1905
+ },
1906
+ );
1907
+ parts.push(generated.stdout);
1908
+ }
1909
+ const diff = parts.filter(Boolean).join("\n");
1910
+ if (!diff.trim()) throw new Error("The run produced no bounded diff.");
1911
+ return diff;
1912
+ }
1913
+
1914
+ export async function repositoryArchive(workspace) {
1915
+ const listed = await run(
1916
+ "git",
1917
+ ["ls-files", "-z", "-co", "--exclude-standard"],
1918
+ workspace,
1919
+ );
1920
+ const files = [...new Set(gitPathList(listed.stdout))].sort();
1921
+ return createZip(
1922
+ await Promise.all(
1923
+ files.map(async (relative) => ({
1924
+ name: relative,
1925
+ data: await readFile(path.join(workspace, relative)),
1926
+ })),
1927
+ ),
1928
+ );
1929
+ }
1930
+
1931
+ async function workspaceFiles(root, current = root) {
1932
+ const files = [];
1933
+ for (const entry of await readdir(current, { withFileTypes: true })) {
1934
+ const absolute = path.join(current, entry.name);
1935
+ const relative = normalizePath(path.relative(root, absolute));
1936
+ if (entry.isSymbolicLink()) continue;
1937
+ if (entry.isDirectory()) {
1938
+ files.push(...(await workspaceFiles(root, absolute)));
1939
+ } else if (entry.isFile()) {
1940
+ files.push(relative);
1941
+ }
1942
+ }
1943
+ return files;
1944
+ }
1945
+
1946
+ function isShareablePath(relative) {
1947
+ const normalized = normalizePath(relative);
1948
+ if (
1949
+ !normalized ||
1950
+ normalized === ".." ||
1951
+ normalized.startsWith("../") ||
1952
+ path.isAbsolute(normalized)
1953
+ ) {
1954
+ return false;
1955
+ }
1956
+ const parts = normalized.split("/");
1957
+ if (parts.some((part) => EXCLUDED_DIRECTORIES.has(part.toLowerCase()))) {
1958
+ return false;
1959
+ }
1960
+ if (
1961
+ EXCLUDED_PATH_PREFIXES.some((prefix) =>
1962
+ normalized.toLowerCase().startsWith(prefix),
1963
+ )
1964
+ ) {
1965
+ return false;
1966
+ }
1967
+ const name = parts.at(-1)?.toLowerCase() ?? "";
1968
+ if (EXCLUDED_FILE_EXTENSIONS.has(path.posix.extname(name))) return false;
1969
+ if (name === ".env.example" || name === ".env.sample") return true;
1970
+ if (
1971
+ name === ".env" ||
1972
+ name.startsWith(".env.") ||
1973
+ [".npmrc", ".netrc", "credentials", "credentials.json"].includes(name) ||
1974
+ /\.(?:key|pem|p12|pfx)$/i.test(name)
1975
+ ) {
1976
+ return false;
1977
+ }
1978
+ return true;
1979
+ }
1980
+
1981
+ function isCodeBearing(relative) {
1982
+ const name = path.posix.basename(relative).toLowerCase();
1983
+ return (
1984
+ CODE_MARKERS.has(name) || CODE_EXTENSIONS.has(path.posix.extname(name))
1985
+ );
1986
+ }
1987
+
1988
+ async function worktreeBase(workspace, requested) {
1989
+ if (!requested || requested.startsWith("greenfield:")) return "HEAD";
1990
+ const exists = await run(
1991
+ "git",
1992
+ ["cat-file", "-e", `${requested}^{commit}`],
1993
+ workspace,
1994
+ { allowFailure: true },
1995
+ );
1996
+ if (exists.code !== 0) {
1997
+ throw new Error(
1998
+ `The frozen base revision ${requested} is not available in this repository.`,
1999
+ );
2000
+ }
2001
+ return requested;
2002
+ }
2003
+
2004
+ export async function createZip(files) {
2005
+ const localParts = [];
2006
+ const centralParts = [];
2007
+ let offset = 0;
2008
+ let total = 0;
2009
+ for (const file of files) {
2010
+ const name = Buffer.from(normalizePath(file.name), "utf8");
2011
+ const data = Buffer.from(file.data);
2012
+ total += data.length;
2013
+ if (total > MAX_ARCHIVE_BYTES)
2014
+ throw new Error("Repository archive exceeds the 25 MB connector limit.");
2015
+ const compressed = await deflate(data);
2016
+ const crc = crc32(data);
2017
+ const local = Buffer.alloc(30);
2018
+ local.writeUInt32LE(0x04034b50, 0);
2019
+ local.writeUInt16LE(20, 4);
2020
+ local.writeUInt16LE(0x0800, 6);
2021
+ local.writeUInt16LE(8, 8);
2022
+ local.writeUInt32LE(crc, 14);
2023
+ local.writeUInt32LE(compressed.length, 18);
2024
+ local.writeUInt32LE(data.length, 22);
2025
+ local.writeUInt16LE(name.length, 26);
2026
+ localParts.push(local, name, compressed);
2027
+
2028
+ const central = Buffer.alloc(46);
2029
+ central.writeUInt32LE(0x02014b50, 0);
2030
+ central.writeUInt16LE(20, 4);
2031
+ central.writeUInt16LE(20, 6);
2032
+ central.writeUInt16LE(0x0800, 8);
2033
+ central.writeUInt16LE(8, 10);
2034
+ central.writeUInt32LE(crc, 16);
2035
+ central.writeUInt32LE(compressed.length, 20);
2036
+ central.writeUInt32LE(data.length, 24);
2037
+ central.writeUInt16LE(name.length, 28);
2038
+ central.writeUInt32LE(offset, 42);
2039
+ centralParts.push(central, name);
2040
+ offset += local.length + name.length + compressed.length;
2041
+ }
2042
+ const central = Buffer.concat(centralParts);
2043
+ const end = Buffer.alloc(22);
2044
+ end.writeUInt32LE(0x06054b50, 0);
2045
+ end.writeUInt16LE(files.length, 8);
2046
+ end.writeUInt16LE(files.length, 10);
2047
+ end.writeUInt32LE(central.length, 12);
2048
+ end.writeUInt32LE(offset, 16);
2049
+ return Buffer.concat([...localParts, central, end]);
2050
+ }
2051
+
2052
+ async function copyWorkspace(source, target) {
2053
+ for (const entry of await readdir(source, { withFileTypes: true })) {
2054
+ if ([".git", ".engineeros", "node_modules"].includes(entry.name)) continue;
2055
+ const from = path.join(source, entry.name);
2056
+ const to = path.join(target, entry.name);
2057
+ if (entry.isDirectory()) {
2058
+ await mkdir(to, { recursive: true });
2059
+ await copyWorkspace(from, to);
2060
+ } else if (entry.isFile()) {
2061
+ await writeFile(to, await readFile(from));
2062
+ }
2063
+ }
2064
+ }
2065
+
2066
+ function normalizePath(value) {
2067
+ return String(value ?? "")
2068
+ .trim()
2069
+ .replaceAll("\\", "/")
2070
+ .replace(/^\.\//, "");
2071
+ }
2072
+
2073
+ function gitPathList(value) {
2074
+ return String(value ?? "")
2075
+ .split("\0")
2076
+ .map(normalizePath)
2077
+ .filter(Boolean);
2078
+ }
2079
+
2080
+ function run(command, args, cwd, options = {}) {
2081
+ return new Promise((resolve, reject) => {
2082
+ const child = spawn(command, args, {
2083
+ cwd,
2084
+ shell: false,
2085
+ windowsHide: true,
2086
+ });
2087
+ let stdout = "";
2088
+ let stderr = "";
2089
+ child.stdout.setEncoding("utf8");
2090
+ child.stderr.setEncoding("utf8");
2091
+ child.stdout.on("data", (chunk) => (stdout += chunk));
2092
+ child.stderr.on("data", (chunk) => (stderr += chunk));
2093
+ child.once("error", reject);
2094
+ child.once("close", (code) => {
2095
+ const result = { code: code ?? 1, stdout, stderr };
2096
+ if (code === 0 || options.allowFailure) resolve(result);
2097
+ else
2098
+ reject(
2099
+ new Error(`${command} ${args.join(" ")} failed: ${stderr || stdout}`),
2100
+ );
2101
+ });
2102
+ });
2103
+ }
2104
+
2105
+ function crc32(buffer) {
2106
+ let crc = 0xffffffff;
2107
+ for (const byte of buffer) {
2108
+ crc ^= byte;
2109
+ for (let bit = 0; bit < 8; bit += 1)
2110
+ crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));
2111
+ }
2112
+ return (crc ^ 0xffffffff) >>> 0;
2113
+ }