gabbe-kit 1.0.2 → 1.1.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/scripts/init.py CHANGED
@@ -15,6 +15,113 @@ SOURCE_AGENTS_DIR = KIT_SOURCE / "agents"
15
15
  # PROJECT_ROOT: Where the user is running the script from (the project they want to configure)
16
16
  PROJECT_ROOT = Path.cwd()
17
17
 
18
+ # FORCE: when True, re-template even preserve-set files (still backed up first).
19
+ # Set from the --force CLI flag in main(). Default False = never overwrite user files.
20
+ FORCE = False
21
+
22
+ # --- Install manifest recorder ---------------------------------------------
23
+ # The wizard records everything it creates under PROJECT_ROOT into
24
+ # `.gabbe/manifest.json` (the same schema gabbe/installer.py reads), so that
25
+ # `gabbe uninstall` can fully reverse a wizard install — symlinks, generated
26
+ # trees, config files and copied kit files alike. Paths outside PROJECT_ROOT
27
+ # (e.g. a global `~/agents` install) cannot live in a project manifest and are
28
+ # skipped; their wiring under PROJECT_ROOT is still recorded and reversible.
29
+ MANIFEST_SCHEMA_VERSION = 1
30
+ _MANIFEST_ENTRIES: list[dict] = []
31
+ _RECORDED_PATHS: set[str] = set()
32
+
33
+
34
+ def _rel_to_project(path):
35
+ """Return `path` relative to PROJECT_ROOT, or None if it escapes it.
36
+
37
+ Resolves the PARENT only — never dereferences the leaf — so a freshly-created
38
+ symlink (e.g. the wired root AGENTS.md) is recorded under its own name rather
39
+ than its link target (which would collide with the copied kit file).
40
+ """
41
+ p = Path(path)
42
+ try:
43
+ full = p.parent.resolve() / p.name
44
+ return str(full.relative_to(PROJECT_ROOT.resolve()))
45
+ except (ValueError, OSError):
46
+ return None
47
+
48
+
49
+ def _record(path, kind, agent="shared", backup_of=None):
50
+ """Record a created artifact for the uninstall manifest (idempotent per path)."""
51
+ rel = _rel_to_project(path)
52
+ if rel is None or rel in (".", ""):
53
+ return
54
+ entry = {"path": rel, "kind": kind, "agent": agent, "backup_of": backup_of}
55
+ if kind == "copy":
56
+ try:
57
+ import hashlib
58
+
59
+ entry["hash"] = hashlib.sha256(Path(path).read_bytes()).hexdigest()
60
+ except OSError:
61
+ entry["hash"] = ""
62
+ # Last write wins, but prefer keeping a backup_of linkage if one was recorded.
63
+ if rel in _RECORDED_PATHS:
64
+ for e in _MANIFEST_ENTRIES:
65
+ if e["path"] == rel:
66
+ if backup_of and not e.get("backup_of"):
67
+ e["backup_of"] = backup_of
68
+ if kind == "copy" and "hash" in entry:
69
+ e["hash"] = entry["hash"]
70
+ return
71
+ _MANIFEST_ENTRIES.append(entry)
72
+ _RECORDED_PATHS.add(rel)
73
+
74
+
75
+ def _record_tree(root):
76
+ """Record every file under an installed kit dir (kind=copy) for reversal."""
77
+ root = Path(root)
78
+ if not root.exists():
79
+ return
80
+ for p in sorted(root.rglob("*")):
81
+ if p.is_file() and not p.is_symlink():
82
+ _record(p, "copy")
83
+
84
+
85
+ def write_install_manifest():
86
+ """Write `.gabbe/manifest.json` capturing the wizard's tracked artifacts."""
87
+ if not _MANIFEST_ENTRIES:
88
+ return
89
+ import importlib
90
+
91
+ try:
92
+ version = importlib.import_module("gabbe").__version__
93
+ except Exception:
94
+ version = "wizard"
95
+ mp = PROJECT_ROOT / ".gabbe" / "manifest.json"
96
+ # Merge with any prior manifest so a re-run never drops earlier wiring (e.g.
97
+ # agents selected in a previous install). New entries win on path collisions.
98
+ merged: dict[str, dict] = {}
99
+ if mp.exists():
100
+ try:
101
+ prior = json.loads(mp.read_text())
102
+ for e in prior.get("entries", []):
103
+ if isinstance(e, dict) and "path" in e:
104
+ merged[e["path"]] = e
105
+ except (ValueError, OSError):
106
+ pass
107
+ for e in _MANIFEST_ENTRIES:
108
+ merged[e["path"]] = e
109
+ entries = sorted(merged.values(), key=lambda e: e["path"])
110
+ agents = sorted({e.get("agent", "shared") for e in entries if e.get("agent") != "shared"})
111
+ manifest = {
112
+ "schema_version": MANIFEST_SCHEMA_VERSION,
113
+ "installer_version": version,
114
+ "timestamp": "",
115
+ "agents": agents,
116
+ "entries": entries,
117
+ }
118
+ mp.parent.mkdir(parents=True, exist_ok=True)
119
+ mp.write_text(json.dumps(manifest, indent=2, sort_keys=True))
120
+ print(
121
+ f" {GREEN}✓ Recorded install manifest ({len(_MANIFEST_ENTRIES)} entries) for uninstall{NC}"
122
+ )
123
+
124
+
18
125
  # Colors
