pantheon-opencode 1.5.0-beta.9 → 1.5.1

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 (84) hide show
  1. package/AGENTS.md +14 -63
  2. package/CHANGELOG.md +326 -0
  3. package/README.md +77 -29
  4. package/README.pt-BR.md +5 -6
  5. package/commands/pantheon.md +1 -35
  6. package/package.json +2 -3
  7. package/plugin.json +1 -1
  8. package/pyproject.toml +3 -5
  9. package/scripts/doctor.mjs +260 -5
  10. package/scripts/install/plugin.mjs +9 -12
  11. package/scripts/mcp_persistence_server.py +1 -1
  12. package/scripts/sync-tui.mjs +8 -11
  13. package/src/agents/apollo.md +1 -0
  14. package/src/agents/gaia.md +1 -0
  15. package/src/agents/mnemosyne.md +11 -1
  16. package/src/agents/zeus.md +10 -52
  17. package/src/instructions/memory-protocol.instructions.md +6 -3
  18. package/src/instructions/zeus-anti-stall.instructions.md +2 -4
  19. package/src/instructions/zeus-council-synthesis.instructions.md +3 -28
  20. package/src/instructions/zeus-timeout-retry.instructions.md +3 -28
  21. package/src/mcp/mcp_persistence_server.py +1 -1
  22. package/src/mcp/memory_mcp_server.py +81 -27
  23. package/src/pantheon/background-job-board.ts +4 -4
  24. package/src/pantheon/{delegation-compaction.ts → compaction-context.ts} +10 -100
  25. package/src/pantheon/cost-command.ts +1 -2
  26. package/src/pantheon/delegation-enforce.ts +59 -14
  27. package/src/pantheon/goal-loop.ts +1 -1
  28. package/src/pantheon/goal-store.ts +1 -1
  29. package/src/pantheon/idle-continuation.ts +4 -6
  30. package/src/pantheon/model-command.ts +1 -2
  31. package/src/pantheon/native-task-status.ts +2 -2
  32. package/src/pantheon/presets.d.mts +0 -20
  33. package/src/pantheon/presets.mjs +0 -64
  34. package/src/pantheon/session-guard.ts +2 -2
  35. package/src/pantheon/session-id.ts +30 -0
  36. package/src/pantheon/task-result-guard.ts +2 -3
  37. package/src/pantheon/todo-enforcer.ts +3 -3
  38. package/src/pantheon/tool-context.ts +23 -0
  39. package/src/pantheon/v2-bridge.ts +1 -4
  40. package/src/plugin-v2.ts +8 -21
  41. package/src/plugin.ts +61 -245
  42. package/src/plugins/pantheon-hooks.ts +2 -2
  43. package/src/plugins/tui/dist/tui.d.ts +229 -103
  44. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  45. package/src/plugins/tui/dist/tui.js +495 -333
  46. package/src/plugins/tui/package-lock.json +5 -2
  47. package/src/plugins/tui/package.json +5 -2
  48. package/src/plugins/tui/src/index.tsx +710 -409
  49. package/src/routing.yml +0 -16
  50. package/src/skills/context-compression/SKILL.md +1 -1
  51. package/scripts/generate-preset-docs.mjs +0 -300
  52. package/scripts/generate-prompts.sh +0 -222
  53. package/scripts/hash_verify.py +0 -192
  54. package/scripts/install/component.mjs +0 -24
  55. package/scripts/install/migrate-config.mjs +0 -302
  56. package/scripts/test-context-compression.sh +0 -169
  57. package/src/mcp/toon_codec.py +0 -491
  58. package/src/pantheon/auto-wake.ts +0 -85
  59. package/src/pantheon/chat-reminders.ts +0 -9
  60. package/src/pantheon/comment-checker.ts +0 -48
  61. package/src/pantheon/compaction-assert.ts +0 -160
  62. package/src/pantheon/compaction-handoff.ts +0 -304
  63. package/src/pantheon/cost-tracker.ts +0 -108
  64. package/src/pantheon/delegate-manager.ts +0 -766
  65. package/src/pantheon/delegation-classifier.ts +0 -307
  66. package/src/pantheon/delegation-finalize.ts +0 -406
  67. package/src/pantheon/delegation-notify.ts +0 -212
  68. package/src/pantheon/delegation-toast.ts +0 -73
  69. package/src/pantheon/delegation.ts +0 -1337
  70. package/src/pantheon/dispatch-guard.ts +0 -109
  71. package/src/pantheon/native-probe.ts +0 -234
  72. package/src/pantheon/permission-eval.ts +0 -284
  73. package/src/pantheon/preemptive-compact.ts +0 -76
  74. package/src/pantheon/provider-capabilities.ts +0 -221
  75. package/src/pantheon/provider-stream-tracker.ts +0 -182
  76. package/src/pantheon/retry-policy.ts +0 -212
  77. package/src/pantheon/step-cap.ts +0 -110
  78. package/src/pantheon/token-opt.ts +0 -689
  79. package/src/pantheon/toon-codec.ts +0 -481
  80. package/src/pantheon/v2-events.ts +0 -148
  81. package/src/pantheon/v2-hooks.ts +0 -287
  82. package/src/pantheon/v2-tool-definitions.ts +0 -331
  83. package/src/pantheon/zeus-delegate-with-retry.ts +0 -406
  84. package/src/plugins/tui/dist/tui.tsx +0 -2853
