opencode-dev-framework 1.1.0 → 1.3.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.
package/dist/installer.js CHANGED
@@ -2,7 +2,8 @@ import { promises as fs } from "node:fs";
2
2
  import { dirname, join, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { createInterface } from "node:readline";
5
- import { DEFAULT_PROTECT } from "./config.js";
5
+ import { splitCommand } from "./command-utils.js";
6
+ import { checkConfigEnforceable, DEFAULT_PROTECT, resolveConfig } from "./config.js";
6
7
  import { detectProject } from "./detect.js";
7
8
  /** Directory containing the project templates shipped with the package. */
8
9
  export const TEMPLATES_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "templates");
@@ -271,10 +272,188 @@ export async function writeDetectedConfig(targetDir, options = {}) {
271
272
  }
272
273
  return { action: "skipped" };
273
274
  }
275
+ /** Bounded trial-run timeout (seconds): init UX, not a gate suite. */
276
+ export const TRIAL_RUN_TIMEOUT_SECONDS = 120;
277
+ /**
278
+ * Run each runnable detected command once to verify the guess (plan 15).
279
+ * Only `test`/`typecheck` run bare — lint/format templates carry
280
+ * `{file}`/`{dir}` placeholders and are reported as unverified by the
281
+ * caller skipping them (absent or empty commands are skipped, not failed).
282
+ * The two trials run concurrently; each is bounded by `timeout` seconds.
283
+ * Report-only by construction: results annotate, never throw — including
284
+ * for runners that reject despite the host never-rejects contract.
285
+ */
286
+ export async function trialRunDetectedCommands(directory, commands, run, opts = {}) {
287
+ const entries = [
288
+ ["test", commands.test],
289
+ ["typecheck", commands.typecheck],
290
+ ];
291
+ const runnable = [];
292
+ for (const [name, template] of entries) {
293
+ if (typeof template === "string" && template !== "")
294
+ runnable.push({ name, command: template });
295
+ }
296
+ return Promise.all(runnable.map(async ({ name, command }) => {
297
+ const started = Date.now();
298
+ let result;
299
+ try {
300
+ result = await run(splitCommand(command), {
301
+ cwd: directory,
302
+ timeout: opts.timeout ?? TRIAL_RUN_TIMEOUT_SECONDS,
303
+ });
304
+ }
305
+ catch (error) {
306
+ return {
307
+ name,
308
+ command,
309
+ ok: false,
310
+ exitCode: 127,
311
+ timedOut: false,
312
+ durationMs: Date.now() - started,
313
+ error: error instanceof Error ? error.message : String(error),
314
+ };
315
+ }
316
+ return {
317
+ name,
318
+ command,
319
+ ok: result.exitCode === 0 && !result.timedOut,
320
+ exitCode: result.exitCode,
321
+ timedOut: result.timedOut,
322
+ durationMs: Date.now() - started,
323
+ };
324
+ }));
325
+ }
326
+ /** Render trial-run results as CLI/tool output lines. */
327
+ export function formatTrialRun(results) {
328
+ if (results.length === 0) {
329
+ return ["Trial-run: no runnable commands detected — verify manually."];
330
+ }
331
+ return [
332
+ "Trial-run:",
333
+ ...results.map((r) => {
334
+ const secs = (r.durationMs / 1000).toFixed(1);
335
+ if (r.error !== undefined) {
336
+ return ` ${r.name} (${r.command}): ERROR (${r.error}) — verify this command`;
337
+ }
338
+ const status = r.ok ? "PASS" : `FAIL (exit ${r.exitCode}${r.timedOut ? ", timed out" : ""})`;
339
+ const suffix = r.ok ? "" : " — verify this command";
340
+ return ` ${r.name} (${r.command}): ${status} (${secs}s)${suffix}`;
341
+ }),
342
+ ];
343
+ }
274
344
  /** Resolve a user-supplied directory (default cwd) to an absolute path. */
275
345
  export function resolveTargetDir(dir) {
276
346
  return resolve(dir ?? process.cwd());
277
347
  }