19
126
  GREEN = "\033[0;32m"
20
127
  YELLOW = "\033[1;33m"
@@ -77,6 +184,211 @@ def build_tech_map_from_skills(agents_dir):
77
184
  # Initial placeholders - will be populated in main()
78
185
  TECH_MAP: dict[str, Any] = {}
79
186
 
187
+
188
+ # Remaining unfilled [PLACEHOLDER:] fields after population, surfaced as an
189
+ # end-of-install warning so users are never silently shipped blank fields.
190
+ _UNFILLED_PLACEHOLDERS: list[str] = []
191
+
192
+ # Per-package-manager command derivations for the [PLACEHOLDER:] command fields
193
+ # the Jinja substitution does not cover. Keyed by the resolved package manager.
194
+ _PM_COMMANDS = {
195
+ "npm": {
196
+ "dev": "npm run dev",
197
+ "test_coverage": "npm test -- --coverage",
198
+ "test_single": "npm test -- path/to/file.test.ts",
199
+ "typecheck": "tsc --noEmit",
200
+ "lint": "eslint .",
201
+ "format": "prettier --write .",
202
+ },
203
+ "pnpm": {
204
+ "dev": "pnpm dev",
205
+ "test_coverage": "pnpm test --coverage",
206
+ "test_single": "pnpm vitest run src/path/to/file.test.ts",
207
+ "typecheck": "pnpm tsc --noEmit",
208
+ "lint": "pnpm eslint .",
209
+ "format": "pnpm prettier --write .",
210
+ },
211
+ "yarn": {
212
+ "dev": "yarn dev",
213
+ "test_coverage": "yarn test --coverage",
214
+ "test_single": "yarn test path/to/file.test.ts",
215
+ "typecheck": "yarn tsc --noEmit",
216
+ "lint": "yarn eslint .",
217
+ "format": "yarn prettier --write .",
218
+ },
219
+ "pip": {
220
+ "dev": "uvicorn main:app --reload",
221
+ "test_coverage": "pytest --cov",
222
+ "test_single": "pytest path/to/test_file.py::test_name",
223
+ "typecheck": "mypy .",
224
+ "lint": "ruff check .",
225
+ "format": "ruff format .",
226
+ },
227
+ "go mod": {
228
+ "dev": "go run .",
229
+ "test_coverage": "go test -cover ./...",
230
+ "test_single": "go test ./path/to/pkg -run TestName",
231
+ "typecheck": "go vet ./...",
232
+ "lint": "golangci-lint run",
233
+ "format": "gofmt -w .",
234
+ },
235
+ "cargo": {
236
+ "dev": "cargo run",
237
+ "test_coverage": "cargo tarpaulin",
238
+ "test_single": "cargo test test_name",
239
+ "typecheck": "cargo check",
240
+ "lint": "cargo clippy",
241
+ "format": "cargo fmt",
242
+ },
243
+ "composer": {
244
+ "dev": "php artisan serve",
245
+ "test_coverage": "php artisan test --coverage",
246
+ "test_single": "php artisan test --filter=TestName",
247
+ "typecheck": "phpstan analyse --level=9",
248
+ "lint": "pint --test",
249
+ "format": "pint",
250
+ },
251
+ }
252
+
253
+
254
+ def _detect_repo_url(base):
255
+ """Best-effort git remote URL (https form), or None."""
256
+ try:
257
+ import subprocess
258
+
259
+ out = subprocess.run(
260
+ ["git", "-C", str(base), "remote", "get-url", "origin"],
261
+ capture_output=True,
262
+ text=True,
263
+ timeout=5,
264
+ )
265
+ url = out.stdout.strip()
266
+ if url:
267
+ if url.startswith("git@") and ":" in url:
268
+ host, path = url[4:].split(":", 1)
269
+ url = f"https://{host}/{path}"
270
+ return url.removesuffix(".git")
271
+ except Exception:
272
+ pass
273
+ return None
274
+
275
+
276
+ def _detect_ci_cd(base):
277
+ if (base / ".github" / "workflows").exists():
278
+ return "GitHub Actions"
279
+ if (base / ".gitlab-ci.yml").exists():
280
+ return "GitLab CI"
281
+ if (base / ".circleci").exists():
282
+ return "CircleCI"
283
+ return None
284
+
285
+
286
+ def _detect_deploy_target(base):
287
+ if (base / "vercel.json").exists():
288
+ return "Vercel"
289
+ if (base / "Dockerfile").exists() or (base / "docker-compose.yml").exists():
290
+ return "Docker/K8s"
291
+ if (base / "serverless.yml").exists():
292
+ return "AWS Lambda"
293
+ return None
294
+
295
+
296
+ def populate_placeholders(content, pm, base):
297
+ """Fill derivable [PLACEHOLDER:] fields, tag the rest OPTIONAL, and record
298
+ which remain so the installer can warn the user to complete them.
299
+
300
+ Returns the updated content. Appends remaining field names to the module
301
+ global `_UNFILLED_PLACEHOLDERS` for the end-of-install warning.
302
+ """
303
+ import re
304
+
305
+ cmds = _PM_COMMANDS.get(pm, _PM_COMMANDS["npm"])
306
+ derived = dict(cmds)
307
+ repo = _detect_repo_url(base)
308
+ if repo:
309
+ derived["repo_url"] = repo
310
+ ci = _detect_ci_cd(base)
311
+ if ci:
312
+ derived["ci_cd"] = ci
313
+ deploy = _detect_deploy_target(base)
314
+ if deploy:
315
+ derived["deployment_target"] = deploy
316
+
317
+ out_lines = []
318
+ # Matches `key: "[PLACEHOLDER: ...]"` (the YAML-ish command/config fields).
319
+ kv_re = re.compile(r'^(\s*)([a-z_]+):\s*"\[PLACEHOLDER:[^"]*\]"\s*$')
320
+ for line in content.splitlines():
321
+ m = kv_re.match(line)
322
+ if m:
323
+ indent, key = m.group(1), m.group(2)
324
+ if key in derived:
325
+ out_lines.append(f'{indent}{key}: "{derived[key]}"')
326
+ continue
327
+ # Unknown value: keep the field, mark it clearly OPTIONAL, and record it.
328
+ _UNFILLED_PLACEHOLDERS.append(key)
329
+ out_lines.append(line + " # <!-- OPTIONAL: fill this in yourself -->")
330
+ continue
331
+ # Prose / inline placeholders: tag the line OPTIONAL (don't fabricate prose).
332
+ if "[PLACEHOLDER" in line:
333
+ _UNFILLED_PLACEHOLDERS.append(line.strip()[:48])
334
+ if "OPTIONAL" not in line:
335
+ out_lines.append(line + " <!-- OPTIONAL: fill this in yourself -->")
336
+ else:
337
+ out_lines.append(line)
338
+ continue
339
+ out_lines.append(line)
340
+ return "\n".join(out_lines)
341
+
342
+
343
+ def detect_existing_project(cwd):
344
+ """Detect whether `cwd` is an existing codebase and infer its stack.
345
+
346
+ Prefers the richer, unit-tested gabbe.detect module when GABBE is importable
347
+ (pip install); falls back to a self-contained sniff so the wizard still works
348
+ when run standalone via npx/curl (where the gabbe package is not present).
349
+ """
350
+ try:
351
+ from gabbe import detect as _detect # type: ignore
352
+
353
+ return _detect.detect_project(cwd)
354
+ except Exception:
355
+ pass
356
+ base = Path(cwd)
357
+ manifests = [
358
+ ("pnpm-lock.yaml", "TypeScript", "pnpm"),
359
+ ("yarn.lock", "TypeScript", "yarn"),
360
+ ("package.json", "TypeScript", "npm"),
361
+ ("pyproject.toml", "Python", "pip"),
362
+ ("requirements.txt", "Python", "pip"),
363
+ ("go.mod", "Go", "go mod"),
364
+ ("Cargo.toml", "Rust", "cargo"),
365
+ ("composer.json", "PHP", "composer"),
366
+ ("pom.xml", "Java", "maven"),
367
+ ("build.gradle", "Java", "gradle"),
368
+ ("Gemfile", "Ruby", "bundler"),
369
+ ]
370
+ language = pm = None
371
+ signals = []
372
+ for name, lang, pmgr in manifests:
373
+ if (base / name).exists():
374
+ language, pm = lang, pmgr
375
+ signals.append(f"found {name}")
376
+ break
377
+ has_git = (base / ".git").exists()
378
+ if has_git:
379
+ signals.append("git repository")
380
+ is_existing = bool(language or has_git)
381
+ return {
382
+ "is_existing": is_existing,
383
+ "language": language,
384
+ "framework": None,
385
+ "package_manager": pm,
386
+ "project_name": None,
387
+ "has_git": has_git,
388
+ "signals": signals,
389
+ }
390
+
391
+
80
392
  # --- Helper Functions ---