@@ -1,491 +0,0 @@
1
- #!/usr/bin/env python3
2
- """WS3 TOON codec (PR #94) — Token-Oriented Object Notation.
3
-
4
- Minimal deterministic encoding for board signals, checkpoints and KV
5
- payloads. Semantics identical to JSON; structurally smaller (no braces,
6
- no per-key quotes, no commas); JSON fallback when the parser is
7
- absent/fails.
8
-
9
- Only the standard library (``json`` + ``re``) — prohibited: external
10
- gateway, generative embedding.
11
-
12
- Encoding rules (mirrored byte-for-byte by ``src/pantheon/toon-codec.ts``):
13
-
14
- - Scalars: ``None``/``True``/``False`` → ``null``/``true``/``false``;
15
- numbers → shortest form; strings bare when unambiguous, else
16
- JSON-quoted (quotes/backslash/newline, leading/trailing space,
17
- ``null``/``true``/``false``/numeric lookalikes, ``{}``/``[]``).
18
- - Dicts: one ``key: value`` line each; nested values on deeper indent
19
- (2 spaces); empty dict → ``{}``.
20
- - Lists of scalars: ``- item`` lines; empty list → ``[]``.
21
- - Lists of dicts with uniform keys: ``@table k1|k2`` header + ``v1|v2``
22
- rows (savings are per payload class — ~11% on content-dominated board
23
- records up to ~47% on large tabular checkpoints — see
24
- ``docs/ws3-token-opt-measurements.md`` for the reproducible table).
25
- - Dict values never need quoting for ``:`` (split is on the FIRST colon);
26
- list items / top-level scalars that look like ``key: ...`` are quoted.
27
- """
28
-
29
- from __future__ import annotations
30
-
31
- import json
32
- import re
33
- from dataclasses import dataclass
34
- from typing import Any
35
-
36
- TABLE_MARKER = "@table "
37
-
38
- #: Default cap on nested-block depth accepted by ``toon_decode`` (DoS guard:
39
- #: hostile deeply-nested input fails with ``ValueError``, never RecursionError).
40
- TOON_MAX_DEPTH = 100
41
-
42
- #: Default cap on input length accepted by ``toon_decode`` (DoS guard).
43
- TOON_MAX_CHARS = 1_000_000
44
-
45
- _BARE_KEY_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.@+~/-]*$")
46
- _INT_RE = re.compile(r"^-?\d+$")
47
- _FLOAT_RE = re.compile(r"^-?(?:\d+\.\d+|\d+\.\d*[eE][+-]?\d+|\d+[eE][+-]?\d+)$")
48
- _KEYLIKE_RE = re.compile(
49
- r'^(?:"(?:[^"\\]|\\.)*"|[A-Za-z0-9_][A-Za-z0-9_.@+~/\-]*)\s*:(?:\s+|$)'
50
- )
51
-
52
- _RESERVED_WORDS = frozenset({"null", "true", "false", "{}", "[]"})
53
-
54
-
55
- def _looks_numeric(text: str) -> bool:
56
- return bool(_INT_RE.match(text) or _FLOAT_RE.match(text))
57
-
58
-
59
- def _quote(text: str) -> str:
60
- return json.dumps(text, ensure_ascii=False)
61
-
62
-
63
- def _bare_value(text: str, *, in_table: bool = False) -> bool:
64
- """Whether a string value is unambiguous without quotes in VALUE position.
65
-
66
- In table cells (``in_table=True``) a bare ``|`` would split the row, so
67
- values containing ``|`` must be quoted.
68
- """
69
- if not text or text != text.strip():
70
- return False
71
- if text in _RESERVED_WORDS or _looks_numeric(text):
72
- return False
73
- if in_table and "|" in text:
74
- return False
75
- return not ('"' in text or "\\" in text or "\n" in text or "\r" in text)
76
-
77
-
78
- def _encode_scalar(
79
- value: Any, *, item_position: bool = False, table_cell: bool = False
80
- ) -> str:
81
- if value is None:
82
- return "null"
83
- if isinstance(value, bool):
84
- return "true" if value else "false"
85
- if isinstance(value, int):
86
- return str(value)
87
- if isinstance(value, float):
88
- return repr(value)
89
- text = str(value)
90
- if _bare_value(text, in_table=table_cell) and not (
91
- item_position and _KEYLIKE_RE.match(text)
92
- ):
93
- # "- key: ..." reads as a dict item — quote to keep the string.
94
- return text
95
- return _quote(text)
96
-
97
-
98
- def _encode_key(key: str) -> str:
99
- if _BARE_KEY_RE.match(key):
100
- return key
101
- return _quote(key)
102
-
103
-
104
- def _is_uniform_dict_list(value: Any) -> bool:
105
- if not isinstance(value, list) or not value:
106
- return False
107
- if not all(isinstance(item, dict) for item in value):
108
- return False
109
- first_keys = list(value[0].keys())
110
- if not first_keys:
111
- return False
112
- return all(list(item.keys()) == first_keys for item in value)
113
-
114
-
115
- def _split_cells(line: str) -> list[str]:
116
- """Split a table row on ``|`` outside double quotes."""
117
- cells: list[str] = []
118
- current: list[str] = []
119
- in_quotes = False
120
- escaped = False
121
- for char in line:
122
- if escaped:
123
- current.append(char)
124
- escaped = False
125
- elif char == "\\" and in_quotes:
126
- current.append(char)
127
- escaped = True
128
- elif char == '"':
129
- current.append(char)
130
- in_quotes = not in_quotes
131
- elif char == "|" and not in_quotes:
132
- cells.append("".join(current))
133
- current = []
134
- else:
135
- current.append(char)
136
- cells.append("".join(current))
137
- return cells
138
-
139
-
140
- def toon_encode(value: Any) -> str:
141
- """Encode ``value`` to a TOON string (deterministic, no spaces wasted)."""
142
- return "\n".join(_encode_value(value, 0))
143
-
144
-
145
- def _encode_value(value: Any, indent: int) -> list[str]:
146
- pad = " " * indent
147
- if value is None or isinstance(value, (bool, int, float, str)):
148
- return [pad + _encode_scalar(value)]
149
- if isinstance(value, dict):
150
- return _encode_dict(value, pad, indent)
151
- if isinstance(value, list):
152
- return _encode_list(value, pad, indent)
153
- raise TypeError(f"TOON cannot encode {type(value).__name__}")
154
-
155
-
156
- def _encode_dict(value: dict[Any, Any], pad: str, indent: int) -> list[str]:
157
- if not value:
158
- return [pad + "{}"]
159
- lines: list[str] = []
160
- for key, item in value.items():
161
- encoded_key = _encode_key(str(key))
162
- if item is None or isinstance(item, (bool, int, float, str)):
163
- lines.append(f"{pad}{encoded_key}: {_encode_scalar(item)}")
164
- elif isinstance(item, dict) and not item:
165
- lines.append(f"{pad}{encoded_key}: {{}}")
166
- elif isinstance(item, list) and not item:
167
- lines.append(f"{pad}{encoded_key}: []")
168
- else:
169
- lines.append(f"{pad}{encoded_key}:")
170
- lines.extend(_encode_value(item, indent + 2))
171
- return lines
172
-
173
-
174
- def _encode_list(value: list[Any], pad: str, indent: int) -> list[str]:
175
- if not value:
176
- return [pad + "[]"]
177
- if _is_uniform_dict_list(value):
178
- return _encode_table(value, pad)
179
- lines: list[str] = []
180
- for item in value:
181
- lines.extend(_encode_item(item, indent))
182
- return lines
183
-
184
-
185
- def _encode_table(value: list[Any], pad: str) -> list[str]:
186
- first = value[0]
187
- assert isinstance(first, dict)
188
- keys = list(first.keys())
189
- lines = [pad + TABLE_MARKER + "|".join(_encode_key(str(k)) for k in keys)]
190
- for item in value:
191
- assert isinstance(item, dict)
192
- cells = [
193
- _encode_scalar(item[k], item_position=True, table_cell=True) for k in keys
194
- ]
195
- lines.append(pad + "|".join(cells))
196
- return lines
197
-
198
-
199
- def _encode_item(item: Any, indent: int) -> list[str]:
200
- pad = " " * indent
201
- if item is None or isinstance(item, (bool, int, float, str)):
202
- return [f"{pad}- {_encode_scalar(item, item_position=True)}"]
203
- if isinstance(item, dict) and not item:
204
- return [f"{pad}- {{}}"]
205
- if isinstance(item, list) and not item:
206
- return [f"{pad}- []"]
207
- sub = _encode_value(item, indent + 2)
208
- first = sub[0].strip()
209
- return [f"{pad}- {first}", *sub[1:]]
210
-
211
-
212
- def _parse_scalar(token: str) -> Any:
213
- if token == "null":
214
- return None
215
- if token in {"true", "false"}:
216
- return token == "true"
217
- if token in {"{}", "[]"}:
218
- return {} if token == "{}" else []
219
- if _looks_numeric(token):
220
- return int(token) if _INT_RE.match(token) else float(token)
221
- if token.startswith('"'):
222
- return json.loads(token)
223
- return token
224
-
225
-
226
- def _indent_of(line: str) -> int:
227
- return len(line) - len(line.lstrip(" "))
228
-
229
-
230
- def _split_key_value(text: str) -> tuple[str, str]:
231
- """Split ``key: value`` on the FIRST colon (values may contain colons)."""
232
- if text.startswith('"'):
233
- try:
234
- key, end = json.JSONDecoder().raw_decode(text)
235
- except json.JSONDecodeError as exc:
236
- raise ValueError(f"TOON: line without ':' separator: {text!r}") from exc
237
- rest_text = text[end:].lstrip()
238
- if not rest_text.startswith(":"):
239
- raise ValueError(f"TOON: line without ':' separator: {text!r}")
240
- if not isinstance(key, str) or not key:
241
- raise ValueError(f"TOON: empty key in line: {text!r}")
242
- return key, rest_text[1:].strip()
243
- idx = text.find(":")
244
- if idx < 0:
245
- raise ValueError(f"TOON: line without ':' separator: {text!r}")
246
- raw_key = text[:idx].strip()
247
- if not raw_key:
248
- raise ValueError(f"TOON: empty key in line: {text!r}")
249
- key = raw_key
250
- rest = text[idx + 1 :].strip()
251
- return key, rest
252
-
253
-
254
- def toon_decode(
255
- text: str, *, max_depth: int = TOON_MAX_DEPTH, max_chars: int = TOON_MAX_CHARS
256
- ) -> Any:
257
- """Decode a TOON string back to the identical value (raises ValueError).
258
-
259
- ``max_depth``/``max_chars`` are DoS guards: oversized inputs fail with a
260
- controlled ``ValueError`` instead of ``RecursionError``/memory blowup.
261
- """
262
- if len(text) > max_chars:
263
- raise ValueError(
264
- f"TOON: input too large ({len(text)} chars > max_chars={max_chars})"
265
- )
266
- lines = [line for line in text.split("\n") if line.strip() != ""]
267
- if not lines:
268
- raise ValueError("TOON: empty input")
269
- stripped = lines[0].strip()
270
- if stripped.startswith("{") or stripped.startswith("["):
271
- try:
272
- return json.loads(text)
273
- except json.JSONDecodeError as exc:
274
- raise ValueError(f"TOON: invalid JSON fallback: {exc}") from exc
275
- value, next_idx = _parse_block(lines, 0, 0, 0, max_depth)
276
- if next_idx != len(lines):
277
- raise ValueError(f"TOON: trailing content at line {next_idx + 1}")
278
- return value
279
-
280
-
281
- def _parse_block(
282
- lines: list[str], idx: int, indent: int, depth: int, max_depth: int
283
- ) -> tuple[Any, int]:
284
- if depth > max_depth:
285
- raise ValueError(f"TOON: max_depth={max_depth} exceeded")
286
- stripped = lines[idx].strip()
287
- if stripped.startswith("@table "):
288
- return _parse_table(lines, idx, indent)
289
- if stripped.startswith("- ") or stripped == "-":
290
- return _parse_list(lines, idx, indent, depth, max_depth)
291
- return _parse_dict(lines, idx, indent, depth, max_depth)
292
-
293
-
294
- def _parse_table(
295
- lines: list[str], idx: int, indent: int
296
- ) -> tuple[list[dict[str, Any]], int]:
297
- header = lines[idx].strip()[len(TABLE_MARKER) :]
298
- keys = [
299
- _parse_scalar(cell) if cell.startswith('"') else cell
300
- for cell in _split_cells(header)
301
- ]
302
- if not keys or any(not k for k in keys):
303
- raise ValueError(f"TOON: bad @table header at line {idx + 1}")
304
- rows: list[dict[str, Any]] = []
305
- idx += 1
306
- while idx < len(lines) and _indent_of(lines[idx]) == indent:
307
- row_stripped = lines[idx].strip()
308
- if row_stripped.startswith(("@table ", "- ")) or row_stripped == "-":
309
- break
310
- if ":" in row_stripped and _KEYLIKE_RE.match(row_stripped):
311
- break
312
- cells = _split_cells(row_stripped)
313
- if len(cells) != len(keys):
314
- raise ValueError(f"TOON: row width mismatch at line {idx + 1}")
315
- rows.append({k: _parse_scalar(c) for k, c in zip(keys, cells, strict=True)})
316
- idx += 1
317
- return rows, idx
318
-
319
-
320
- def _parse_dict(
321
- lines: list[str], idx: int, indent: int, depth: int, max_depth: int
322
- ) -> tuple[dict[str, Any], int]:
323
- result: dict[str, Any] = {}
324
- while idx < len(lines):
325
- line = lines[idx]
326
- if line.strip() == "" or _indent_of(line) != indent:
327
- break
328
- stripped = line.strip()
329
- if stripped.startswith(("@table ", "- ")) or stripped == "-":
330
- break
331
- key, rest = _split_key_value(stripped)
332
- if rest == "":
333
- idx += 1
334
- if idx >= len(lines) or _indent_of(lines[idx]) <= indent:
335
- raise ValueError(f"TOON: missing nested block for key {key!r}")
336
- nested, idx = _parse_block(
337
- lines, idx, _indent_of(lines[idx]), depth + 1, max_depth
338
- )
339
- result[key] = nested
340
- else:
341
- result[key] = _parse_scalar(rest)
342
- idx += 1
343
- return result, idx
344
-
345
-
346
- @dataclass
347
- class _ListParseContext:
348
- """Shared cursor for ``- key: value`` list-item parsing (PLR0913)."""
349
-
350
- lines: list[str]
351
- indent: int
352
- depth: int
353
- max_depth: int
354
-
355
-
356
- def _parse_list_continuation(
357
- ctx: _ListParseContext, idx: int, item: dict[str, Any]
358
- ) -> int:
359
- """Consume ``indent+`` continuation lines (``key: value``) of a dict item."""
360
- lines, indent, depth, max_depth = ctx.lines, ctx.indent, ctx.depth, ctx.max_depth
361
- while idx < len(lines) and _indent_of(lines[idx]) > indent:
362
- cont = lines[idx].strip()
363
- sub_key, sub_rest = _split_key_value(cont)
364
- if sub_rest == "":
365
- idx += 1
366
- if idx >= len(lines) or _indent_of(lines[idx]) <= _indent_of(
367
- lines[idx - 1]
368
- ):
369
- raise ValueError(f"TOON: missing nested block for key {sub_key!r}")
370
- nested, idx = _parse_block(
371
- lines, idx, _indent_of(lines[idx]), depth + 1, max_depth
372
- )
373
- item[sub_key] = nested
374
- else:
375
- item[sub_key] = _parse_scalar(sub_rest)
376
- idx += 1
377
- return idx
378
-
379
-
380
- def _parse_list_dict_item(
381
- ctx: _ListParseContext, idx: int, rest: str
382
- ) -> tuple[dict[str, Any], int]:
383
- """Parse a ``- key: value`` dict item plus its continuation lines."""
384
- lines, indent, depth, max_depth = ctx.lines, ctx.indent, ctx.depth, ctx.max_depth
385
- key, sub_rest = _split_key_value(rest)
386
- item: dict[str, Any] = {}
387
- if sub_rest == "":
388
- idx += 1
389
- if idx >= len(lines) or _indent_of(lines[idx]) <= indent:
390
- raise ValueError(f"TOON: missing nested block for key {key!r}")
391
- nested, idx = _parse_block(
392
- lines, idx, _indent_of(lines[idx]), depth + 1, max_depth
393
- )
394
- item[key] = nested
395
- else:
396
- item[key] = _parse_scalar(sub_rest)
397
- idx += 1
398
- idx = _parse_list_continuation(ctx, idx, item)
399
- return item, idx
400
-
401
-
402
- def _parse_list(
403
- lines: list[str], idx: int, indent: int, depth: int, max_depth: int
404
- ) -> tuple[list[Any], int]:
405
- items: list[Any] = []
406
- while idx < len(lines):
407
- line = lines[idx]
408
- if _indent_of(line) != indent:
409
- break
410
- stripped = line.strip()
411
- if not (stripped.startswith("- ") or stripped == "-"):
412
- break
413
- rest = stripped[1:].strip()
414
- if rest == "":
415
- idx += 1
416
- if idx >= len(lines) or _indent_of(lines[idx]) <= indent:
417
- raise ValueError(
418
- f"TOON: missing nested block in list at line {idx + 1}"
419
- )
420
- nested, idx = _parse_block(
421
- lines, idx, _indent_of(lines[idx]), depth + 1, max_depth
422
- )
423
- items.append(nested)
424
- continue
425
- if _KEYLIKE_RE.match(rest):
426
- ctx = _ListParseContext(lines, indent, depth, max_depth)
427
- item, idx = _parse_list_dict_item(ctx, idx, rest)
428
- items.append(item)
429
- else:
430
- items.append(_parse_scalar(rest))
431
- idx += 1
432
- return items, idx
433
-
434
-
435
- def toon_decode_auto(
436
- text: str, *, max_depth: int = TOON_MAX_DEPTH, max_chars: int = TOON_MAX_CHARS
437
- ) -> Any:
438
- """Decode TOON, falling back to JSON (mirrors "parser absent" mode).
439
-
440
- Raises ValueError with a consistent ``TOON:`` message when the input is
441
- neither valid TOON nor valid JSON (never leaks the raw JSON error).
442
- """
443
- stripped = text.strip()
444
- if stripped.startswith("{") or stripped.startswith("["):
445
- try:
446
- return json.loads(text)
447
- except json.JSONDecodeError as exc:
448
- raise ValueError(f"TOON: invalid JSON fallback: {exc}") from exc
449
- try:
450
- return toon_decode(text, max_depth=max_depth, max_chars=max_chars)
451
- except ValueError:
452
- pass
453
- try:
454
- return json.loads(text)
455
- except json.JSONDecodeError as exc:
456
- raise ValueError(
457
- f"TOON: invalid input (neither TOON nor JSON): {stripped[:60]!r}"
458
- ) from exc
459
-
460
-
461
- def _chars_to_tokens(chars: int) -> int:
462
- """Deterministic token estimate: ``ceil(chars / 4)`` (WS3 metering basis)."""
463
- if chars <= 0:
464
- return 0
465
- return -(-chars // 4)
466
-
467
-
468
- def toon_size_report(value: Any) -> dict[str, Any]:
469
- """Compare JSON vs TOON sizes for ``value``.
470
-
471
- Reports BOTH chars and tokens: token ratios on tiny payloads suffer
472
- ceiling bias (``ceil`` rounds 161→41 vs 143→36), so the char columns are
473
- the honest basis and the token columns show what metering will debit.
474
- Per-class numbers: see ``docs/ws3-token-opt-measurements.md``.
475
- """
476
- compact_json = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
477
- toon = toon_encode(value)
478
- ratio = len(toon) / len(compact_json) if compact_json else 1.0
479
- json_tokens = _chars_to_tokens(len(compact_json))
480
- toon_tokens = _chars_to_tokens(len(toon))
481
- token_ratio = toon_tokens / json_tokens if json_tokens else 1.0
482
- return {
483
- "json_chars": len(compact_json),
484
- "toon_chars": len(toon),
485
- "ratio": round(ratio, 4),
486
- "saved_pct": round((1.0 - ratio) * 100.0, 2),
487
- "json_tokens": json_tokens,
488
- "toon_tokens": toon_tokens,
489
- "token_ratio": round(token_ratio, 4),
490
- "token_saved_pct": round((1.0 - token_ratio) * 100.0, 2),
491
- }
@@ -1,85 +0,0 @@
1
- /**
2
- * Auto-Wake Consumer — scans signal files from the BackgroundJobBoard
3
- * and returns completed job signals for Zeus to process.
4
- *
5
- * Signal files are created by the board on every terminal state transition
6
- * (completed/error/cancelled). This module consumes them atomically by
7
- * reading the `.signal.json` content, then renaming to `.consumed.json`,
8
- * preventing race conditions where the same signal is processed twice.
9
- *
10
- * The rename is the commit point: if Zeus crashes between the read and the
11
- * rename, the `.signal.json` file remains and will be re-processed on restart.
12
- * This gives **at-least-once** delivery, which is acceptable because the board's
13
- * `markReconciled()` is idempotent.
14
- *
15
- * @module auto-wake
16
- */
17
-
18
- import { existsSync } from 'node:fs'
19
- import { readdir, readFile, rename } from 'node:fs/promises'
20
- import { join } from 'node:path'
21
-
22
- /** Signal structure written by BackgroundJobBoard.writeSignal(). */
23
- export interface WakeSignal {
24
- taskID: string
25
- alias: string
26
- agent: string
27
- state: string
28
- summary: string | null
29
- timestamp: number
30
- }
31
-
32
- /** Default signal directory (matches BoardOptions.signalDir default in plugin.ts). */
33
- const DEFAULT_SIGNAL_DIR = '.pantheon/deepwork/board-signals'
34
-
35
- /**
36
- * Scan the signal directory for `*.signal.json` files, atomically consume
37
- * each by renaming to `*.consumed.json`, and return the parsed signals.
38
- *
39
- * Safe to call multiple times — already-consumed files (`.consumed.json`)
40
- * are ignored, and the atomic rename prevents double-processing.
41
- *
42
- * The flow per signal file:
43
- * 1. Read the `.signal.json` content
44
- * 2. Rename `.signal.json` → `.consumed.json` (atomic: OS-level rename)
45
- * 3. If rename succeeds, push the signal into the result
46
- * 4. If rename fails (another process consumed it first), skip
47
- *
48
- * @param signalDir Directory to scan (default: `.pantheon/deepwork/board-signals`)
49
- * @returns List of wake signals from newly consumed files
50
- */
51
- export async function consumeWakeSignals(signalDir?: string): Promise<WakeSignal[]> {
52
- const dir = signalDir ?? DEFAULT_SIGNAL_DIR
53
-
54
- // If the signal directory doesn't exist, there are no signals
55
- if (!existsSync(dir)) {
56
- return []
57
- }
58
-
59
- const entries = await readdir(dir, { withFileTypes: true })
60
- const signals: WakeSignal[] = []
61
-
62
- for (const entry of entries) {
63
- if (!entry.isFile()) continue
64
- if (!entry.name.endsWith('.signal.json')) continue
65
-
66
- const signalPath = join(dir, entry.name)
67
- const consumedName = entry.name.replace(/\.signal\.json$/, '.consumed.json')
68
- const consumedPath = join(dir, consumedName)
69
-
70
- try {
71
- // Step 1: Read the file content
72
- const content = await readFile(signalPath, 'utf-8')
73
- const data = JSON.parse(content) as WakeSignal
74
-
75
- // Step 2: Atomically rename — this is the commit point.
76
- // If this fails, the .signal.json remains and we'll retry next call.
77
- await rename(signalPath, consumedPath)
78
-
79
- // Step 3: Only add to results after successful rename
80
- signals.push(data)
81
- } catch {}
82
- }
83
-
84
- return signals
85
- }
@@ -1,9 +0,0 @@
1
- /**
2
- * Retired transcript-notification module.
3
- *
4
- * Delegation lifecycle state must not be queued for delivery into user
5
- * messages. Visibility is provided by the board/list/read tools and TUI
6
- * toasts; this intentionally exports no delivery API.
7
- *
8
- * @module chat-reminders
9
- */
@@ -1,48 +0,0 @@
1
- /**
2
- * Comment Checker — detects trivial/auto-generated comments that make code
3
- * look machine-produced rather than human-written.
4
- *
5
- * Used by @themis (Layer 1: Surface review) to flag comments that add no
6
- * information value and signal AI-generated code.
7
- */
8
-
9
- /** Regex patterns matching trivial, uninformative comments. */
10
- export const TRIVIAL_PATTERNS: readonly RegExp[] = [
11
- /#\s*increment\s+\w+/i,
12
- /#\s*decrement\s+\w+/i,
13
- /#\s*set\s+\w+/i,
14
- /#\s*loop\s+over/i,
15
- /#\s*(initialize|init)\s+\w+/i,
16
- /#\s*(return|yield)\s+\w+/i,
17
- ]
18
-
19
- export interface CommentCheckResult {
20
- /** Number of trivial comments found (0 = clean). */
21
- score: number
22
- /** Human-readable descriptions of each flagged comment. */
23
- flags: string[]
24
- }
25
-
26
- /**
27
- * Scan source code for trivial comments that add no information value.
28
- *
29
- * Returns a score (count of trivial comments) and a list of flags describing
30
- * each match. A score of 0 means no trivial comments were detected.
31
- */
32
- export function checkCommentDensity(source: string): CommentCheckResult {
33
- const flags: string[] = []
34
- const lines = source.split('\n')
35
-
36
- for (let i = 0; i < lines.length; i++) {
37
- const line = lines[i] as string
38
- for (const pattern of TRIVIAL_PATTERNS) {
39
- if (pattern.test(line)) {
40
- const trimmed = line.trim()
41
- flags.push(`Line ${i + 1}: trivial comment — "${trimmed}"`)
42
- break // one flag per line, even if multiple patterns match
43
- }
44
- }
45
- }
46
-
47
- return { score: flags.length, flags }
48
- }