opencode-dev-framework 1.5.1 → 1.7.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/init.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Shared per-project setup flow: the `/df-init` server command and the
3
+ * `dev_framework_init` custom tool are two callers of one implementation.
4
+ * The deterministic half (scaffold templates, detected config, trial-run,
5
+ * brief) runs in code; the judgment half (resolve the brief, draft config
6
+ * + hardening, present the diff) rides back to the agent as prompt text.
7
+ *
8
+ * Note: `bin/df` intentionally keeps its own orchestration of the same
9
+ * installer primitives — the CLI prompts interactively on conflicts
10
+ * (TTY), while everything here is non-interactive by construction.
11
+ */
12
+ import type { RunCommand } from "./host.js";
13
+ export interface InitScaffoldOptions {
14
+ wizard?: boolean;
15
+ /** Rewrite files that differ from the templates (default: skip them). */
16
+ overwrite?: boolean;
17
+ }
18
+ export interface InitScaffold {
19
+ created: string[];
20
+ overwritten: string[];
21
+ skipped: string[];
22
+ configAction: string;
23
+ /** Trial-run lines (non-wizard) or wizard-brief lines, for the report. */
24
+ detailLines: string[];
25
+ /** True when this run changed anything (templates or config). */
26
+ fresh: boolean;
27
+ }
28
+ export declare function runInitScaffold(directory: string, run: RunCommand, options?: InitScaffoldOptions): Promise<InitScaffold>;
29
+ export declare function scaffoldReportLines(scaffold: InitScaffold, directory: string): string[];
30
+ /**
31
+ * Compose the prompt text the `/df-init` command submits back to the
32
+ * session. A fresh scaffold hands the agent the brief plus standing
33
+ * instructions; a re-run on an already-configured project reports
34
+ * status. Skipped files may be identical OR differing-but-preserved —
35
+ * the counts cannot tell them apart, so the status says so instead of
36
+ * claiming everything is current.
37
+ */
38
+ export declare function composeInitPrompt(scaffold: InitScaffold, directory: string, warnings?: string[]): string;
39
+ export interface InitCommandDeps {
40
+ directory: string;
41
+ run: RunCommand;
42
+ delivery: unknown;
43
+ /** Throws when the owning setup/state went stale mid-scaffold. */
44
+ checkAlive: () => void;
45
+ /** Reload the project config after scaffolding; throws on invalid config. */
46
+ reload: () => Promise<void>;
47
+ /** Deliver the handoff to the session; throws on transport failure. */
48
+ deliver: (text: string, delivery: unknown) => Promise<void>;
49
+ /** Side-channel observe (warn on reload failure). Never throws. */
50
+ note: (level: "warn", message: string, extra?: Record<string, unknown>) => Promise<void>;
51
+ }
52
+ /**
53
+ * Execute the `/df-init` command with injected dependencies (pure policy,
54
+ * testable without a plugin context). Scaffold first, re-check liveness
55
+ * across the long await (file IO + trial-runs), reload the just-written
56
+ * config, then deliver the handoff. A reload failure degrades to a
57
+ * warning inside the prompt — `/df-init` is the command you run to fix
58
+ * a broken setup, so it must not fail on exactly the broken setups.
59
+ * A delivery failure throws: the scaffold succeeded, only the handoff
60
+ * back failed, and the message says how to recover.
61
+ */
62
+ export declare function runInitCommand(deps: InitCommandDeps): Promise<void>;
package/dist/init.js ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Shared per-project setup flow: the `/df-init` server command and the
3
+ * `dev_framework_init` custom tool are two callers of one implementation.
4
+ * The deterministic half (scaffold templates, detected config, trial-run,
5
+ * brief) runs in code; the judgment half (resolve the brief, draft config
6
+ * + hardening, present the diff) rides back to the agent as prompt text.
7
+ *
8
+ * Note: `bin/df` intentionally keeps its own orchestration of the same
9
+ * installer primitives — the CLI prompts interactively on conflicts
10
+ * (TTY), while everything here is non-interactive by construction.
11
+ */
12
+ import { detectProject } from "./detect.js";
13
+ import { buildWizardBrief, formatBriefSkipped, formatTrialRun, formatWizardBrief, installTemplates, trialRunDetectedCommands, writeDetectedConfig, } from "./installer.js";
14
+ export async function runInitScaffold(directory, run, options = {}) {
15
+ const overwrite = options.overwrite ?? false;
16
+ const io = { overwriteExisting: overwrite, skipExisting: !overwrite };
17
+ const result = await installTemplates(directory, io);
18
+ const configResult = await writeDetectedConfig(directory, io);
19
+ const fresh = result.created.length > 0 ||
20
+ result.overwritten.length > 0 ||
21
+ configResult.action === "created" ||
22
+ configResult.action === "overwritten";
23
+ // Detail work runs only when something changed: rebuilding the wizard
24
+ // brief (detection + real command executions) on a no-op re-run would
25
+ // burn minutes to restate what the report already says. Non-wizard
26
+ // keeps its exact historical trigger (config created/overwritten).
27
+ const detailLines = [];
28
+ const wantDetail = options.wizard === true
29
+ ? fresh
30
+ : configResult.action === "created" || configResult.action === "overwritten";
31
+ if (wantDetail) {
32
+ if (options.wizard === true) {
33
+ try {
34
+ const brief = await buildWizardBrief(directory, run);
35
+ detailLines.push("", ...formatWizardBrief(brief));
36
+ }
37
+ catch (error) {
38
+ detailLines.push("", formatBriefSkipped(error));
39
+ }
40
+ }
41
+ else {
42
+ try {
43
+ const { commands } = detectProject(directory);
44
+ const trial = await trialRunDetectedCommands(directory, commands, run);
45
+ detailLines.push("", ...formatTrialRun(trial));
46
+ }
47
+ catch (error) {
48
+ detailLines.push("", `Trial-run: skipped (${error instanceof Error ? error.message : String(error)}) — verify commands manually`);
49
+ }
50
+ }
51
+ }
52
+ return {
53
+ created: result.created,
54
+ overwritten: result.overwritten,
55
+ skipped: result.skipped,
56
+ configAction: configResult.action,
57
+ detailLines,
58
+ fresh,
59
+ };
60
+ }
61
+ export function scaffoldReportLines(scaffold, directory) {
62
+ return [
63
+ `Installed opencode-dev-framework templates into ${directory}.`,
64
+ `Created: ${scaffold.created.length} file(s)`,
65
+ `Overwritten: ${scaffold.overwritten.length} file(s)`,
66
+ `Skipped: ${scaffold.skipped.length} file(s)`,
67
+ `Config: ${scaffold.configAction}`,
68
+ ...(scaffold.created.length > 0
69
+ ? ["", "Created files:", ...scaffold.created.map((f) => `- ${f}`)]
70
+ : []),
71
+ ...(scaffold.overwritten.length > 0
72
+ ? ["", "Overwritten files:", ...scaffold.overwritten.map((f) => `- ${f}`)]
73
+ : []),
74
+ ...scaffold.detailLines,
75
+ ...(!scaffold.fresh
76
+ ? ["", "Already configured: nothing changed, so no brief was rebuilt."]
77
+ : []),
78
+ ];
79
+ }
80
+ /**
81
+ * Compose the prompt text the `/df-init` command submits back to the
82
+ * session. A fresh scaffold hands the agent the brief plus standing
83
+ * instructions; a re-run on an already-configured project reports
84
+ * status. Skipped files may be identical OR differing-but-preserved —
85
+ * the counts cannot tell them apart, so the status says so instead of
86
+ * claiming everything is current.
87
+ */
88
+ export function composeInitPrompt(scaffold, directory, warnings = []) {
89
+ const warningLines = warnings.length > 0 ? [...warnings.map((w) => `Warning: ${w}`), ""] : [];
90
+ if (!scaffold.fresh) {
91
+ return [
92
+ `opencode-dev-framework is already set up in ${directory}: ` +
93
+ `config ${scaffold.configAction}, ${scaffold.skipped.length} template file(s) left untouched.`,
94
+ "Untouched means identical or differing-but-preserved — differing files were NOT refreshed.",
95
+ ...warningLines,
96
+ "Verify with /df-status and a small probe edit; change nothing unless the user asks.",
97
+ ].join("\n");
98
+ }
99
+ return [
100
+ ...scaffoldReportLines(scaffold, directory),
101
+ ...warningLines,
102
+ "",
103
+ "Set up opencode-dev-framework for this project from the report and brief above. " +
104
+ "Follow the project-config skill to resolve the open questions — ask at most 3 genuinely " +
105
+ "user-only questions, resolve the rest yourself by reading the repo and running the commands — " +
106
+ "then present .opencode-dev-framework.yml + hardening.md for review. Do not commit unreviewed.",
107
+ ].join("\n");
108
+ }
109
+ /**
110
+ * Execute the `/df-init` command with injected dependencies (pure policy,
111
+ * testable without a plugin context). Scaffold first, re-check liveness
112
+ * across the long await (file IO + trial-runs), reload the just-written
113
+ * config, then deliver the handoff. A reload failure degrades to a
114
+ * warning inside the prompt — `/df-init` is the command you run to fix
115
+ * a broken setup, so it must not fail on exactly the broken setups.
116
+ * A delivery failure throws: the scaffold succeeded, only the handoff
117
+ * back failed, and the message says how to recover.
118
+ */
119
+ export async function runInitCommand(deps) {
120
+ const scaffold = await runInitScaffold(deps.directory, deps.run, { wizard: true });
121
+ deps.checkAlive();
122
+ const warnings = [];
123
+ try {
124
+ await deps.reload();
125
+ }
126
+ catch (error) {
127
+ const detail = error instanceof Error ? error.message : String(error);
128
+ warnings.push(`the new config could not be reloaded (${detail}) — the session keeps its previous contract; restart or fix the config and re-run.`);
129
+ await deps.note("warn", "df-init scaffolded but the config could not be reloaded", {
130
+ directory: deps.directory,
131
+ error: detail,
132
+ });
133
+ }
134
+ const text = composeInitPrompt(scaffold, deps.directory, warnings);
135
+ try {
136
+ await deps.deliver(text, deps.delivery);
137
+ }
138
+ catch (error) {
139
+ const detail = error instanceof Error ? error.message : String(error);
140
+ throw new Error(`df-init scaffolded ${scaffold.created.length} file(s) (config ${scaffold.configAction}) ` +
141
+ `but the handoff back to the session failed (${detail}); retry /df-init — a re-run reports status without touching anything.`);
142
+ }
143
+ }
package/dist/logger.d.ts CHANGED
@@ -3,6 +3,15 @@
3
3
  */