81
393
 
82
394
 
@@ -140,7 +452,32 @@ def ask_multiselect(question, options):
140
452
  return selected
141
453
 
142
454
 
143
- def safe_merge_directory(src_root, dst_root, is_kit_root=False):
455
+ def _backup_before_overwrite(dst_file):
456
+ """Back up an existing target file to <name>.gabbe-bak before it is overwritten.
457
+
458
+ Guarantees the never-clobber invariant: any pre-existing content is always
459
+ recoverable. The first backup wins (we never overwrite an existing .gabbe-bak,
460
+ so re-running install keeps the user's ORIGINAL, not a kit copy from a prior run).
461
+ """
462
+ backup = Path(str(dst_file) + ".gabbe-bak")
463
+ if not backup.exists():
464
+ try:
465
+ shutil.copy2(dst_file, backup)
466
+ print(f" {YELLOW}! Backed up existing {dst_file.name} -> {backup.name}{NC}")
467
+ except Exception:
468
+ pass
469
+
470
+
471
+ def safe_merge_directory(src_root, dst_root, is_kit_root=False, force=None):
472
+ """Merge the kit tree into a target without ever losing user data.
473
+
474
+ Preserve-set files (and memory/project trees) are left untouched. Any OTHER
475
+ pre-existing file is backed up to <name>.gabbe-bak before being refreshed, so
476
+ nothing is clobbered. With force=True, even preserve-set files are re-templated
477
+ (still backed up first).
478
+ """
479
+ if force is None:
480
+ force = FORCE
144
481
  PRESERVE_FILES = {"AGENTS.md", "CONSTITUTION.md", "TASKS.md", "policies.yml", "config.json"}
