@michelj/context-guard 0.4.4 → 0.6.2

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 (101) hide show
  1. package/Coordinator.md +88 -0
  2. package/Executor.md +53 -0
  3. package/README.md +72 -102
  4. package/README.zh-CN.md +72 -102
  5. package/SKILL.md +26 -33
  6. package/THIRD_PARTY_NOTICES.md +47 -0
  7. package/Tester.md +53 -0
  8. package/bin/build-runtime.mjs +96 -0
  9. package/bin/context-guard-skill.js +287 -69
  10. package/bin/postinstall.js +1 -1
  11. package/hooks.json +80 -4
  12. package/licenses/JSONParse-MIT.txt +24 -0
  13. package/licenses/Marked-MIT.txt +44 -0
  14. package/licenses/Portless-Apache-2.0.txt +201 -0
  15. package/package.json +31 -5
  16. package/prototype/LICENSES/Marked-MIT.txt +44 -0
  17. package/prototype/LICENSES/Ready-redistribution.txt +14 -0
  18. package/prototype/attachments.mjs +75 -0
  19. package/prototype/coordinator-markdown.mjs +283 -0
  20. package/prototype/coordinator-working-blot.mjs +124 -0
  21. package/prototype/vendor/marked.mjs +2189 -0
  22. package/prototype/workbench-app.js +5197 -0
  23. package/prototype/workbench-data.js +33 -0
  24. package/prototype/workbench-sync.mjs +898 -0
  25. package/prototype/workbench.css +1050 -0
  26. package/prototype/workbench.html +139 -4861
  27. package/prototype/working-blot-atlas.png +0 -0
  28. package/references/agent-handoff.md +40 -0
  29. package/references/claude-runtime.md +120 -0
  30. package/references/cloud-sync-interface.md +66 -0
  31. package/references/design-current.md +14 -0
  32. package/references/map-mount.md +41 -0
  33. package/references/map-read.md +50 -0
  34. package/references/memory-definition.md +120 -0
  35. package/references/memory-filesystem-v2/Bug.en.md +162 -0
  36. package/references/memory-filesystem-v2/Bug.md +162 -0
  37. package/references/memory-filesystem-v2/Bug_Coordinater.md +8 -0
  38. package/references/memory-filesystem-v2/Bug_Executor.md +8 -0
  39. package/references/memory-filesystem-v2/Bug_Tester.md +7 -0
  40. package/references/memory-filesystem-v2/Idea.en.md +36 -0
  41. package/references/memory-filesystem-v2/Idea.md +36 -0
  42. package/references/memory-filesystem-v2/Node_Module_Index.en.md +88 -0
  43. package/references/memory-filesystem-v2/Node_Module_Index.md +88 -0
  44. package/references/memory-filesystem-v2/README.md +60 -0
  45. package/references/memory-filesystem-v2/Todo.en.md +137 -0
  46. package/references/memory-filesystem-v2/Todo.md +137 -0
  47. package/references/memory-filesystem-v2/Todo_Coordinater.md +7 -0
  48. package/references/memory-filesystem-v2/Todo_Executor.md +7 -0
  49. package/references/memory-filesystem-v2/Todo_Tester.md +7 -0
  50. package/references/named-workbench.md +124 -0
  51. package/references/plan-review.md +12 -0
  52. package/references/server-memory.md +276 -0
  53. package/references/test-check.md +7 -0
  54. package/references/user-reply.md +38 -0
  55. package/references/workbench-interface.md +531 -0
  56. package/roles.md +13 -0
  57. package/scripts/context_guard.py +1163 -321
  58. package/scripts/context_guard_hook.py +1864 -63
  59. package/scripts/map_owns.py +68 -138
  60. package/scripts/shared/LICENSES/JSONParse-MIT.txt +24 -0
  61. package/scripts/shared/filesystem-v2.mjs +430 -0
  62. package/scripts/shared/io.mjs +117 -0
  63. package/scripts/shared/map-model.mjs +506 -0
  64. package/scripts/shared/memory-schema.mjs +13 -0
  65. package/scripts/shared/protocol-blobs.mjs +112 -0
  66. package/scripts/shared/protocol-map.mjs +146 -0
  67. package/scripts/shared/protocol-snapshots.mjs +84 -0
  68. package/scripts/shared/protocol-store.mjs +624 -0
  69. package/scripts/shared/protocol-workflow.mjs +226 -0
  70. package/scripts/shared/protocol.mjs +125 -0
  71. package/scripts/shared/vendor/jsonparse.cjs +413 -0
  72. package/scripts/workbench/access.mjs +496 -0
  73. package/scripts/workbench/attachments.mjs +92 -0
  74. package/scripts/workbench/browser-login.mjs +78 -0
  75. package/scripts/workbench/claude-runtime.mjs +372 -0
  76. package/scripts/workbench/cli.mjs +980 -0
  77. package/scripts/workbench/device-heartbeat.mjs +72 -0
  78. package/scripts/workbench/hook-status.mjs +38 -0
  79. package/scripts/workbench/inbox.mjs +155 -0
  80. package/scripts/workbench/journal.mjs +56 -0
  81. package/scripts/workbench/memory-merge.mjs +65 -0
  82. package/scripts/workbench/memory.mjs +252 -0
  83. package/scripts/workbench/named-proxy.mjs +108 -0
  84. package/scripts/workbench/named.mjs +152 -0
  85. package/scripts/workbench/portless-routes.mjs +51 -0
  86. package/scripts/workbench/project.mjs +327 -0
  87. package/scripts/workbench/projections.mjs +68 -0
  88. package/scripts/workbench/protocol-client.mjs +165 -0
  89. package/scripts/workbench/protocol-delivery.mjs +133 -0
  90. package/scripts/workbench/protocol-device.mjs +316 -0
  91. package/scripts/workbench/protocol-events.mjs +53 -0
  92. package/scripts/workbench/protocol-repository.mjs +58 -0
  93. package/scripts/workbench/reconcile.mjs +244 -0
  94. package/scripts/workbench/registry.mjs +111 -0
  95. package/scripts/workbench/runtime.mjs +54 -0
  96. package/scripts/workbench/server.mjs +1171 -0
  97. package/scripts/workbench/store.mjs +243 -0
  98. package/scripts/workbench/sync-coordinator.mjs +518 -0
  99. package/scripts/workbench/sync.mjs +86 -0
  100. package/references/bug-record-template.md +0 -37
  101. package/references/context-template.md +0 -19
