codersforge 0.0.1__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.
Files changed (41) hide show
  1. codersforge/__init__.py +4 -0
  2. codersforge/__main__.py +8 -0
  3. codersforge/_core/CORE_VERSION +33 -0
  4. codersforge/_core/__init__.py +8 -0
  5. codersforge/_core/archive.py +319 -0
  6. codersforge/_core/backup.py +417 -0
  7. codersforge/_core/config.py +206 -0
  8. codersforge/_core/domain.py +382 -0
  9. codersforge/_core/errors.py +36 -0
  10. codersforge/_core/events.py +381 -0
  11. codersforge/_core/findings.py +265 -0
  12. codersforge/_core/gates.py +395 -0
  13. codersforge/_core/identity.py +259 -0
  14. codersforge/_core/index.py +262 -0
  15. codersforge/_core/items.py +513 -0
  16. codersforge/_core/ledger.py +194 -0
  17. codersforge/_core/lessons.py +142 -0
  18. codersforge/_core/messages.py +293 -0
  19. codersforge/_core/migrate.py +221 -0
  20. codersforge/_core/output.py +41 -0
  21. codersforge/_core/paths.py +62 -0
  22. codersforge/_core/py.typed +0 -0
  23. codersforge/_core/schema.py +113 -0
  24. codersforge/_core/ulid.py +36 -0
  25. codersforge/_core/upgrade.py +57 -0
  26. codersforge/_core/versions.py +20 -0
  27. codersforge/_core/views.py +67 -0
  28. codersforge/_core/walls.py +231 -0
  29. codersforge/_core/workflow.py +745 -0
  30. codersforge/_docs.py +33 -0
  31. codersforge/checks.py +94 -0
  32. codersforge/cli.py +865 -0
  33. codersforge/domain.py +270 -0
  34. codersforge/py.typed +0 -0
  35. codersforge/workflows.yaml +129 -0
  36. codersforge-0.0.1.dist-info/METADATA +81 -0
  37. codersforge-0.0.1.dist-info/RECORD +41 -0
  38. codersforge-0.0.1.dist-info/WHEEL +4 -0
  39. codersforge-0.0.1.dist-info/entry_points.txt +2 -0
  40. codersforge-0.0.1.dist-info/licenses/LICENSE +202 -0
  41. codersforge-0.0.1.dist-info/licenses/NOTICE +7 -0