145
482
  notified_preservations = set()
146
483
 
@@ -161,7 +498,8 @@ def safe_merge_directory(src_root, dst_root, is_kit_root=False):
161
498
  # when is_kit_root=True, so the symlink-fallback path (is_kit_root
162
499
  # defaults to False) clobbered existing user files. User content
163
500
  # must never be overwritten regardless of how the merge was reached.
164
- if dst_file.exists():
501
+ # With force=True the user explicitly opted into re-templating these.
502
+ if dst_file.exists() and not force:
165
503
  if in_memory:
166
504
  preserve = True
167
505
  elif in_project:
@@ -185,15 +523,35 @@ def safe_merge_directory(src_root, dst_root, is_kit_root=False):
185
523
  continue
186
524
 
187
525
  if dst_file.exists():
526
+ # Never clobber: only files whose bytes differ from the incoming kit
527
+ # file are backed up (identical files need no backup). This covers
528
+ # user-modified kit files AND, with force=True, preserve-set files.
529
+ try:
530
+ differs = src_file.read_bytes() != dst_file.read_bytes()
531
+ except Exception:
532
+ differs = True
533
+ if differs:
534
+ _backup_before_overwrite(dst_file)
188
535
  try:
189
536
  dst_file.unlink()
190
537
  except Exception:
