unitbob 0.1.10 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ // The connector-owned pytest-bdd reporter (spec 32). Python has no Cucumber
2
+ // Messages emitter, so the connector ships this small deterministic plugin. It
3
+ // hangs off pytest-bdd's public scenario/step hooks and writes one JSON document
4
+ // the Rails PytestBddJson parser reads:
5
+ //
6
+ // { "version": 1, "scenarios": [ { name, tags, status, failure, steps: [...] } ] }
7
+ //
8
+ // It only records — it never reconciles markers or aggregates capabilities. It
9
+ // is connector-owned and never part of the LLM-generated step definitions.
10
+ export const PYTEST_BDD_PLUGIN = `# Written by the unitbob connector — do not edit.
11
+ import json
12
+ import os
13
+
14
+ _UNITBOB_REPORT = {"version": 1, "scenarios": []}
15
+ _UNITBOB_CURRENT = {}
16
+
17
+
18
+ def pytest_bdd_before_scenario(request, feature, scenario):
19
+ _UNITBOB_CURRENT[id(scenario)] = {
20
+ "name": scenario.name,
21
+ "tags": sorted(scenario.tags),
22
+ "status": "passed",
23
+ "failure": "",
24
+ "steps": [],
25
+ }
26
+
27
+
28
+ def _record_step(scenario, step, status):
29
+ entry = _UNITBOB_CURRENT.get(id(scenario))
30
+ if entry is None:
31
+ return
32
+ entry["steps"].append({
33
+ "keyword": getattr(step, "keyword", "").strip(),
34
+ "text": step.name,
35
+ "status": status,
36
+ })
37
+
38
+
39
+ def pytest_bdd_after_step(request, feature, scenario, step, step_func):
40
+ _record_step(scenario, step, "passed")
41
+
42
+
43
+ def pytest_bdd_step_error(request, feature, scenario, step, step_func, step_func_args, exception):
44
+ entry = _UNITBOB_CURRENT.get(id(scenario))
45
+ if entry is not None:
46
+ entry["status"] = "failed"
47
+ entry["failure"] = "{}: {}".format(type(exception).__name__, exception)
48
+ _record_step(scenario, step, "failed")
49
+
50
+
51
+ def pytest_bdd_after_scenario(request, feature, scenario):
52
+ entry = _UNITBOB_CURRENT.pop(id(scenario), None)
53
+ if entry is not None:
54
+ _UNITBOB_REPORT["scenarios"].append(entry)
55
+
56
+
57
+ def pytest_sessionfinish(session, exitstatus):
58
+ out = os.environ.get("UNITBOB_PYTEST_BDD_REPORT")
59
+ if out:
60
+ with open(out, "w") as handle:
61
+ json.dump(_UNITBOB_REPORT, handle)
62
+ `;
@@ -0,0 +1,25 @@
1
+ import { Wire } from "../wire.js";
2
+ // Fetch the contract action brief for one red check (spec 32). One operation for
3
+ // both maps and both intents: the digest names the exact current version (and so
4
+ // its contract system), `test_id` is that kind's own id, `intent` is fix|accept.
5
+ // The server composes the whole prompt; the connector prints its plain-language
6
+ // `message` and the copy-ready `prompt`. A 422 (not current / not failing /
7
+ // unknown intent) surfaces via WireError; nothing is fabricated.
8
+ export async function contractPrompt(config, args = [], deps) {
9
+ const suiteDigest = (args[0] ?? '').trim();
10
+ const testId = (args[1] ?? '').trim();
11
+ const intent = (args[2] ?? 'fix').trim();
12
+ if (!suiteDigest || !testId) {
13
+ throw new Error('Usage: unitbob contract-prompt <suite_digest> <test_id> [fix|accept]');
14
+ }
15
+ if (intent !== 'fix' && intent !== 'accept') {
16
+ throw new Error(`intent must be "fix" or "accept" (got "${intent}").`);
17
+ }
18
+ const d = {
19
+ getContractPrompt: (digest, id, action) => new Wire(config).getContractPrompt(digest, id, action),
20
+ stdout: process.stdout,
21
+ ...deps,
22
+ };
23
+ const packet = await d.getContractPrompt(suiteDigest, testId, intent);
24
+ d.stdout.write(`${packet.message}\n\n${packet.prompt}\n`);
25
+ }
@@ -20,9 +20,21 @@ export async function mapPrepare(config, _args = [], deps) {
20
20
  throw new Error(`graphify update failed: ${detail}`);
21
21
  }
