forge-foundation 0.1.0a1__py3-none-any.whl

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.
forge/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Forge — a deterministic project kernel for autonomous software
2
+ development.
3
+
4
+ The kernel owns project state as an event-sourced task graph. Humans,
5
+ planners, executors, verifiers, and MCP servers are interchangeable
6
+ clients of the same official API (forge.kernel.Kernel). There is no AI
7
+ in the kernel; it is pure, deterministic, and zero-dependency.
8
+
9
+ LLM ──┐
10
+ ├──► Kernel ──► events.log (source of truth)
11
+ Human ─┘
12
+ """
13
+
14
+ __version__ = "0.1.0a1"
15
+ # 0.1.0-alpha: the KERNEL is stable and frozen at v1 (docs/SPEC.md,
16
+ # Appendix A: Versioning & Freeze Policy); the ecosystem around it
17
+ # (executor, reviewer, MCP, UIs) is under active development. The
18
+ # kernel contract never tracks this number.
19
+
20
+ from .model import ( # noqa: F401
21
+ EVIDENCE_HARD, EVIDENCE_SOFT, SCHEMA_VERSION,
22
+ PRIORITIES, PRIORITY_WEIGHT, OP_SHAPES,
23
+ STATUS_TODO, STATUS_IN_PROGRESS, STATUS_NEEDS_REVISION, STATUS_DONE,
24
+ Evidence, TaskNode, Graph, GraphError,
25
+ )
26
+ from .store import EVENT_FILE, Store, load_project # noqa: F401
27
+ from .scheduler import blockers, is_container, next_task, progress, ready_tasks # noqa: F401
28
+ from .context import build_context, to_json, to_markdown # noqa: F401
29
+ from .query import QueryError, run_query # noqa: F401
30
+ from .kernel import Kernel # noqa: F401
31
+ from .sdk import ( # noqa: F401
32
+ ForgeClient, ContextError, ProposalError, PLANNER_OPS,
33
+ context_package, parse_context, slugify, validate_proposal,
34
+ )
forge/cli.py ADDED
@@ -0,0 +1,586 @@
1
+ """Forge CLI (`forge`).
2
+
3
+ A human can run an entire software project through this interface. LLM
4
+ clients (planner/executor/verifier agents) emit exactly the same events
5
+ through the same Kernel API.
6
+
7
+ Usage: forge <command> [args] (run `forge --help` or `forge <command> --help`)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+
16
+ from . import __version__
17
+ from .context import STATUS_ICON
18
+ from .kernel import Kernel
19
+ from .model import GraphError
20
+ from .scheduler import is_container
21
+ from .store import EVENT_FILE, Store
22
+
23
+
24
+ # --------------------------------------------------------------------------- helpers
25
+ def _setup_stdout() -> None:
26
+ try:
27
+ sys.stdout.reconfigure(encoding="utf-8")
28
+ except Exception:
29
+ pass
30
+
31
+
32
+ def _node_label(g: Graph, tid: str) -> str:
33
+ t = g.tasks[tid]
34
+ eff = t.effective_status(g.tasks)
35
+ label = tid
36
+ if t.title and t.title != tid:
37
+ label += f" — {t.title}"
38
+ if is_container(t):
39
+ label += " (group)"
40
+ return f"{label} {STATUS_ICON[eff]}"
41
+
42
+
43
+ def _print_tree(g: Graph, tid: str, prefix: str, is_last: bool, seen: set[str]) -> None:
44
+ # seen holds the current ancestry path only. A repeat along the path is
45
+ # a true cycle; a node re-printed under a different branch (a DAG with
46
+ # multiple parents) is legitimate and must not be flagged.
47
+ if tid in seen:
48
+ print(prefix + ("└── " if is_last else "├── ") + f"{tid} (cycle!)")
49
+ return
50
+ seen.add(tid)
51
+ print(prefix + ("└── " if is_last else "├── ") + _node_label(g, tid))
52
+ kids = sorted((g.tasks[d] for d in g.tasks[tid].depends_on), key=lambda t: t.created_seq)
53
+ child_prefix = prefix + (" " if is_last else "│ ")
54
+ for i, kid in enumerate(kids):
55
+ _print_tree(g, kid.id, child_prefix, i == len(kids) - 1, seen)
56
+ seen.remove(tid)
57
+
58
+
59
+ def _parse_child(spec: str) -> dict:
60
+ """'Title', 'Title::desc', or 'Title::desc::acc1;acc2'."""
61
+ parts = spec.split("::")
62
+ title = parts[0].strip()
63
+ desc = parts[1].strip() if len(parts) > 1 else ""
64
+ acceptance = [a.strip() for a in parts[2].split(";") if a.strip()] if len(parts) > 2 else []
65
+ return {"title": title, "description": desc, "acceptance": acceptance}
66
+
67
+
68
+ # --------------------------------------------------------------------------- demo seed
69
+ def _seed_demo(k: Kernel) -> None:
70
+ k.create_task("Snake Game", "A terminal snake game built via Forge.",
71
+ acceptance=["game runs", "unit tests pass"], priority="high")
72
+ k.expand("snake-game", [
73
+ {"title": "Window", "description": "Terminal window setup", "acceptance": ["renders a frame"]},
74
+ {"title": "Renderer", "description": "Draws the board state", "acceptance": ["renders snakes, food, score"]},
75
+ {"title": "Input", "description": "Keyboard controls", "acceptance": ["arrow keys move the snake"]},
76
+ {"title": "Snake Logic", "description": "Movement and growth", "acceptance": ["grows on food"]},
77
+ {"title": "Food", "description": "Spawning and eating", "acceptance": ["spawns on empty cell"]},
78
+ {"title": "Collision", "description": "Wall and self collision", "acceptance": ["game over on hit"]},
79
+ ])
80
+ k.expand("renderer", [
81
+ {"title": "Camera", "description": "Viewport", "acceptance": ["follows the snake"]},
82
+ {"title": "UI", "description": "Score and status bar", "acceptance": ["score updates"]},
83
+ {"title": "Lighting", "description": "ASCII shading", "acceptance": ["depth shading"]},
84
+ {"title": "Particle System", "description": "Death explosion", "acceptance": ["particles on game over"]},
85
+ ])
86
+ k.start("window")
87
+ k.add_evidence("window", "hard", "unittest", "test_window passes (14 assertions)")
88
+ k.verify_pass("window")
89
+ k.start("input")
90
+ k.verify_fail("input", "movement handler misses edge cases (diagonal input races)")
91
+ k.add_evidence("input", "soft", "peer review", "logic otherwise sound; fix races then re-verify")
92
+ k.retry("input")
93
+ k.verify_pass("input")
94
+ k.start("camera")
95
+ k.add_evidence("camera", "hard", "unittest", "test_camera passes (9 assertions)")
96
+ k.verify_pass("camera")
97
+ k.start("ui")
98
+
99
+
100
+ # --------------------------------------------------------------------------- commands
101
+ def cmd_init(args) -> int:
102
+ Store(args.dir).init()
103
+ print(f"initialized project at {args.dir} ({EVENT_FILE})")
104
+ return 0
105
+
106
+
107
+ def cmd_create(args, k: Kernel) -> int:
108
+ ev = k.create_task(args.title, args.desc, args.acceptance, args.file, id=args.id,
109
+ priority=args.priority)
110
+ print(ev["id"])
111
+ return 0
112
+
113
+
114
+ def cmd_update(args, k: Kernel) -> int:
115
+ changes = {}
116
+ if args.title is not None: changes["title"] = args.title
117
+ if args.desc is not None: changes["description"] = args.desc
118
+ if args.acceptance is not None: changes["acceptance"] = args.acceptance
119
+ if args.file is not None: changes["files"] = args.file
120
+ if args.priority is not None: changes["priority"] = args.priority
121
+ k.update_task(args.task, **changes)
122
+ print(f"updated {args.task}")
123
+ return 0
124
+
125
+
126
+ def cmd_dep(args, k: Kernel) -> int:
127
+ if args.remove:
128
+ k.remove_dependency(args.task, args.depends_on)
129
+ else:
130
+ k.add_dependency(args.task, args.depends_on)
131
+ print(f"{'removed' if args.remove else 'added'} dependency: {args.task} -> {args.depends_on}")
132
+ return 0
133
+
134
+
135
+ def cmd_expand(args, k: Kernel) -> int:
136
+ children = [_parse_child(s) for s in args.child]
137
+ ev = k.expand(args.task, children)
138
+ print(f"expanded {args.task} into: {', '.join(c['id'] for c in ev['children'])}")
139
+ return 0
140
+
141
+
142
+ def cmd_start(args, k: Kernel) -> int:
143
+ k.start(args.task)
144
+ print(f"{args.task} -> in_progress")
145
+ return 0
146
+
147
+
148
+ def cmd_verify_pass(args, k: Kernel) -> int:
149
+ k.verify_pass(args.task, force=args.force)
150
+ print(f"{args.task} -> done")
151
+ return 0
152
+
153
+
154
+ def cmd_verify_fail(args, k: Kernel) -> int:
155
+ k.verify_fail(args.task, args.reason)
156
+ print(f"{args.task} -> needs_revision")
157
+ return 0
158
+
159
+
160
+ def cmd_retry(args, k: Kernel) -> int:
161
+ k.retry(args.task)
162
+ print(f"{args.task} -> in_progress")
163
+ return 0
164
+
165
+
166
+ def cmd_reopen(args, k: Kernel) -> int:
167
+ k.reopen(args.task)
168
+ print(f"{args.task} -> in_progress")
169
+ return 0
170
+
171
+
172
+ def cmd_evidence(args, k: Kernel) -> int:
173
+ k.add_evidence(args.task, args.kind, args.source, args.detail)
174
+ print(f"{args.task}: evidence [{args.kind}] {args.source}")
175
+ return 0
176
+
177
+
178
+ def cmd_note(args, k: Kernel) -> int:
179
+ k.add_note(args.task, args.text)
180
+ print(f"{args.task}: note added")
181
+ return 0
182
+
183
+
184
+ def cmd_delete(args, k: Kernel) -> int:
185
+ k.delete(args.task)
186
+ print(f"deleted {args.task}")
187
+ return 0
188
+
189
+
190
+ def cmd_show(args, k: Kernel) -> int:
191
+ print(k.context(args.task, "json" if args.json else "markdown"))
192
+ return 0
193
+
194
+
195
+ def cmd_inspect(args, k: Kernel) -> int:
196
+ info = k.inspect(args.task)
197
+ if args.json:
198
+ print(json.dumps(info, ensure_ascii=False, indent=2))
199
+ return 0
200
+ g = k.graph
201
+ print(f"{info['id']} — {info['title']}")
202
+ print("-" * max(len(info["id"]) + len(info["title"]) + 3, 24))
203
+ print(f"Status: {STATUS_ICON[info['status']]} {info['status']}"
204
+ + (" (container: completes when children do)" if info["container"] else ""))
205
+ print(f"Priority: {info['priority']}")
206
+ print(f"Completion: {info['completion']}% ({info['completion_text']})")
207
+ if info["children"]:
208
+ print("Children:")
209
+ for c in info["children"]:
210
+ print(f" {c['icon']} {c['id']} — {c['title']} ({c['status']})")
211
+ if info["depends_on"]:
212
+ print(f"Depends on: {', '.join(info['depends_on'])}")
213
+ if info["blocks"]:
214
+ print(f"Blocks: {', '.join(info['blocks'])}")
215
+ if info["acceptance"]:
216
+ print("Acceptance:")
217
+ for a in info["acceptance"]:
218
+ print(f" - {a}")
219
+ if info["files"] or info["produces"]:
220
+ print(f"Files: {', '.join(info['files']) or '(none)'}")
221
+ print(f"Produces: {', '.join(info['produces']) or '(none)'}")
222
+ if info["evidence"]:
223
+ print("Evidence:")
224
+ for e in info["evidence"]:
225
+ print(f" [{e['kind']}] {e['source']} — {e['detail']}")
226
+ if info["notes"]:
227
+ print("Notes:")
228
+ for n in info["notes"]:
229
+ print(f" - {n}")
230
+ print("History:")
231
+ for h in info["history"]:
232
+ extra = f" ({h['summary']})" if h["summary"] else ""
233
+ print(f" #{h['seq']:>4} {h['op']}{extra}")
234
+ return 0
235
+
236
+
237
+ def cmd_query(args, k: Kernel) -> int:
238
+ result = k.query(args.expr)
239
+ if args.json:
240
+ print(json.dumps(result, ensure_ascii=False, indent=2))
241
+ return 0
242
+ if isinstance(result, list) and result and isinstance(result[0], str):
243
+ for item in result:
244
+ print(item)
245
+ elif isinstance(result, list) and not result:
246
+ print("(no matches)")
247
+ else:
248
+ for item in result:
249
+ print(item)
250
+ return 0
251
+
252
+
253
+ def cmd_export(args, k: Kernel) -> int:
254
+ payload = k.to_export_json()
255
+ if args.file:
256
+ with open(args.file, "w", encoding="utf-8") as f:
257
+ f.write(payload + "\n")
258
+ print(f"exported {len(k.export_events())} events to {args.file}")
259
+ else:
260
+ print(payload)
261
+ return 0
262
+
263
+
264
+ def cmd_import(args, k: Kernel) -> int:
265
+ with open(args.file, encoding="utf-8") as f:
266
+ events = json.load(f)
267
+ result = k.import_events(events)
268
+ print(f"imported {result['imported']} events -> project now has {result['tasks']} tasks")
269
+ return 0
270
+
271
+
272
+ def cmd_graph(args, k: Kernel) -> int:
273
+ g = k.graph
274
+ if not g.tasks:
275
+ print("(empty graph)")
276
+ return 0
277
+ if args.task is not None:
278
+ if args.task not in g.tasks:
279
+ print(f"no such task: {args.task}", file=sys.stderr)
280
+ return 1
281
+ _print_tree(g, args.task, "", True, set())
282
+ return 0
283
+ roots = g.roots()
284
+ if not roots:
285
+ roots = sorted(g.tasks.values(), key=lambda t: t.created_seq)[:1]
286
+ for i, r in enumerate(roots):
287
+ _print_tree(g, r.id, "", i == len(roots) - 1, set())
288
+ return 0
289
+
290
+
291
+ def cmd_ready(args, k: Kernel) -> int:
292
+ for tid in k.ready():
293
+ print(tid)
294
+ return 0
295
+
296
+
297
+ def cmd_next(args, k: Kernel) -> int:
298
+ tid = k.next()
299
+ if tid is None:
300
+ print("nothing ready")
301
+ return 1
302
+ print(tid)
303
+ return 0
304
+
305
+
306
+ def cmd_blockers(args, k: Kernel) -> int:
307
+ result = k.blockers(args.task, chain=args.chain)
308
+ if not result:
309
+ print("none")
310
+ return 0
311
+ if args.chain:
312
+ for path in result:
313
+ print(" -> ".join(path))
314
+ else:
315
+ for b in result:
316
+ print(b)
317
+ return 0
318
+
319
+
320
+ def cmd_progress(args, k: Kernel) -> int:
321
+ p = k.progress()
322
+ print(f"done {p['done']}/{p['total']} ({p['percent']}%)")
323
+ print(f"todo {p['todo']} | in_progress {p['in_progress']} | "
324
+ f"needs_revision {p['needs_revision']} | done {p['done']}")
325
+ return 0
326
+
327
+
328
+ def cmd_validate(args, k: Kernel) -> int:
329
+ problems = k.graph.problems()
330
+ if not problems:
331
+ print(f"graph OK: {len(k.graph.tasks)} tasks, {k.graph.seq} events")
332
+ return 0
333
+ for p in problems:
334
+ print(p, file=sys.stderr)
335
+ return 1
336
+
337
+
338
+ def cmd_log(args, k: Kernel) -> int:
339
+ events = k.store.read_events()
340
+ tail = events[-args.tail:] if args.tail else events
341
+ for ev in tail:
342
+ op = ev["op"]
343
+ target = ev.get("id") or ev.get("task") or ev.get("depends_on", "")
344
+ print(f"#{ev['seq']:>4} {op:<22} {target:<28} {ev.get('ts', '')}")
345
+ return 0
346
+
347
+
348
+ def cmd_undo(args, k: Kernel) -> int:
349
+ removed = k.undo(args.count)
350
+ for ev in removed:
351
+ op = ev["op"]
352
+ target = ev.get("id") or ev.get("task") or ev.get("depends_on", "")
353
+ print(f"undid #{ev['seq']} {op} ({target})")
354
+ if k.graph.tasks:
355
+ print(f"project now: {len(k.graph.tasks)} tasks")
356
+ else:
357
+ print("project now: empty")
358
+ return 0
359
+
360
+
361
+ def cmd_replay(args, k: Kernel) -> int:
362
+ stats = k.replay()
363
+ print(f"replayed {stats['events']} events -> {stats['tasks']} tasks, "
364
+ f"{stats['done']} done")
365
+ return 0
366
+
367
+
368
+ def cmd_demo(args, k: Kernel) -> int:
369
+ if k.graph.tasks:
370
+ print("project is not empty; demo needs a fresh project", file=sys.stderr)
371
+ return 1
372
+ _seed_demo(k)
373
+ print("seeded demo project (Snake Game)")
374
+ return 0
375
+
376
+
377
+ def cmd_propose(args, k: Kernel) -> int:
378
+ from .sdk import ForgeClient, ProposalError
379
+ client = ForgeClient(args.dir)
380
+ try:
381
+ with open(args.file, encoding="utf-8") as f:
382
+ proposal = json.load(f)
383
+ except FileNotFoundError:
384
+ print(f"error: proposal file not found: {args.file}", file=sys.stderr)
385
+ return 1
386
+ except json.JSONDecodeError as e:
387
+ print(f"error: proposal file is not valid JSON: {e}", file=sys.stderr)
388
+ return 1
389
+ try:
390
+ # envelope check + kernel verdict: whole or nothing
391
+ result = client.propose(proposal)
392
+ except ProposalError as e:
393
+ print(f"proposal rejected (protocol): {e}", file=sys.stderr)
394
+ return 1
395
+ print(f"committed {result['committed']} events from {result['proposal_id']} "
396
+ f"(confidence {result['confidence']}) -> project now has "
397
+ f"{result['tasks']} tasks")
398
+ return 0
399
+
400
+
401
+ def cmd_context(args, k: Kernel) -> int:
402
+ from .sdk import ForgeClient
403
+ client = ForgeClient(args.dir)
404
+ print(client.context(args.task))
405
+ return 0
406
+
407
+
408
+ # --------------------------------------------------------------------------- parser
409
+ def build_parser() -> argparse.ArgumentParser:
410
+ p = argparse.ArgumentParser(prog="forge", description="Forge — a deterministic project kernel. "
411
+ "execution engine for autonomous software development. "
412
+ "Version " + __version__)
413
+ p.add_argument("-d", "--dir", default=".", help="project directory (default: .)")
414
+ sub = p.add_subparsers(dest="cmd", required=True)
415
+
416
+ sub.add_parser("init", help="create a new project (events.log) in DIR")
417
+
418
+ c = sub.add_parser("create", help="create a task")
419
+ c.add_argument("title")
420
+ c.add_argument("--id", help="explicit id (default: slug of title)")
421
+ c.add_argument("--desc", default="")
422
+ c.add_argument("-a", "--acceptance", action="append", default=[], help="repeatable")
423
+ c.add_argument("-f", "--file", action="append", default=[], help="repeatable")
424
+ c.add_argument("--priority", choices=["low", "medium", "high"], default="medium")
425
+
426
+ c = sub.add_parser("update", help="update task fields")
427
+ c.add_argument("task")
428
+ c.add_argument("--title")
429
+ c.add_argument("--desc")
430
+ c.add_argument("-a", "--acceptance", action="append", help="replaces the list")
431
+ c.add_argument("-f", "--file", action="append", help="replaces the list")
432
+ c.add_argument("--priority", choices=["low", "medium", "high"])
433
+
434
+ c = sub.add_parser("dep", help="add a dependency: TASK cannot finish until DEPENDS_ON is done")
435
+ c.add_argument("task")
436
+ c.add_argument("depends_on")
437
+ c.add_argument("--remove", action="store_true", help="remove instead of add")
438
+
439
+ c = sub.add_parser("expand", help="turn TASK into a container; it completes when children do")
440
+ c.add_argument("task")
441
+ c.add_argument("-c", "--child", action="append", required=True,
442
+ help="'Title' | 'Title::desc' | 'Title::desc::acc1;acc2' — repeatable")
443
+
444
+ c = sub.add_parser("start", help="todo -> in_progress")
445
+ c.add_argument("task")
446
+ c = sub.add_parser("verify-pass", help="in_progress/needs_revision -> done (requires deps done)")
447
+ c.add_argument("task")
448
+ c.add_argument("--force", action="store_true", help="pass even with incomplete dependencies")
449
+ c = sub.add_parser("verify-fail", help="in_progress -> needs_revision")
450
+ c.add_argument("task")
451
+ c.add_argument("--reason", required=True)
452
+ c = sub.add_parser("retry", help="needs_revision -> in_progress")
453
+ c.add_argument("task")
454
+ c = sub.add_parser("reopen", help="done -> in_progress")
455
+ c.add_argument("task")
456
+
457
+ c = sub.add_parser("evidence", help="attach evidence to a task")
458
+ c.add_argument("task")
459
+ c.add_argument("--kind", required=True, choices=["hard", "soft"],
460
+ help="hard = tests/compile/benchmark, soft = LLM/human review")
461
+ c.add_argument("--source", required=True)
462
+ c.add_argument("--detail", default="")
463
+
464
+ c = sub.add_parser("note", help="append a note to a task")
465
+ c.add_argument("task")
466
+ c.add_argument("text")
467
+
468
+ c = sub.add_parser("delete", help="delete a task (no dependents, no children)")
469
+ c.add_argument("task")
470
+
471
+ c = sub.add_parser("show", help="task context package (what an LLM client sees)")
472
+ c.add_argument("task")
473
+ c.add_argument("--json", action="store_true")
474
+
475
+ c = sub.add_parser("context", help="Context Contract package for TASK (YAML) — "
476
+ "the standard ~500-token handoff to any coding agent")
477
+ c.add_argument("task")
478
+
479
+ c = sub.add_parser("inspect", help="everything about one task: status, children, evidence, history")
480
+ c.add_argument("task")
481
+ c.add_argument("--json", action="store_true")
482
+
483
+ c = sub.add_parser("query", help="query the graph: 'status == needs_revision and priority == high'")
484
+ c.add_argument("expr", help="e.g. 'status == done', '\"snake\" in title', 'blockers(renderer)'")
485
+ c.add_argument("--json", action="store_true")
486
+
487
+ c = sub.add_parser("export", help="write the event log as portable JSON")
488
+ c.add_argument("file", nargs="?", help="output file (default: stdout)")
489
+
490
+ c = sub.add_parser("import", help="merge an exported event log into this project")
491
+ c.add_argument("file")
492
+
493
+ c = sub.add_parser("graph", help="render the task tree")
494
+ c.add_argument("task", nargs="?", help="render subtree rooted at TASK")
495
+
496
+ sub.add_parser("ready", help="list tasks ready to work on")
497
+ sub.add_parser("next", help="print the single next task (priority, then creation order)")
498
+ c = sub.add_parser("blockers", help="incomplete dependencies of TASK")
499
+ c.add_argument("task")
500
+ c.add_argument("--chain", action="store_true", help="show full root-cause paths")
501
+
502
+ sub.add_parser("progress", help="project progress summary")
503
+ sub.add_parser("validate", help="check graph consistency")
504
+ c = sub.add_parser("log", help="show the event log")
505
+ c.add_argument("--tail", type=int, help="only last N events")
506
+ c = sub.add_parser("undo", help="truncate the last N events from the log")
507
+ c.add_argument("count", nargs="?", type=int, default=1)
508
+ sub.add_parser("replay", help="reconstruct the graph from the log")
509
+ sub.add_parser("demo", help="seed a demo project (Snake Game)")
510
+
511
+ c = sub.add_parser("propose", help="commit a proposal file: protocol check, then kernel commits or rejects whole")
512
+ c.add_argument("file")
513
+
514
+ # Ecosystem plugins contribute their own subparsers via the
515
+ # forge.commands entry-point group (see forge/plugins.py). A known
516
+ # command whose package is not installed gets a stub subparser with an
517
+ # install hint instead of argparse's bare "invalid choice".
518
+ from .plugins import discover, stub_for_ecosystem
519
+ plugin_commands = discover(sub)
520
+ plugin_commands.update(stub_for_ecosystem(sub, plugin_commands))
521
+ p._forge_plugin_commands = plugin_commands
522
+
523
+ return p
524
+
525
+
526
+ COMMANDS = {
527
+ "init": cmd_init,
528
+ "create": cmd_create,
529
+ "update": cmd_update,
530
+ "dep": cmd_dep,
531
+ "expand": cmd_expand,
532
+ "start": cmd_start,
533
+ "verify-pass": cmd_verify_pass,
534
+ "verify-fail": cmd_verify_fail,
535
+ "retry": cmd_retry,
536
+ "reopen": cmd_reopen,
537
+ "evidence": cmd_evidence,
538
+ "note": cmd_note,
539
+ "delete": cmd_delete,
540
+ "show": cmd_show,
541
+ "context": cmd_context,
542
+ "inspect": cmd_inspect,
543
+ "query": cmd_query,
544
+ "export": cmd_export,
545
+ "import": cmd_import,
546
+ "graph": cmd_graph,
547
+ "ready": cmd_ready,
548
+ "next": cmd_next,
549
+ "blockers": cmd_blockers,
550
+ "progress": cmd_progress,
551
+ "validate": cmd_validate,
552
+ "log": cmd_log,
553
+ "undo": cmd_undo,
554
+ "replay": cmd_replay,
555
+ "demo": cmd_demo,
556
+ "propose": cmd_propose,
557
+ }
558
+
559
+
560
+ def main(argv: list[str] | None = None) -> int:
561
+ _setup_stdout()
562
+ parser = build_parser()
563
+ args = parser.parse_args(argv)
564
+ commands = dict(COMMANDS)
565
+ commands.update(getattr(parser, "_forge_plugin_commands", {}))
566
+ try:
567
+ if args.cmd == "init":
568
+ return cmd_init(args)
569
+ k = Kernel(args.dir)
570
+ return commands[args.cmd](args, k)
571
+ except GraphError as e:
572
+ print(f"error: {e}", file=sys.stderr)
573
+ return 1
574
+ except FileNotFoundError:
575
+ print(f"error: {args.dir} is not a project (run: forge init {args.dir})", file=sys.stderr)
576
+ return 1
577
+ except OSError as e:
578
+ # e.g. -d pointing at a file (FileExistsError from store.init) or a
579
+ # project whose events.log is a directory (PermissionError on open).
580
+ # Clean error, never a traceback.
581
+ print(f"error: {e}", file=sys.stderr)
582
+ return 1
583
+
584
+
585
+ if __name__ == "__main__":
586
+ sys.exit(main())