191
538
  pass
192
539
  shutil.copy2(src_file, dst_file)
540
+ bak = str(dst_file) + ".gabbe-bak"
541
+ _record(
542
+ dst_file,
543
+ "copy",
544
+ backup_of=_rel_to_project(bak) if os.path.exists(bak) else None,
545
+ )
193
546
 
194
547
 
195
- def create_symlink(source, target):
196
- """Creates a symlink from target to source, backing up if exists."""
548
+ def create_symlink(source, target, agent="shared"):
549
+ """Creates a symlink from target to source, backing up if exists.
550
+
551
+ Records the created link (and any backup) in the install manifest so
552
+ `gabbe uninstall` can reverse it and restore the user's original.
553
+ """
554
+ backup_of = None
197
555
  if target.is_symlink():
198
556
  target.unlink()
199
557
  elif target.exists():
@@ -202,9 +560,11 @@ def create_symlink(source, target):
202
560
  f" {YELLOW}! Backing up existing directory {target.name} to {target.name}.bak{NC}"
203
561
  )
204
562
  shutil.move(str(target), str(target) + ".bak")
563
+ backup_of = _rel_to_project(str(target) + ".bak")
205
564
  else:
206
565
  print(f" {YELLOW}! Backing up existing file {target.name} to {target.name}.bak{NC}")
207
566
  target.rename(Path(str(target) + ".bak"))
567
+ backup_of = _rel_to_project(str(target) + ".bak")
208
568
 
209
569
  # Ensure parent dir exists
210
570
  target.parent.mkdir(parents=True, exist_ok=True)
@@ -218,16 +578,19 @@ def create_symlink(source, target):
218
578
  try:
219
579
  os.symlink(link_path, target)
220
580
  print(f" {GREEN}✓ Linked {target.name} -> {link_path}{NC}")
581
+ _record(target, "symlink", agent=agent, backup_of=backup_of)
221
582
  except OSError as e:
222
583
  # Fallback for Windows (no admin rights) or restricted environments
223
584
  print(f" {YELLOW}! Symlink failed ({e}), falling back to copy...{NC}")
224
585
  try:
225
586
  if source.is_dir():
226
587
  safe_merge_directory(source, target)
588
+ _record(target, "tree", agent=agent, backup_of=backup_of)
227
589
  else:
228
590
  if target.exists():
229
591
  target.unlink()
230
592
  shutil.copy2(source, target)