@@ -10,6 +10,9 @@ from __future__ import annotations
10
10
 
11
11
  import argparse
12
12
  import json
13
+ import hashlib
14
+ import uuid
15
+ from context_guard import run_node_workbench
13
16
  import sys
14
17
  from pathlib import Path
15
18
 
@@ -117,6 +120,18 @@ def lookup(doc: dict, file: str) -> dict | None:
117
120
  if isinstance(b, dict) and b.get("status") != "dormant"
118
121
  ]
119
122
 
123
+ def todo_rows(n):
124
+ return [
125
+ {
126
+ "id": item.get("id"),
127
+ "title": item.get("title"),
128
+ "status": item.get("status") or "pending",
129
+ "sessions": item.get("sessions") or [],
130
+ }
131
+ for item in (n.get("todos") or [])
132
+ if isinstance(item, dict)
133
+ ]
134
+
120
135
  extra_bugs = []
121
136
  nid = node.get("id")
122
137
  for n, _ in walk_nodes(root):
@@ -163,6 +178,7 @@ def lookup(doc: dict, file: str) -> dict | None:
163
178
  "tie_ids": [n.get("id") for n in ties] if len(ties) > 1 else [],
164
179
  "memories": mem_rows(node),
165
180
  "also_memories": extra_mems,
181
+ "todos": todo_rows(node),
166
182
  "bugs": bug_rows(node),
167
183
  "also_bugs": extra_bugs,
168
184
  "ancestors": [
@@ -170,6 +186,7 @@ def lookup(doc: dict, file: str) -> dict | None:
170
186
  "id": a.get("id"),
171
187
  "title": a.get("title"),
172
188
  "memories": mem_rows(a),
189
+ "todos": todo_rows(a),
173
190
  "bugs": bug_rows(a),
174
191
  }
175
192
  for a in chain[:-1]
@@ -214,21 +231,22 @@ def build_owns_index(doc: dict) -> dict:
214
231
 