codersforge/cli.py ADDED
@@ -0,0 +1,865 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The ``codersforge`` command line (CONTRACT §10).
3
+
4
+ Every v1 command is registered here with its arguments. The shared core
5
+ (``codersforge._core``, vendored from Pluginforge) supplies errors, output,
6
+ config and the event log. Commands whose feature has not landed yet exit with
7
+ code 10 and name the feature that implements them.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import os
14
+ import sys
15
+ from collections.abc import Callable, Mapping, Sequence
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import Any, NoReturn
19
+
20
+ from codersforge import __version__
21
+ from codersforge._core.archive import Archiver
22
+ from codersforge._core.backup import Backups
23
+ from codersforge._core.config import init_project, load_config
24
+ from codersforge._core.errors import ExitCode, ForgeError
25
+ from codersforge._core.events import EventStore
26
+ from codersforge._core.findings import RESOLUTIONS, Findings
27
+ from codersforge._core.gates import CHANNELS, Gate, Gates
28
+ from codersforge._core.identity import Identity, resolve, run_hook
29
+ from codersforge._core.index import Index, require_type
30
+ from codersforge._core.items import Item, Items, parse_id
31
+ from codersforge._core.ledger import Ledger
32
+ from codersforge._core.lessons import Lessons
33
+ from codersforge._core.messages import KINDS as MSG_KINDS
34
+ from codersforge._core.messages import PRIORITIES as MSG_PRIORITIES
35
+ from codersforge._core.messages import STATES as MSG_STATES
36
+ from codersforge._core.messages import Messages
37
+ from codersforge._core.migrate import Migrator, Plan
38
+ from codersforge._core.output import Output
39
+ from codersforge._core.paths import Layout, find_root
40
+ from codersforge._core.views import describe_item
41
+ from codersforge._core.walls import lane_guard_hook
42
+ from codersforge.domain import DOMAIN, NEEDS_SEVERITY, PRIORITIES, REVISE_TARGETS, SEVERITIES
43
+
44
+ PROG = "codersforge"
45
+
46
+ ITEM_TYPES = tuple(t.name for t in DOMAIN.item_types)
47
+ GATE_KINDS = tuple(k.name for k in DOMAIN.gate_kinds)
48
+
49
+ Builder = Callable[[argparse.ArgumentParser], None]
50
+
51
+
52
+ class _Parser(argparse.ArgumentParser):
53
+ """An argparse parser that raises instead of printing and exiting with 2."""
54
+
55
+ def error(self, message: str) -> NoReturn:
56
+ raise ForgeError(ExitCode.USAGE, "usage", message)
57
+
58
+
59
+ def _no_args(_: argparse.ArgumentParser) -> None:
60
+ """Command takes no arguments."""
61
+
62
+
63
+ def _id(p: argparse.ArgumentParser, name: str = "id", help_text: str = "item ID") -> None:
64
+ p.add_argument(name, metavar=name.upper(), help=help_text)
65
+
66
+
67
+ def _build_init(p: argparse.ArgumentParser) -> None:
68
+ p.add_argument("--project", metavar="NAME", help="project name (default: the directory name)")
69
+
70
+
71
+ def _build_new(p: argparse.ArgumentParser) -> None:
72
+ p.add_argument("type", choices=ITEM_TYPES, help="item type")
73
+ p.add_argument("title", help="short title, 1-80 characters")
74
+ p.add_argument("--epic", metavar="ID")
75
+ p.add_argument("--priority", choices=PRIORITIES, default="normal")
76
+ p.add_argument("--severity", choices=SEVERITIES)
77
+ p.add_argument("--depends-on", metavar="ID", nargs="+", default=[])
78
+
79
+
80
+ def _build_move(p: argparse.ArgumentParser) -> None:
81
+ _id(p)
82
+ p.add_argument("state", metavar="STATE", help="target state (CONTRACT §6)")
83
+ p.add_argument("--note")
84
+
85
+
86
+ def _build_rename(p: argparse.ArgumentParser) -> None:
87
+ _id(p)
88
+ p.add_argument("title", help="new title")
89
+
90
+
91
+ def _build_assign(p: argparse.ArgumentParser) -> None:
92
+ _id(p)
93
+ p.add_argument("role", help="role name (CONTRACT §9)")
94
+ p.add_argument("--task")
95
+
96
+
97
+ def _build_gate_open(p: argparse.ArgumentParser) -> None:
98
+ p.add_argument("kind", choices=GATE_KINDS, metavar="KIND", help="gate kind (CONTRACT §7.1)")
99
+ p.add_argument("id", nargs="?", metavar="ID", help="item ID; omit for a project gate")
100
+ p.add_argument("--summary", required=True, help="what is being decided, 1-200 characters")
101
+ p.add_argument("--option", action="append", default=[], help="an answer offered; repeatable")
102
+
103
+
104
+ def _build_gate_rule(p: argparse.ArgumentParser) -> None:
105
+ _id(p, "gate", "gate ID, e.g. FEAT-0123:G2:1")
106
+ p.add_argument(
107
+ "ruling", metavar="RULING", help="one of the gate kind's rulings (CONTRACT §7.1)"
108
+ )
109
+ p.add_argument("--target", choices=REVISE_TARGETS, help="required with revise on G2")
110
+ p.add_argument("--note", help="required by some rulings, e.g. every risk response")
111
+ p.add_argument(
112
+ "--review-by",
113
+ metavar="YYYY-MM-DD",
114
+ help="when an accepted, shared or transferred risk is reviewed",
115
+ )
116
+ p.add_argument("--party", help="who a risk is shared with or transferred to")
117
+ p.add_argument(
118
+ "--channel", choices=CHANNELS, help="where the ruling was made (default: tui or console)"
119
+ )
120
+
121
+
122
+ def _build_gate_list(p: argparse.ArgumentParser) -> None:
123
+ p.add_argument("--open", action="store_true", help="only gates awaiting a ruling")
124
+ p.add_argument("--item", metavar="ID", help="only gates on this item")
125
+
126
+
127
+ def _build_finding_add(p: argparse.ArgumentParser) -> None:
128
+ _id(p)
129
+ p.add_argument("summary")
130
+ p.add_argument("--severity", choices=SEVERITIES, required=True)
131
+ p.add_argument("--rule", metavar="RULE-ID")
132
+ p.add_argument("--at", metavar="PATH:LINE")
133
+
134
+
135
+ def _build_finding_resolve(p: argparse.ArgumentParser) -> None:
136
+ _id(p, "finding", "finding ID")
137
+ p.add_argument("--how", choices=RESOLUTIONS, required=True)
138
+
139
+
140
+ def _build_msg_send(p: argparse.ArgumentParser) -> None:
141
+ p.add_argument("body", help="the message, at most 8 KiB; put larger content in a file")
142
+ p.add_argument("--from", dest="sender", required=True, metavar="ROLE", help="who said it")
143
+ p.add_argument("--to", required=True, metavar="ROLE", help="who it is for")
144
+ p.add_argument("--kind", choices=MSG_KINDS, required=True)
145
+ p.add_argument("--priority", choices=MSG_PRIORITIES, default="normal")
146
+ p.add_argument("--reply-to", metavar="MSG-ID")
147
+
148
+
149
+ def _build_msg_state(p: argparse.ArgumentParser) -> None:
150
+ _id(p, "msg", "message ID")
151
+ p.add_argument("state", choices=MSG_STATES)
152
+ p.add_argument(
153
+ "--until", metavar="TIMESTAMP", help="required with snoozed, e.g. 2026-11-20T09:00Z"
154
+ )
155
+
156
+
157
+ def _build_lesson_add(p: argparse.ArgumentParser) -> None:
158
+ p.add_argument("summary")
159
+ p.add_argument("--from", dest="from_item", metavar="ID")
160
+ p.add_argument("--tag", action="append", default=[])
161
+
162
+
163
+ def _build_list(p: argparse.ArgumentParser) -> None:
164
+ p.add_argument("--type", choices=ITEM_TYPES)
165
+ p.add_argument("--state", metavar="STATE")
166
+ p.add_argument("--epic", metavar="ID")
167
+ p.add_argument("--open", action="store_true", help="only items not DONE, ABANDONED or ARCHIVED")
168
+
169
+
170
+ def _build_ledger(p: argparse.ArgumentParser) -> None:
171
+ p.add_argument("--check", action="store_true", help="fail if LEDGER.md is stale")
172
+
173
+
174
+ def _build_migrate(p: argparse.ArgumentParser) -> None:
175
+ p.add_argument("--check", action="store_true", help="only report what is out of date")
176
+
177
+
178
+ def _build_backup(p: argparse.ArgumentParser) -> None:
179
+ p.add_argument("--to", metavar="DIR", help="folder outside the project (default: backup.dir)")
180
+ p.add_argument(
181
+ "--recipient",
182
+ action="append",
183
+ default=[],
184
+ metavar="KEY",
185
+ help="age or SSH public key that can decrypt it; repeatable (default: backup.recipients)",
186
+ )
187
+
188
+
189
+ def _build_restore(p: argparse.ArgumentParser) -> None:
190
+ p.add_argument("archive", metavar="ARCHIVE")
191
+ p.add_argument(
192
+ "--identity", required=True, metavar="FILE", help="age identity (private key) file"
193
+ )
194
+
195
+
196
+ # (name, help, builder, feature that implements it)
197
+ COMMANDS: tuple[tuple[str, str, Builder, str], ...] = (
198
+ ("init", "create .codersforge/ for this repository", _build_init, "FEAT-0013"),
199
+ ("new", "create an item", _build_new, "FEAT-0004"),
200
+ ("move", "move an item to another state", _build_move, "FEAT-0005"),
201
+ ("rename", "rename an item", _build_rename, "FEAT-0004"),
202
+ ("assign", "assign an item to a role", _build_assign, "FEAT-0004"),
203
+ ("show", "show an item, its state, gates, findings and history", _id, "FEAT-0007"),
204
+ ("list", "list items in ID order", _build_list, "FEAT-0010"),
205
+ ("ledger", "regenerate LEDGER.md", _build_ledger, "FEAT-0011"),
206
+ ("reindex", "rebuild the index from the event log", _no_args, "FEAT-0010"),
207
+ ("archive", "roll up a closed item", _id, "FEAT-0012"),
208
+ ("verify", "check the event log's hash chain", _no_args, "FEAT-0002"),
209
+ ("migrate", "upgrade schema versions", _build_migrate, "FEAT-0014"),
210
+ ("backup", "write an encrypted archive of .codersforge/", _build_backup, "FEAT-0015"),
211
+ ("restore", "restore an archive and verify it", _build_restore, "FEAT-0015"),
212
+ )
213
+
214
+ # (group, help, ((subcommand, help, builder, feature), ...))
215
+ GROUPS: tuple[tuple[str, str, tuple[tuple[str, str, Builder, str], ...]], ...] = (
216
+ (
217
+ "gate",
218
+ "open, rule and list gates",
219
+ (
220
+ ("open", "open a gate on an item or the project", _build_gate_open, "FEAT-0006"),
221
+ ("rule", "rule on a gate (operator only)", _build_gate_rule, "FEAT-0006"),
222
+ ("list", "list gates", _build_gate_list, "FEAT-0006"),
223
+ ),
224
+ ),
225
+ (
226
+ "finding",
227
+ "record and resolve findings",
228
+ (
229
+ ("add", "add a finding to an item", _build_finding_add, "FEAT-0007"),
230
+ ("resolve", "resolve a finding", _build_finding_resolve, "FEAT-0007"),
231
+ ),
232
+ ),
233
+ (
234
+ "msg",
235
+ "relay messages between roles (orchestrator only)",
236
+ (
237
+ ("send", "send a message", _build_msg_send, "FEAT-0008"),
238
+ ("state", "record a message state change", _build_msg_state, "FEAT-0008"),
239
+ ),
240
+ ),
241
+ (
242
+ "lesson",
243
+ "record lessons",
244
+ (("add", "add a lesson", _build_lesson_add, "FEAT-0007"),),
245
+ ),
246
+ (
247
+ "hook",
248
+ "Claude Code hook entry points (read hook input on stdin)",
249
+ (
250
+ ("identity", "PreToolUse: pin the caller's role", _no_args, "FEAT-0003"),
251
+ (
252
+ "lane-guard",
253
+ "PreToolUse: deny reads and writes behind a wall",
254
+ _no_args,
255
+ "FEAT-0009",
256
+ ),
257
+ ),
258
+ ),
259
+ )
260
+
261
+ #: Commands that run without a pinned identity (CONTRACT §9): they write no events.
262
+ NO_IDENTITY = frozenset(
263
+ {"init", "verify", "show", "list", "gate list", "hook identity", "hook lane-guard"}
264
+ )
265
+
266
+
267
+ def command_names() -> list[str]:
268
+ """Every v1 command as typed, e.g. ``gate rule``."""
269
+ names = [name for name, _, _, _ in COMMANDS]
270
+ for group, _, subs in GROUPS:
271
+ names.extend(f"{group} {sub}" for sub, _, _, _ in subs)
272
+ return names
273
+
274
+
275
+ def _global_options() -> _Parser:
276
+ """Options accepted both before and after the command name."""
277
+ common = _Parser(add_help=False, argument_default=argparse.SUPPRESS)
278
+ common.add_argument("--json", action="store_true", help="one JSON document on stdout")
279
+ common.add_argument(
280
+ "--root", metavar="PATH", help="repository root (default: nearest .codersforge/)"
281
+ )
282
+ common.add_argument("--quiet", action="store_true", help="errors only")
283
+ return common
284
+
285
+
286
+ def build_parser() -> argparse.ArgumentParser:
287
+ """The complete argument parser."""
288
+ common = _global_options()
289
+ epilog = "commands:\n" + "\n".join(f" {name}" for name in command_names())
290
+ parser = _Parser(
291
+ prog=PROG,
292
+ description="Codersforge: a gated, multi-agent product team for Claude Code.",
293
+ epilog=epilog,
294
+ formatter_class=argparse.RawDescriptionHelpFormatter,
295
+ parents=[common],
296
+ )
297
+ parser.add_argument("--version", action="version", version=f"{PROG} {__version__}")
298
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND", required=True)
299
+
300
+ for name, help_text, builder, feature in COMMANDS:
301
+ p = sub.add_parser(name, help=help_text, parents=[common])
302
+ builder(p)
303
+ p.set_defaults(feature=feature, command_name=name)
304
+
305
+ for group, help_text, subs in GROUPS:
306
+ g = sub.add_parser(group, help=help_text, parents=[common])
307
+ gsub = g.add_subparsers(dest="subcommand", metavar="SUBCOMMAND", required=True)
308
+ for sub_name, sub_help, builder, feature in subs:
309
+ p = gsub.add_parser(sub_name, help=sub_help, parents=[common])
310
+ builder(p)
311
+ p.set_defaults(feature=feature, command_name=f"{group} {sub_name}")
312
+
313
+ return parser
314
+
315
+
316
+ def _wants_json(argv: Sequence[str]) -> bool:
317
+ """Whether ``--json`` was given, known even when parsing fails."""
318
+ return "--json" in argv
319
+
320
+
321
+ def _root_arg(args: argparse.Namespace) -> Path | None:
322
+ root = getattr(args, "root", None)
323
+ return Path(root) if root else None
324
+
325
+
326
+ @dataclass(frozen=True)
327
+ class Context:
328
+ """What a command handler gets: its arguments, output, and pinned identity."""
329
+
330
+ args: argparse.Namespace
331
+ out: Output
332
+ identity: Identity | None = None
333
+
334
+ def who(self) -> Identity:
335
+ """The pinned identity; an internal error if the command was not given one."""
336
+ if self.identity is None:
337
+ raise ForgeError(ExitCode.INTERNAL, "no_identity", f"{self.args.command_name} wrote")
338
+ return self.identity
339
+
340
+ def emit(
341
+ self,
342
+ store: EventStore,
343
+ event_type: str,
344
+ data: Mapping[str, Any] | None = None,
345
+ *,
346
+ item: str | None = None,
347
+ title: str | None = None,
348
+ ) -> dict[str, Any]:
349
+ """Append an event as the pinned identity. There is no way to name another actor."""
350
+ who = self.who()
351
+ return store.append(
352
+ event_type,
353
+ actor=who.role,
354
+ session=who.session,
355
+ data=data,
356
+ item=item,
357
+ title=title,
358
+ )
359
+
360
+
361
+ def needs_identity(args: argparse.Namespace) -> bool:
362
+ """Whether a parsed command must run under a pinned role."""
363
+ if args.command_name in {"ledger", "migrate"}:
364
+ return not args.check
365
+ return args.command_name not in NO_IDENTITY
366
+
367
+
368
+ def _cmd_init(ctx: Context) -> None:
369
+ args, out = ctx.args, ctx.out
370
+ root = _root_arg(args) or Path.cwd()
371
+ layout = init_project(root, DOMAIN, args.project)
372
+ repo = (layout.state / ".git").is_dir()
373
+ history = (
374
+ "It is a git repository of its own."
375
+ if repo
376
+ else "WARNING: git was not found, so it has no history; install git and run `git init` "
377
+ f"in {DOMAIN.state_dir}/."
378
+ )
379
+ out.result(
380
+ {"ok": True, "root": str(layout.root), "state": str(layout.state), "git": repo},
381
+ f"Initialized {DOMAIN.state_dir}/ in {layout.root}. It is private: "
382
+ f"{DOMAIN.state_dir}/ is in .gitignore and is never committed. {history}",
383
+ )
384
+
385
+
386
+ def _cmd_verify(ctx: Context) -> None:
387
+ args, out = ctx.args, ctx.out
388
+ layout = find_root(DOMAIN, explicit=_root_arg(args))
389
+ load_config(layout, DOMAIN)
390
+ result = EventStore(layout, DOMAIN).verify()
391
+ if not result.ok:
392
+ raise ForgeError(
393
+ ExitCode.DATA,
394
+ "chain_broken",
395
+ f"{layout.events} line {result.line}: {result.reason} "
396
+ f"({result.events} events before it are intact)",
397
+ )
398
+ noun = "event" if result.events == 1 else "events"
399
+ out.result(
400
+ {"ok": True, "events": result.events},
401
+ f"Event log intact: {result.events} {noun}, hash chain verified.",
402
+ )
403
+
404
+
405
+ def _items(ctx: Context) -> Items:
406
+ layout = find_root(DOMAIN, explicit=_root_arg(ctx.args))
407
+ config = load_config(layout, DOMAIN)
408
+ return Items(layout, DOMAIN, ctx.identity, config.data)
409
+
410
+
411
+ def _where(items: Items, item: Item) -> str:
412
+ """``ID — title — path``, the contract's form for an item with a file."""
413
+ path = items.file(item).relative_to(items.layout.root)
414
+ return f"{item.label()} \u2014 {path}"
415
+
416
+
417
+ def _new_fields(args: argparse.Namespace, items: Items, identity: Identity) -> dict[str, Any]:
418
+ """Codersforge's rules for a new item, checked before anything is written."""
419
+ if args.type in NEEDS_SEVERITY and args.severity is None:
420
+ raise ForgeError(
421
+ ExitCode.USAGE, "severity_required", f"a {args.type} needs --severity (CONTRACT §7.3)"
422
+ )
423
+ if args.type not in NEEDS_SEVERITY and args.severity is not None:
424
+ raise ForgeError(
425
+ ExitCode.USAGE,
426
+ "severity_not_allowed",
427
+ f"only {' and '.join(sorted(NEEDS_SEVERITY))} items have a severity",
428
+ )
429
+ known = items.all() if (args.epic or args.depends_on) else {}
430
+ if args.epic:
431
+ if args.type == "epic":
432
+ raise ForgeError(ExitCode.USAGE, "epic_in_epic", "an epic cannot belong to an epic")
433
+ parse_id(args.epic)
434
+ parent = known.get(args.epic)
435
+ if parent is None:
436
+ raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {args.epic}")
437
+ if parent.type != "epic":
438
+ raise ForgeError(
439
+ ExitCode.USAGE, "not_an_epic", f"{parent.label()} is a {parent.type}, not an epic"
440
+ )
441
+ depends_on = list(dict.fromkeys(args.depends_on))
442
+ for dep in depends_on:
443
+ parse_id(dep)
444
+ if dep not in known:
445
+ raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {dep}")
446
+ # Trust records where the request came from (CONTRACT §4). `new` never makes
447
+ # external items: those arrive through import.
448
+ trust = "operator" if identity.role in {"operator", "orchestrator"} else "trusted"
449
+ return {
450
+ "epic": args.epic,
451
+ "priority": args.priority,
452
+ "severity": args.severity,
453
+ "depends_on": depends_on,
454
+ "trust": trust,
455
+ }
456
+
457
+
458
+ def _cmd_new(ctx: Context) -> None:
459
+ items = _items(ctx)
460
+ fields = _new_fields(ctx.args, items, ctx.who())
461
+ item = items.create(ctx.args.type, ctx.args.title, fields)
462
+ ctx.out.result(item.as_dict(), f"Created {_where(items, item)}")
463
+
464
+
465
+ def _cmd_rename(ctx: Context) -> None:
466
+ items = _items(ctx)
467
+ item, old = items.rename(ctx.args.id, ctx.args.title)
468
+ if old == item.title:
469
+ ctx.out.result(item.as_dict(), f"Unchanged: {item.label()}")
470
+ else:
471
+ ctx.out.result(item.as_dict(), f"Renamed {item.label()} (was: {old})")
472
+
473
+
474
+ def _cmd_archive(ctx: Context) -> None:
475
+ layout, config = _layout_and_config(ctx)
476
+ done = Archiver(layout, DOMAIN, ctx.who(), config).archive(ctx.args.id)
477
+ rollup = (layout.state / done.item.path).relative_to(layout.root)
478
+ removed = f"{DOMAIN.state_dir}/{done.removed}"
479
+ if done.finished:
480
+ message = f"Finished archiving {done.item.label()}: removed {removed}, kept {rollup}"
481
+ else:
482
+ count = len(done.files)
483
+ noun = "file" if count == 1 else "files"
484
+ message = (
485
+ f"Archived {done.item.label()} ({done.previous_state}) \u2192 {rollup}; "
486
+ f"{count} {noun} rolled up, {removed} removed"
487
+ )
488
+ ctx.out.result(done.as_dict(), message)
489
+
490
+
491
+ def _cmd_move(ctx: Context) -> None:
492
+ items = _items(ctx)
493
+ item, old = items.move(ctx.args.id, ctx.args.state, ctx.args.note)
494
+ ctx.out.result(
495
+ {**item.as_dict(), "from": old},
496
+ f"Moved {item.label()}: {old} \u2192 {item.state}",
497
+ )
498
+
499
+
500
+ def _cmd_assign(ctx: Context) -> None:
501
+ items = _items(ctx)
502
+ item = items.assign(ctx.args.id, ctx.args.role, ctx.args.task)
503
+ ctx.out.result(item.as_dict(), f"Assigned {item.label()} to {item.assignee}")
504
+
505
+
506
+ def _gates(ctx: Context) -> Gates:
507
+ layout = find_root(DOMAIN, explicit=_root_arg(ctx.args))
508
+ config = load_config(layout, DOMAIN)
509
+ return Gates(layout, DOMAIN, ctx.identity, config.data)
510
+
511
+
512
+ def _gate_line(gate: Gate, titles: Mapping[str, str]) -> str:
513
+ """``GATE-ID — summary — on ID — title — status``; desk-only is marked."""
514
+ on = f" \u2014 on {gate.item} \u2014 {titles.get(gate.item, '?')}" if gate.item else ""
515
+ desk = " (desk-only)" if gate.desk_only else ""
516
+ return f"{gate.id} \u2014 {gate.summary}{on} \u2014 {gate.status()}{desk}"
517
+
518
+
519
+ def _titles(gates: Gates) -> dict[str, str]:
520
+ return {i.id: i.title for i in Items(gates.layout, DOMAIN).all().values()}
521
+
522
+
523
+ def _cmd_gate_open(ctx: Context) -> None:
524
+ gates = _gates(ctx)
525
+ gate = gates.open(ctx.args.kind, ctx.args.id, ctx.args.summary, ctx.args.option)
526
+ ctx.out.result(gate.as_dict(), f"Opened {_gate_line(gate, _titles(gates))}")
527
+
528
+
529
+ def _cmd_gate_rule(ctx: Context) -> None:
530
+ gates = _gates(ctx)
531
+ who = ctx.who()
532
+ channel = ctx.args.channel or ("tui" if who.session == "tui" else "console")
533
+ gate = gates.rule(
534
+ ctx.args.gate,
535
+ ctx.args.ruling,
536
+ channel=channel,
537
+ target=ctx.args.target,
538
+ note=ctx.args.note,
539
+ review_by=ctx.args.review_by,
540
+ party=ctx.args.party,
541
+ )
542
+ ctx.out.result(gate.as_dict(), f"Ruled {_gate_line(gate, _titles(gates))}")
543
+
544
+
545
+ def _cmd_gate_list(ctx: Context) -> None:
546
+ gates = _gates(ctx)
547
+ found = [
548
+ g
549
+ for g in gates.all().values()
550
+ if (not ctx.args.open or g.is_open) and (ctx.args.item is None or g.item == ctx.args.item)
551
+ ]
552
+ titles = _titles(gates)
553
+ lines = [_gate_line(g, titles) for g in found] or ["No gates."]
554
+ ctx.out.result({"gates": [g.as_dict() for g in found]}, "\n".join(lines))
555
+
556
+
557
+ def _layout_and_config(ctx: Context) -> tuple[Layout, Mapping[str, Any]]:
558
+ layout = find_root(DOMAIN, explicit=_root_arg(ctx.args))
559
+ return layout, load_config(layout, DOMAIN).data
560
+
561
+
562
+ def _cmd_finding_add(ctx: Context) -> None:
563
+ layout, _ = _layout_and_config(ctx)
564
+ found = Findings(layout, DOMAIN, ctx.identity).add(
565
+ ctx.args.id, ctx.args.severity, ctx.args.summary, rule=ctx.args.rule, at=ctx.args.at
566
+ )
567
+ where = f" at {found.at}" if found.at else ""
568
+ ctx.out.result(
569
+ found.as_dict(), f"Raised {found.id} \u2014 {found.severity} \u2014 {found.summary}{where}"
570
+ )
571
+
572
+
573
+ def _cmd_finding_resolve(ctx: Context) -> None:
574
+ layout, _ = _layout_and_config(ctx)
575
+ found = Findings(layout, DOMAIN, ctx.identity).resolve(ctx.args.finding, ctx.args.how)
576
+ ctx.out.result(
577
+ found.as_dict(), f"Resolved {found.id} \u2014 {found.summary} \u2014 {found.status()}"
578
+ )
579
+
580
+
581
+ def _cmd_lesson_add(ctx: Context) -> None:
582
+ layout, _ = _layout_and_config(ctx)
583
+ lesson = Lessons(layout, DOMAIN, ctx.identity).add(
584
+ ctx.args.summary, from_item=ctx.args.from_item, tags=ctx.args.tag
585
+ )
586
+ ctx.out.result(lesson.as_dict(), f"Recorded {lesson.label()}")
587
+
588
+
589
+ def _cmd_msg_send(ctx: Context) -> None:
590
+ layout, config = _layout_and_config(ctx)
591
+ message = Messages(layout, DOMAIN, ctx.identity, config).send(
592
+ ctx.args.sender,
593
+ ctx.args.to,
594
+ ctx.args.kind,
595
+ ctx.args.body,
596
+ priority=ctx.args.priority,
597
+ reply_to=ctx.args.reply_to,
598
+ )
599
+ ctx.out.result(message.as_dict(), f"Relayed {message.label()} \u2014 {message.outcome}")
600
+
601
+
602
+ def _cmd_msg_state(ctx: Context) -> None:
603
+ layout, config = _layout_and_config(ctx)
604
+ message = Messages(layout, DOMAIN, ctx.identity, config).set_state(
605
+ ctx.args.msg, ctx.args.state, until=ctx.args.until
606
+ )
607
+ until = f" until {message.until}" if message.until else ""
608
+ ctx.out.result(message.as_dict(), f"{message.label()} \u2014 {message.state}{until}")
609
+
610
+
611
+ def _cmd_show(ctx: Context) -> None:
612
+ layout, _ = _layout_and_config(ctx)
613
+ events = list(EventStore(layout, DOMAIN).events())
614
+ if ctx.args.id.startswith("LESSON-"):
615
+ lessons = Lessons(layout, DOMAIN)
616
+ lesson = lessons.all().get(ctx.args.id)
617
+ if lesson is None:
618
+ raise ForgeError(ExitCode.NOT_FOUND, "lesson_not_found", f"no lesson {ctx.args.id}")
619
+ tags = f" [{', '.join(lesson.tags)}]" if lesson.tags else ""
620
+ source = f" \u2014 from {lesson.from_item}" if lesson.from_item else ""
621
+ ctx.out.result(lesson.as_dict(), f"{lesson.label()}{tags}{source}")
622
+ return
623
+ view = describe_item(events, DOMAIN, ctx.args.id)
624
+ item = view.item
625
+ path = (layout.state / item.path).relative_to(layout.root)
626
+ facts = [item.type, item.state, f"priority {item.fields.get('priority', 'normal')}"]
627
+ if item.fields.get("severity"):
628
+ facts.append(f"severity {item.fields['severity']}")
629
+ if item.fields.get("epic"):
630
+ facts.append(f"epic {item.fields['epic']}")
631
+ if item.assignee:
632
+ facts.append(f"assigned {item.assignee}")
633
+ lines = [f"{item.label()} \u2014 {path}", " " + " \u00b7 ".join(facts)]
634
+ sections = (
635
+ ("Gates", [f"{g.id} \u2014 {g.summary} \u2014 {g.status()}" for g in view.gates]),
636
+ (
637
+ "Findings",
638
+ [
639
+ f"{f.id} \u2014 {f.severity} \u2014 {f.summary} \u2014 {f.status()}"
640
+ for f in view.findings
641
+ ],
642
+ ),
643
+ ("Lessons", [x.label() for x in view.lessons]),
644
+ (
645
+ "History",
646
+ [
647
+ f"{h['ts'][:16].replace('T', ' ')} {h['actor']}: {h['from']} \u2192 {h['to']}"
648
+ for h in view.history
649
+ ],
650
+ ),
651
+ )
652
+ for title, rows in sections:
653
+ if rows:
654
+ lines.append(f"{title}:")
655
+ lines.extend(f" {row}" for row in rows)
656
+ ctx.out.result(view.as_dict(), "\n".join(lines))
657
+
658
+
659
+ def _cmd_list(ctx: Context) -> None:
660
+ layout, _ = _layout_and_config(ctx)
661
+ require_type(DOMAIN, ctx.args.type)
662
+ found = Index(layout, DOMAIN).items(
663
+ type_name=ctx.args.type,
664
+ state=ctx.args.state,
665
+ epic=ctx.args.epic,
666
+ open_only=ctx.args.open,
667
+ )
668
+ dash = " \u2014 "
669
+ lines = [dash.join((i.id, i.title, i.state, i.type)) for i in found] or ["No items."]
670
+ ctx.out.result({"items": [i.as_dict() for i in found]}, "\n".join(lines))
671
+
672
+
673
+ def _cmd_reindex(ctx: Context) -> None:
674
+ layout, _ = _layout_and_config(ctx)
675
+ index = Index(layout, DOMAIN)
676
+ repair = index.reindex()
677
+ count = len(index.items())
678
+ lines = [f"Rebuilt the index: {count} items."]
679
+ if repair.states_fixed:
680
+ lines.append(f"Front-matter corrected from the log: {', '.join(repair.states_fixed)}")
681
+ if repair.files_recreated:
682
+ lines.append(f"Item files recreated from the log: {', '.join(repair.files_recreated)}")
683
+ doc = {
684
+ "items": count,
685
+ "states_fixed": list(repair.states_fixed),
686
+ "files_recreated": list(repair.files_recreated),
687
+ "archives_damaged": list(repair.archives_damaged),
688
+ }
689
+ if repair.archives_damaged:
690
+ # A rollup is the only copy of a closed item's files: never rebuilt, always loud.
691
+ raise ForgeError(
692
+ ExitCode.DATA,
693
+ "archive_damaged",
694
+ "missing or not matching the log: "
695
+ + ", ".join(f"{DOMAIN.state_dir}/archive/{i}.md" for i in repair.archives_damaged)
696
+ + "; restore them from a backup",
697
+ )
698
+ ctx.out.result(doc, "\n".join(lines))
699
+
700
+
701
+ def _cmd_ledger(ctx: Context) -> None:
702
+ layout, config = _layout_and_config(ctx)
703
+ ledger = Ledger(layout, DOMAIN, str(config["project"]))
704
+ events = list(EventStore(layout, DOMAIN).events())
705
+ names = [f"{DOMAIN.state_dir}/{name}" for name in ledger.paths()]
706
+ if ctx.args.check:
707
+ stale = ledger.stale(events)
708
+ if stale:
709
+ raise ForgeError(
710
+ ExitCode.REFUSED,
711
+ "ledger_stale",
712
+ f"out of date: {', '.join(stale)}; run `{DOMAIN.name} ledger`",
713
+ )
714
+ ctx.out.result({"stale": []}, f"Current: {', '.join(names)}")
715
+ return
716
+ changed = ledger.write(events)
717
+ message = f"Wrote {', '.join(changed)}" if changed else f"Already current: {', '.join(names)}"
718
+ ctx.out.result({"changed": changed}, message)
719
+
720
+
721
+ def _cmd_backup(ctx: Context) -> None:
722
+ layout, config = _layout_and_config(ctx)
723
+ settings = config["backup"]
724
+ to = ctx.args.to or settings["dir"]
725
+ if not to:
726
+ raise ForgeError(
727
+ ExitCode.USAGE,
728
+ "no_backup_dir",
729
+ "name a folder outside the project: --to DIR, or backup.dir in config.yaml",
730
+ )
731
+ recipients = ctx.args.recipient or list(settings["recipients"])
732
+ made = Backups(layout, DOMAIN, ctx.who()).create(Path(to), recipients, str(config["project"]))
733
+ noun = "recipient" if made.recipients == 1 else "recipients"
734
+ message = (
735
+ f"Backed up {DOMAIN.state_dir}/ ({made.events} events, {made.files} files) "
736
+ f"\u2192 {made.path}, encrypted to {made.recipients} {noun}"
737
+ )
738
+ if not made.chain_ok:
739
+ message += f"\nWARNING: the event log's hash chain is broken; run `{DOMAIN.name} verify`"
740
+ ctx.out.result(made.as_dict(), message)
741
+
742
+
743
+ def _cmd_restore(ctx: Context) -> None:
744
+ root = _root_arg(ctx.args) or Path.cwd()
745
+ layout = Layout.at(root, DOMAIN)
746
+ done = Backups(layout, DOMAIN, ctx.who()).restore(
747
+ Path(ctx.args.archive), Path(ctx.args.identity)
748
+ )
749
+ ctx.out.result(
750
+ done.as_dict(),
751
+ f"Restored {DOMAIN.state_dir}/ from {done.archive.name} (made {done.created}): "
752
+ f"{done.events} events and {done.files} files verified",
753
+ )
754
+
755
+
756
+ def _describe_plan(plan: Plan) -> str:
757
+ parts = []
758
+ if plan.events:
759
+ parts.append(f"{plan.events} event{'s' if plan.events != 1 else ''}")
760
+ if plan.items:
761
+ ids = ", ".join(i for i, _ in plan.items)
762
+ parts.append(f"{len(plan.items)} item file{'s' if len(plan.items) != 1 else ''} ({ids})")
763
+ if plan.config:
764
+ parts.append("config.yaml")
765
+ return ", ".join(parts)
766
+
767
+
768
+ def _cmd_migrate(ctx: Context) -> None:
769
+ layout, config = _layout_and_config(ctx)
770
+ migrator = Migrator(layout, DOMAIN, ctx.identity, config)
771
+ if ctx.args.check:
772
+ plan = migrator.plan()
773
+ if not plan.empty:
774
+ raise ForgeError(
775
+ ExitCode.REFUSED,
776
+ "migration_needed",
777
+ f"older than this release: {_describe_plan(plan)}; "
778
+ f"run `{DOMAIN.name} migrate` as the operator",
779
+ )
780
+ ctx.out.result(plan.as_dict(), "Nothing to migrate: every record is current")
781
+ return
782
+ done = migrator.run()
783
+ if done.backup is None:
784
+ ctx.out.result(done.as_dict(), "Nothing to migrate: every record is current")
785
+ return
786
+ ctx.out.result(
787
+ done.as_dict(),
788
+ f"Migrated {_describe_plan(done.plan)}. Originals are in {DOMAIN.state_dir}/{done.backup}/",
789
+ )
790
+
791
+
792
+ def _cmd_hook_lane_guard(_: Context) -> None:
793
+ response = run_hook(DOMAIN, sys.stdin.read(), lane_guard_hook)
794
+ if response:
795
+ sys.stdout.write(response + "\n")
796
+
797
+
798
+ def _cmd_hook_identity(_: Context) -> None:
799
+ # Hook output is Claude Code's format, not ours: print it as-is, or nothing.
800
+ response = run_hook(DOMAIN, sys.stdin.read())
801
+ if response:
802
+ sys.stdout.write(response + "\n")
803
+
804
+
805
+ HANDLERS: dict[str, Callable[[Context], None]] = {
806
+ "init": _cmd_init,
807
+ "verify": _cmd_verify,
808
+ "new": _cmd_new,
809
+ "move": _cmd_move,
810
+ "archive": _cmd_archive,
811
+ "rename": _cmd_rename,
812
+ "assign": _cmd_assign,
813
+ "gate open": _cmd_gate_open,
814
+ "gate rule": _cmd_gate_rule,
815
+ "gate list": _cmd_gate_list,
816
+ "finding add": _cmd_finding_add,
817
+ "finding resolve": _cmd_finding_resolve,
818
+ "lesson add": _cmd_lesson_add,
819
+ "show": _cmd_show,
820
+ "list": _cmd_list,
821
+ "reindex": _cmd_reindex,
822
+ "ledger": _cmd_ledger,
823
+ "migrate": _cmd_migrate,
824
+ "backup": _cmd_backup,
825
+ "restore": _cmd_restore,
826
+ "msg send": _cmd_msg_send,
827
+ "msg state": _cmd_msg_state,
828
+ "hook identity": _cmd_hook_identity,
829
+ "hook lane-guard": _cmd_hook_lane_guard,
830
+ }
831
+
832
+
833
+ def _run(args: argparse.Namespace, out: Output) -> None:
834
+ """Dispatch a parsed command: pin identity first, so a refusal comes before anything."""
835
+ identity = resolve(DOMAIN) if needs_identity(args) else None
836
+ handler = HANDLERS.get(args.command_name)
837
+ if handler is None:
838
+ raise ForgeError(
839
+ ExitCode.INTERNAL,
840
+ "not_implemented",
841
+ f"'{args.command_name}' is not implemented yet; it arrives with {args.feature}",
842
+ )
843
+ handler(Context(args, out, identity))
844
+
845
+
846
+ def main(argv: Sequence[str] | None = None) -> int:
847
+ """Entry point. Returns the process exit code."""
848
+ arguments = list(sys.argv[1:] if argv is None else argv)
849
+ out = Output(prog=PROG, json_mode=_wants_json(arguments))
850
+ try:
851
+ args = build_parser().parse_args(arguments)
852
+ out = Output(
853
+ prog=PROG, json_mode=getattr(args, "json", False), quiet=getattr(args, "quiet", False)
854
+ )
855
+ _run(args, out)
856
+ except ForgeError as err:
857
+ out.error(err)
858
+ return int(err.code)
859
+ except Exception as exc: # last resort: never show a traceback by default
860
+ if os.environ.get(DOMAIN.env("DEBUG")) == "1":
861
+ raise
862
+ detail = f"{type(exc).__name__}: {exc}"
863
+ out.error(ForgeError(ExitCode.INTERNAL, "internal_error", detail))
864
+ return int(ExitCode.INTERNAL)
865
+ return int(ExitCode.OK)