348
+ /**
349
+ * List Makefile target names (plan 16). Names only, no semantics: the
350
+ * agent decides which (if any) are canonical wrappers. Capped at 30.
351
+ * Grouped targets (`lint test: deps`) split into both names; pattern
352
+ * rules, dot-directives, assignments, and make keywords never match.
353
+ * Probes GNUmakefile/makefile/Makefile in GNU make precedence order.
354
+ * Empty when no makefile exists or none is readable — report-only.
355
+ */
356
+ export async function listMakefileTargets(directory) {
357
+ let content = null;
358
+ for (const name of ["GNUmakefile", "makefile", "Makefile"]) {
359
+ try {
360
+ content = await fs.readFile(join(directory, name), "utf8");
361
+ break;
362
+ }
363
+ catch {
364
+ // Not present or unreadable — try the next name.
365
+ }
366
+ }
367
+ if (content === null)
368
+ return [];
369
+ const keywords = /^(export|unexport|override|define|endef|ifeq|ifneq|ifdef|ifndef|else|endif|include|-include|sinclude)$/;
370
+ const namePattern = /^[A-Za-z0-9_][A-Za-z0-9_.%-]*$/;
371
+ const targets = [];
372
+ for (const line of content.split("\n")) {
373
+ // Leading char excludes comments, recipes, dot-directives, and `%`
374
+ // pattern rules; `[^:=]` keeps the match left of any assignment.
375
+ const match = /^([^:#=\s][^:=]*?)\s*:(?!=)/.exec(line);
376
+ if (match === null)
377
+ continue;
378
+ for (const token of match[1].split(/\s+/)) {
379
+ if (!namePattern.test(token) || keywords.test(token) || targets.includes(token))
380
+ continue;
381
+ targets.push(token);
382
+ if (targets.length >= 30)
383
+ break;
384
+ }
385
+ if (targets.length >= 30)
386
+ break;
387
+ }
388
+ return targets;
389
+ }
390
+ /**
391
+ * Build the agent-handoff brief (plan 16): detection, trial-run, Makefile
392
+ * target names, and the shared enforceability verdict in one bundle. The
393
+ * LLM session agent is the wizard's presenter — this is the machine side,
394
+ * hints only, and the project-config skill still verifies everything by
395
+ * running. Trial/target failures annotate, never throw; a nonexistent
396
+ * directory rejects via detection, so both callers isolate the brief in
397
+ * try/catch (see `formatBriefSkipped`).
398
+ */
399
+ export async function buildWizardBrief(directory, run, opts = {}) {
400
+ const { language, commands } = detectProject(directory);
401
+ const [trial, makeTargets] = await Promise.all([
402
+ trialRunDetectedCommands(directory, commands, run, opts),
403
+ listMakefileTargets(directory),
404
+ ]);
405
+ const enforceability = checkConfigEnforceable(resolveConfig({ profile: "standard", commands }));
406
+ const questions = [];
407
+ if (makeTargets.length > 0) {
408
+ const shown = makeTargets.slice(0, 8).join(", ");
409
+ questions.push(`Makefile targets detected (${shown}${makeTargets.length > 8 ? ", …" : ""}) — ` +
410
+ "do canonical wrappers (e.g. make check/test/lint) replace the guessed bare commands?");
411
+ }
412
+ for (const t of trial) {
413
+ if (t.ok || questions.length >= 3)
414
+ continue;
415
+ questions.push(`Trial-run flagged ${t.name} (${t.command}) — verify the real command before trusting the guess.`);
416
+ }
417
+ if (enforceability.ok === false && questions.length < 3) {
418
+ questions.push(`Draft is not enforceable: ${enforceability.error}`);
419
+ }
420
+ return {
421
+ language,
422
+ commands,
423
+ trial,
424
+ makeTargets,
425
+ enforceability,
426
+ questions: questions.slice(0, 3),
427
+ };
428
+ }
429
+ /** Shared report-only fallback when the brief itself cannot be built. */
430
+ export function formatBriefSkipped(error) {
431
+ const detail = error instanceof Error ? error.message : String(error);
432
+ return `Wizard brief: skipped (${detail}) — verify commands manually`;
433
+ }
434
+ /** Render the wizard brief as CLI/tool output lines, ending in the handoff. */
435
+ export function formatWizardBrief(brief) {
436
+ const guessed = `Guessed commands: test=${brief.commands.test ?? "(none)"}, typecheck=${brief.commands.typecheck ?? "(none)"}`;
437
+ const lines = [
438
+ "Wizard brief (machine-generated hints — verify by running, see the project-config skill):",
439
+ `Detected language: ${brief.language ?? "(unknown)"}`,
440
+ guessed,
441
+ ...formatTrialRun(brief.trial),
442
+ brief.makeTargets.length > 0
443
+ ? `Makefile targets: ${brief.makeTargets.join(", ")}`
444
+ : "Makefile targets: (none — no Makefile)",
445
+ brief.enforceability.ok
446
+ ? "Enforceability: draft passes the shared bar (blocking profile + real checks)."
447
+ : `Enforceability: FAIL — ${brief.enforceability.error}`,
448
+ ];
449
+ if (brief.questions.length > 0) {
450
+ lines.push("Open questions (at most 3):", ...brief.questions.map((q, i) => ` ${i + 1}. ${q}`));
451
+ }
452
+ lines.push("", "Handoff: follow the project-config skill (templates/.opencode/skills/project-config/SKILL.md) " +
453
+ "to resolve the questions above, run the real commands, and present " +
454
+ ".opencode-dev-framework.yml + hardening.md for review. Do not write without review.");
455
+ return lines;
456
+ }
278
457
  /**
279
458
  * Set the top-level `profile:` key in a config file. Edits the raw text
280
459
  * instead of re-serializing the YAML so user comments and formatting survive.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,101 @@
1
+ ---
2
+ name: project-config
3
+ description: >
4
+ Draft an opencode-dev-framework configuration for the current project:
5
+ read its build files and CI, map the real verification commands, and
6
+ propose the yml plus a hardening draft for user review. Use when setting
7
+ up the plugin on a new project instead of hand-writing the config.
8
+ ---
9
+
10
+ # Project Configuration
11
+
12
+ Write the plugin config the project deserves — derived from its actual
13
+ build system, not guessed. You propose; the user disposes.
14
+
15
+ ## When to use
16
+
17
+ Setting up the plugin on a project for the first time, instead of
18
+ hand-writing `.opencode-dev-framework.yml` or trusting `df init`
19
+ detection alone. Also when the existing config smells wrong — gate
20
+ passing vacuously, commands that don't match CI, a red tree nobody can
21
+ explain.
22
+
23
+ ## Wizard brief (when `df init --wizard` ran first)
24
+
25
+ The brief hands you machine-generated hints: detected language, guessed
26
+ commands with trial-run results, Makefile target names, the shared
27
+ enforceability verdict, and at most 3 open questions. Treat it as a
28
+ starting brief, not findings:
29
+
30
+ + Re-run every command yourself before trusting it — trial results go
31
+ stale, and a PASS can still hide a semantic gap (e.g. a typecheck
32
+ that skips generated artifacts).
33
+ + The Makefile target list is names only; you decide which are
34
+ canonical wrappers.
35
+ + Answer the brief's questions first, then do your own pass — the
36
+ brief doesn't know about CI tiebreakers or env-gated suites.
37
+
38
+ Interaction budget: resolve everything resolvable yourself; come back
39
+ with the review diff plus at most 3 questions, all genuinely
40
+ user-only. Never interrogate mid-run — proceed on safe defaults and
41
+ list assumptions.
42
+
43
+ ## Steps
44
+
45
+ 1. **Read the build truth, in authority order.** CI workflow first (it is
46
+ the tiebreaker when scripts disagree), then the build files for the
47
+ project's ecosystem — `Makefile`, `package.json` scripts, `go.mod`
48
+ toolchains, `pyproject.toml` / `tox.ini` / `noxfile.py`, `Cargo.toml`
49
+ + `.cargo/config.toml`, `pom.xml` / `build.gradle(.kts)`, `Rakefile`,
50
+ `composer.json`, `CMakeLists.txt` (+ CTest), Bazel (`BUILD`,
51
+ `WORKSPACE`, `MODULE.bazel`), `meson.build`, `SConstruct` — then
52
+ CONTRIBUTING and existing lint configs. (`build.ninja` is generated
53
+ output; find what generates it instead of reading it.) You are
54
+ looking for: the full verification command(s), per-language
55
+ lint/format invocations, integration tests with special needs (docker,
56
+ network, credentials), generated assets and how they rebuild, and
57
+ paths that must never be edited.
58
+
59
+ 2. **Prefer wrappers over bare tools.** If the project verifies via
60
+ `make check`, `npm run verify`, or a CI job, the config's `commands`
61
+ must invoke the wrapper — never reconstruct it from bare tool calls
62
+ that skip steps. Note ordering traps (generated code must rebuild
63
+ before typecheck; lint before test when the suite counts warnings).
64
+
65
+ 3. **Place what doesn't fit unit scope in `gate.acceptance`.**
66
+ Integration suites, contract tests, docs lint, vulnerability scans —
67
+ each as a named acceptance check with its real command.
68
+
69
+ 4. **Draft `hardening.md`** from what you observed, in the five sections
70
+ from `docs/user/hardening.md`: the project way to build, full
71
+ verification before done, fresh review cadence, scope discipline,
72
+ executing plans under `/df-goal`. Exact commands and paths. No vague
73
+ injunctions ("be thorough") — those get interpreted minimally.
74
+
75
+ 5. **Self-check before presenting.** The draft must satisfy the
76
+ enforceability bar: a blocking profile (`standard`/`strict`, i.e.
77
+ `gate.block_on_failure: true`) and at least one real check
78
+ (typecheck/test command, changed-file lint, non-empty
79
+ `gate.acceptance`, or `gate.require_review`). A draft with none of
80
+ these is vacuous — fix it, don't present it.
81
+
82
+ 6. **Present the full diff for review. Never write without review, never
83
+ commit.** The user owns the merge. Say plainly which commands you
84
+ verified by running, which you inferred from files, and which need
85
+ the user's confirmation.
86
+
87
+ ## Output
88
+
89
+ + The proposed `.opencode-dev-framework.yml` and `hardening.md` content
90
+ as a reviewable diff, each command annotated verified-by-running,
91
+ inferred-from-files, or needs-confirmation.
92
+ + The enforceability self-check result (blocking profile + at least one
93
+ real check, or the deficiencies fixed before presenting).
94
+
95
+ ## What stays out
96
+
97
+ + Secrets, tokens, internal URLs, customer names — the config and the
98
+ hardening file are designed to be committable.
99
+ + Anything the gate already enforces (don't restate the config inside
100
+ the hardening file).
101
+ + Auto-commit. The skill ends at the reviewed diff.