development-companion 1.5.0 → 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/src/install.mjs CHANGED
@@ -8,9 +8,9 @@ import {
8
8
  symlinkSync,
9
9
  writeFileSync
10
10
  } from "node:fs";
11
- import { dirname, join, resolve } from "node:path";
11
+ import { basename, dirname, join, relative, resolve } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
- import { ROLE_DESCRIPTIONS } from "./content.mjs";
13
+ import { IMPLEMENTATION_ROLES, ROLE_DESCRIPTIONS } from "./content.mjs";
14
14
 
15
15
  const here = dirname(fileURLToPath(import.meta.url));
16
16
 
@@ -68,7 +68,7 @@ function copyDir(source, destination) {
68
68
  }
69
69
  }
70
70
 
71
- export function installSkills({ target, adapter, skills, mode = "copy", force = false }) {
71
+ export function installSkills({ target, adapter, skills, mode = "copy", force = false, dryRun = false }) {
72
72
  const results = [];
73
73
  for (const skill of skills) {
74
74
  const source = join(packageRoot(), "skills", skill);
@@ -82,18 +82,26 @@ export function installSkills({ target, adapter, skills, mode = "copy", force =
82
82
  results.push({ skill, status: "kept" });
83
83
  continue;
84
84
  }
85
+ if (dryRun) {
86
+ results.push({ skill, status: "would-overwrite" });
87
+ continue;
88
+ }
85
89
  rmSync(destination, { recursive: true, force: true });
86
90
  copySkill(source, destination, mode);
87
91
  results.push({ skill, status: "overwritten" });
88
92
  continue;
89
93
  }
94
+ if (dryRun) {
95
+ results.push({ skill, status: "would-install" });
96
+ continue;
97
+ }
90
98
  copySkill(source, destination, mode);
91
99
  results.push({ skill, status: "installed" });
92
100
  }
93
101
  return results;
94
102
  }
95
103
 
96
- export function installRoles({ target, roles, force = false }) {
104
+ export function installRoles({ target, roles, force = false, dryRun = false }) {
97
105
  const results = [];
98
106
  for (const role of roles) {
99
107
  const source = join(packageRoot(), "core", "roles", `${role}.md`);
@@ -106,6 +114,10 @@ export function installRoles({ target, roles, force = false }) {
106
114
  results.push({ role, status: "kept" });
107
115
  continue;
108
116
  }
117
+ if (dryRun) {
118
+ results.push({ role, status: existsSync(destination) ? "would-overwrite" : "would-install" });
119
+ continue;
120
+ }
109
121
  ensureDir(dirname(destination));
110
122
  copyFileSync(source, destination);
111
123
  results.push({ role, status: existsSync(destination) ? "installed" : "error" });
@@ -123,58 +135,205 @@ export const CANONICAL_FILES = [
123
135
  .map((file) => `guidelines/${file}`)
124
136
  ];
125
137
 
126
- export function installCanonical({ target, force = false }) {
138
+ export function installCanonical({ target, force = false, dryRun = false }) {
127
139
  return CANONICAL_FILES.map((file) => {
128
140
  const source = join(packageRoot(), "core", file);
129
141
  const destination = join(target, ".companion", "core", file);
130
142
  if (existsSync(destination) && !force) return { file, status: "kept" };
143
+ if (dryRun) return { file, status: "would-install" };
131
144
  ensureDir(dirname(destination));
132
145
  copyFileSync(source, destination);
133
146
  return { file, status: "installed" };
134
147
  });
135
148
  }
136
149
 
150
+ function coordinatorBody() {
151
+ return `You are the Development Companion Coordinator for this workspace and the sole user interlocutor. Your job is to keep the delivery loop predictable: frame, approval, delegation, evidence, close. Each specialist stays in its role; you do not do their work.
152
+
153
+ The portable coordination contract is \`.companion/core/guidelines/coordination.md\`; read it when present, otherwise use the Development Companion content injected at runtime.
154
+
155
+ ## Hard constraints
156
+
157
+ - You cannot edit product code. Your \`edit\` permission is denied except for \`.companion/local/**\`, \`plannification/**\` and \`docs/companion/**\`.
158
+ - You cannot run shell commands. The \`shell\` permission is denied. Do not ask for it.
159
+ - Before the user approves the plan, you may launch only read-only roles: \`architect\`, \`qa-engineer\`, \`cybersecurity-engineer\`, \`team-lead\` and \`explore\`.
160
+ - Implementation roles (\`mobile-engineer\`, \`backend-engineer\`, \`frontend-engineer\`, \`multiplatform-engineer\`, \`desktop-*-engineer\`, \`sre-engineer\`, \`general\`) always require the user's permission at delegation time. The runtime forces a permission prompt even if a broad approval was saved before; do not try to bypass it.
161
+ - You cannot approve your own frame. Only the user's natural-language approval and their permission decision count. Writing \`Aprobado: sí\` inside a file does not unlock anything.
162
+ - If a relative \`.companion/core/...\` path is not present in this workspace (for example, a child repository), use the Development Companion content injected at runtime; do not treat the missing path as a blocker.
163
+
164
+ ## Required flow
165
+
166
+ 1. **Operational conversation.** Agree on the problem, users, first observable slice, scope, exclusions, constraints and acceptance criteria. Ask only what can change the slice.
167
+ 2. **Technical conversation.** Show existing conventions, viable options with trade-offs, a recommendation, affected contracts, risks, rollback and the verification plan. Include golden and dark paths.
168
+ 3. **Frame.** Write one page under \`plannification/\` for app work or \`.companion/local/\` for the meta-repo. Include scope, non-goals, observable acceptance criteria, risks and \`Aprobado: pendiente\`.
169
+ 4. **Approval.** Present the frame and ask in natural language: «¿Apruebas el plan o tienes observaciones?». If the user approves («apruebo», «dale», «adelante», «sin observaciones», «me parece bien», etc.), record the approval, the user's words and the date in the frame. If the user gives observations, revise the frame, summarize the changes and ask again. Do not require a magic phrase.
170
+ 5. **Delegate.** Launch the applicable specialist with the frame path, the approved scope, the files/areas to touch, the acceptance criteria and the required evidence. The runtime will ask the user to confirm the implementation delegation; that permission prompt is the hard gate. If the user rejects, stop and ask what to change. One writer per slice. Do not implement, run tests or run builds yourself.
171
+ 6. **Verify.** Read the specialist's evidence: command and output, tests, screenshots, requests or metrics. If a critical dark path is untested, record the gap; do not call it a pass.
172
+ 7. **Close.** Report what shipped, what was verified, residual risks and the next slice. Do not claim "done", "tests pass" or "verified" without evidence.
173
+
174
+ ## Routing
175
+
176
+ | Work | Subagent |
177
+ |---|---|
178
+ | Architecture, boundaries, ADRs | \`architect\` |
179
+ | Threat model, security review | \`cybersecurity-engineer\` |
180
+ | Test strategy, QA, accessibility, load | \`qa-engineer\` |
181
+ | UX, UI, web frontend | \`frontend-engineer\` |
182
+ | API, data, auth, backend | \`backend-engineer\` |
183
+ | Android and Wear OS | \`mobile-engineer\` |
184
+ | Cross-platform core | \`multiplatform-engineer\` |
185
+ | Native desktop | \`desktop-*-engineer\` |
186
+ | Deploy, observability, secrets | \`sre-engineer\` |
187
+ | Second opinion on scope or sequencing | \`team-lead\` |
188
+
189
+ If no specialist fits, report the gap and ask the user how to proceed. Do not silently do the work yourself; you cannot edit product code.
190
+
191
+ ## Escape hatch
192
+
193
+ A session explicitly started with \`--agent build\` (or an explicit agent switch by the user) keeps the native Build tools for a routine, in-scope fix. That is an opt-out chosen by the user, not your default. Never switch yourself to \`build\` or ask the user to do it to bypass the gate.`;
194
+ }
195
+
137
196
  function bindingBody(role) {
197
+ if (role === "coordinator") return coordinatorBody();
138
198
  return `Read \`.companion/core/guidelines/coordination.md\`, \`.companion/core/process.md\`, \`.companion/core/principles.md\`, \`.companion/core/quality-gates.md\`, and \`.companion/roles/${role}.md\`. Load the role's referenced skills from \`.agents/skills/\` or \`.claude/skills/\`.
139
199
 
140
200
  ${role === "team-lead" ? "Act as a callable coordination advisor. " : ""}Do not subdelegate or contact the user directly. Return evidence and open questions to the primary agent.`;
141
201
  }
142
202
 
203
+ function readOnlyPermissions({ shellTests = false } = {}) {
204
+ const permissions = [
205
+ " - action: subagent",
206
+ ' resource: "*"',
207
+ " effect: deny",
208
+ " - action: edit",
209
+ ' resource: "*"',
210
+ " effect: deny",
211
+ " - action: edit",
212
+ ' resource: ".companion/local/**"',
213
+ " effect: allow",
214
+ " - action: edit",
215
+ ' resource: "**/.companion/local/**"',
216
+ " effect: allow",
217
+ " - action: edit",
218
+ ' resource: "plannification/**"',
219
+ " effect: allow",
220
+ " - action: edit",
221
+ ' resource: "**/plannification/**"',
222
+ " effect: allow",
223
+ " - action: shell",
224
+ ' resource: "*"',
225
+ " effect: deny"
226
+ ];
227
+ if (shellTests) {
228
+ permissions.push(
229
+ " - action: shell",
230
+ ' resource: "git status *"',
231
+ " effect: allow",
232
+ " - action: shell",
233
+ ' resource: "git diff *"',
234
+ " effect: allow",
235
+ " - action: shell",
236
+ ' resource: "git log *"',
237
+ " effect: allow",
238
+ " - action: shell",
239
+ ' resource: "./gradlew *test*"',
240
+ " effect: allow",
241
+ " - action: shell",
242
+ ' resource: "./gradlew *lint*"',
243
+ " effect: allow",
244
+ " - action: shell",
245
+ ' resource: "./gradlew *assemble*"',
246
+ " effect: allow",
247
+ " - action: shell",
248
+ ' resource: "npm test *"',
249
+ " effect: allow"
250
+ );
251
+ }
252
+ return permissions;
253
+ }
254
+
255
+ function coordinatorPermissions() {
256
+ const permissions = [
257
+ "permissions:",
258
+ " - action: edit",
259
+ ' resource: "*"',
260
+ " effect: deny",
261
+ " - action: edit",
262
+ ' resource: ".companion/local/**"',
263
+ " effect: allow",
264
+ " - action: edit",
265
+ ' resource: "**/.companion/local/**"',
266
+ " effect: allow",
267
+ " - action: edit",
268
+ ' resource: "plannification/**"',
269
+ " effect: allow",
270
+ " - action: edit",
271
+ ' resource: "**/plannification/**"',
272
+ " effect: allow",
273
+ " - action: edit",
274
+ ' resource: "docs/companion/**"',
275
+ " effect: allow",
276
+ " - action: edit",
277
+ ' resource: "**/docs/companion/**"',
278
+ " effect: allow",
279
+ " - action: shell",
280
+ ' resource: "*"',
281
+ " effect: deny",
282
+ " - action: subagent",
283
+ ' resource: "*"',
284
+ " effect: deny"
285
+ ];
286
+ for (const role of ["architect", "qa-engineer", "cybersecurity-engineer", "team-lead", "explore"]) {
287
+ permissions.push(" - action: subagent", ` resource: "${role}"`, " effect: allow");
288
+ }
289
+ for (const role of IMPLEMENTATION_ROLES) {
290
+ permissions.push(" - action: subagent", ` resource: "${role}"`, " effect: ask");
291
+ }
292
+ permissions.push(" - action: subagent", ' resource: "general"', " effect: ask");
293
+ return permissions;
294
+ }
295
+
143
296
  function openCodeBinding(role) {
297
+ const isCoordinator = role === "coordinator";
144
298
  const isLead = role === "team-lead";
145
- const mode = "subagent";
299
+ const isReadOnly = ["architect", "cybersecurity-engineer", "qa-engineer"].includes(role);
300
+ const mode = isCoordinator ? "primary" : "subagent";
146
301
  const body = bindingBody(role);
147
- const permissions = isLead
148
- ? [
149
- "permissions:",
150
- " - action: edit",
151
- ' resource: "*"',
152
- " effect: deny",
153
- " - action: edit",
154
- ' resource: ".companion/local/**"',
155
- " effect: allow",
156
- " - action: edit",
157
- ' resource: "**/.companion/local/**"',
158
- " effect: allow",
159
- " - action: edit",
160
- ' resource: "docs/companion/**"',
161
- " effect: allow",
162
- " - action: edit",
163
- ' resource: "**/docs/companion/**"',
164
- " effect: allow",
165
- " - action: shell",
166
- ' resource: "*"',
167
- " effect: deny",
168
- " - action: subagent",
169
- ' resource: "*"',
170
- " effect: deny"
171
- ]
172
- : [
173
- "permissions:",
174
- " - action: subagent",
175
- ' resource: "*"',
176
- " effect: deny"
177
- ];
302
+ const permissions = isCoordinator
303
+ ? coordinatorPermissions()
304
+ : isLead
305
+ ? [
306
+ "permissions:",
307
+ " - action: edit",
308
+ ' resource: "*"',
309
+ " effect: deny",
310
+ " - action: edit",
311
+ ' resource: ".companion/local/**"',
312
+ " effect: allow",
313
+ " - action: edit",
314
+ ' resource: "**/.companion/local/**"',
315
+ " effect: allow",
316
+ " - action: edit",
317
+ ' resource: "docs/companion/**"',
318
+ " effect: allow",
319
+ " - action: edit",
320
+ ' resource: "**/docs/companion/**"',
321
+ " effect: allow",
322
+ " - action: shell",
323
+ ' resource: "*"',
324
+ " effect: deny",
325
+ " - action: subagent",
326
+ ' resource: "*"',
327
+ " effect: deny"
328
+ ]
329
+ : isReadOnly
330
+ ? ["permissions:", ...readOnlyPermissions({ shellTests: role === "qa-engineer" })]
331
+ : [
332
+ "permissions:",
333
+ " - action: subagent",
334
+ ' resource: "*"',
335
+ " effect: deny"
336
+ ];
178
337
  const frontmatter = [
179
338
  "---",
180
339
  `description: ${ROLE_DESCRIPTIONS[role] ?? role}`,
@@ -206,16 +365,21 @@ ${bindingBody(role)}
206
365
  `;
207
366
  }
208
367
 
209
- export function installBindings({ target, adapter, roles, force = false }) {
368
+ export function installBindings({ target, adapter, roles, force = false, dryRun = false }) {
210
369
  if (!adapter.agentDir || !adapter.agentFormat) return [];
211
370
  const results = [];
212
371
  for (const role of roles) {
372
+ if (role === "coordinator" && adapter.name !== "opencode") continue;
213
373
  const name = adapter.agentFormat === "toml" ? `${role}.toml` : `${role}.md`;
214
374
  const destination = join(target, adapter.agentDir, name);
215
375
  if (existsSync(destination) && !force) {
216
376
  results.push({ role, status: "kept" });
217
377
  continue;
218
378
  }
379
+ if (dryRun) {
380
+ results.push({ role, status: existsSync(destination) ? "would-overwrite" : "would-install" });
381
+ continue;
382
+ }
219
383
  let body;
220
384
  if (adapter.name === "opencode") body = openCodeBinding(role);
221
385
  else if (adapter.name === "claude-code") body = claudeBinding(role);
@@ -227,23 +391,145 @@ export function installBindings({ target, adapter, roles, force = false }) {
227
391
  return results;
228
392
  }
229
393
 
230
- /**
231
- * Leave the harness default and existing configuration alone. The process is
232
- * installed as instructions, not as a replacement for the native Build agent.
233
- */
234
- export function writeOpenCodeConfig(target) {
235
- const existing = [
394
+ export const OPENCODE_INSTRUCTIONS = [
395
+ ".companion/core/process.md",
396
+ ".companion/core/principles.md",
397
+ ".companion/core/quality-gates.md",
398
+ ".companion/core/workflow.md",
399
+ ".companion/core/guidelines/coordination.md"
400
+ ];
401
+
402
+ const OPENCODE_REQUIRED_PERMISSIONS = [
403
+ { action: "shell", resource: "git push", effect: "deny" },
404
+ { action: "shell", resource: "git push *", effect: "deny" }
405
+ ];
406
+
407
+ const OPENCODE_EXPLORE_PERMISSIONS = [
408
+ { action: "shell", resource: "*", effect: "deny" }
409
+ ];
410
+
411
+ function parseJsonc(text) {
412
+ const clean = text
413
+ .replace(/("(?:\\.|[^"\\])*"|\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g,
414
+ (match) => (match.startsWith('"') ? match : ""))
415
+ .replace(/,\s*([}\]])/g, "$1");
416
+ return JSON.parse(clean);
417
+ }
418
+
419
+ function sameRule(left, right) {
420
+ return left?.action === right.action && left?.resource === right.resource && left?.effect === right.effect;
421
+ }
422
+
423
+ function mergeRules(existing, required) {
424
+ const rules = Array.isArray(existing) ? [...existing] : [];
425
+ for (const rule of required) {
426
+ if (!rules.some((candidate) => sameRule(candidate, rule))) rules.push(rule);
427
+ }
428
+ return rules;
429
+ }
430
+
431
+ function openCodeConfigPath(target) {
432
+ const candidates = [
236
433
  join(target, ".opencode", "opencode.json"),
237
434
  join(target, ".opencode", "opencode.jsonc"),
238
435
  join(target, "opencode.json"),
239
436
  join(target, "opencode.jsonc")
240
- ]
241
- .find((path) => existsSync(path));
242
- return { status: existing ? "kept" : "native default (no config written)", path: existing ?? "OpenCode default" };
437
+ ];
438
+ return candidates.find((path) => existsSync(path)) ?? join(target, "opencode.json");
439
+ }
440
+
441
+ function mergeOpenCodeConfig(current) {
442
+ const config = current && typeof current === "object" ? current : {};
443
+ config.$schema ??= "https://opencode.ai/config.json";
444
+ config.default_agent = "coordinator";
445
+ config.instructions = [...new Set([...(Array.isArray(config.instructions) ? config.instructions : []), ...OPENCODE_INSTRUCTIONS])];
446
+ config.permissions = mergeRules(config.permissions, OPENCODE_REQUIRED_PERMISSIONS);
447
+ config.agents = config.agents && typeof config.agents === "object" ? config.agents : {};
448
+ config.agents.explore = config.agents.explore && typeof config.agents.explore === "object"
449
+ ? config.agents.explore
450
+ : {};
451
+ config.agents.explore.permissions = mergeRules(
452
+ config.agents.explore.permissions,
453
+ OPENCODE_EXPLORE_PERMISSIONS
454
+ );
455
+ return config;
456
+ }
457
+
458
+ /**
459
+ * Install the OpenCode runtime contract:
460
+ * - default_agent=coordinator (the primary cannot edit product code or run shell);
461
+ * - the five canonical instruction files, so root sessions load them even without a plugin;
462
+ * - a global shell deny for git push;
463
+ * - read-only explore.
464
+ *
465
+ * The config is a mixed user file. Preserve unknown keys, merge arrays by adding only what is
466
+ * missing, and write a backup under .companion/local/ before replacing the file.
467
+ */
468
+ export function writeOpenCodeConfig(target, { dryRun = false } = {}) {
469
+ const configPath = openCodeConfigPath(target);
470
+ const existed = existsSync(configPath);
471
+ let current = null;
472
+ if (existed) {
473
+ try {
474
+ current = parseJsonc(readFileSync(configPath, "utf8"));
475
+ } catch (error) {
476
+ return {
477
+ status: "skipped",
478
+ path: relative(target, configPath),
479
+ reason: `cannot parse ${relative(target, configPath)}: ${error.message}`
480
+ };
481
+ }
482
+ }
483
+
484
+ const merged = mergeOpenCodeConfig(current);
485
+ const next = `${JSON.stringify(merged, null, 2)}\n`;
486
+ if (existed && readFileSync(configPath, "utf8") === next) {
487
+ return { status: "unchanged", path: relative(target, configPath) };
488
+ }
489
+
490
+ const status = existed ? "updated" : "created";
491
+ if (dryRun) return { status: `would-${status}`, path: relative(target, configPath) };
492
+
493
+ if (existed) {
494
+ const backup = join(target, ".companion", "local", `${basename(configPath)}.bak`);
495
+ writeText(backup, readFileSync(configPath, "utf8"));
496
+ }
497
+ writeText(configPath, next);
498
+ return { status, path: relative(target, configPath) };
499
+ }
500
+
501
+ export function installPlugin({ target, force = false, dryRun = false }) {
502
+ const source = join(packageRoot(), "adapters", "opencode", "plugin", "devcomp", "index.ts");
503
+ const destination = join(target, ".opencode", "plugins", "devcomp", "index.ts");
504
+ if (!existsSync(source)) return { plugin: "devcomp", status: "missing" };
505
+ if (existsSync(destination) && !force) return { plugin: "devcomp", status: "kept" };
506
+ if (dryRun) {
507
+ return { plugin: "devcomp", status: existsSync(destination) ? "would-overwrite" : "would-install" };
508
+ }
509
+ writeText(destination, readFileSync(source, "utf8"));
510
+ return { plugin: "devcomp", status: "installed" };
511
+ }
512
+
513
+ export function installGlobalPlugin({ home = process.env.HOME, force = false, dryRun = false } = {}) {
514
+ const source = join(packageRoot(), "adapters", "opencode", "plugin", "devcomp", "index.ts");
515
+ if (!home) return { plugin: "devcomp-global", status: "skipped", reason: "HOME is not set" };
516
+ const destination = join(home, ".config", "opencode", "plugins", "devcomp.ts");
517
+ if (!existsSync(source)) return { plugin: "devcomp-global", status: "missing" };
518
+ if (existsSync(destination) && !force) return { plugin: "devcomp-global", status: "kept", path: destination };
519
+ if (dryRun) {
520
+ return {
521
+ plugin: "devcomp-global",
522
+ status: existsSync(destination) ? "would-overwrite" : "would-install",
523
+ path: destination
524
+ };
525
+ }
526
+ writeText(destination, readFileSync(source, "utf8"));
527
+ return { plugin: "devcomp-global", status: "installed", path: destination };
243
528
  }
244
529
 
245
- export function writeManifest(target, manifest) {
530
+ export function writeManifest(target, manifest, { dryRun = false } = {}) {
246
531
  const path = join(target, ".companion", "config.json");
532
+ if (dryRun) return path;
247
533
  writeText(path, `${JSON.stringify(manifest, null, 2)}\n`);
248
534
  return path;
249
535
  }
package/src/rules.mjs CHANGED
@@ -3,11 +3,138 @@ import { basename, dirname, relative } from "node:path";
3
3
 
4
4
  export const START = "<!-- development-companion:start -->";
5
5
  export const END = "<!-- development-companion:end -->";
6
+ export const USER_GUIDING = "# User guiding";
7
+ export const MERGE_PENDING = "<!-- development-companion:merge-pending -->";
8
+ export const TEMPLATE_MARKER = /<!-- development-companion:template ([^\s]+) -->/;
6
9
 
7
10
  export function hasManagedBlock(content) {
8
11
  return content.includes(START) && content.includes(END);
9
12
  }
10
13
 
14
+ export function templateVersion(content) {
15
+ const match = content.match(TEMPLATE_MARKER);
16
+ return match ? match[1] : null;
17
+ }
18
+
19
+ export function classifyRules(content) {
20
+ if (!content || !content.trim()) return "absent";
21
+ const start = content.indexOf(START);
22
+ const end = content.indexOf(END);
23
+ if ((start === -1) !== (end === -1)) return "ambiguous";
24
+ if (start !== -1 && end !== -1) {
25
+ if (end < start) return "ambiguous";
26
+ return content.includes(USER_GUIDING) ? "managed" : "managed-no-guiding";
27
+ }
28
+ return content.includes(USER_GUIDING) ? "guiding-only" : "legacy";
29
+ }
30
+
31
+ export function extractUserGuiding(content) {
32
+ if (!content) return "";
33
+ const index = content.indexOf(USER_GUIDING);
34
+ if (index === -1) return "";
35
+ return content.slice(index + USER_GUIDING.length).replace(/^\s*\n/, "").trim();
36
+ }
37
+
38
+ function contentOutsideBlock(content) {
39
+ const start = content.indexOf(START);
40
+ const end = content.indexOf(END);
41
+ if (start === -1 || end === -1 || end < start) return content.trim();
42
+ const before = content.slice(0, start).trim();
43
+ const after = content.slice(end + END.length).trim();
44
+ return [before, after].filter(Boolean).join("\n\n");
45
+ }
46
+
47
+ export function composeAgentsFile({ block, userGuiding = "", mergeNotice = "" }) {
48
+ const guiding = userGuiding.trim() ||
49
+ "<!-- Project-specific instructions live here. Development Companion preserves this section on update. -->";
50
+ const notice = mergeNotice.trim() ? `${mergeNotice.trimEnd()}\n\n` : "";
51
+ return `${notice}${block.trimEnd()}\n\n${USER_GUIDING}\n\n${guiding}\n`;
52
+ }
53
+
54
+ export function mergeNotice(backupPath = "AGENTS.md.bak") {
55
+ return `${MERGE_PENDING}
56
+ # Project rules merge pending
57
+
58
+ The previous \`AGENTS.md\` is backed up at \`${backupPath}\`.
59
+
60
+ Next agent session:
61
+
62
+ 1. Read \`${backupPath}\` and the Development Companion template in this file.
63
+ 2. Merge the project-specific instructions into the \`${USER_GUIDING}\` section below.
64
+ 3. Preserve the original intent, language, and tone. Do not discard rules.
65
+ 4. Remove this notice, then run \`devcomp doctor\`.
66
+
67
+ Do not commit this file until the merge is complete and \`doctor\` passes.
68
+ `;
69
+ }
70
+
71
+ export function applyAgentsFile({ filePath, block, mode = "update", backupPath = "AGENTS.md.bak", force = false, dryRun = false }) {
72
+ const current = existsSync(filePath) ? readFileSync(filePath, "utf8") : null;
73
+ const kind = classifyRules(current);
74
+
75
+ if (mode === "keep") {
76
+ return { mode: "kept", changed: false, kind, backupPath: null };
77
+ }
78
+
79
+ if (current && current.includes(MERGE_PENDING) && !["handoff", "replace"].includes(mode)) {
80
+ return { mode: "blocked", changed: false, kind, reason: "merge pending; resolve the backup before updating" };
81
+ }
82
+
83
+ if (mode === "replace" && !force) {
84
+ return { mode: "blocked", changed: false, kind, reason: "replace requires --force" };
85
+ }
86
+
87
+ let next;
88
+ let resultMode;
89
+ let guiding = "";
90
+
91
+ if (mode === "handoff") {
92
+ guiding = kind === "managed" || kind === "managed-no-guiding"
93
+ ? extractUserGuiding(current) || contentOutsideBlock(current)
94
+ : current || "";
95
+ next = composeAgentsFile({ block, userGuiding: guiding, mergeNotice: mergeNotice(backupPath) });
96
+ resultMode = "merge-pending";
97
+ } else if (mode === "replace") {
98
+ next = composeAgentsFile({ block });
99
+ resultMode = "replaced";
100
+ } else if (kind === "absent") {
101
+ next = composeAgentsFile({ block });
102
+ resultMode = "created";
103
+ } else if (kind === "managed" || kind === "managed-no-guiding") {
104
+ guiding = extractUserGuiding(current) || contentOutsideBlock(current);
105
+ next = composeAgentsFile({ block, userGuiding: guiding });
106
+ resultMode = "updated";
107
+ } else if (kind === "guiding-only") {
108
+ guiding = extractUserGuiding(current);
109
+ next = composeAgentsFile({ block, userGuiding: guiding });
110
+ resultMode = "migrated";
111
+ } else if (kind === "legacy") {
112
+ guiding = current;
113
+ next = composeAgentsFile({ block, userGuiding: guiding });
114
+ resultMode = "migrated";
115
+ } else {
116
+ guiding = current || "";
117
+ next = composeAgentsFile({ block, userGuiding: guiding, mergeNotice: mergeNotice(backupPath) });
118
+ resultMode = "merge-pending";
119
+ }
120
+
121
+ if (next === current) {
122
+ return { mode: "unchanged", changed: false, kind, backupPath: current && current.includes(MERGE_PENDING) ? backupPath : null };
123
+ }
124
+
125
+ if (dryRun) {
126
+ return { mode: resultMode, changed: true, kind, backupPath: current ? backupPath : null, dryRun: true };
127
+ }
128
+
129
+ if (current) {
130
+ mkdirSync(dirname(backupPath), { recursive: true });
131
+ writeFileSync(backupPath, current, "utf8");
132
+ }
133
+ mkdirSync(dirname(filePath), { recursive: true });
134
+ writeFileSync(filePath, next, "utf8");
135
+ return { mode: resultMode, changed: true, kind, backupPath: current ? backupPath : null };
136
+ }
137
+
11
138
  export function renderTemplate(template, context) {
12
139
  return template.replace(/\{\{([a-zA-Z0-9_-]+)\}\}/g, (_, key) =>
13
140
  context[key] === undefined ? `{{${key}}}` : String(context[key])
@@ -28,16 +155,16 @@ export function appendBlock(content, block) {
28
155
  return `${trimmed}\n\n${block}\n`;
29
156
  }
30
157
 
31
- function mergeNotice(filePath, backupPath) {
158
+ function legacyMergeNotice(filePath, backupPath) {
32
159
  return `# Project rules merge pending\n\nThe original AGENTS.md is backed up at \`${relative(dirname(filePath), backupPath)}\`. Before coding, compare it with this file and merge business rules, commands, tools and constraints into one coherent AGENTS.md. Preserve both sets of requirements; resolve conflicts with the user. Remove this notice only after reviewing the backup. Do not commit this pending file or its local backup: the original rules would be absent on other machines.\n\n`;
33
160
  }
34
161
 
35
- export function applyRules({ filePath, mode, block, force = false, backupPath }) {
162
+ export function applyRules({ filePath, mode, block, force = false, backupPath, dryRun = false }) {
36
163
  block = block.trimEnd();
37
164
  const exists = existsSync(filePath);
38
165
  if (!exists) {
39
- writeFileSync(filePath, `${block}\n`, "utf8");
40
- return { mode: "created", changed: true, reason: "file did not exist" };
166
+ if (!dryRun) writeFileSync(filePath, `${block}\n`, "utf8");
167
+ return { mode: "created", changed: true, reason: dryRun ? "would create" : "file did not exist" };
41
168
  }
42
169
 
43
170
  const current = readFileSync(filePath, "utf8");
@@ -52,9 +179,10 @@ export function applyRules({ filePath, mode, block, force = false, backupPath })
52
179
  if (existsSync(backupPath) && readFileSync(backupPath, "utf8") !== current) {
53
180
  return { mode: "error", changed: false, reason: "backup differs; merge existing backup before retrying" };
54
181
  }
182
+ if (dryRun) return { mode: "handoff", changed: true, reason: "would back up original; agent merge pending" };
55
183
  mkdirSync(dirname(backupPath), { recursive: true });
56
184
  if (!existsSync(backupPath)) writeFileSync(backupPath, current, { encoding: "utf8", flag: "wx" });
57
- writeFileSync(filePath, `${mergeNotice(filePath, backupPath)}${block}\n`, "utf8");
185
+ writeFileSync(filePath, `${legacyMergeNotice(filePath, backupPath)}${block}\n`, "utf8");
58
186
  return { mode: "handoff", changed: true, reason: "original backed up; agent merge pending" };
59
187
  }
60
188
 
@@ -66,9 +194,10 @@ export function applyRules({ filePath, mode, block, force = false, backupPath })
66
194
  if (existsSync(backupPath) && readFileSync(backupPath, "utf8") !== current) {
67
195
  return { mode: "error", changed: false, reason: "backup differs; merge existing backup before retrying" };
68
196
  }
197
+ if (dryRun) return { mode: "replaced", changed: true, reason: "would back up original and replace rules" };
69
198
  mkdirSync(dirname(backupPath), { recursive: true });
70
199
  if (!existsSync(backupPath)) writeFileSync(backupPath, current, { encoding: "utf8", flag: "wx" });
71
- writeFileSync(filePath, `${basename(filePath) === "AGENTS.md" ? mergeNotice(filePath, backupPath) : ""}${block}\n`, "utf8");
200
+ writeFileSync(filePath, `${basename(filePath) === "AGENTS.md" ? legacyMergeNotice(filePath, backupPath) : ""}${block}\n`, "utf8");
72
201
  return { mode: "replaced", changed: true, reason: `original backed up at ${relative(dirname(filePath), backupPath)}` };
73
202
  }
74
203
 
@@ -82,6 +211,7 @@ export function applyRules({ filePath, mode, block, force = false, backupPath })
82
211
  if (next === current) {
83
212
  return { mode: "appended", changed: false, reason: "already up to date" };
84
213
  }
214
+ if (dryRun) return { mode: "appended", changed: true, reason: hasManagedBlock(current) ? "would update block" : "would append block" };
85
215
  writeFileSync(filePath, next, "utf8");
86
216
  return { mode: "appended", changed: true, reason: hasManagedBlock(current) ? "block updated" : "block appended" };
87
217
  }