22
22
  readFreshGraph(config.projectRoot);
23
- const [decompose, relate] = await Promise.all([actual.getRecipe('decompose'), actual.getRecipe('relate')]);
24
- const packet = writeMapBuildRequest(config.projectRoot, { decompose, relate });
23
+ const [decompose, relate, extractSurfaces, decomposeSurfaces] = await Promise.all([
24
+ actual.getRecipe('decompose'),
25
+ actual.getRecipe('relate'),
26
+ actual.getRecipe('extract_surfaces'),
27
+ actual.getRecipe('decompose_surfaces'),
28
+ ]);
29
+ const packet = writeMapBuildRequest(config.projectRoot, {
30
+ decompose,
31
+ relate,
32
+ extract_surfaces: extractSurfaces,
33
+ decompose_surfaces: decomposeSurfaces,
34
+ });
25
35
  process.stdout.write(`Map build request written to ${packet.project_root}/.unitbob/map-build/request.json\n`);
26
- process.stdout.write(`Next: build the Map Document at ${packet.output_path} following recipes.decompose and ` +
27
- 'recipes.relate inside that request, then run `unitbob put-map-build`.\n');
36
+ process.stdout.write(`Next: build BOTH lenses following the recipes in that request the decompose map at ` +
37
+ `${packet.output_path} (recipes.decompose, recipes.relate), and the surface map at ` +
38
+ `${packet.surface_output_path} (recipes.extract_surfaces → ${packet.surfaces_path}, then ` +
39
+ 'recipes.decompose_surfaces) — then run `unitbob put-map-build`.\n');
28
40
  }
@@ -1,16 +1,26 @@
1
1
  import { readFileSync } from 'node:fs';
2
- import { readHostMapOutput, readMapBuildRequest } from "../files/mapBuild.js";
2
+ import { readHostMapOutput, readMapBuildRequest, readSurfaceDocument, readSurfacesInventory, } from "../files/mapBuild.js";
3
3
  import { Wire } from "../wire.js";