593
+ _record(target, "copy", agent=agent, backup_of=backup_of)
231
594
  print(f" {GREEN}✓ Copied {target.name} (Symlink fallback){NC}")
232
595
  except Exception as e2:
233
596
  print(f" {RED}x Failed to copy {target}: {e2}{NC}")
@@ -310,6 +673,9 @@ def setup_skills_for_platform(platform, agents_dir, target_dir):
310
673
  ]
311
674
  subprocess.run(cmd, check=True)
312
675
  print(f" {GREEN}✓ Processed skills for {platform}{NC}")
676
+ # Record the generated skills tree so uninstall removes exactly it.
677
+ _slug = "".join(c if (c.isalnum() or c in "-_") else "-" for c in platform.lower())
678
+ _record(target_dir, "tree", agent=_slug.strip("-") or "shared")
313
679
  except Exception as e:
314
680
  print(f"{RED}Error running skill compiler: {e}{NC}")
315
681
  else:
@@ -347,10 +713,16 @@ def run_bench():
347
713
 
348
714
 
349
715
  def main():
350
- global PROJECT_ROOT
716
+ global PROJECT_ROOT, FORCE
717
+ # Start each run with a clean manifest recorder (globals persist in-process).
718
+ _MANIFEST_ENTRIES.clear()
719
+ _RECORDED_PATHS.clear()
720
+ _UNFILLED_PLACEHOLDERS.clear()
351
721
  if "--bench" in sys.argv:
352
722
  run_bench()
353
723
  return
724
+ if "--force" in sys.argv:
725
+ FORCE = True
354
726
  if not SOURCE_AGENTS_DIR.exists():
355
727
  if (KIT_SOURCE / "AGENTS.md").exists():
356
728
  pass
@@ -421,13 +793,37 @@ def main():
421
793
  else:
422
794
  shutil.copytree(SOURCE_AGENTS_DIR, target_agents_dir)
423
795
  print(f" {GREEN}✓ Kit installed to {target_agents_dir}{NC}")
796
+ # Record the freshly-copied kit tree (only if it lives under PROJECT_ROOT;
797
+ # global/custom installs outside the project are not in its manifest).
798
+ _record_tree(target_agents_dir)
424
799
 
425
800
  AGENTS_DIR = target_agents_dir
426
801
 
427
802
  # --- Step 2: Interview ---
428
803
  print(f"\n{YELLOW}Part 2: Project Context{NC}")
429
804
 
430
- project_name = ask("Project Name", PROJECT_ROOT.name)
805
+ # Brownfield autodetect: recognise an existing codebase and prefill from it.
806
+ detected = detect_existing_project(PROJECT_ROOT)
807
+ refactor_mode = False
808
+ if detected.get("is_existing"):
809
+ print(
810
+ f" {BLUE}→ Existing project detected ({', '.join(detected.get('signals', [])) or 'source present'}).{NC}"
811
+ )
812
+ if detected.get("language"):
813
+ print(f" {BLUE}→ Stack looks like: {detected['language']}", end="")
814
+ if detected.get("framework"):
815
+ print(f" / {detected['framework']}", end="")
816
+ print(f"{NC}")
817
+ mode_idx = select_index(
818
+ "How should GABBE engage this project?",
819
+ [
820
+ "Greenfield build — scaffold a new system here",
821
+ "Upgrade / Refactor — onboard onto the EXISTING codebase",
822
+ ],
823
+ )
824
+ refactor_mode = mode_idx == 1
825
+
826
+ project_name = ask("Project Name", detected.get("project_name") or PROJECT_ROOT.name)
431
827
  description = ask("One-line Description", "A new software project")
432
828
 
433
829
  # Team & Type
@@ -472,7 +868,10 @@ def main():
472
868
  if language_choice == "Other":
473
869
  language = ask("Enter Language")
474
870
 
475
- framework = ask("Primary Framework (e.g. Next.js, FastAPI, Laravel)", "None")
871
+ framework = ask(
872
+ "Primary Framework (e.g. Next.js, FastAPI, Laravel)",
873
+ detected.get("framework") or "None",
874
+ )
476
875
 