4
4
  export type LogLevel = "debug" | "info" | "warn" | "error";
5
5
  export declare const LOG_SERVICE = "opencode-dev-framework";
6
+ /** Leaf directory/file for the default user-level log. */
7
+ export declare const LOG_DIR_NAME = "opencode-dev-framework";
8
+ export declare const LOG_FILE_NAME = "opencode-dev-framework.log";
9
+ /**
10
+ * Rotation cap: the active log never grows past this; one backup
11
+ * (`*.1`) is kept, so worst case is 2× cap. 5MB holds thousands of
12
+ * evaluations (lines are a few hundred bytes, summaries a few KB).
13
+ */
14
+ export declare const MAX_LOG_BYTES: number;
6
15
  export type LogFn = (level: LogLevel, message: string, extra?: Record<string, unknown>) => Promise<void>;
7
16
  type V1Client = {
8
17
  app?: {
@@ -16,6 +25,28 @@ type V1Client = {
16
25
  }) => Promise<unknown>;
17
26
  };
18
27
  };
28
+ export interface LogPathInput {
29
+ platform?: string;
30
+ env?: Record<string, string | undefined>;
31
+ home?: string | null;
32
+ tmp?: string;
33
+ }
34
+ /**
35
+ * Resolve the user-level default log file. Pure given explicit
36
+ * inputs (production passes the real ones). `null` only when no
37
+ * home directory is known AND tmp is unavailable — vanishingly
38
+ * rare; callers treat null as file-logging-off (stderr remains).
39
+ * Never inside the repo: a repo-local log would surface as an
40
+ * untracked changed file and poison the tracker.
41
+ */
42
+ export declare function resolveDefaultLogFile(input?: LogPathInput): string | null;
43
+ /**
44
+ * Rotate the active log past the cap: the previous backup is
45
+ * dropped, the active file becomes the backup, and appends start
46
+ * fresh. Concurrent writers can interleave stat/rename and lose a
47
+ * line — acceptable for a best-effort log, never for enforcement.
48
+ */
49
+ export declare function rotateLogFile(filePath: string, maxBytes: number): Promise<void>;
19
50
  /**
20
51
  * Create a logger. If a V1 client is provided, forwards to `client.app.log`
21
52
  * (as tests expect). Otherwise logs to stderr/file (V2 runtime).
package/dist/logger.js CHANGED
@@ -1,14 +1,115 @@
1
1
  /**
2
2
  * Structured logging wrapper. Supports both V1 (client.app.log) and V2 (stderr/file).
3
3
  */