4
4
  export async function putMapBuild(config, _args = [], deps) {
5
5
  const packet = readMapBuildRequest(config.projectRoot);
6
6
  const graph = JSON.parse(readFileSync(packet.graph_path, 'utf8'));
7
+ // Both lenses must be present locally before anything is sent — the host stores
8
+ // the bundle atomically or not at all (spec 31). A missing artifact here throws
9
+ // and no partial upload happens.
7
10
  const mapDocument = readHostMapOutput(packet.output_path);
11
+ const surfaces = readSurfacesInventory(packet.surfaces_path);
12
+ const surfaceDocument = readSurfaceDocument(packet.surface_output_path);
8
13
  const actual = {
9
14
  putMapBuild: (payload) => new Wire(config).putMapBuild(payload),
10
15
  ...deps,
11
16
  };
12
- const result = await actual.putMapBuild({ graph, map_document: mapDocument });
13
- process.stdout.write(`Map uploaded (${result.map_digest}, graph ${result.graph_digest}) ` +
17
+ const result = await actual.putMapBuild({
18
+ graph,
19
+ map_document: mapDocument,
20
+ surfaces,
21
+ surface_document: surfaceDocument,
22
+ });
23
+ process.stdout.write(`Map uploaded (map ${result.map_digest}, surface ${result.surface_digest}, graph ${result.graph_digest}) ` +
14
24
  `${result.reused ? 'reused' : 'created'} version ${result.map_version_id}.\n` +
15
25
  `${result.map_url}\n`);
16
26
  }
@@ -1,35 +1,49 @@
1
- import { readHostSuiteOutput, readSuiteBuildRequest } from "../files/suiteBuild.js";
2
- import { validateStack } from "../runner/precheck.js";
1
+ import { readHostSuiteOutputs, readSuiteBuildRequest } from "../files/suiteBuild.js";
3
2
  import { Wire } from "../wire.js";
4
- // Read the task and the host's answer, verify the answer parses and carries the
5
- // whole suite artifact, confirm the host-selected stack against local project
6
- // markers (fail closeda mismatch uploads nothing), then upload
7
- // `{ map_digest, suite_file, runner_manifest, test_metadata }`. `map_digest`
8
- // comes from the task never the host's answer so the host cannot claim a
9
- // different map than it was given. If the answer is unparseable or incomplete,
10
- // nothing is uploaded and the previous suite stands.
3
+ // Read the task and the host's answers, verify each branch parses and carries a
4
+ // safe-path artifact envelope, then upload both peer branches in one batch
5
+ // (spec 32). `source_digest` comes from the task never the host's answer so
6
+ // the host cannot claim a different map than each branch was given. A branch the
7
+ // host could not build is uploaded as a `build_error`, which never rolls back the
8
+ // peer branch. If a branch's answer is unparseable, nothing is uploaded.
11
9
  export async function putSuiteBuild(config, _args = [], deps) {
12
10
  const request = readSuiteBuildRequest(config.projectRoot);
13
- const output = readHostSuiteOutput(request.output_path, config.projectRoot);
14
- const actual = {
15
- putSuiteBuild: (payload) => new Wire(config).putSuiteBuild(payload),
16
- validateStack,
11
+ const outputs = readHostSuiteOutputs(request.output_path, request);
12
+ const d = {
13
+ putSuiteBuilds: (items) => new Wire(config).putSuiteBuilds(items),
14
+ stdout: process.stdout,
17
15
  ...deps,
18
16
  };
19
- const runner = String(output.runner_manifest.runner ?? '');
20
- const check = actual.validateStack(config.projectRoot, runner);
21
- if (!check.ok) {
22
- throw new Error(check.message ?? `Local project does not match the selected runner "${runner}".`);
23
- }
24
- const result = await actual.putSuiteBuild({
25
- map_digest: request.map_digest,
26
- suite_file: output.suite_file,
27
- runner_manifest: output.runner_manifest,
28
- test_metadata: output.test_metadata,
17
+ const digestFor = new Map(request.branches.map((branch) => [branch.suite_kind, branch.source_digest]));
18
+ const items = outputs.map((output) => {
19
+ const sourceDigest = digestFor.get(output.suite_kind) ?? '';
20
+ if (output.build_error) {
21
+ return { suite_kind: output.suite_kind, source_digest: sourceDigest, build_error: output.build_error };
22
+ }
23
+ return {
24
+ suite_kind: output.suite_kind,
25
+ source_digest: sourceDigest,
26
+ artifacts: {
27
+ suite_file: output.suite_file,
28
+ runner_manifest: output.runner_manifest,
29
+ test_metadata: output.test_metadata,
30
+ },
31
+ };
29
32
  });
30
- const tallies = Object.entries(result.counts)
31
- .map(([name, value]) => `${value} ${name}`)
32
- .join(', ');
33
- process.stdout.write(`Suite uploaded (${result.suite_digest}) as version ${result.suite_version_id}` +
34
- `${tallies ? ` — ${tallies}` : ''}.\n${result.map_url}\n`);
33
+ const results = await d.putSuiteBuilds(items);
34
+ for (const result of results) {
35
+ d.stdout.write(`${printResult(result)}\n`);
36
+ }
37
+ }
38
+ function printResult(result) {
39
+ if (result.status === 'error' || result.status === 'build_error') {
40
+ return `${result.suite_kind}: not published — ${result.error ?? 'the host could not build this suite'}.`;
41
+ }
42
+ const tallies = result.counts
43
+ ? Object.entries(result.counts)
44
+ .map(([name, value]) => `${value} ${name}`)
45
+ .join(', ')
46
+ : '';
47
+ const digest = result.suite_digest ? ` (${result.suite_digest})` : '';
48
+ return `${result.suite_kind}: ${result.status}${digest}${tallies ? ` — ${tallies}` : ''}.`;
35
49
  }
package/dist/verbs/run.js CHANGED
@@ -1,59 +1,90 @@
1
1
  import { materializeGuardrails } from "../files/guardrails.js";
2
+ import { materializeBehavioral } from "../files/behavioral.js";
2
3
  import { validateStack } from "../runner/precheck.js";
3
4
  import { runRspecSuite } from "../runner/rspec.js";
4
5
  import { runVitestSuite } from "../runner/vitest.js";
5
6
  import { runPytestSuite } from "../runner/pytest.js";
7
+ import { runBddSuite } from "../runner/bdd.js";
8
+ import { boundReport } from "../runner/boundReport.js";
6
9
  import { Wire } from "../wire.js";
7
- // Bound failure text for transport/storage hygiene (spec 26). This is a size
8
- // limit only, not a privacy filter — application values in failure messages are
9
- // accepted, not scrubbed.
10
- const MAX_FAILURE_CHARS = 8000;
11
10
  const OUTPUT_TAIL_CHARS = 2000;
12
- // The check flow (spec 30): fetch the current suite blob, confirm the local
13
- // project matches its runner, materialize the guardrail file, execute the
14
- // connector-owned strategy named by `runner_manifest.runner`, and ship the raw
15
- // machine-readable report (or a structured runner error) to Rails.
16
11
  export async function run(config, _args, deps) {
17
12
  const wire = new Wire(config);
18
13
  const d = {
19
- getSuite: () => wire.getSuite(),
20
- postRun: (payload) => wire.postRun(payload),
21
- materializeGuardrails,
22
- runSuite: runSuiteByRunner,
14
+ getSuites: () => wire.getSuites(),
15
+ postRunsBatch: (runs) => wire.postRunsBatch(runs),
16
+ materializeStructural: (projectRoot, item) => materializeGuardrails(projectRoot, {
17
+ suite_digest: item.suite_digest,
18
+ suite_file: { path: item.suite_file.path, content: item.suite_file.content },
19
+ runner_manifest: item.runner_manifest,
20
+ }),
21
+ materializeBehavioral: (projectRoot, item) => materializeBehavioral(projectRoot, item.suite_file).mainPath,
22
+ runStructural: runStructuralByRunner,
23
+ runBehavioral: runBddSuite,
23
24
  validateStack,
24
25
  stdout: process.stdout,
25
26
  ...deps,
26
27
  };
27
- const suite = await d.getSuite();
28
- if (suite === null) {
29
- d.stdout.write('No Unitbob suite exists yet. Generate the test suite first, then run /unitbob check again.\n');
28
+ const suites = await d.getSuites();
29
+ const ready = suites.filter((item) => item.status === 'ready');
30
+ if (ready.length === 0) {
31
+ d.stdout.write('No Unitbob suites exist yet. Generate them first, then run the Unitbob checks again.\n');
30
32
  return;
31
33
  }
32
- // Fail closed before touching the working tree: a stack mismatch writes no files.
33
- const runner = suite.runner_manifest.runner;
34
+ const runs = [];
35
+ for (const item of ready) {
36
+ runs.push(await buildRunPayload(config, d, item));
37
+ }
38
+ const { results, map_url } = await d.postRunsBatch(runs);
39
+ for (const result of results)
40
+ d.stdout.write(`${result.summary}\n`);
41
+ if (map_url)
42
+ d.stdout.write(`${map_url}\n`);
43
+ }
44
+ // One branch's run payload. A stack mismatch, a materialize failure, or a runner
45
+ // that produced no report all become this branch's structured suite error — the
46
+ // peer branch is unaffected. This connector never installs anything: a missing
47
+ // or broken runner surfaces here as a suite error, not an install.
48
+ async function buildRunPayload(config, d, item) {
49
+ const runner = item.runner_manifest.runner;
50
+ const behavioral = item.suite_kind === 'behavioral';
51
+ // Confirm the local stack before touching the tree, for both contract systems.
52
+ // A mismatch is this branch's suite error — reported and left for the peer
53
+ // branch to run regardless. The behavioral check confirms only the base
54
+ // language; a missing BDD runner still surfaces from the run itself, since
55
+ // check installs nothing.
34
56
  const check = d.validateStack(config.projectRoot, runner);
35
57
  if (!check.ok)
36
- throw new Error(check.message ?? `Local project does not match the suite runner "${runner}".`);
37
- d.materializeGuardrails(config.projectRoot, suite);
38
- const result = await d.runSuite(config.projectRoot, runner, suite.suite_file.path).catch((err) => ({
39
- stdout: '',
40
- stderr: err.message,
41
- code: null,
42
- command: runner,
43
- args: [],
44
- resultPath: '',
45
- report: '',
46
- }));
47
- const payload = rawRunPayload(suite.suite_digest, runner, result);
48
- const summary = await d.postRun(payload);
49
- d.stdout.write(`${summary.summary}\n`);
50
- if (summary.map_url)
51
- d.stdout.write(`${summary.map_url}\n`);
58
+ return suiteError(item.suite_digest, check.message ?? `Local project does not match "${runner}".`);
59
+ let result;
60
+ try {
61
+ if (behavioral) {
62
+ const mainPath = d.materializeBehavioral(config.projectRoot, item);
63
+ result = await d.runBehavioral(config.projectRoot, runner, mainPath);
64
+ }
65
+ else {
66
+ d.materializeStructural(config.projectRoot, item);
67
+ result = await d.runStructural(config.projectRoot, runner, item.suite_file.path);
68
+ }
69
+ }
70
+ catch (err) {
71
+ return suiteError(item.suite_digest, err.message);
72
+ }
73
+ const report = boundReport(runner, result);
74
+ if (report === null) {
75
+ return {
76
+ suite_digest: item.suite_digest,
77
+ suite_error: {
78
+ command: [result.command, ...result.args].join(' '),
79
+ exit_code: result.code,
80
+ result_path: result.resultPath,
81
+ output_tail: outputTail(result),
82
+ },
83
+ };
84
+ }
85
+ return { suite_digest: item.suite_digest, run_result: report };
52
86
  }
53
- // The connector-owned strategy table: `runner_manifest.runner` names one of
54
- // these; only suite and result paths vary. Host-provided command strings are
55
- // never executed.
56
- function runSuiteByRunner(projectRoot, runner, suitePath) {
87
+ function runStructuralByRunner(projectRoot, runner, suitePath) {
57
88
  switch (runner) {
58
89
  case 'rspec':
59
90
  return runRspecSuite(projectRoot, suitePath);
@@ -62,119 +93,15 @@ function runSuiteByRunner(projectRoot, runner, suitePath) {
62
93
  case 'pytest':
63
94
  return runPytestSuite(projectRoot, suitePath);
64
95
  default:
65
- return Promise.reject(new Error(`Unsupported runner "${runner}" — rebuild the suite with /unitbob suite.`));
96
+ return Promise.reject(new Error(`Unsupported runner "${runner}" — rebuild the suite.`));
66
97
  }
67
98
  }
68
- // The machine-readable report comes from the runner's own output file, which
69
- // the app under test cannot pollute. A run that produced no report is a
70
- // structured suite error — command, exit code, expected result path, output
71
- // tail — which Rails records without repainting capabilities.
72
- function rawRunPayload(suiteDigest, runner, result) {
73
- const report = boundedReport(runner, result);
74
- if (report !== null)
75
- return { suite_digest: suiteDigest, run_result: report };
99
+ function suiteError(suiteDigest, message) {
76
100
  return {
77
101
  suite_digest: suiteDigest,
78
- suite_error: {
79
- command: [result.command, ...result.args].join(' '),
80
- exit_code: result.code,
81
- result_path: result.resultPath,
82
- output_tail: outputTail(result),
83
- },
102
+ suite_error: { command: '', exit_code: null, result_path: '', output_tail: message },
84
103
  };
85
104
  }
86
- // JSON reports (rspec, vitest) are parsed only to size-bound failure text, then
87
- // re-serialized; the XML report is bounded per failure element the same way.
88
- // `null` means "no usable report" — the suite-error path. Stdout is only a
89
- // fallback for an rspec double that emits its report there.
90
- function boundedReport(runner, result) {
91
- if (runner === 'pytest')
92
- return result.report.trim() ? boundJunitXml(result.report) : null;
93
- const parsed = parseJsonObject(result.report) ?? (runner === 'rspec' ? parseJsonObject(result.stdout) : null);
94
- if (!parsed)
95
- return null;
96
- const bounded = runner === 'rspec' ? boundRspecFailures(parsed) : boundVitestFailures(parsed);
97
- return JSON.stringify(bounded);
98
- }
99
- // Truncate long per-example failure message/backtrace before transport. Other
100
- // fields pass through untouched; Rails owns the capability join and status mapping.
101
- function boundRspecFailures(rspecJson) {
102
- const examples = rspecJson.examples;
103
- if (!Array.isArray(examples))
104
- return rspecJson;
105
- const bounded = examples.map((example) => {
106
- if (!example || typeof example !== 'object')
107
- return example;
108
- const ex = example;
109
- const exception = ex.exception;
110
- if (!exception || typeof exception !== 'object')
111
- return ex;
112
- const exc = exception;
113
- const next = { ...exc };
114
- if (typeof exc.message === 'string')
115
- next.message = truncate(exc.message);
116
- if (Array.isArray(exc.backtrace))
117
- next.backtrace = exc.backtrace.slice(0, 20);
118
- return { ...ex, exception: next };
119
- });
120
- return { ...rspecJson, examples: bounded };
121
- }
122
- function boundVitestFailures(vitestJson) {
123
- const testResults = vitestJson.testResults;
124
- if (!Array.isArray(testResults))
125
- return vitestJson;
126
- const bounded = testResults.map((fileResult) => {
127
- if (!fileResult || typeof fileResult !== 'object')
128
- return fileResult;
129
- const file = fileResult;
130
- const assertions = file.assertionResults;
131
- if (!Array.isArray(assertions))
132
- return file;
133
- const next = assertions.map((assertion) => {
134
- if (!assertion || typeof assertion !== 'object')
135
- return assertion;
136
- const a = assertion;
137
- if (!Array.isArray(a.failureMessages))
138
- return a;
139
- return { ...a, failureMessages: a.failureMessages.map((m) => (typeof m === 'string' ? truncate(m) : m)) };
140
- });
141
- return { ...file, assertionResults: next };
142
- });
143
- return { ...vitestJson, testResults: bounded };
144
- }
145
- function truncate(text) {
146
- return text.length > MAX_FAILURE_CHARS ? `${text.slice(0, MAX_FAILURE_CHARS)}… (truncated)` : text;
147
- }
148
- // pytest's JUnit XML has no size bound of its own: one failing assertion can
149
- // carry a multi-megabyte diff plus captured stdout/stderr. Bound the two things
150
- // Rails reads (the failure/error/skipped `message` attribute and the element
151
- // body) plus the captured-output blocks, keeping the document well-formed so
152
- // Rails' strict XML parse still succeeds.
153
- function boundJunitXml(xml) {
154
- const boundedBodies = xml.replace(/(<(failure|error|skipped|system-out|system-err)\b[^>]*>)([\s\S]*?)(<\/\2>)/g, (_match, open, _tag, body, close) => `${boundXmlMessageAttr(open)}${boundXmlText(body)}${close}`);
155
- // Self-closing forms (e.g. <failure message="…"/>) carry everything in the attr.
156
- return boundedBodies.replace(/<(failure|error|skipped)\b[^>]*\/>/g, (tag) => boundXmlMessageAttr(tag));
157
- }
158
- function boundXmlMessageAttr(tag) {
159
- // Attribute values escape their own quotes, so matching to the next `"` is safe.
160
- return tag.replace(/(\bmessage=")([\s\S]*?)(")/, (_m, pre, value, post) => value.length > MAX_FAILURE_CHARS ? `${pre}${boundXmlText(value)}… (truncated)${post}` : `${pre}${value}${post}`);
161
- }
162
- function boundXmlText(text) {
163
- return text.length > MAX_FAILURE_CHARS ? `${truncateXml(text)}… (truncated)` : text;
164
- }
165
- // Slice without cutting inside an XML entity, which would break a strict parse.
166
- function truncateXml(text) {
167
- return text.slice(0, MAX_FAILURE_CHARS).replace(/&[^;]*$/, '');
168
- }
169
- function parseJsonObject(text) {
170
- try {
171
- const parsed = JSON.parse(text);
172
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
173
- }
174
- catch {
175
- return null;
176
- }
177
- }
178
105
  function outputTail(result) {
179
106
  const bits = [];
180
107
  if (result.stderr.trim())
@@ -1,35 +1,40 @@
1
1
  import { materializeHelper } from "../files/guardrails.js";
2
- import { writeSuiteBuildRequest } from "../files/suiteBuild.js";
2
+ import { recipeNameFor, writeSuiteBuildRequest } from "../files/suiteBuild.js";
3
3
  import { anyStackPrecheck } from "../runner/precheck.js";
4
4
  import { Wire } from "../wire.js";
5
- // Confirm at least one supported stack is present (Rails+RSpec, Vitest, or
6
- // pytest the host LLM picks the primary one during generation), materialize
7
- // the Ruby boot helper a generated RSpec suite would require, then fetch the
8
- // generate recipe and the per-block capability assignment and write the host's
9
- // task to `.unitbob/suite-build/request.json`. No model is called and no
10
- // source is read here that is the host's job, framed by
11
- // ai/agents/suite_builder.md. An unsupported project stops with one actionable
12
- // message and writes nothing; a no-current-map error from the server surfaces
13
- // (via WireError) with guidance to run `/unitbob map` first.
5
+ // Confirm at least one supported stack is present, materialize the Ruby boot
6
+ // helper a generated RSpec suite would require, then fetch both peer assignments
7
+ // (spec 32) and each branch's recipe, and write the host's task to
8
+ // `.unitbob/suite-build/request.json`. No model is called and no source is read
9
+ // here that is the host's job, framed by the two generation recipes. An
10
+ // unsupported project stops with one actionable message and writes nothing; a
11
+ // no-current-map error from the server surfaces (via WireError) with guidance to
12
+ // rebuild the map first.
14
13
  export async function suitePrepare(config, _args = [], deps) {
15
14
  const wire = new Wire(config);
16
15
  const actual = {
17
16
  getRecipe: (name) => wire.getRecipe(name),
18
- getSuitePackets: () => wire.getSuitePackets(),
17
+ getSuitePacketsBatch: () => wire.getSuitePacketsBatch(),
19
18
  precheck: anyStackPrecheck,
19
+ stdout: process.stdout,
20
20
  ...deps,
21
21
  };
22
22
  const check = actual.precheck(config.projectRoot);
23
23
  if (!check.ok)
24
24
  throw new Error(check.message ?? 'Unsupported runtime.');
25
25
  materializeHelper(config.projectRoot);
26
- const [recipe, packets] = await Promise.all([actual.getRecipe('generate'), actual.getSuitePackets()]);
27
- const request = writeSuiteBuildRequest(config.projectRoot, {
28
- map_digest: packets.map_digest,
29
- recipe,
30
- blocks: packets.blocks,
31
- });
32
- process.stdout.write(`Suite build request written to ${request.project_root}/.unitbob/suite-build/request.json\n`);
33
- process.stdout.write(`Next: write the complete guardrail spec and ${request.output_path} following \`recipe\` and the ` +
34
- 'per-block capability `blocks` inside that request, run it locally to green, then run `unitbob put-suite-build`.\n');
26
+ const packets = await actual.getSuitePacketsBatch();
27
+ const branches = await Promise.all(packets.map(async (packet) => ({
28
+ suite_kind: packet.suite_kind,
29
+ source_digest: packet.source_digest,
30
+ path_root: packet.path_root,
31
+ recipe: await actual.getRecipe(recipeNameFor(packet)),
32
+ assignment: packet.assignment,
33
+ })));
34
+ const request = writeSuiteBuildRequest(config.projectRoot, branches);
35
+ const kinds = branches.map((branch) => branch.suite_kind).join(' and ');
36
+ actual.stdout.write(`Suite build request written to ${request.project_root}/.unitbob/suite-build/request.json\n`);
37
+ actual.stdout.write(`Next: build both peer suites (${kinds}) following each branch's \`recipe\` and \`assignment\`, ` +
38
+ `write your answer to ${request.output_path} as a branches array, run each locally to green, ` +
39
+ 'then run `unitbob put-suite-build`.\n');
35
40
  }
package/dist/wire.js CHANGED
@@ -40,16 +40,73 @@ export class Wire {
40
40
  constructor(config) {
41
41
  this.config = config;
42
42
  }
43
- // PUT /repos/:id/map_build — upload the fresh graph and host-built map as one
44
- // atomic blob. Rails validates, versions, and computes all digests.
43
+ // PUT /repos/:id/map_build — upload the fresh graph and both host-built lenses
44
+ // (decompose map_document + surfaces inventory + grouped surface_document) as
45
+ // one atomic bundle. Rails validates both documents, versions, and computes all
46
+ // digests; either lens failing rejects the whole bundle (spec 31).
45
47
  async putMapBuild(payload) {
46
48
  const res = await this.send('PUT', this.repoPath('map_build'), payload);
47
49
  await this.ensureOk(res, `PUT ${this.repoPath('map_build')}`);
48
50
  return (await res.json());
49
51
  }
50
- // GET /repos/:id/suite_packets — the host's assignment (the capabilities to
51
- // guard). Relayed opaque; 409 (no current map) surfaces as a WireError carrying
52
- // the server's "run /unitbob map first" guidance.
52
+ // GET /repos/:id/suite_packets — the two peer assignments (spec 32), exactly
53
+ // one per contract system. Relayed opaque; 409 (no current map) surfaces as a
54
+ // WireError carrying the server's "run the Unitbob map first" guidance.
55
+ async getSuitePacketsBatch() {
56
+ const res = await this.send('GET', this.repoPath('suite_packets'));
57
+ await this.ensureOk(res, `GET ${this.repoPath('suite_packets')}`);
58
+ const body = (await res.json());
59
+ if (!Array.isArray(body.suite_packets)) {
60
+ throw new WireError(`GET ${this.repoPath('suite_packets')} returned no suite_packets array.`);
61
+ }
62
+ return body.suite_packets;
63
+ }
64
+ // PUT /repos/:id/suite_builds — upload both peer branches in one batch (spec
65
+ // 32). Each item is validated and published independently; the response
66
+ // carries one result per suite_kind.
67
+ async putSuiteBuilds(items) {
68
+ const res = await this.send('PUT', this.repoPath('suite_builds'), { suite_builds: items });
69
+ await this.ensureOk(res, `PUT ${this.repoPath('suite_builds')}`);
70
+ const body = (await res.json());
71
+ if (!Array.isArray(body.results)) {
72
+ throw new WireError(`PUT ${this.repoPath('suite_builds')} returned no results array.`);
73
+ }
74
+ return body.results;
75
+ }
76
+ // GET /repos/:id/suites — both current suites (spec 32), exactly two peer
77
+ // items. A `ready` item carries its blob; a `not_built` item is skipped.
78
+ async getSuites() {
79
+ const res = await this.send('GET', this.repoPath('suites'));
80
+ await this.ensureOk(res, `GET ${this.repoPath('suites')}`);
81
+ const body = (await res.json());
82
+ if (!Array.isArray(body.suites)) {
83
+ throw new WireError(`GET ${this.repoPath('suites')} returned no suites array.`);
84
+ }
85
+ return body.suites;
86
+ }
87
+ // POST /repos/:id/runs/batch — ship each branch's raw report (or suite error)
88
+ // in one batch; the server parses each against the exact stored version and
89
+ // returns one summary per branch plus one shared map URL.
90
+ async postRunsBatch(runs) {
91
+ const res = await this.send('POST', this.repoPath('runs/batch'), { runs });
92
+ await this.ensureOk(res, `POST ${this.repoPath('runs/batch')}`);
93
+ const body = (await res.json());
94
+ if (!Array.isArray(body.results)) {
95
+ throw new WireError(`POST ${this.repoPath('runs/batch')} returned no results array.`);
96
+ }
97
+ return { results: body.results, map_url: String(body.map_url ?? '') };
98
+ }
99
+ // GET /repos/:id/contract_prompt?suite_digest=&test_id=&intent= — the one
100
+ // contract action operation for both maps and both intents (spec 32).
101
+ async getContractPrompt(suiteDigest, testId, intent) {
102
+ const query = new URLSearchParams({ suite_digest: suiteDigest, test_id: testId, intent });
103
+ const url = `${this.repoPath('contract_prompt')}?${query}`;
104
+ const res = await this.send('GET', url);
105
+ await this.ensureOk(res, `GET ${url}`);
106
+ return (await res.json());
107
+ }
108
+ // GET /repos/:id/suite_packets — the legacy singular assignment (spec 26),
109
+ // kept for the structural-only flow. Relayed opaque.
53
110
  async getSuitePackets() {
54
111
  const res = await this.send('GET', this.repoPath('suite_packets'));
55
112
  await this.ensureOk(res, `GET ${this.repoPath('suite_packets')}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unitbob",
3
- "version": "0.1.10",
3
+ "version": "0.2.0",
4
4
  "description": "Unitbob connector — thin local hands for the Unitbob Rails brain. Owns no domain logic: it runs tools, relays bytes over the wire, and prints what the server returns.",
5
5
  "type": "module",
6
6
  "bin": {