477
876
  db_options = ["PostgreSQL", "MySQL/MariaDB", "MongoDB", "SQLite", "Redis", "None"]
478
877
  databases = ask_multiselect("Databases used", db_options)
@@ -693,8 +1092,15 @@ def main():
693
1092
  # Strip the marker comments themselves for clean output
694
1093
  content = content.replace(cli_start, "").replace(cli_end, "")
695
1094
 
1095
+ # Fill derivable [PLACEHOLDER:] fields (commands, repo_url, ci/cd,
1096
+ # deploy target); tag the rest OPTIONAL and record them for a warning.
1097
+ content = populate_placeholders(content, pm, PROJECT_ROOT)
1098
+
696
1099
  target_agents_md = AGENTS_DIR / "AGENTS.md"
697
1100
  target_agents_md.write_text(content)
1101
+ # Refresh the manifest hash now that AGENTS.md holds substituted content
1102
+ # (the earlier copy recorded the raw template hash).
1103
+ _record(target_agents_md, "copy", agent="shared")
698
1104
  print(f" {GREEN}✓ Configured {target_agents_md}{NC}")
699
1105
  else:
700
1106
  print(f" {RED}x Template not found: {template_path}{NC}")
@@ -826,6 +1232,7 @@ def main():
826
1232
  aider_conf = PROJECT_ROOT / ".aider.conf.yml"
827
1233
  if not aider_conf.exists():
828
1234
  aider_conf.write_text("read:\n - agents/AGENTS.md\n - agents/skills/\n")
1235
+ _record(aider_conf, "copy", agent="aider")
829
1236
  print(f" {GREEN}✓ Wired .aider.conf.yml{NC}")
830
1237
 
831
1238
  # "Gemini" is the split-out target; "Gemini / Antigravity" kept for backward
@@ -849,8 +1256,9 @@ def main():
849
1256
  "notes": "Managed by init.py",
850
1257
  }
851
1258
  (gemini_dir / "settings.json").write_text(json.dumps(settings_content, indent=2))
1259
+ _record(gemini_dir / "settings.json", "copy", agent="gemini")
852
1260
  # Gemini CLI natively reads a GEMINI.md context file; point it at AGENTS.md.
853
- create_symlink(agents_md_src, PROJECT_ROOT / "GEMINI.md")
1261
+ create_symlink(agents_md_src, PROJECT_ROOT / "GEMINI.md", agent="gemini")
854
1262
  print(f" {GREEN}✓ Wired .gemini/settings.json + GEMINI.md{NC}")
855
1263
 
856
1264
  # Universal agentskills.io target: .agents/skills/<slug>/SKILL.md is read by
@@ -876,6 +1284,7 @@ def main():
876
1284
  )
877
1285
  + "\n"
878
1286
  )
1287
+ _record(opencode_conf, "copy", agent="opencode")
879
1288
  setup_skills_for_platform("OpenCode", AGENTS_DIR, PROJECT_ROOT / ".agents" / "skills")
880
1289
  print(f" {GREEN}✓ Wired opencode.json + .agents/skills{NC}")
881
1290
 
@@ -1027,10 +1436,81 @@ Here is your mission to finalize the setup:
1027
1436
 
1028
1437
  mission_file = PROJECT_ROOT / "SETUP_MISSION.md"
1029
1438
  mission_file.write_text(mission)
1439
+ _record(mission_file, "copy", agent="shared")
1030
1440
  print(f"\n{GREEN}✓ Mission saved to SETUP_MISSION.md{NC}")
1031
1441
 