4
- import { appendFile } from "node:fs/promises";
4
+ import { appendFile, mkdir, rename, rm, stat } from "node:fs/promises";
5
+ import { homedir, tmpdir } from "node:os";
6
+ import { dirname, isAbsolute, join } from "node:path";
5
7
  export const LOG_SERVICE = "opencode-dev-framework";
8
+ /** Leaf directory/file for the default user-level log. */
9
+ export const LOG_DIR_NAME = "opencode-dev-framework";
10
+ export const LOG_FILE_NAME = "opencode-dev-framework.log";
11
+ /**
12
+ * Rotation cap: the active log never grows past this; one backup
13
+ * (`*.1`) is kept, so worst case is 2× cap. 5MB holds thousands of
14
+ * evaluations (lines are a few hundred bytes, summaries a few KB).
15
+ */
16
+ export const MAX_LOG_BYTES = 5 * 1024 * 1024;
17
+ /**
18
+ * Resolve the user-level default log file. Pure given explicit
19
+ * inputs (production passes the real ones). `null` only when no
20
+ * home directory is known AND tmp is unavailable — vanishingly
21
+ * rare; callers treat null as file-logging-off (stderr remains).
22
+ * Never inside the repo: a repo-local log would surface as an
23
+ * untracked changed file and poison the tracker.
24
+ */
25
+ export function resolveDefaultLogFile(input = {}) {
26
+ const platform = input.platform ?? process.platform;
27
+ const env = input.env ?? process.env;
28
+ const home = input.home !== undefined ? input.home : safeHomedir();
29
+ if (platform === "win32") {
30
+ if (env.LOCALAPPDATA) {
31
+ return join(env.LOCALAPPDATA, LOG_DIR_NAME, LOG_FILE_NAME);
32
+ }
33
+ // No LOCALAPPDATA: fall through to tmp, not a Unix-style home path.
34
+ const winTmp = input.tmp ?? safeTmpdir();
35
+ return winTmp ? join(winTmp, LOG_DIR_NAME, LOG_FILE_NAME) : null;
36
+ }
37
+ if (platform === "darwin" && home) {
38
+ return join(home, "Library", "Logs", LOG_FILE_NAME);
39
+ }
40
+ if (home) {
41
+ // Empty counts as unset and relative as invalid (XDG basedir spec);
42
+ // either would otherwise land the log relative to CWD — possibly
43
+ // inside the repo, where it would poison the change tracker.
44
+ const xdg = env.XDG_DATA_HOME;
45
+ const base = xdg && isAbsolute(xdg) ? xdg : join(home, ".local", "share");
46
+ return join(base, LOG_DIR_NAME, LOG_FILE_NAME);
47
+ }
48
+ const tmp = input.tmp ?? safeTmpdir();
49
+ return tmp ? join(tmp, LOG_DIR_NAME, LOG_FILE_NAME) : null;
50
+ }
51
+ function safeHomedir() {
52
+ try {
53
+ return homedir();
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ function safeTmpdir() {
60
+ try {
61
+ return tmpdir();
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ /** Best-effort file write: creates the parent dir, rotates past the cap, never throws. */
68
+ async function appendLogFile(filePath, line, maxBytes = MAX_LOG_BYTES) {
69
+ try {
70
+ await mkdir(dirname(filePath), { recursive: true });
71
+ await rotateLogFile(filePath, maxBytes);
72
+ await appendFile(filePath, `${line}\n`);
73
+ }
74
+ catch {
75
+ // best-effort
76
+ }
77
+ }
78
+ /**
79
+ * Rotate the active log past the cap: the previous backup is
80
+ * dropped, the active file becomes the backup, and appends start
81
+ * fresh. Concurrent writers can interleave stat/rename and lose a
82
+ * line — acceptable for a best-effort log, never for enforcement.
83
+ */
84
+ export async function rotateLogFile(filePath, maxBytes) {
85
+ let size = 0;
86
+ try {
87
+ size = (await stat(filePath)).size;
88
+ }
89
+ catch {
90
+ return; // missing — nothing to rotate
91
+ }
92
+ if (size <= maxBytes)
93
+ return;
94
+ try {
95
+ await rm(`${filePath}.1`, { force: true });
96
+ await rename(filePath, `${filePath}.1`);
97
+ }
98
+ catch {
99
+ // best-effort
100
+ }
101
+ }
6
102
  /**
7
103
  * Create a logger. If a V1 client is provided, forwards to `client.app.log`
8
104
  * (as tests expect). Otherwise logs to stderr/file (V2 runtime).
9
105
  */
10
106
  export function createLogger(client) {
11
- const filePath = process.env.OPENCODE_DEV_FRAMEWORK_LOG_FILE;
107
+ // Explicit override wins (empty string disables file logging:
108
+ // the falsy filePath below skips all writes); otherwise a
109
+ // user-level default so the "loud" record exists without
110
+ // configuration. Resolved once: the path cannot change under
111
+ // a running server.
112
+ const filePath = process.env.OPENCODE_DEV_FRAMEWORK_LOG_FILE ?? resolveDefaultLogFile() ?? undefined;
12
113
  return async (level, message, extra) => {
13
114
  const line = JSON.stringify({
14
115
  timestamp: new Date().toISOString(),
@@ -33,12 +134,7 @@ export function createLogger(client) {
33
134
  }
34
135
  }
35
136
  if (filePath) {
36
- try {
37
- await appendFile(filePath, `${line}\n`);
38
- }
39
- catch {
40
- // best-effort
41
- }
137
+ await appendLogFile(filePath, line);
42
138
  }
43
139
  return;
44
140
  }
@@ -52,12 +148,7 @@ export function createLogger(client) {
52
148
  // ignore
53
149
  }
54
150
  if (filePath) {
55
- try {
56
- await appendFile(filePath, `${line}\n`);
57
- }
58
- catch {
59
- // best-effort
60
- }
151
+ await appendLogFile(filePath, line);
61
152
  }
62
153
  };
63
154
  }
@@ -0,0 +1,14 @@
1
+ /** Trimmed-character floor for a substantive review. */
2
+ export declare const REVIEW_MIN_CHARS = 200;
3
+ /** Whitespace-separated-token floor for a substantive review. */
4
+ export declare const REVIEW_MIN_WORDS = 30;
5
+ /** Review artifact state with substance gradations. */
6
+ export type ReviewState = "missing" | "empty" | "thin" | "template" | "present";
7
+ /**
8
+ * Assess already-read review content. Pure. Order matters: empty,
9
+ * then template markers (a short file with TODOs reports the more
10
+ * actionable reason), then length floors.
11
+ */
12
+ export declare function assessReviewContent(content: string): Exclude<ReviewState, "missing">;
13
+ export declare function thinReviewMessage(changedFiles: string[]): string;
14
+ export declare function templateReviewMessage(changedFiles: string[]): string;
package/dist/review.js ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Review substance (plan 17 §3).
3
+ *
4
+ * `artifactState()` accepts any non-empty file, so a five-word
5
+ * "looks good" checkboxes the `require_review` duty without doing
6
+ * it. These are the framework's contract for what counts as a
7
+ * review: long enough to hold scope, findings, and resolutions,
8
+ * with no leftover template scaffolding.
9
+ *
10
+ * Thresholds stay constants in code with tests, not user config —
11
+ * "what counts as a review" is a framework contract, not a
12
+ * per-project preference. Deliberate padding (`ok ok ok …` to the
13
+ * floor) is out of scope: nothing here stops deliberate sabotage,
14
+ * it only puts checkboxing on the record for honest-but-eager
15
+ * agents.
16
+ *
17
+ * The artifact path literal mirrors `REVIEW_ARTIFACT_REL` in
18
+ * `harness.ts` (kept inline to avoid a module cycle; both are
19
+ * pinned by tests).
20
+ */
21
+ const REVIEW_REL = ".opencode/opencode-dev-framework/review.md";
22
+ /** Trimmed-character floor for a substantive review. */
23
+ export const REVIEW_MIN_CHARS = 200;
24
+ /** Whitespace-separated-token floor for a substantive review. */
25
+ export const REVIEW_MIN_WORDS = 30;
26
+ /**
27
+ * Universal placeholder markers — editing conventions, not
28
+ * per-project vocabulary, so a single hardcoded list is safe.
29
+ * Short tokens use word boundaries so ordinary prose never trips
30
+ * them; all matched case-insensitively against the raw content.
31
+ */
32
+ const TEMPLATE_PATTERNS = [
33
+ /\btodo\b/i,
34
+ /\btbd\b/i,
35
+ /\bfixme\b/i,
36
+ /\bxxx\b/i,
37
+ /lorem ipsum/i,
38
+ /placeholder/i,
39
+ /\[insert/i,
40
+ /to be (filled|completed|determined)/i,
41
+ /\bfill in\b/i,
42
+ /unfilled/i,
43
+ ];
44
+ /**
45
+ * Assess already-read review content. Pure. Order matters: empty,
46
+ * then template markers (a short file with TODOs reports the more
47
+ * actionable reason), then length floors.
48
+ */
49
+ export function assessReviewContent(content) {
50
+ if (content.trim() === "")
51
+ return "empty";
52
+ if (TEMPLATE_PATTERNS.some((pattern) => pattern.test(content)))
53
+ return "template";
54
+ // Unfilled checklist scaffolding with nothing checked off.
55
+ if (/\[ \]/.test(content) && !/\[[xX]\]/.test(content))
56
+ return "template";
57
+ const words = content.trim().split(/\s+/).length;
58
+ if (content.trim().length < REVIEW_MIN_CHARS || words < REVIEW_MIN_WORDS)
59
+ return "thin";
60
+ return "present";
61
+ }
62
+ /** Guidance appended to thin/template summaries: what to write. */
63
+ function reviewCadenceReminder() {
64
+ return (`Before declaring done you must run the project's peer-review cadence: ` +
65
+ `style-enforcer on the changed files, then test-grounder (evidence: tests that ` +
66
+ `fail without the change, commands that actually pass), and code-reviewer / pattern-guardian ` +
67
+ `for correctness and drift. Resolve every blocking finding, then write a summary of the ` +
68
+ `review findings and their resolution to ${REVIEW_REL}.\n\n` +
69
+ `Investigation-only reviewers: do not ask them to edit product code.`);
70
+ }
71
+ export function thinReviewMessage(changedFiles) {
72
+ const files = changedFiles.map((f) => ` - ${f}`).join("\n");
73
+ return (`opencode-dev-framework completion gate — the peer-review artifact exists but has no ` +
74
+ `substance (under ${REVIEW_MIN_CHARS} characters / ${REVIEW_MIN_WORDS} words). ` +
75
+ `A checkbox note is not a review. This session changed files:\n${files}\n\n` +
76
+ `Rewrite ${REVIEW_REL} fresh for THIS session's changes — scope, findings, ` +
77
+ `and resolutions, in your own words.\n\n` +
78
+ reviewCadenceReminder());
79
+ }
80
+ export function templateReviewMessage(changedFiles) {
81
+ const files = changedFiles.map((f) => ` - ${f}`).join("\n");
82
+ return (`opencode-dev-framework completion gate — the peer-review artifact still contains ` +
83
+ `template placeholders or an unfilled checklist. Finish the review before declaring ` +
84
+ `done. This session changed files:\n${files}\n\n` +
85
+ `Rewrite ${REVIEW_REL} fresh for THIS session's changes — scope, findings, ` +
86
+ `and resolutions, with every placeholder replaced by real findings.\n\n` +
87
+ reviewCadenceReminder());
88
+ }
@@ -0,0 +1,26 @@
1
+ import type { ResolvedConfig } from "./types.js";
2
+ /** Stable header prefix identifying roster parts in the system prompt. */
3
+ export declare const ROSTER_MARKER = "## Session duties (opencode-dev-framework";
4
+ /** Max acceptance checks listed verbatim before collapsing to `+ N more`. */
5
+ export declare const MAX_ROSTER_ACCEPTANCE = 5;
6
+ /** Max command characters shown verbatim before truncation. */
7
+ export declare const MAX_ROSTER_COMMAND_LENGTH = 120;
8
+ /**
9
+ * Render the per-project duty roster for session-start legibility.
10
+ *
11
+ * Pure projection of `ResolvedConfig` to a short markdown checklist:
12
+ * which gate steps will run at idle, over what scope, whether the
13
+ * review artifact is required, and the block budget. Returns null
14
+ * only for `off` (no duties enforced). When nothing is configured
15
+ * the roster says so explicitly — "nothing will stop you" is itself
16
+ * legibility.
17
+ */
18
+ export declare function renderDutyRoster(config: ResolvedConfig): string | null;
19
+ /** True when the exact roster text is already present in the system parts. */
20
+ export declare function rosterPresent(parts: ReadonlyArray<{
21
+ text: string;
22
+ } | string>, roster: string): boolean;
23
+ /** Index of an existing roster part (by stable marker), or -1 when absent. */
24
+ export declare function findRosterIndex(parts: ReadonlyArray<{
25
+ text: string;
26
+ } | string>): number;
package/dist/roster.js ADDED
@@ -0,0 +1,99 @@
1
+ import { normalizeCommandMap } from "./command-utils.js";
2
+ import { REVIEW_ARTIFACT_REL } from "./harness.js";
3
+ /** Stable header prefix identifying roster parts in the system prompt. */
4
+ export const ROSTER_MARKER = "## Session duties (opencode-dev-framework";
5
+ /** Max acceptance checks listed verbatim before collapsing to `+ N more`. */
6
+ export const MAX_ROSTER_ACCEPTANCE = 5;
7
+ /** Max command characters shown verbatim before truncation. */
8
+ export const MAX_ROSTER_COMMAND_LENGTH = 120;
9
+ function truncateCommand(command) {
10
+ if (command.length <= MAX_ROSTER_COMMAND_LENGTH)
11
+ return command;
12
+ return `${command.slice(0, MAX_ROSTER_COMMAND_LENGTH - 1)}…`;
13
+ }
14
+ function describeLint(config) {
15
+ const { default: defaultLint, byExtension } = normalizeCommandMap(config.commands.lint);
16
+ const exts = Object.keys(byExtension);
17
+ if (defaultLint !== undefined && exts.length === 0) {
18
+ return `\`${truncateCommand(defaultLint)}\``;
19
+ }
20
+ if (defaultLint !== undefined && exts.length > 0) {
21
+ return `\`${truncateCommand(defaultLint)}\` + per-extension (${exts.sort().join(", ")})`;
22
+ }
23
+ if (exts.length > 0) {
24
+ return `per-extension (${exts.sort().join(", ")})`;
25
+ }
26
+ return null;
27
+ }
28
+ /**
29
+ * Render the per-project duty roster for session-start legibility.
30
+ *
31
+ * Pure projection of `ResolvedConfig` to a short markdown checklist:
32
+ * which gate steps will run at idle, over what scope, whether the
33
+ * review artifact is required, and the block budget. Returns null
34
+ * only for `off` (no duties enforced). When nothing is configured
35
+ * the roster says so explicitly — "nothing will stop you" is itself
36
+ * legibility.
37
+ */
38
+ export function renderDutyRoster(config) {
39
+ if (config.profile === "off")
40
+ return null;
41
+ const blockingNote = config.profile === "advisory" ? " (advisory — failures warn, never block)" : "";
42
+ const lines = [`${ROSTER_MARKER}, profile ${config.profile})${blockingNote}`];
43
+ lines.push("Before you finish, this will run:");
44
+ const steps = [];
45
+ if (config.gate.run_typecheck && config.commands.typecheck !== undefined) {
46
+ steps.push(`- [ ] typecheck: \`${truncateCommand(config.commands.typecheck)}\``);
47
+ }
48
+ if (config.gate.run_tests) {
49
+ const template = config.gate.scope === "changed" ? config.commands.test_changed : config.commands.test;
50
+ if (template !== undefined) {
51
+ steps.push(`- [ ] test (${config.gate.scope}): \`${truncateCommand(template)}\``);
52
+ }
53
+ }
54
+ if (config.gate.lint_changed) {
55
+ const lint = describeLint(config);
56
+ if (lint !== null) {
57
+ steps.push(`- [ ] lint changed files: ${lint}`);
58
+ }
59
+ }
60
+ const acceptance = config.gate.acceptance;
61
+ for (const check of acceptance.slice(0, MAX_ROSTER_ACCEPTANCE)) {
62
+ steps.push(`- [ ] acceptance:${check.name}: \`${truncateCommand(check.command)}\``);
63
+ }
64
+ if (acceptance.length > MAX_ROSTER_ACCEPTANCE) {
65
+ steps.push(`- [ ] + ${acceptance.length - MAX_ROSTER_ACCEPTANCE} more acceptance checks`);
66
+ }
67
+ if (config.gate.require_review) {
68
+ steps.push(`- [ ] review: write ${REVIEW_ARTIFACT_REL}`);
69
+ }
70
+ if (config.preflight.length > 0) {
71
+ const taskWord = config.preflight.length === 1 ? "task" : "tasks";
72
+ steps.push(`- [ ] preflight: complete ${config.preflight.length} ${taskWord} -> preflight.md before editing`);
73
+ }
74
+ if (steps.length === 0) {
75
+ lines.push("No checks configured — gate will skip.");
76
+ }
77
+ else {
78
+ lines.push(...steps);
79
+ }
80
+ const skipNote = config.gate.skip_unchanged
81
+ ? "Skips only when no files changed."
82
+ : "Runs even with no changed files.";
83
+ lines.push(`Budget: ${config.gate.max_blocks} blocks. ${skipNote}`);
84
+ return lines.join("\n");
85
+ }
86
+ /** True when the exact roster text is already present in the system parts. */
87
+ export function rosterPresent(parts, roster) {
88
+ return parts.some((part) => {
89
+ const text = typeof part === "string" ? part : part.text;
90
+ return text.includes(roster);
91
+ });
92
+ }
93
+ /** Index of an existing roster part (by stable marker), or -1 when absent. */
94
+ export function findRosterIndex(parts) {
95
+ return parts.findIndex((part) => {
96
+ const text = typeof part === "string" ? part : part.text;
97
+ return text.includes(ROSTER_MARKER);
98
+ });
99
+ }
@@ -0,0 +1,36 @@
1
+ import type { Profile, ResolvedConfig } from "./types.js";
2
+ /** Enforceable subset of the resolved config, snapshotted at session start. */
3
+ export interface EnforceableSnapshot {
4
+ profile: Profile;
5
+ runTypecheck: boolean;
6
+ runTests: boolean;
7
+ lintChanged: boolean;
8
+ requireReview: boolean;
9
+ blockOnFailure: boolean;
10
+ scope: "all" | "changed";
11
+ maxBlocks: number;
12
+ hasTypecheck: boolean;
13
+ hasTest: boolean;
14
+ hasTestChanged: boolean;
15
+ hasLint: boolean;
16
+ /** Acceptance check name → command. */
17
+ acceptance: Record<string, string>;
18
+ preflightCount: number;
19
+ }
20
+ /** Project the enforceable subset out of a resolved config. Pure. */
21
+ export declare function snapshotEnforceable(config: ResolvedConfig): EnforceableSnapshot;
22
+ /**
23
+ * Diff a session-start snapshot against the live config, returning one
24
+ * human-readable line per duty reduction. Empty means the contract is
25
+ * intact (or was only strengthened). Pure.
26
+ *
27
+ * Deliberate limitations:
28
+ * - Command *modifications* are not flagged — only removals. A changed
29
+ * command string cannot be judged statically.
30
+ * - Acceptance command edits for a retained name are not flagged, for
31
+ * the same reason; only removed names are.
32
+ * - A weakened profile reports as a single profile line; field-level
33
+ * cascades (e.g. `block_on_failure` flipping with the profile
34
+ * default) are suppressed as noise.
35
+ */
36
+ export declare function diffWeakening(before: EnforceableSnapshot, after: ResolvedConfig): string[];