polyctl 0.7.0__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.
- polyctl/__init__.py +7 -0
- polyctl/__main__.py +5 -0
- polyctl/a2a.py +226 -0
- polyctl/a2a_mcp.py +546 -0
- polyctl/acp.py +417 -0
- polyctl/adapters/README.md +101 -0
- polyctl/adapters/aider.json +32 -0
- polyctl/adapters/amazon-q.json +15 -0
- polyctl/adapters/amp.json +16 -0
- polyctl/adapters/antigravity.json +120 -0
- polyctl/adapters/claude-code.json +229 -0
- polyctl/adapters/cloud-generic.json +57 -0
- polyctl/adapters/codex.json +47 -0
- polyctl/adapters/command-code.json +45 -0
- polyctl/adapters/copilot.json +17 -0
- polyctl/adapters/cursor-agent.json +29 -0
- polyctl/adapters/deepseek.json +13 -0
- polyctl/adapters/droid.json +34 -0
- polyctl/adapters/gemini.json +30 -0
- polyctl/adapters/grok.json +22 -0
- polyctl/adapters/hermes.json +34 -0
- polyctl/adapters/kilocode.json +30 -0
- polyctl/adapters/kimi.json +23 -0
- polyctl/adapters/kiro.json +332 -0
- polyctl/adapters/ollama.json +29 -0
- polyctl/adapters/omp.json +34 -0
- polyctl/adapters/openai-api.json +68 -0
- polyctl/adapters/opencode.json +162 -0
- polyctl/adapters/pi.json +24 -0
- polyctl/adapters/pr-agent.json +54 -0
- polyctl/adapters/profiles.json +9 -0
- polyctl/adapters/qoder.json +163 -0
- polyctl/adapters/qwen.json +27 -0
- polyctl/adapters/reasonix.json +25 -0
- polyctl/adapters/rewriters/rtk.json +24 -0
- polyctl/adapters/trae.json +31 -0
- polyctl/adapters/vendors.json +42 -0
- polyctl/adapters/warp.json +88 -0
- polyctl/allowlist.py +1756 -0
- polyctl/api_review.py +920 -0
- polyctl/cli.py +835 -0
- polyctl/conformance_harness.py +9 -0
- polyctl/demo.py +503 -0
- polyctl/drivers.py +146 -0
- polyctl/email.py +160 -0
- polyctl/features.py +98 -0
- polyctl/journal.py +144 -0
- polyctl/language.py +945 -0
- polyctl/lib.py +1296 -0
- polyctl/matrix.py +660 -0
- polyctl/mcp.py +1362 -0
- polyctl/ntfy.py +169 -0
- polyctl/outbound.py +39 -0
- polyctl/parts/__init__.py +5 -0
- polyctl/parts/cli_authority.py +2615 -0
- polyctl/parts/cli_channels.py +1325 -0
- polyctl/parts/cli_checks.py +2293 -0
- polyctl/parts/cli_completion.py +686 -0
- polyctl/parts/cli_evidence.py +141 -0
- polyctl/parts/cli_gain.py +375 -0
- polyctl/parts/cli_harness.py +392 -0
- polyctl/parts/cli_hooks.py +1816 -0
- polyctl/parts/cli_install.py +638 -0
- polyctl/parts/cli_lanes.py +106 -0
- polyctl/parts/cli_maintenance.py +2536 -0
- polyctl/parts/cli_next.py +248 -0
- polyctl/parts/cli_pr.py +53 -0
- polyctl/parts/cli_project.py +2857 -0
- polyctl/parts/cli_review.py +5158 -0
- polyctl/parts/cli_status.py +898 -0
- polyctl/parts/lib_adapters.py +2933 -0
- polyctl/parts/lib_alarms.py +2106 -0
- polyctl/parts/lib_events.py +224 -0
- polyctl/parts/lib_evidence.py +412 -0
- polyctl/parts/lib_gates.py +2099 -0
- polyctl/parts/lib_lanes.py +829 -0
- polyctl/parts/lib_mail.py +1541 -0
- polyctl/parts/lib_next.py +652 -0
- polyctl/parts/lib_pr.py +331 -0
- polyctl/parts/lib_slices.py +3337 -0
- polyctl/parts/lib_state.py +2415 -0
- polyctl/parts/lib_transcript.py +4118 -0
- polyctl/pressure.py +325 -0
- polyctl/prices.json +47 -0
- polyctl/procs.py +1194 -0
- polyctl/settings.py +505 -0
- polyctl/skill/SKILL.md +365 -0
- polyctl/skillkit.py +503 -0
- polyctl/storage.py +2055 -0
- polyctl/telegram.py +327 -0
- polyctl/tiers.py +123 -0
- polyctl/verdicts.py +41 -0
- polyctl/watchdog.py +3887 -0
- polyctl/web.py +337 -0
- polyctl-0.7.0.dist-info/METADATA +235 -0
- polyctl-0.7.0.dist-info/RECORD +99 -0
- polyctl-0.7.0.dist-info/WHEEL +4 -0
- polyctl-0.7.0.dist-info/entry_points.txt +5 -0
- polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""Harnesses: `polyctl harness probe`, which asks each harness that speaks ACP what it supports (ACP-PROBE), and
|
|
2
|
+
`polyctl harness seen`, where a person reads the harness configuration an agent changed (HARNESS-CONFIG).
|
|
3
|
+
|
|
4
|
+
A part of src/polyctl/cli.py, run in its namespace by `_part` as the parts moved out of it are (#44); it is
|
|
5
|
+
not importable on its own.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def harness_profile_path(adapter_id):
|
|
10
|
+
"""Where what a harness said it supports is kept: ~/.polyctl/harness/<id>.json, the machine's, as its binaries are.
|
|
11
|
+
|
|
12
|
+
The id names a file, so one that is not a plain name - a separator, a leading dot - is refused rather than
|
|
13
|
+
followed out of that folder (PROBE-SHIPPED).
|
|
14
|
+
"""
|
|
15
|
+
import re
|
|
16
|
+
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", str(adapter_id)):
|
|
17
|
+
raise ValueError(f"{adapter_id!r} is no adapter id a harness profile is named by")
|
|
18
|
+
return os.path.join(A.HOME, ".polyctl", "harness", f"{adapter_id}.json")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def cmd_harness(cfg, args):
|
|
22
|
+
"""Ask each harness whose adapter says how to start it in ACP what it supports, and keep the answer (ACP-PROBE).
|
|
23
|
+
|
|
24
|
+
Only an adapter's `acp.argv` is started, found as polyctl finds any program, and only the harnesses named,
|
|
25
|
+
or every one whose adapter declares that command. The adapter is one the package ships: an ACP command
|
|
26
|
+
is a program polyctl starts, and a user's or a project's layer is a file the agents it describes can write, so
|
|
27
|
+
the command such a layer declares is named and never started, as a turn's and a route's are not
|
|
28
|
+
(TURN-ARGV, ROUTE-ARGV, PROBE-SHIPPED). Each is asked `initialize` and, with --sessions,
|
|
29
|
+
`session/list` for this directory; it is sent no prompt and opens no session, so asking spends no quota.
|
|
30
|
+
What it answers is kept in ~/.polyctl/harness/<id>.json with when it was asked and which binary answered: how
|
|
31
|
+
many sessions it listed is kept, and nothing of what they are. A harness that is not installed is said
|
|
32
|
+
to be so; one that does not answer in --timeout seconds is said not to, and the command exits 1.
|
|
33
|
+
|
|
34
|
+
`polyctl harness seen` is a person's command of its own (_harness_seen).
|
|
35
|
+
"""
|
|
36
|
+
from . import acp
|
|
37
|
+
from .storage import replace_file_durably
|
|
38
|
+
if getattr(args, "action", None) == "seen":
|
|
39
|
+
return _harness_seen(cfg, args)
|
|
40
|
+
if getattr(args, "by", None) or getattr(args, "digest", None) or getattr(args, "ask", False):
|
|
41
|
+
print("--by, --digest and --ask belong to polyctl harness seen, where a person records what they read; probe takes "
|
|
42
|
+
"none of them")
|
|
43
|
+
return 2
|
|
44
|
+
root = cfg.get("root") or os.getcwd()
|
|
45
|
+
# Only the adapters the package ships; what a user's or a project's layer declares of an ACP command - an
|
|
46
|
+
# adapter of its own, or another command for one polyctl ships - is named, and not started (PROBE-SHIPPED).
|
|
47
|
+
catalog = {adapter_id: adapter for adapter_id, adapter in A.package_adapters().items()
|
|
48
|
+
if adapter.get("contract", A.ADAPTER_CONTRACT) == A.ADAPTER_CONTRACT}
|
|
49
|
+
layered = sorted(adapter_id for adapter_id, entry in A.adapter_catalog(cfg.get("root")).items()
|
|
50
|
+
if entry["source"] != "package" and isinstance(entry["adapter"].get("acp"), dict)
|
|
51
|
+
and entry["adapter"].get("acp") != (catalog.get(adapter_id) or {}).get("acp"))
|
|
52
|
+
named = list(getattr(args, "ids", None) or [])
|
|
53
|
+
unknown = [adapter_id for adapter_id in named if adapter_id not in catalog]
|
|
54
|
+
if unknown:
|
|
55
|
+
held = [adapter_id for adapter_id in unknown if adapter_id in layered]
|
|
56
|
+
if held:
|
|
57
|
+
print(f"{C['red']}not started{C['reset']}: polyctl ships no adapter {', '.join(map(A.shown_text, held))}, and "
|
|
58
|
+
"it starts the ACP command of one the package ships alone, never one a user's or a project's layer "
|
|
59
|
+
"declares")
|
|
60
|
+
missing = [adapter_id for adapter_id in unknown if adapter_id not in held]
|
|
61
|
+
if missing:
|
|
62
|
+
print(f"{C['red']}no adapter{C['reset']} {', '.join(map(A.shown_text, missing))}; `polyctl adapters` lists them")
|
|
63
|
+
return 2
|
|
64
|
+
noted = [adapter_id for adapter_id in layered if not named or adapter_id in named]
|
|
65
|
+
if noted:
|
|
66
|
+
print(f"{C['dim']}Not started: the ACP command a user's or a project's layer declares for "
|
|
67
|
+
f"{', '.join(map(A.shown_text, noted))}; polyctl starts the one an adapter it ships declares, and only "
|
|
68
|
+
f"that.{C['reset']}")
|
|
69
|
+
silent = [adapter_id for adapter_id in named if not isinstance(catalog[adapter_id].get("acp"), dict)]
|
|
70
|
+
if silent:
|
|
71
|
+
print(f"{C['red']}no ACP command{C['reset']}: the adapter polyctl ships for {', '.join(map(A.shown_text, silent))} "
|
|
72
|
+
"declares no `acp.argv`")
|
|
73
|
+
return 2
|
|
74
|
+
chosen = named or sorted(adapter_id for adapter_id, adapter in catalog.items()
|
|
75
|
+
if isinstance(adapter.get("acp"), dict))
|
|
76
|
+
if not chosen:
|
|
77
|
+
print(f"{C['dim']}No adapter polyctl ships says how to start its harness in ACP (`acp.argv`).{C['reset']}")
|
|
78
|
+
return 1
|
|
79
|
+
failed = 0
|
|
80
|
+
for adapter_id in chosen:
|
|
81
|
+
argv = [str(part) for part in catalog[adapter_id]["acp"].get("argv") or []]
|
|
82
|
+
# What the harness answers is a vendor's, and an id named on the command line is a person's: each is shown
|
|
83
|
+
# escaped, as `polyctl agents` shows a hook's (LEADS-MCP), as an id a layer declares is where it is named above.
|
|
84
|
+
if not argv:
|
|
85
|
+
failed += 1
|
|
86
|
+
print(f" {A.shown_text(adapter_id):<12} {C['red']}no command{C['reset']}: its `acp.argv` is empty")
|
|
87
|
+
continue
|
|
88
|
+
try:
|
|
89
|
+
target = harness_profile_path(adapter_id) # a harness is asked only where its answer can be kept
|
|
90
|
+
except ValueError as exc:
|
|
91
|
+
failed += 1
|
|
92
|
+
print(f" {A.shown_text(adapter_id):<12} {C['red']}not asked{C['reset']}: {A.shown_text(exc)}")
|
|
93
|
+
continue
|
|
94
|
+
path, version = A.resolve_binary(argv[0])
|
|
95
|
+
if path is None:
|
|
96
|
+
print(f" {A.shown_text(adapter_id):<12} {C['dim']}not installed: {A.shown_text(argv[0])} is on no path "
|
|
97
|
+
f"polyctl searches{C['reset']}")
|
|
98
|
+
continue
|
|
99
|
+
try:
|
|
100
|
+
found = acp.probe([path] + argv[1:], root, timeout=args.timeout, sessions=args.sessions)
|
|
101
|
+
except acp.ProbeError as exc:
|
|
102
|
+
failed += 1
|
|
103
|
+
print(f" {A.shown_text(adapter_id):<12} {C['red']}no answer{C['reset']}: {A.shown_text(exc)}")
|
|
104
|
+
_probe_left(adapter_id, exc.still_running)
|
|
105
|
+
continue
|
|
106
|
+
left = found.pop("still_running", [])
|
|
107
|
+
profile = dict({"id": adapter_id, "measured_at": int(time.time()), "argv": argv, "binary": path,
|
|
108
|
+
"binary_version": version}, **found)
|
|
109
|
+
os.makedirs(os.path.dirname(target), exist_ok=True)
|
|
110
|
+
replace_file_durably(target, (json.dumps(profile, indent=1, sort_keys=True) + "\n").encode(UTF8))
|
|
111
|
+
agent = " ".join(A.shown_text(part) for part in (found["agent"].get("name"), found["agent"].get("version"))
|
|
112
|
+
if part)
|
|
113
|
+
print(f" {A.shown_text(adapter_id):<12} ACP {A.shown_text(found['protocol_version'])} "
|
|
114
|
+
f"{agent or '(unnamed)'} load {'yes' if found['load_session'] else 'no'} "
|
|
115
|
+
f"session: {A.shown_text(', '.join(found['session'])) or '-'} "
|
|
116
|
+
f"mcp: {A.shown_text(', '.join(found['mcp'])) or '-'}"
|
|
117
|
+
+ (f" sessions here: {found['sessions']}" if "sessions" in found else ""))
|
|
118
|
+
if left:
|
|
119
|
+
failed += 1
|
|
120
|
+
_probe_left(adapter_id, left)
|
|
121
|
+
return 1 if failed else 0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _probe_left(adapter_id, left):
|
|
125
|
+
"""Say what of a probed agent still runs after the probe stopped it: asked, not assumed stopped
|
|
126
|
+
(WINDOWS-STOP-PROVEN), whether the agent answered or not (ACP-PROBE-LEFT)."""
|
|
127
|
+
if left:
|
|
128
|
+
print(f" {A.shown_text(adapter_id):<12} {C['red']}{len(left)} process(es) of its agent still run after the "
|
|
129
|
+
f"probe stopped it{C['reset']}: {list(left)}; {_stop_by_hand()}")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ---- what a harness reads from the tree, read by a person before anything polyctl starts here runs (HARNESS-CONFIG) ----
|
|
133
|
+
|
|
134
|
+
def _turn_lines(identity):
|
|
135
|
+
"""What a role's block says of its command, a line for each thing it says, as a person reads it (TURN-ARGV); a
|
|
136
|
+
reviewer's routes a line each, so one route's change reads as that route's (ROUTE-ARGV)."""
|
|
137
|
+
lines = []
|
|
138
|
+
for key, value in sorted((identity or {}).items()):
|
|
139
|
+
if value is None:
|
|
140
|
+
continue
|
|
141
|
+
if isinstance(value, list) and value and all(isinstance(item, dict) for item in value):
|
|
142
|
+
lines += [f"{key}[{at}]: {json.dumps(item, ensure_ascii=False, sort_keys=True)}"
|
|
143
|
+
for at, item in enumerate(value)]
|
|
144
|
+
else:
|
|
145
|
+
lines.append(f"{key}: {json.dumps(value, ensure_ascii=False)}")
|
|
146
|
+
return [A.shown_text(line) for line in lines]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _harness_change_lines(root, path, state, view):
|
|
150
|
+
"""The lines that show one change as it stands: its diff from HEAD where it is text (HARNESS-CONFIG); for a role's
|
|
151
|
+
command, the command a turn would start and what its block says, beside what was last accepted (TURN-ARGV)."""
|
|
152
|
+
import difflib
|
|
153
|
+
import shlex
|
|
154
|
+
kind = view[0] if view else "deleted"
|
|
155
|
+
if kind == "turn":
|
|
156
|
+
_, role, identity, accepted, (ident, argv) = view
|
|
157
|
+
starts = (A.shown_text(" ".join(shlex.quote(str(part)) for part in argv)) if argv
|
|
158
|
+
else f"nothing: no adapter polyctl ships composes it ({A.shown_text(ident or 'none named')})")
|
|
159
|
+
lines = list(difflib.unified_diff(_turn_lines(accepted), _turn_lines(identity), lineterm="",
|
|
160
|
+
fromfile="accepted" if accepted else "nothing accepted",
|
|
161
|
+
tofile=".polyctl/config.json"))
|
|
162
|
+
# With the transport at acp a route is reached another way than the command shown, which a person accepts with
|
|
163
|
+
# it (REVIEW-PATH-HIGHS).
|
|
164
|
+
through = [f"or, as review.transport is {A.shown_text(identity['transport'])}, through its adapter's ACP "
|
|
165
|
+
"command, where that was measured to hold a reviewer to reads"] \
|
|
166
|
+
if role == "reviewer" and isinstance(identity, dict) and identity.get("transport") else []
|
|
167
|
+
return [f"{A.HELD_COMMANDS[role]} would start: {starts}"] + through + lines
|
|
168
|
+
if kind == "deleted":
|
|
169
|
+
return ["deleted: HEAD holds it, and a harness started here reads none"]
|
|
170
|
+
if kind == "special":
|
|
171
|
+
return [f"{view[1]}, not a regular file: a harness that opens it reads whatever its writer sends"]
|
|
172
|
+
if kind == "missing":
|
|
173
|
+
return ["nothing: the link leads nowhere"]
|
|
174
|
+
if kind == "link":
|
|
175
|
+
target, inner = view[1], view[2]
|
|
176
|
+
if inner is None:
|
|
177
|
+
return [f"a link to the folder {A.shown_text(target)}: each file in it is a change of its own below"]
|
|
178
|
+
return [f"a link to {A.shown_text(target)}, which holds:"] \
|
|
179
|
+
+ _harness_change_lines(root, path, "untracked", inner)
|
|
180
|
+
data, size = view[1], view[2]
|
|
181
|
+
if data is None:
|
|
182
|
+
return [f"{size} bytes, more than polyctl shows here: read the whole file before you record it"]
|
|
183
|
+
if b"\0" in data:
|
|
184
|
+
return [f"{size} bytes, not text: read it with a tool that shows such a file before you record it"]
|
|
185
|
+
before = b""
|
|
186
|
+
if state in ("modified", "hidden"):
|
|
187
|
+
try:
|
|
188
|
+
before = A._git_output(root, "cat-file", "blob", f"HEAD:{path}")
|
|
189
|
+
except RuntimeError:
|
|
190
|
+
before = b""
|
|
191
|
+
lines = list(difflib.unified_diff(before.decode(UTF8, "replace").splitlines(),
|
|
192
|
+
data.decode(UTF8, "replace").splitlines(),
|
|
193
|
+
fromfile=f"HEAD:{path}" if before else "nothing", tofile=path, lineterm=""))
|
|
194
|
+
return [A.shown_text(line) for line in lines] or ["empty"]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _harness_seen_text(record, changes):
|
|
198
|
+
"""Who saw the changes that stand, as a person reads it: what polyctl wrote itself, and the person who recorded the rest,
|
|
199
|
+
and when (HARNESS-SEEN-OWN)."""
|
|
200
|
+
standing = {(path, sha) for path, _, sha in changes}
|
|
201
|
+
wrote = sorted(item["path"] for item in record.get("written") or []
|
|
202
|
+
if isinstance(item, dict) and (item.get("path"), item.get("sha256")) in standing)
|
|
203
|
+
others = [change for change in changes if change[0] not in wrote]
|
|
204
|
+
parts = []
|
|
205
|
+
if wrote:
|
|
206
|
+
parts.append(f"polyctl wrote {', '.join(A.shown_text(path) for path in wrote)} itself")
|
|
207
|
+
if others:
|
|
208
|
+
when = time.strftime("%d %b %H:%M", time.localtime(float(record.get("at") or 0)))
|
|
209
|
+
parts.append(f"{record.get('by') or 'a person'} recorded {A.harness_config_line(others)} on {when}")
|
|
210
|
+
return "; ".join(parts)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _record_seen(root, by, digest):
|
|
214
|
+
"""Record what a person was shown, while it is what the digest was taken of; the command's exit (HARNESS-CONFIG)."""
|
|
215
|
+
try:
|
|
216
|
+
changes = A.harness_config_changes(root)
|
|
217
|
+
except Exception as exc:
|
|
218
|
+
print(f"{C['red']}not recorded{C['reset']}: what a harness reads from this tree cannot be read "
|
|
219
|
+
f"({A.shown_text(' '.join(str(exc).split()))})")
|
|
220
|
+
return 1
|
|
221
|
+
unseen = A.harness_unseen(changes, A.harness_seen_record(root) or {})
|
|
222
|
+
if not unseen or A.harness_config_digest(unseen) != digest:
|
|
223
|
+
print(f"{C['red']}refused{C['reset']}: what a harness reads here is not what that digest was taken of - it "
|
|
224
|
+
f"changed since it was shown, or the digest is another's. Nothing was recorded; "
|
|
225
|
+
f"`polyctl harness seen --by {A.copyable_word(by) or '<your name>'}` shows it as it stands now")
|
|
226
|
+
return 2
|
|
227
|
+
A.record_harness_seen(root, changes, by, digest)
|
|
228
|
+
print(f"{C['green']}recorded{C['reset']}: {A.shown_text(by)} has seen {A.harness_config_line(unseen)}; a wake, refill, "
|
|
229
|
+
"nudge, hunt or lane starts in this tree again")
|
|
230
|
+
return 0
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _harness_seen(cfg, args):
|
|
234
|
+
"""Show a person the harness configuration an agent changed in this tree, and record it as seen (HARNESS-CONFIG).
|
|
235
|
+
|
|
236
|
+
What a harness reads from a project - hooks, plugins, MCP servers, instructions - acts in the next session started
|
|
237
|
+
there, before any review has seen it, so no wake, refill, nudge, hunt or lane starts here while a change to it
|
|
238
|
+
stands unseen. With --by alone each unseen change is shown as it stands, its diff from HEAD where it is text, with
|
|
239
|
+
the digest of exactly those bytes, and nothing is recorded. With --by and that digest it is recorded as seen, kept
|
|
240
|
+
in ~/.polyctl outside the tree; a change made since it was shown refuses the record, so what is recorded is what was
|
|
241
|
+
read, as `polyctl person-review` records a verdict. It is a person's command, as `polyctl waive` is: --by names a person and
|
|
242
|
+
never an agent or a role, the login and whether a terminal was attached are recorded beside the name, and no grant
|
|
243
|
+
polyctl checks admits it.
|
|
244
|
+
|
|
245
|
+
With --ask, at a terminal, the changes are shown and the person is asked, and a yes records exactly what was shown,
|
|
246
|
+
as the digest does: one step for a person's own tool approvals, which Claude Code writes into
|
|
247
|
+
.claude/settings.local.json each time a tool is allowed for good, and which polyctl cannot tell from an agent's write
|
|
248
|
+
(HARNESS-SEEN-OWN). Nobody at a terminal - a pipe, a scheduled job, an agent's tool call, or a terminal at EOF
|
|
249
|
+
nobody can type into (HARNESS-SEEN-EOF) - is never a yes, and prints the `--digest` command that records what was
|
|
250
|
+
shown.
|
|
251
|
+
"""
|
|
252
|
+
root = cfg["root"]
|
|
253
|
+
if getattr(args, "ids", None):
|
|
254
|
+
print("polyctl harness seen names no adapter: it shows what every harness polyctl knows reads from this tree")
|
|
255
|
+
return 2
|
|
256
|
+
by = (getattr(args, "by", None) or "").strip()
|
|
257
|
+
if not by or not by.isprintable() or len(by) > 80:
|
|
258
|
+
print("--by is required: the person who reads the changes, in one line of at most 80 characters")
|
|
259
|
+
return 2
|
|
260
|
+
if by.lower() in _agent_names(cfg):
|
|
261
|
+
print(f"--by names an agent or a role ({by}); seeing what a harness runs is a person's act")
|
|
262
|
+
return 2
|
|
263
|
+
ask, wanted = bool(getattr(args, "ask", False)), (getattr(args, "digest", None) or "").strip()
|
|
264
|
+
if ask and wanted:
|
|
265
|
+
print("--ask and --digest are two ways to record what was shown; give one of them")
|
|
266
|
+
return 2
|
|
267
|
+
shown = {}
|
|
268
|
+
try:
|
|
269
|
+
# Each role's command among them, as its block in .polyctl/config.json says it (TURN-ARGV).
|
|
270
|
+
A.record_turn_baseline(root, "first reading")
|
|
271
|
+
changes = A.harness_config_changes(root, shown=shown)
|
|
272
|
+
except Exception as exc:
|
|
273
|
+
print(f"{C['red']}not read{C['reset']}: what a harness reads from this tree cannot be read "
|
|
274
|
+
f"({A.shown_text(' '.join(str(exc).split()))}); nothing polyctl starts here runs until it can, and nothing "
|
|
275
|
+
"was recorded")
|
|
276
|
+
return 1
|
|
277
|
+
if not changes:
|
|
278
|
+
print(f"{C['green']}nothing a harness reads from this tree differs from HEAD{C['reset']}, and each role's "
|
|
279
|
+
"command is the one accepted; nothing to record")
|
|
280
|
+
return 0
|
|
281
|
+
record = A.harness_seen_record(root) or {}
|
|
282
|
+
unseen = A.harness_unseen(changes, record)
|
|
283
|
+
if not unseen:
|
|
284
|
+
print(f"{C['green']}seen{C['reset']}: each change to what a harness reads here is seen as it stands - "
|
|
285
|
+
f"{_harness_seen_text(record, changes)}")
|
|
286
|
+
return 0
|
|
287
|
+
digest = A.harness_config_digest(unseen)
|
|
288
|
+
if wanted:
|
|
289
|
+
return _record_seen(root, by, wanted)
|
|
290
|
+
print(f"{C['b']}harness configuration nobody has seen{C['reset']}: {len(unseen)} change(s) to what a harness "
|
|
291
|
+
"reads from this tree, each as it stands now")
|
|
292
|
+
for path, state, _ in unseen:
|
|
293
|
+
print(f"\n{C['b']}{A.shown_text(path)}{C['reset']} ({A.HARNESS_CONFIG_STATES.get(state, state)})")
|
|
294
|
+
for line in _harness_change_lines(root, path, state, shown.get(path)):
|
|
295
|
+
print(f" {line}")
|
|
296
|
+
print(f"\ndigest {digest}")
|
|
297
|
+
# The name goes into each command a person copies quoted as one word for any shell they paste it into: copied,
|
|
298
|
+
# `--by Ada Lovelace` named `Lovelace` an adapter and was refused, and a `;` or a `$(...)` in a name ran as a
|
|
299
|
+
# command. A name no quoting holds as one word in every shell is put in no command (LEADS-MCP).
|
|
300
|
+
named = A.copyable_word(by) or "<your name>"
|
|
301
|
+
unquotable = "" if A.copyable_word(by) else (f" ({A.shown_text(by)} holds a sign a shell reads as more than a "
|
|
302
|
+
"name: type the command with your name as you write it)")
|
|
303
|
+
if ask:
|
|
304
|
+
answer = _confirm(f"Record exactly these as seen by {A.shown_text(by)}? [y/N] ")
|
|
305
|
+
if not answer:
|
|
306
|
+
print("Nothing was recorded" + (f": nobody can answer here, {_no_answer_why()}; read the "
|
|
307
|
+
f"changes above, then `polyctl harness seen --by {named} --digest {digest}` "
|
|
308
|
+
f"records them{unquotable}" if answer is None else "."))
|
|
309
|
+
return 1
|
|
310
|
+
return _record_seen(root, by, digest)
|
|
311
|
+
print(f"Nothing is recorded yet. Read each change above, then\n polyctl harness seen --by {named} --digest {digest}\n"
|
|
312
|
+
f"records exactly these bytes as seen; a change made since refuses it. At a terminal, "
|
|
313
|
+
f"`polyctl harness seen --by {named} --ask` shows them and records them on your yes{unquotable}.")
|
|
314
|
+
return 0
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
# ---- a harness's lifecycle hooks: `polyctl agent-hook EVENT`, and `polyctl agents` (HOOK-SPOOL) ---------------------------
|
|
318
|
+
|
|
319
|
+
AGENT_HOOK_BYTES = 1 << 20 # a hook's input past this is not read
|
|
320
|
+
AGENT_HOOK_WAIT = 2.0 # seconds a hook's input may take to arrive
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _hook_input():
|
|
324
|
+
"""The JSON a hook hands its command on standard input, or {}: read for AGENT_HOOK_WAIT seconds at most, so
|
|
325
|
+
a harness that leaves the stream open never holds its own turn on polyctl."""
|
|
326
|
+
import threading
|
|
327
|
+
if sys.stdin is None or sys.stdin.isatty():
|
|
328
|
+
return {}
|
|
329
|
+
got = []
|
|
330
|
+
|
|
331
|
+
def read():
|
|
332
|
+
try:
|
|
333
|
+
got.append(sys.stdin.read(AGENT_HOOK_BYTES + 1))
|
|
334
|
+
except (OSError, ValueError):
|
|
335
|
+
pass
|
|
336
|
+
|
|
337
|
+
reader = threading.Thread(target=read, daemon=True)
|
|
338
|
+
reader.start()
|
|
339
|
+
reader.join(AGENT_HOOK_WAIT)
|
|
340
|
+
raw = got[0] if got else ""
|
|
341
|
+
if not raw or len(raw) > AGENT_HOOK_BYTES:
|
|
342
|
+
return {}
|
|
343
|
+
try:
|
|
344
|
+
payload = json.loads(raw)
|
|
345
|
+
except ValueError:
|
|
346
|
+
return {}
|
|
347
|
+
return payload if isinstance(payload, dict) else {}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def cmd_agent_hook(cfg, args):
|
|
351
|
+
"""Record one lifecycle event a harness's hook hands polyctl in the machine's event log, and nothing else (HOOK-SPOOL).
|
|
352
|
+
|
|
353
|
+
The hook names the event in polyctl's words (A.AGENT_EVENTS) and, with --harness, the adapter it is.
|
|
354
|
+
From what the hook hands over on standard input polyctl keeps the session's id and directory, and a
|
|
355
|
+
tool's name or a notification's type where the event is one: never a prompt, a tool's input or
|
|
356
|
+
output, or a transcript. It writes nothing on standard output, which a harness may read as its
|
|
357
|
+
own input, and always exits 0, so a hook can neither fail a turn nor hold it: an event polyctl does not
|
|
358
|
+
know, or one from a directory that is no polyctl project, is not recorded, and nothing is said.
|
|
359
|
+
"""
|
|
360
|
+
root = cfg.get("root")
|
|
361
|
+
if args.event not in A.AGENT_EVENTS or not root or not os.path.isdir(os.path.join(root, ".polyctl")):
|
|
362
|
+
return 0
|
|
363
|
+
payload = _hook_input()
|
|
364
|
+
|
|
365
|
+
def text(key, limit=256):
|
|
366
|
+
value = payload.get(key)
|
|
367
|
+
return value[:limit] if isinstance(value, str) and value.strip() else None
|
|
368
|
+
|
|
369
|
+
A.emit_event(root, f"agent-{args.event}", {
|
|
370
|
+
"harness": args.harness, "session": text("session_id", 128), "cwd": text("cwd", 1024),
|
|
371
|
+
"tool": text("tool_name", 128) if args.event in ("tool", "tool-done") else None,
|
|
372
|
+
"notice": text("notification_type", 64) if args.event == "notification" else None})
|
|
373
|
+
return 0
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def cmd_agents(cfg, args):
|
|
377
|
+
"""The sessions this project's harnesses' hooks have spoken of, and what each is doing now (HOOK-SPOOL)."""
|
|
378
|
+
sessions = sorted(A.agent_sessions(cfg["root"]).values(), key=lambda s: s.get("at") or 0, reverse=True)
|
|
379
|
+
if not sessions:
|
|
380
|
+
print(f"{C['dim']}No harness has told polyctl of a session here through its hooks.{C['reset']}")
|
|
381
|
+
return 0
|
|
382
|
+
now = time.time()
|
|
383
|
+
tone = {"working": C["green"], "waiting": C["yellow"], "idle": C["dim"], "ended": C["dim"]}
|
|
384
|
+
for session in sessions:
|
|
385
|
+
since = _elapsed(now - float(session.get("at") or now))
|
|
386
|
+
# The harness's name and the session's id are what a hook's command line and input said, and any program on
|
|
387
|
+
# the machine can run the hook: shown escaped, so an escape sequence is not acted on and a line feed starts
|
|
388
|
+
# no row of its own (LEADS-MCP).
|
|
389
|
+
print(f" {tone.get(session['state'], '')}{session['state']:<8}{C['reset']} "
|
|
390
|
+
f"{A.shown_text(session.get('harness') or '?'):<12} {A.shown_text(session['session'][:24]):<24} "
|
|
391
|
+
f"{since:>8} last: {session['event']}")
|
|
392
|
+
return 0
|