215
232
 
216
233
  def write_owns_index(root: Path) -> Path:
217
- dest = root / ".codex" / "context" / "owns-index.json"
218
- dest.write_text(
219
- json.dumps(build_owns_index(load_map(root)), ensure_ascii=False, indent=2) + "\n",
220
- encoding="utf-8",
221
- )
222
- return dest
234
+ write_cards(root)
235
+ return root / ".codex" / "context" / "owns-index.json"
223
236
 
224
237
 
225
238
  def stamp_map(root: Path) -> Path:
226
- path = root / ".codex" / "context" / "map.json"
227
- doc = json.loads(path.read_text(encoding="utf-8"))
228
- if doc.get("root"):
229
- stamp_owns(doc["root"], CG_OWNS)
230
- path.write_text(json.dumps(doc, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
231
- return path
239
+ snapshot = run_node_workbench(["map", "read", "--root", str(root)])
240
+ doc = snapshot["doc"]
241
+ operations = []
242
+ for node, _ in walk_nodes(doc["root"]):
243
+ owns = CG_OWNS.get(node["id"])
244
+ if owns is not None and owns != node.get("owns"):
245
+ operations.append({"type": "update", "id": node["id"], "fields": {"owns": owns}})
246
+ if operations:
247
+ run_node_workbench(["map", "apply", "--root", str(root)], {
248
+ "baseVersion": snapshot["version"], "operationId": str(uuid.uuid4()), "operations": operations})
249
+ return root / ".codex" / "context" / "map.json"
232
250
 
233
251
 
234
252
  def flow_neighbors(doc: dict, nid: str) -> list[dict]:
@@ -271,6 +289,15 @@ def card_markdown(node: dict, chain: list, doc: dict) -> str:
271
289
  for m in node.get("ideas") or []:
272
290
  if isinstance(m, dict) and m.get("text"):
273
291
  ideas.append(f"- {m.get('text')}")
292
+ todos = []
293
+ for item in node.get("todos") or []:
294
+ if not isinstance(item, dict):
295
+ continue
296
+ extra = also_ids(item)
297
+ tag = f" · 也挂 {', '.join(extra)}" if extra else ""
298
+ todos.append(
299
+ f"- {item.get('id')}: {item.get('title') or ''} [{item.get('status') or 'pending'}]{tag}"
300
+ )
274
301
  bugs = []
275
302
  for b in node.get("bugs") or []:
276
303
  if not isinstance(b, dict) or b.get("status") == "dormant":
@@ -296,6 +323,11 @@ def card_markdown(node: dict, chain: list, doc: dict) -> str:
296
323
  bugs.append(
297
324
  f"- [{bid}](../bugs/{bid}.md) → [经验](../fixes/{bid}.md) {b.get('title') or ''} · 主卡 {n.get('id')}"
298
325
  )
326
+ for item in n.get("todos") or []:
327
+ if isinstance(item, dict) and nid in also_ids(item):
328
+ todos.append(
329
+ f"- {item.get('id')}: {item.get('title') or ''} [{item.get('status') or 'pending'}] · 主卡 {n.get('id')}"
330
+ )
299
331
  rel_s = ", ".join(
300
332
  f"{r['id']}({r['label']})" if r.get("label") else r["id"] for r in related
301
333
  ) or "(none)"
@@ -316,6 +348,7 @@ def card_markdown(node: dict, chain: list, doc: dict) -> str:
316
348
  ]
317
349
  if ideas:
318
350
  lines.extend(["## Idea", "", "\n".join(ideas), ""])
351
+ lines.extend(["## TODO", "", "\n".join(todos) if todos else "(无)", ""])
319
352
  lines.extend([
320
353
  "## Bug",
321
354
  "",
@@ -330,24 +363,8 @@ def card_markdown(node: dict, chain: list, doc: dict) -> str:
330
363
 
331
364
 
332
365
  def write_cards(root: Path) -> Path:
333
- ctx = root / ".codex" / "context"
334
- dest = ctx / "cards"
335
- dest.mkdir(parents=True, exist_ok=True)
336
- for old in dest.glob("*.md"):
337
- old.unlink()
338
- doc = load_map(root)
339
- tree = doc.get("root") or doc
340
- for node, chain in walk_nodes(tree):
341
- if node.get("proposal") == "cancelled" or not node.get("id"):
342
- continue
343
- (dest / f"{node['id']}.md").write_text(
344
- card_markdown(node, chain, doc), encoding="utf-8"
345
- )
346
- write_owns_index(root)
347
- write_bugs_index(root)
348
- write_tasks_index(root)
349
- write_jump_index(root)
350
- return dest
366
+ run_node_workbench(["map", "projections", "--root", str(root), "--wait"])
367
+ return root / ".codex" / "context" / "cards"
351
368
 
352
369
 
353
370
  def parse_md_fields(text: str) -> dict:
@@ -363,122 +380,31 @@ def parse_md_fields(text: str) -> dict:
363
380
 
364
381
 
365
382
  def write_bugs_index(root: Path) -> Path:
366
- ctx = root / ".codex" / "context"
367
- bugs_dir = ctx / "bugs"
368
- index: dict = {}
369
- if bugs_dir.is_dir():
370
- for path in sorted(bugs_dir.glob("B*.md")):
371
- fields = parse_md_fields(path.read_text(encoding="utf-8"))
372
- bid = path.stem
373
- title = fields.get("_title") or bid
374
- if title.startswith(bid + " "):
375
- title = title[len(bid) + 1 :]
376
- keys = [k.strip() for k in (fields.get("keys") or "").split(",") if k.strip()]
377
- index[bid] = {
378
- "title": title,
379
- "keys": keys,
380
- "status": fields.get("status") or "",
381
- "bug": f".codex/context/bugs/{bid}.md",
382
- "fix": fields.get("fix") or f".codex/context/fixes/{bid}.md",
383
- "card": fields.get("card") or "",
384
- }
385
- dest = ctx / "bugs-index.json"
386
- dest.write_text(json.dumps(index, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
387
- return dest
383
+ write_cards(root)
384
+ return root / ".codex" / "context" / "bugs-index.json"
388
385
 
389
386
 
390
387
  def write_tasks_index(root: Path) -> Path:
391
- ctx = root / ".codex" / "context"
392
- tasks_dir = ctx / "tasks"
393
- index: dict = {}
394
- if tasks_dir.is_dir():
395
- for path in sorted(tasks_dir.glob("J*.md")):
396
- fields = parse_md_fields(path.read_text(encoding="utf-8"))
397
- jid = path.stem
398
- title = fields.get("_title") or jid
399
- if title.startswith(jid + " "):
400
- title = title[len(jid) + 1 :]
401
- keys = [k.strip() for k in (fields.get("keys") or "").split(",") if k.strip()]
402
- chain = [p.strip() for p in (fields.get("chain") or "").replace(">", " ").split() if p.strip()]
403
- index[jid] = {
404
- "title": title,
405
- "keys": keys,
406
- "task": f".codex/context/tasks/{jid}.md",
407
- "chain": chain,
408
- "card": fields.get("card") or "",
409
- }
410
- dest = ctx / "tasks-index.json"
411
- dest.write_text(json.dumps(index, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
412
- return dest
388
+ write_cards(root)
389
+ return root / ".codex" / "context" / "tasks-index.json"
413
390
 
414
391
 
415
392
  def write_jump_index(root: Path) -> Path:
416
- ctx = ctx_dir(root)
417
- owns = []
418
- map_path = ctx / "map.json"
419
- if map_path.is_file():
420
- doc = load_map(root)
421
- tree = doc.get("root") or doc
422
- for node, chain in walk_nodes(tree):
423
- if node.get("proposal") == "cancelled" or not node.get("id"):
424
- continue
425
- ancestors = [n.get("id") for n in chain[:-1] if n.get("id")]
426
- for owned in node.get("owns") or []:
427
- owns.append(
428
- {
429
- "path": owned,
430
- "node": node.get("id"),
431
- "kind": node.get("kind"),
432
- "card": f".codex/context/cards/{node['id']}.md",
433
- "chain": ancestors,
434
- }
435
- )
436
- else:
437
- for r in read_json(ctx / "owns-index.json", {"owns": []}).get("owns") or []:
438
- if not r.get("path") or not r.get("node"):
439
- continue
440
- owns.append(
441
- {
442
- "path": r.get("path"),
443
- "node": r.get("node"),
444
- "kind": r.get("kind"),
445
- "card": f".codex/context/cards/{r.get('node')}.md",
446
- "chain": r.get("chain") or [],
447
- }
448
- )
449
- packed = {
450
- "owns": owns,
451
- "bugs": read_json(ctx / "bugs-index.json", {}),
452
- "tasks": read_json(ctx / "tasks-index.json", {}),
453
- }
454
- dest = ctx / "jump-index.json"
455
- dest.write_text(json.dumps(packed, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
456
- return dest
393
+ write_cards(root)
394
+ return root / ".codex" / "context" / "jump-index.json"
457
395
 
458
396
 
459
397
  def load_packed(root: Path) -> dict:
460
398
  ctx = ctx_dir(root)
461
- dest = ctx / "jump-index.json"
462
- if dest.is_file():
463
- return read_json(dest, {"owns": [], "bugs": {}, "tasks": {}})
464
- owns = []
465
- for r in read_json(ctx / "owns-index.json", {"owns": []}).get("owns") or []:
466
- if not r.get("path") or not r.get("node"):
467
- continue
468
- owns.append(
469
- {
470
- "path": r["path"],
471
- "node": r["node"],
472
- "kind": r.get("kind"),
473
- "card": f".codex/context/cards/{r['node']}.md",
474
- "chain": r.get("chain") or [],
475
- }
476
- )
477
- return {
478
- "owns": owns,
479
- "bugs": read_json(ctx / "bugs-index.json", {}),
480
- "tasks": read_json(ctx / "tasks-index.json", {}),
481
- }
399
+ version = hashlib.sha256((ctx / "map.json").read_bytes()).hexdigest()
400
+ status = read_json(ctx / "projection-status.json", {})
401
+ if status.get("status") != "ready" or status.get("sourceVersion") != version:
402
+ write_cards(root)
403
+ packed = read_json(ctx / "jump-index.json", {})
404
+ current = hashlib.sha256((ctx / "map.json").read_bytes()).hexdigest()
405
+ if packed.get("sourceVersion") != current:
406
+ raise ValueError("Map changed while reading indexes; read the current node with context-guard map read")
407
+ return packed
482
408
 
483
409
 
484
410
  def lookup_owns(rows: list, file: str) -> dict | None:
@@ -614,7 +540,7 @@ def jump(root: Path, *, path="", bug="", task="", last=False, packed=None) -> di
614
540
  lines = [ln for ln in sess.read_text(encoding="utf-8").splitlines() if ln.strip()]
615
541
  if not lines:
616
542
  return {"kind": "session", "open": [], "then": []}
617
- row = json.loads(lines[-1])
543
+ row = next((value for value in (json.loads(line) for line in reversed(lines)) if value.get("event") != "maintenance"), {})
618
544
  open_files: list[str] = []
619
545
  then: list[str] = []
620
546
  for tid in row.get("tasks") or []:
@@ -626,9 +552,13 @@ def jump(root: Path, *, path="", bug="", task="", last=False, packed=None) -> di
626
552
  if not open_files:
627
553
  open_files = then[:2]
628
554
  then = then[2:]
555
+ if not open_files and row.get("session_id"):
556
+ session_file = ctx / "sessions" / f"{row['session_id']}.md"
557
+ if session_file.is_file():
558
+ open_files = [f".codex/context/sessions/{row['session_id']}.md"]
629
559
  return {
630
560
  "kind": "session",
631
- "id": row.get("id"),
561
+ "id": row.get("session_id") or row.get("id"),
632
562
  "open": open_files[:3],
633
563
  "then": then[:6],
634
564
  }
@@ -0,0 +1,24 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2012 Tim Caswell
4
+
5
+ Permission is hereby granted, free of charge,
6
+ to any person obtaining a copy of this software and
7
+ associated documentation files (the "Software"), to
8
+ deal in the Software without restriction, including
9
+ without limitation the rights to use, copy, modify,
10
+ merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom
12
+ the Software is furnished to do so,
13
+ subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice
16
+ shall be included in all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
22
+ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.