@pennixrv/trellis 0.7.2-beta.25 → 0.7.2-beta.27
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.
- package/dist/migrations/manifests/0.7.2-beta.26.json +8 -0
- package/dist/migrations/manifests/0.7.2-beta.27.json +8 -0
- package/dist/templates/codex/hooks/turn-guard.py +67 -0
- package/dist/templates/codex/hooks.json +63 -0
- package/dist/templates/common/bundled-skills/trellis-decision-space-construction-and-merging/workflow.md +6 -2
- package/dist/templates/common/bundled-skills/trellis-delivery-review-and-closeout/workflow.md +13 -9
- package/dist/templates/common/bundled-skills/trellis-goal-exploration-and-requirements/workflow.md +3 -1
- package/dist/templates/common/bundled-skills/trellis-solution-design-and-convergence/workflow.md +9 -1
- package/dist/templates/common/bundled-skills/trellis-task-implementation/workflow.md +2 -2
- package/dist/templates/common/commands/continue.md +9 -2
- package/dist/templates/common/skills/request-intake.md +2 -0
- package/dist/templates/omp/extensions/trellis/index.ts.txt +16 -9
- package/dist/templates/opencode/plugins/inject-workflow-state.js +15 -7
- package/dist/templates/pi/extensions/trellis/index.ts.txt +9 -4
- package/dist/templates/shared-hooks/index.d.ts.map +1 -1
- package/dist/templates/shared-hooks/index.js +1 -0
- package/dist/templates/shared-hooks/index.js.map +1 -1
- package/dist/templates/shared-hooks/inject-shell-session-context.py +27 -1
- package/dist/templates/shared-hooks/inject-workflow-state.py +44 -27
- package/dist/templates/trellis/index.d.ts.map +1 -1
- package/dist/templates/trellis/index.js +1 -0
- package/dist/templates/trellis/index.js.map +1 -1
- package/dist/templates/trellis/scripts/common/task_move.py +9 -3
- package/dist/templates/trellis/scripts/common/task_turn.py +514 -0
- package/dist/templates/trellis/scripts/common/task_workflow.py +289 -68
- package/dist/templates/trellis/scripts/common/workflow_selection.py +23 -38
- package/dist/templates/trellis/scripts/task.py +25 -4
- package/dist/templates/trellis/workflow.md +12 -2
- package/package.json +2 -2
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
"""Codex turn exit evidence; not a task lifecycle or permission authority."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
import shlex
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
|
|
16
|
+
from .active_task import _context_path, _write_json, resolve_context_key
|
|
17
|
+
from .io import JSON_READ_MISSING, read_json_checked, write_json
|
|
18
|
+
from .task_move import layout_lock, require_settled_layout
|
|
19
|
+
from .task_utils import resolve_task_dir
|
|
20
|
+
from .task_workflow import PHASE_IDS, TaskWorkflowError, _artifact_digest, _state, design_preflight
|
|
21
|
+
|
|
22
|
+
KINDS = ("bounded_reply", "task_complete", "waiting_authorization",
|
|
23
|
+
"waiting_input", "external_block", "user_stop")
|
|
24
|
+
SCOPES = ("explanation", "inspection", "handoff_admission", "maintenance")
|
|
25
|
+
TICKET_ID = re.compile(r"[0-9a-f]{32}\Z")
|
|
26
|
+
MAX_CORRECTIONS = 2
|
|
27
|
+
TICKET_SECONDS = 30
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TurnError(ValueError):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _digest(value: object) -> str:
|
|
35
|
+
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
36
|
+
separators=(",", ":")).encode()).hexdigest()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _text(value: object, name: str, limit: int = 512) -> str:
|
|
40
|
+
if not isinstance(value, str) or not value.strip() or len(value) > limit:
|
|
41
|
+
raise TurnError(f"TASK_TURN_INVALID: missing or invalid {name}")
|
|
42
|
+
return value
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _runtime_path(root: Path, path: Path) -> Path:
|
|
46
|
+
runtime = root / ".trellis/.runtime"
|
|
47
|
+
path.relative_to(runtime)
|
|
48
|
+
if runtime.is_symlink():
|
|
49
|
+
raise TurnError("TASK_TURN_WITHHELD: redirected runtime")
|
|
50
|
+
current = runtime
|
|
51
|
+
for part in path.relative_to(runtime).parts:
|
|
52
|
+
current = current / part
|
|
53
|
+
if current.is_symlink():
|
|
54
|
+
raise TurnError("TASK_TURN_WITHHELD: redirected runtime")
|
|
55
|
+
if path.exists() and not path.is_file():
|
|
56
|
+
raise TurnError("TASK_TURN_WITHHELD: runtime record is not a regular file")
|
|
57
|
+
return path
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _read(path: Path, *, missing: bool = False) -> dict:
|
|
61
|
+
value, reason = read_json_checked(path)
|
|
62
|
+
if value is None:
|
|
63
|
+
if missing and reason == JSON_READ_MISSING:
|
|
64
|
+
return {}
|
|
65
|
+
raise TurnError("TASK_TURN_WITHHELD: runtime record is " + str(reason))
|
|
66
|
+
return value
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _session(root: Path, key: str) -> tuple[Path, dict]:
|
|
70
|
+
path = _runtime_path(root, _context_path(root, key))
|
|
71
|
+
return path, _read(path, missing=True)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _save(path: Path, context: dict) -> None:
|
|
75
|
+
if not _write_json(path, context):
|
|
76
|
+
raise TurnError("TASK_TURN_WRITE_FAILED: could not save session")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _turn(context: dict, session: str | None = None, turn_id: str | None = None) -> dict:
|
|
80
|
+
value = context.get("turn")
|
|
81
|
+
if (not isinstance(value, dict)
|
|
82
|
+
or set(value) != {"schema_version", "session_id", "turn_id", "prompt_digest", "corrections",
|
|
83
|
+
"evidence", "answers", "interrupted", "observed_task"}
|
|
84
|
+
or type(value.get("schema_version")) is not int
|
|
85
|
+
or value["schema_version"] != 1
|
|
86
|
+
or type(value.get("corrections")) is not int
|
|
87
|
+
or not 0 <= value["corrections"] <= MAX_CORRECTIONS
|
|
88
|
+
or not isinstance(value.get("answers"), dict)
|
|
89
|
+
or not isinstance(value.get("interrupted"), bool)
|
|
90
|
+
or not isinstance(value.get("session_id"), str) or not value["session_id"]
|
|
91
|
+
or not isinstance(value.get("turn_id"), str) or not value["turn_id"]
|
|
92
|
+
or not re.fullmatch(r"[0-9a-f]{64}", str(value.get("prompt_digest")))
|
|
93
|
+
or session is not None and value.get("session_id") != session
|
|
94
|
+
or turn_id is not None and value.get("turn_id") != turn_id):
|
|
95
|
+
raise TurnError("TASK_TURN_WITHHELD: missing, stale or incompatible turn")
|
|
96
|
+
for call_id, answer in value["answers"].items():
|
|
97
|
+
if (not isinstance(call_id, str) or not call_id
|
|
98
|
+
or not isinstance(answer, dict) or set(answer) != {"input_digest", "response_digest", "status"}
|
|
99
|
+
or not re.fullmatch(r"[0-9a-f]{64}", str(answer["input_digest"]))
|
|
100
|
+
or answer["response_digest"] is not None and not re.fullmatch(r"[0-9a-f]{64}", str(answer["response_digest"]))
|
|
101
|
+
or not isinstance(answer["status"], str)
|
|
102
|
+
or answer["status"] not in {"pending", "complete", "incomplete"}):
|
|
103
|
+
raise TurnError("TASK_TURN_WITHHELD: incompatible answer observation")
|
|
104
|
+
return value
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _identity(event: dict) -> tuple[str, str, str]:
|
|
108
|
+
session = _text(event.get("session_id"), "native session_id")
|
|
109
|
+
turn_id = _text(event.get("turn_id"), "native turn_id")
|
|
110
|
+
key = resolve_context_key(event, platform="codex", allow_environment_context=False)
|
|
111
|
+
if key is None:
|
|
112
|
+
raise TurnError("TASK_TURN_WITHHELD: direct Codex identity is required")
|
|
113
|
+
return key, session, turn_id
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _snapshot(root: Path, context: dict, turn: dict) -> dict | None:
|
|
117
|
+
ref = context.get("current_task") or turn.get("observed_task")
|
|
118
|
+
if ref is None:
|
|
119
|
+
return None
|
|
120
|
+
if not isinstance(ref, str):
|
|
121
|
+
raise TurnError("TASK_TURN_WITHHELD: invalid task pointer")
|
|
122
|
+
# Native basename resolution also handles a task moved by complete/cancel.
|
|
123
|
+
directory = resolve_task_dir(ref if (root / ref).exists() else Path(ref).name, root)
|
|
124
|
+
if directory is None:
|
|
125
|
+
raise TurnError("TASK_TURN_WITHHELD: task is missing or ambiguous")
|
|
126
|
+
task = _read(directory / "task.json")
|
|
127
|
+
meta = task.get("meta", {})
|
|
128
|
+
if not isinstance(meta, dict):
|
|
129
|
+
raise TurnError("TASK_TURN_WITHHELD: invalid task metadata")
|
|
130
|
+
state = _state(meta) if meta.get("task_workflow") is not None else None
|
|
131
|
+
artifacts = {}
|
|
132
|
+
if state:
|
|
133
|
+
for phase, record in state["phases"].items():
|
|
134
|
+
artifacts[phase] = _artifact_digest(directory, record["artifact_refs"])
|
|
135
|
+
phase_id = state["current_phase_id"] if state else None
|
|
136
|
+
return {"id": task.get("id") or task.get("name"),
|
|
137
|
+
"path": directory.relative_to(root).as_posix(), "status": task.get("status"),
|
|
138
|
+
"record_digest": _digest(task), "artifacts": artifacts,
|
|
139
|
+
"phase_id": phase_id,
|
|
140
|
+
"phase_status": state["phases"][phase_id]["status"] if state and phase_id else None,
|
|
141
|
+
"route_revision": state["task_route_revision"] if state else None,
|
|
142
|
+
"input_revision": state["input_revision"] if state else None,
|
|
143
|
+
"closeout": state.get("closeout_disposition") if state else None,
|
|
144
|
+
"accepted_contract": (state["phases"][phase_id].get("outcome_kind") == "implementation_contract"
|
|
145
|
+
and state.get("implementation_authorization") is None) if state and phase_id == PHASE_IDS[2] else False}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def begin(root: Path, event: dict) -> dict:
|
|
149
|
+
key, session, turn_id = _identity(event)
|
|
150
|
+
prompt = _text(event.get("prompt"), "prompt", 1024 * 1024)
|
|
151
|
+
with layout_lock(root):
|
|
152
|
+
require_settled_layout(root)
|
|
153
|
+
path, context = _session(root, key)
|
|
154
|
+
previous = _turn(context) if "turn" in context else None
|
|
155
|
+
if previous and previous["turn_id"] == turn_id and previous["prompt_digest"] == _digest(prompt):
|
|
156
|
+
_turn(context, session, turn_id)
|
|
157
|
+
return previous
|
|
158
|
+
turn = {"schema_version": 1, "session_id": session, "turn_id": turn_id,
|
|
159
|
+
"prompt_digest": _digest(prompt),
|
|
160
|
+
"corrections": 0,
|
|
161
|
+
"evidence": None, "answers": {}, "interrupted": False,
|
|
162
|
+
}
|
|
163
|
+
snapshot = _snapshot(root, context, {})
|
|
164
|
+
turn["observed_task"] = snapshot["path"] if snapshot else None
|
|
165
|
+
context["turn"] = turn
|
|
166
|
+
_save(path, context)
|
|
167
|
+
return turn
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _invocation(root: Path, command: str) -> tuple[list[str], str | None, list[str]]:
|
|
171
|
+
if os.name != "posix":
|
|
172
|
+
raise TurnError("TASK_TURN_UNSUPPORTED: invocation rewriting requires a verified POSIX shell")
|
|
173
|
+
# Only single-quoted literals can contain shell expansion characters.
|
|
174
|
+
outside_literals = re.sub(r"""(?:"(?:\\.|[^"\\])*"|'[^']*'|\\.)""",
|
|
175
|
+
lambda match: "" if match[0].startswith("'") else match[0], command)
|
|
176
|
+
if any(c in command for c in ("\n", "\r", "\0")) or any(c in outside_literals for c in ("$", "`", "#")):
|
|
177
|
+
raise TurnError("TASK_TURN_WITHHELD: expansions and multiline shell commands are unsupported")
|
|
178
|
+
lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|<>()")
|
|
179
|
+
lexer.whitespace_split = True
|
|
180
|
+
lexer.commenters = ""
|
|
181
|
+
tokens = list(lexer)
|
|
182
|
+
if any(token and all(c in ";&|<>()" for c in token) for token in tokens):
|
|
183
|
+
raise TurnError("TASK_TURN_WITHHELD: use one direct Python task.py turn command")
|
|
184
|
+
if len(tokens) < 4 or (tokens[0] not in {"python", "python3"} and
|
|
185
|
+
(not Path(tokens[0]).is_absolute() or Path(tokens[0]).resolve() != Path(sys.executable).resolve())):
|
|
186
|
+
raise TurnError("TASK_TURN_WITHHELD: use Python directly")
|
|
187
|
+
index = 3 if tokens[1:3] == ["-X", "utf8"] else 1
|
|
188
|
+
if (len(tokens) <= index + 2 or (root / tokens[index]).resolve() != (root / ".trellis/scripts/task.py").resolve()
|
|
189
|
+
or tokens[index + 1] != "turn" or tokens[index + 2] not in {"show", "record"}):
|
|
190
|
+
raise TurnError("TASK_TURN_WITHHELD: not a native turn invocation")
|
|
191
|
+
argv = tokens[index + 2:]
|
|
192
|
+
ticket = None
|
|
193
|
+
if "--invocation-ticket" in argv:
|
|
194
|
+
if len(argv) < 3 or argv[-2] != "--invocation-ticket" or argv.count("--invocation-ticket") != 1:
|
|
195
|
+
raise TurnError("TASK_TURN_WITHHELD: invalid invocation ticket argument")
|
|
196
|
+
ticket = argv[-1]
|
|
197
|
+
argv = argv[:-2]
|
|
198
|
+
return argv, ticket, tokens[:index + 2]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _ticket_path(root: Path, ticket_id: str) -> Path:
|
|
202
|
+
if not TICKET_ID.fullmatch(ticket_id):
|
|
203
|
+
raise TurnError("TASK_TURN_WITHHELD: invalid invocation ticket")
|
|
204
|
+
return _runtime_path(root, root / ".trellis/.runtime/shell-tickets" / f"turn-{ticket_id}.json")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _expire_tickets(root: Path) -> None:
|
|
208
|
+
directory = root / ".trellis/.runtime/shell-tickets"
|
|
209
|
+
for path in directory.glob("turn-*.json"):
|
|
210
|
+
if not TICKET_ID.fullmatch(path.stem[5:]):
|
|
211
|
+
continue
|
|
212
|
+
try:
|
|
213
|
+
ticket = _read(_runtime_path(root, path))
|
|
214
|
+
except TurnError:
|
|
215
|
+
continue
|
|
216
|
+
if (set(ticket) == {"schema_version", "context_key", "session_id", "turn_id", "tool_use_id",
|
|
217
|
+
"cwd", "argv_digest", "snapshot_digest", "expires_at_epoch", "used"}
|
|
218
|
+
and type(ticket.get("schema_version")) is int and ticket["schema_version"] == 1
|
|
219
|
+
and ticket.get("cwd") == str(root.resolve())
|
|
220
|
+
and type(ticket.get("used")) is bool
|
|
221
|
+
and type(ticket.get("expires_at_epoch")) in (int, float)
|
|
222
|
+
and ticket["expires_at_epoch"] < time.time()):
|
|
223
|
+
path.unlink()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def ticket_input(root: Path, event: dict) -> dict:
|
|
227
|
+
key, session, turn_id = _identity(event)
|
|
228
|
+
tool_input = event.get("tool_input")
|
|
229
|
+
if not isinstance(tool_input, dict):
|
|
230
|
+
raise TurnError("TASK_TURN_WITHHELD: invalid Bash input")
|
|
231
|
+
command = _text(tool_input.get("command"), "Bash command", 16384)
|
|
232
|
+
argv, existing, prefix = _invocation(root, command)
|
|
233
|
+
call_id = _text(event.get("tool_use_id"), "tool_use_id")
|
|
234
|
+
cwd = Path(_text(event.get("cwd"), "cwd", 4096)).resolve()
|
|
235
|
+
if cwd != root.resolve():
|
|
236
|
+
raise TurnError("TASK_TURN_WITHHELD: run turn commands from the project root")
|
|
237
|
+
with layout_lock(root):
|
|
238
|
+
require_settled_layout(root)
|
|
239
|
+
_, context = _session(root, key)
|
|
240
|
+
turn = _turn(context, session, turn_id)
|
|
241
|
+
if turn["interrupted"]:
|
|
242
|
+
raise TurnError("TASK_TURN_WITHHELD: user interrupted this turn")
|
|
243
|
+
snapshot = _digest(_snapshot(root, context, turn))
|
|
244
|
+
if existing:
|
|
245
|
+
ticket = _read(_ticket_path(root, existing))
|
|
246
|
+
_check_ticket(ticket, root, argv, turn)
|
|
247
|
+
if ticket.get("tool_use_id") != call_id:
|
|
248
|
+
raise TurnError("TASK_TURN_WITHHELD: rewritten call identity changed")
|
|
249
|
+
return {**tool_input, "command": shlex.join([*prefix, *argv, "--invocation-ticket", existing])}
|
|
250
|
+
_expire_tickets(root)
|
|
251
|
+
ticket_id = uuid.uuid4().hex
|
|
252
|
+
ticket = {"schema_version": 1, "context_key": key, "session_id": session,
|
|
253
|
+
"turn_id": turn_id, "tool_use_id": call_id, "cwd": str(root.resolve()),
|
|
254
|
+
"argv_digest": _digest(argv), "snapshot_digest": snapshot,
|
|
255
|
+
"expires_at_epoch": time.time() + TICKET_SECONDS, "used": False}
|
|
256
|
+
ticket_path = _ticket_path(root, ticket_id)
|
|
257
|
+
ticket_path.parent.mkdir(parents=True, exist_ok=True)
|
|
258
|
+
if ticket_path.exists():
|
|
259
|
+
raise TurnError("TASK_TURN_WITHHELD: invocation ticket collision")
|
|
260
|
+
if not write_json(ticket_path, ticket):
|
|
261
|
+
raise TurnError("TASK_TURN_WRITE_FAILED: could not issue invocation ticket")
|
|
262
|
+
return {**tool_input, "command": shlex.join([*prefix, *argv, "--invocation-ticket", ticket_id])}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _check_ticket(ticket: dict, root: Path, argv: list[str], turn: dict) -> None:
|
|
266
|
+
if (ticket.get("schema_version") != 1 or ticket.get("used") is not False
|
|
267
|
+
or ticket.get("cwd") != str(root.resolve())
|
|
268
|
+
or ticket.get("session_id") != turn["session_id"] or ticket.get("turn_id") != turn["turn_id"]
|
|
269
|
+
or ticket.get("argv_digest") != _digest(argv)
|
|
270
|
+
or type(ticket.get("expires_at_epoch")) not in (int, float)
|
|
271
|
+
or not 0 <= ticket["expires_at_epoch"] - time.time() <= TICKET_SECONDS):
|
|
272
|
+
raise TurnError("TASK_TURN_WITHHELD: expired, replayed or mismatched invocation")
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _evidence(root: Path, args: argparse.Namespace, turn: dict, snapshot: dict | None) -> dict:
|
|
276
|
+
refs = args.evidence_ref or []
|
|
277
|
+
if not refs or any(not re.fullmatch(r"[A-Za-z0-9_.:/@-]{1,512}", ref) for ref in refs):
|
|
278
|
+
raise TurnError("TASK_TURN_INVALID: nonempty evidence references are required")
|
|
279
|
+
kind = args.kind
|
|
280
|
+
if kind not in KINDS:
|
|
281
|
+
raise TurnError("TASK_TURN_INVALID: unsupported exit kind")
|
|
282
|
+
result = {"kind": kind, "evidence_refs": refs, "snapshot_digest": _digest(snapshot)}
|
|
283
|
+
if kind == "bounded_reply":
|
|
284
|
+
result["scope"] = args.scope
|
|
285
|
+
elif kind in {"waiting_authorization", "waiting_input", "external_block"}:
|
|
286
|
+
result["no_independent_work"] = args.no_independent_work
|
|
287
|
+
result["scope"] = args.scope
|
|
288
|
+
text = _text(args.blocker if kind == "external_block" else args.question,
|
|
289
|
+
"explicit final blocker" if kind == "external_block" else "explicit final question")
|
|
290
|
+
result.update(final_text_digest=_digest(text), final_text_length=len(text))
|
|
291
|
+
if any(value is not None for value in (args.approval_result_ref, args.approval_artifact_revision, args.approval_outcome)):
|
|
292
|
+
if kind != "waiting_authorization" or snapshot is None or args.scope is not None:
|
|
293
|
+
raise TurnError("TASK_TURN_WITHHELD: candidate markers require a task-bound authorization question")
|
|
294
|
+
ref = _text(args.approval_result_ref, "approval result reference")
|
|
295
|
+
revision = _text(args.approval_artifact_revision, "approval artifact revision")
|
|
296
|
+
task_dir = root / snapshot["path"]
|
|
297
|
+
try:
|
|
298
|
+
state = _state(_read(task_dir / "task.json")["meta"])
|
|
299
|
+
candidate = design_preflight(task_dir, state, args.approval_outcome, ref, revision)
|
|
300
|
+
except TaskWorkflowError as error:
|
|
301
|
+
raise TurnError(f"{error.code}: {error}") from error
|
|
302
|
+
result["approval_candidate"] = {"digest": _digest(candidate), "result_ref": ref,
|
|
303
|
+
"artifact_revision": revision, "outcome": args.approval_outcome}
|
|
304
|
+
elif kind == "user_stop":
|
|
305
|
+
result["user_prompt_digest"] = _digest(_text(args.user_instruction, "user instruction", 1024 * 1024))
|
|
306
|
+
if not _valid_exit(result, snapshot, turn):
|
|
307
|
+
raise TurnError("TASK_TURN_WITHHELD: exit evidence does not match native task, scope or user input")
|
|
308
|
+
return result
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _valid_exit(evidence: object, snapshot: dict | None, turn: dict) -> bool:
|
|
312
|
+
if not isinstance(evidence, dict) or evidence.get("kind") not in KINDS or evidence.get("snapshot_digest") != _digest(snapshot):
|
|
313
|
+
return False
|
|
314
|
+
refs = evidence.get("evidence_refs")
|
|
315
|
+
if not isinstance(refs, list) or not refs or not all(isinstance(ref, str) and re.fullmatch(r"[A-Za-z0-9_.:/@-]{1,512}", ref) for ref in refs):
|
|
316
|
+
return False
|
|
317
|
+
kind = evidence["kind"]
|
|
318
|
+
if kind == "bounded_reply":
|
|
319
|
+
return evidence.get("scope") in SCOPES
|
|
320
|
+
if kind == "task_complete":
|
|
321
|
+
return snapshot is not None and snapshot["status"] in {"completed", "cancelled"}
|
|
322
|
+
if kind == "user_stop":
|
|
323
|
+
return evidence.get("user_prompt_digest") == turn["prompt_digest"]
|
|
324
|
+
if evidence.get("no_independent_work") is not True:
|
|
325
|
+
return False
|
|
326
|
+
scope = evidence.get("scope")
|
|
327
|
+
if scope is not None:
|
|
328
|
+
return kind in {"waiting_input", "external_block"} and scope in SCOPES
|
|
329
|
+
if snapshot is None:
|
|
330
|
+
return kind in {"waiting_input", "waiting_authorization", "external_block"}
|
|
331
|
+
if snapshot["status"] in {"completed", "cancelled"}:
|
|
332
|
+
return False
|
|
333
|
+
if kind == "external_block":
|
|
334
|
+
return (snapshot["phase_status"] == "blocked" or
|
|
335
|
+
snapshot["phase_id"] is None and snapshot["closeout"] in {"delivery_ready", "no_go", "cancelled"})
|
|
336
|
+
return (snapshot["phase_status"] == "waiting_user"
|
|
337
|
+
or kind == "waiting_authorization" and snapshot["phase_status"] == "accepted" and snapshot["accepted_contract"])
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def cli(root: Path, args: argparse.Namespace, argv: list[str]) -> dict:
|
|
341
|
+
with layout_lock(root):
|
|
342
|
+
require_settled_layout(root)
|
|
343
|
+
ticket_id = args.invocation_ticket
|
|
344
|
+
if ticket_id is None:
|
|
345
|
+
if args.turn_action == "record":
|
|
346
|
+
raise TurnError("TASK_TURN_WITHHELD: record requires the exact PreToolUse invocation ticket")
|
|
347
|
+
key = resolve_context_key()
|
|
348
|
+
if key is None:
|
|
349
|
+
return {"status": "unavailable", "reason": "no direct session identity"}
|
|
350
|
+
_, context = _session(root, key)
|
|
351
|
+
return {"status": "observed" if "turn" in context else "absent",
|
|
352
|
+
"turn": _turn(context) if "turn" in context else None}
|
|
353
|
+
ticket_path = _ticket_path(root, ticket_id)
|
|
354
|
+
ticket = _read(ticket_path)
|
|
355
|
+
key = _text(ticket.get("context_key"), "ticket context_key")
|
|
356
|
+
if not re.fullmatch(r"[A-Za-z0-9_.-]+", key):
|
|
357
|
+
raise TurnError("TASK_TURN_WITHHELD: invalid ticket context key")
|
|
358
|
+
path, context = _session(root, key)
|
|
359
|
+
turn = _turn(context)
|
|
360
|
+
_check_ticket(ticket, root, argv, turn)
|
|
361
|
+
direct = resolve_context_key(allow_environment_context=True)
|
|
362
|
+
if direct is not None and direct != key:
|
|
363
|
+
raise TurnError("TASK_TURN_WITHHELD: native session and ticket disagree")
|
|
364
|
+
if turn["interrupted"]:
|
|
365
|
+
raise TurnError("TASK_TURN_WITHHELD: interrupted turn")
|
|
366
|
+
snapshot = _snapshot(root, context, turn)
|
|
367
|
+
if ticket.get("snapshot_digest") != _digest(snapshot):
|
|
368
|
+
raise TurnError("TASK_TURN_WITHHELD: task or artifact revision changed")
|
|
369
|
+
evidence = _evidence(root, args, turn, snapshot) if args.turn_action == "record" else None
|
|
370
|
+
# Burn first: a crash can withhold evidence, never reuse a successful call.
|
|
371
|
+
ticket["used"] = True
|
|
372
|
+
if not write_json(ticket_path, ticket):
|
|
373
|
+
raise TurnError("TASK_TURN_WRITE_FAILED: could not consume invocation ticket")
|
|
374
|
+
if evidence is not None:
|
|
375
|
+
turn["evidence"] = evidence
|
|
376
|
+
if snapshot:
|
|
377
|
+
turn["observed_task"] = snapshot["path"]
|
|
378
|
+
_save(path, context)
|
|
379
|
+
return {"status": "recorded" if evidence is not None else "observed", "turn": turn}
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def observe(root: Path, event: dict) -> dict:
|
|
383
|
+
key, session, turn_id = _identity(event)
|
|
384
|
+
with layout_lock(root):
|
|
385
|
+
path, context = _session(root, key)
|
|
386
|
+
turn = _turn(context, session, turn_id)
|
|
387
|
+
snapshot = _snapshot(root, context, turn)
|
|
388
|
+
if snapshot:
|
|
389
|
+
turn["observed_task"] = snapshot["path"]
|
|
390
|
+
if event.get("tool_name") != "request_user_input":
|
|
391
|
+
_save(path, context)
|
|
392
|
+
return {}
|
|
393
|
+
call_id = _text(event.get("tool_use_id"), "tool_use_id")
|
|
394
|
+
input_digest = _digest(event.get("tool_input"))
|
|
395
|
+
response_digest = _digest(event.get("tool_response"))
|
|
396
|
+
prior = turn["answers"].get(call_id)
|
|
397
|
+
if not isinstance(prior, dict) or prior.get("input_digest") != input_digest:
|
|
398
|
+
turn["evidence"] = None
|
|
399
|
+
_save(path, context)
|
|
400
|
+
raise TurnError("TASK_TURN_WITHHELD: answer has no matching native question invocation")
|
|
401
|
+
if prior.get("status") != "pending":
|
|
402
|
+
if prior.get("response_digest") != response_digest:
|
|
403
|
+
turn["evidence"] = None
|
|
404
|
+
_save(path, context)
|
|
405
|
+
raise TurnError("TASK_TURN_WITHHELD: conflicting duplicate answer")
|
|
406
|
+
return {}
|
|
407
|
+
response = event.get("tool_response")
|
|
408
|
+
if isinstance(response, str):
|
|
409
|
+
try:
|
|
410
|
+
response = json.loads(response)
|
|
411
|
+
except ValueError:
|
|
412
|
+
response = None
|
|
413
|
+
tool_input = event.get("tool_input")
|
|
414
|
+
questions = tool_input.get("questions") if isinstance(tool_input, dict) else None
|
|
415
|
+
questions = questions if isinstance(questions, list) else []
|
|
416
|
+
answers = response.get("answers") if isinstance(response, dict) else None
|
|
417
|
+
ids = [q.get("id") if isinstance(q, dict) else None for q in questions]
|
|
418
|
+
complete = (0 < len(ids) <= 3 and all(isinstance(i, str) and i for i in ids)
|
|
419
|
+
and len(set(ids)) == len(ids) and isinstance(answers, dict) and set(ids) == set(answers)
|
|
420
|
+
and all(isinstance(q, dict) and isinstance(q.get("question"), str) and q["question"].strip()
|
|
421
|
+
for q in questions)
|
|
422
|
+
and all(isinstance(answers[i], dict) and isinstance(answers[i].get("answers"), list)
|
|
423
|
+
and answers[i]["answers"] and all(isinstance(v, str) and v.strip() for v in answers[i]["answers"]) for i in ids))
|
|
424
|
+
turn["answers"][call_id] = {"input_digest": input_digest, "response_digest": response_digest,
|
|
425
|
+
"status": "complete" if complete else "incomplete"}
|
|
426
|
+
turn["evidence"] = None
|
|
427
|
+
_save(path, context)
|
|
428
|
+
return {"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext":
|
|
429
|
+
"A real answer returned. Record it, resume a resolved phase wait, and continue authorized work."
|
|
430
|
+
if complete else "No complete answer is established. Do not invent a choice; follow the host cancellation/empty-answer contract and continue independent authorized work."}}
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def question_started(root: Path, event: dict) -> None:
|
|
434
|
+
key, session, turn_id = _identity(event)
|
|
435
|
+
call_id = _text(event.get("tool_use_id"), "tool_use_id")
|
|
436
|
+
input_digest = _digest(event.get("tool_input"))
|
|
437
|
+
with layout_lock(root):
|
|
438
|
+
path, context = _session(root, key)
|
|
439
|
+
turn = _turn(context, session, turn_id)
|
|
440
|
+
prior = turn["answers"].get(call_id)
|
|
441
|
+
if prior is not None:
|
|
442
|
+
if not isinstance(prior, dict) or prior.get("input_digest") != input_digest:
|
|
443
|
+
turn["evidence"] = None
|
|
444
|
+
_save(path, context)
|
|
445
|
+
raise TurnError("TASK_TURN_WITHHELD: question invocation identity changed")
|
|
446
|
+
return
|
|
447
|
+
turn["answers"][call_id] = {"input_digest": input_digest, "response_digest": None, "status": "pending"}
|
|
448
|
+
turn["evidence"] = None
|
|
449
|
+
_save(path, context)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def stop(root: Path, event: dict) -> dict:
|
|
453
|
+
key, session, turn_id = _identity(event)
|
|
454
|
+
with layout_lock(root):
|
|
455
|
+
path, context = _session(root, key)
|
|
456
|
+
turn = _turn(context, session, turn_id)
|
|
457
|
+
if turn["interrupted"]:
|
|
458
|
+
return {"continue": False, "systemMessage": "Trellis: user interruption preserved; no automatic continuation."}
|
|
459
|
+
evidence = turn.get("evidence")
|
|
460
|
+
snapshot = _snapshot(root, context, turn)
|
|
461
|
+
valid = _valid_exit(evidence, snapshot, turn)
|
|
462
|
+
if valid and snapshot is not None and isinstance(evidence, dict) and "approval_candidate" in evidence:
|
|
463
|
+
expected = evidence["approval_candidate"]
|
|
464
|
+
try:
|
|
465
|
+
task_dir = root / snapshot["path"]
|
|
466
|
+
state = _state(_read(task_dir / "task.json")["meta"])
|
|
467
|
+
candidate = design_preflight(task_dir, state, expected["outcome"], expected["result_ref"], expected["artifact_revision"])
|
|
468
|
+
valid = expected["digest"] == _digest(candidate)
|
|
469
|
+
except (TaskWorkflowError, KeyError, TypeError):
|
|
470
|
+
valid = False
|
|
471
|
+
if valid and isinstance(evidence, dict) and evidence.get("kind") in {"waiting_authorization", "waiting_input", "external_block"}:
|
|
472
|
+
message = event.get("last_assistant_message")
|
|
473
|
+
length = evidence.get("final_text_length")
|
|
474
|
+
valid = (isinstance(message, str) and len(message) <= 65536 and type(length) is int
|
|
475
|
+
and 0 < length <= 512 and any(_digest(message[i:i + length]) == evidence["final_text_digest"]
|
|
476
|
+
for i in range(len(message) - length + 1)))
|
|
477
|
+
if valid:
|
|
478
|
+
return {}
|
|
479
|
+
if turn["corrections"] >= MAX_CORRECTIONS:
|
|
480
|
+
return {"continue": False, "systemMessage": "TASK_TURN_PROTECTION_FAILED: correction limit reached; task remains unfinished. Inspect turn evidence before continuing manually."}
|
|
481
|
+
reason = ("Trellis turn guard: continue independent authorized work or ask the actual blocking question; "
|
|
482
|
+
"record native task.py turn evidence before ending. This feedback is not a user answer or approval. "
|
|
483
|
+
"Correction " + str(turn["corrections"] + 1) + " of " + str(MAX_CORRECTIONS) + ".")
|
|
484
|
+
turn["corrections"] += 1
|
|
485
|
+
_save(path, context)
|
|
486
|
+
return {"decision": "block", "reason": reason}
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def interrupt(root: Path, event: dict) -> None:
|
|
490
|
+
key, session, turn_id = _identity(event)
|
|
491
|
+
with layout_lock(root):
|
|
492
|
+
path, context = _session(root, key)
|
|
493
|
+
turn = _turn(context, session, turn_id)
|
|
494
|
+
turn.update(interrupted=True, evidence=None)
|
|
495
|
+
_save(path, context)
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def add_turn_commands(subparsers: argparse._SubParsersAction) -> None:
|
|
499
|
+
parser = subparsers.add_parser("turn", help="Observe or record native current-turn exit evidence")
|
|
500
|
+
actions = parser.add_subparsers(dest="turn_action", required=True)
|
|
501
|
+
show = actions.add_parser("show", help="Read current native turn; missing identity never grants exit evidence")
|
|
502
|
+
show.add_argument("--invocation-ticket")
|
|
503
|
+
record = actions.add_parser("record", help="Record exit evidence using the exact hook-issued invocation")
|
|
504
|
+
record.add_argument("--invocation-ticket")
|
|
505
|
+
record.add_argument("--kind", choices=KINDS, required=True)
|
|
506
|
+
record.add_argument("--scope", choices=SCOPES)
|
|
507
|
+
record.add_argument("--evidence-ref", action="append", required=True)
|
|
508
|
+
record.add_argument("--no-independent-work", action="store_true")
|
|
509
|
+
record.add_argument("--question")
|
|
510
|
+
record.add_argument("--blocker")
|
|
511
|
+
record.add_argument("--approval-result-ref")
|
|
512
|
+
record.add_argument("--approval-artifact-revision")
|
|
513
|
+
record.add_argument("--approval-outcome", choices=("implementation_contract", "analysis_conclusion", "no_go"))
|
|
514
|
+
record.add_argument("--user-instruction")
|