1442
+ # --- Brownfield onboarding artifact ---
1443
+ # In Upgrade/Refactor mode the first job is to UNDERSTAND the existing code,
1444
+ # not scaffold greenfield mission docs. Emit a discovery brief that steers the
1445
+ # agent to map the codebase before changing anything.
1446
+ if refactor_mode:
1447
+ write_brownfield_assessment(project_name, detected)
1448
+
1449
+ # Persist the uninstall manifest of everything we created under PROJECT_ROOT.
1450
+ write_install_manifest()
1451
+
1452
+ # Never ship blank fields silently: if any [PLACEHOLDER:] remain (skipped
1453
+ # interactive setup, or genuinely project-specific fields), tell the user
1454
+ # exactly what to complete and how.
1455
+ if _UNFILLED_PLACEHOLDERS:
1456
+ n = len(_UNFILLED_PLACEHOLDERS)
1457
+ print(
1458
+ f"\n{YELLOW}⚠ {n} optional field(s) in agents/AGENTS.md still need your input "
1459
+ f"(marked with <!-- OPTIONAL -->):{NC}"
1460
+ )
1461
+ for name in _UNFILLED_PLACEHOLDERS[:12]:
1462
+ print(f" - {name}")
1463
+ if n > 12:
1464
+ print(f" ... and {n - 12} more")
1465
+ print(
1466
+ f" {BLUE}→ Search agents/AGENTS.md for 'OPTIONAL' and fill them in, "
1467
+ f"or re-run `gabbe setup` to be prompted.{NC}"
1468
+ )
1469
+
1032
1470
  print(f"{BLUE}Setup Complete! The kit is installed at: {AGENTS_DIR}{NC}")
1033
1471
 
1034
1472
 
1473
+ def write_brownfield_assessment(project_name, detected):
1474
+ """Scaffold a discovery/onboarding brief for an existing codebase."""
1475
+ stack = detected.get("language") or "unknown"
1476
+ if detected.get("framework"):
1477
+ stack += f" / {detected['framework']}"
1478
+ signals = ", ".join(detected.get("signals", [])) or "existing source"
1479
+ doc = f"""# Brownfield Onboarding — {project_name}
1480
+
1481
+ > GABBE installed in **Upgrade / Refactor** mode. This is an EXISTING codebase
1482
+ > ({signals}). Do NOT scaffold a greenfield system. First understand, then change.
1483
+
1484
+ ## Detected
1485
+ - Stack: {stack}
1486
+ - Package manager: {detected.get('package_manager') or 'unknown'}
1487
+ - Git repository: {'yes' if detected.get('has_git') else 'no'}
1488
+
1489
+ ## Phase 0 — Discovery (do this before any change)
1490
+ 1. **Map the codebase**: entry points, modules, data flow, external deps. Record
1491
+ findings in `agents/memory/semantic/` and a top-level `CODEBASE_MAP.md`.
1492
+ 2. **Assess current state**: build/test/CI status, obvious tech debt, risky areas,
1493
+ test coverage. Capture in `ASSESSMENT.md`.
1494
+ 3. **Establish a baseline**: get the existing build + tests green and recorded
1495
+ BEFORE refactoring, so regressions are detectable.
1496
+ 4. **Backlog**: turn findings into a prioritised improvement backlog in `TASKS.md`
1497
+ (use the kit's task templates). Sequence by risk/value.
1498
+
1499
+ ## Phase 1+ — Change safely
1500
+ - Work in small, reversible increments; keep the baseline green at every step.
1501
+ - Apply the relevant kit guides/skills for {stack}.
1502
+ - Use `gabbe verify` / your SDLC gates on each increment.
1503
+
1504
+ ## Safety
1505
+ - GABBE is additive: it has NOT modified your source. Any file it would have
1506
+ overwritten was backed up to `<name>.gabbe-bak`. `gabbe uninstall` reverses
1507
+ the install and restores backups.
1508
+ """
1509
+ out = PROJECT_ROOT / "BROWNFIELD_ONBOARDING.md"
1510
+ out.write_text(doc)
1511
+ _record(out, "copy", agent="shared")
1512
+ print(f" {GREEN}✓ Brownfield onboarding brief saved to BROWNFIELD_ONBOARDING.md{NC}")
1513
+
1514
+
1035
1515
  if __name__ == "__main__":
1036
1516
  main()