okstra 0.168.0 → 0.169.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 (101) hide show
  1. package/README.md +5 -4
  2. package/docs/architecture/storage-model.md +57 -1
  3. package/docs/architecture.md +70 -2
  4. package/docs/cli.md +8 -4
  5. package/docs/for-ai/skills/okstra-code-review.md +3 -2
  6. package/docs/for-ai/skills/okstra-schedule-gen.md +3 -1
  7. package/docs/project-structure-overview.md +14 -11
  8. package/package.json +1 -1
  9. package/runtime/BUILD.json +2 -2
  10. package/runtime/agents/workers/claude-worker.md +6 -5
  11. package/runtime/agents/workers/report-writer-worker.md +9 -4
  12. package/runtime/agents/workers/translator-worker.md +6 -4
  13. package/runtime/bin/okstra-error-log.py +38 -282
  14. package/runtime/prompts/duties/acceptance-critic.md +24 -0
  15. package/runtime/prompts/duties/acceptance-verifier.md +24 -0
  16. package/runtime/prompts/duties/analysis-worker.md +24 -0
  17. package/runtime/prompts/duties/code-reviewer.md +24 -0
  18. package/runtime/prompts/duties/common.md +35 -0
  19. package/runtime/prompts/duties/implementation-executor.md +24 -0
  20. package/runtime/prompts/duties/implementation-verifier.md +24 -0
  21. package/runtime/prompts/duties/lead.md +24 -0
  22. package/runtime/prompts/duties/report-writer.md +24 -0
  23. package/runtime/prompts/duties/reverification-worker.md +24 -0
  24. package/runtime/prompts/duties/schedule-verifier.md +24 -0
  25. package/runtime/prompts/duties/scope-critic.md +24 -0
  26. package/runtime/prompts/duties/translator.md +24 -0
  27. package/runtime/prompts/lead/convergence.md +104 -14
  28. package/runtime/prompts/lead/okstra-lead-contract.md +11 -21
  29. package/runtime/prompts/lead/plan-body-verification.md +16 -1
  30. package/runtime/prompts/lead/report-writer.md +20 -5
  31. package/runtime/prompts/lead/team-contract.md +13 -13
  32. package/runtime/prompts/profiles/_coding-conventions-preflight.md +1 -1
  33. package/runtime/prompts/profiles/_implementation-diff-review.md +1 -1
  34. package/runtime/prompts/profiles/_implementation-executor.md +1 -1
  35. package/runtime/prompts/profiles/implementation.md +4 -2
  36. package/runtime/python/okstra_ctl/adapters/hosts/antigravity/adapter.py +6 -0
  37. package/runtime/python/okstra_ctl/adapters/hosts/antigravity/relay.md +3 -2
  38. package/runtime/python/okstra_ctl/adapters/hosts/capability_adapter.py +8 -0
  39. package/runtime/python/okstra_ctl/adapters/hosts/claude-code/adapter.py +33 -0
  40. package/runtime/python/okstra_ctl/adapters/hosts/claude-code/relay.md +13 -12
  41. package/runtime/python/okstra_ctl/adapters/hosts/codex/adapter.py +6 -0
  42. package/runtime/python/okstra_ctl/adapters/hosts/codex/relay.md +3 -2
  43. package/runtime/python/okstra_ctl/adapters/hosts/external/adapter.py +2 -0
  44. package/runtime/python/okstra_ctl/adapters/hosts/external/relay.md +3 -3
  45. package/runtime/python/okstra_ctl/adapters/hosts/grok/adapter.py +6 -0
  46. package/runtime/python/okstra_ctl/adapters/hosts/grok/relay.md +2 -1
  47. package/runtime/python/okstra_ctl/adapters/hosts/kimi/adapter.py +6 -0
  48. package/runtime/python/okstra_ctl/adapters/hosts/kimi/relay.md +2 -1
  49. package/runtime/python/okstra_ctl/agent_invocation.py +1582 -0
  50. package/runtime/python/okstra_ctl/agent_prompt_cli.py +796 -0
  51. package/runtime/python/okstra_ctl/codex_dispatch.py +2 -107
  52. package/runtime/python/okstra_ctl/context_cost.py +46 -5
  53. package/runtime/python/okstra_ctl/dispatch_core.py +538 -43
  54. package/runtime/python/okstra_ctl/dispatch_state.py +461 -36
  55. package/runtime/python/okstra_ctl/doctor.py +90 -16
  56. package/runtime/python/okstra_ctl/entrypoints/hosts.py +87 -9
  57. package/runtime/python/okstra_ctl/error_log_write.py +308 -0
  58. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +214 -23
  59. package/runtime/python/okstra_ctl/path_hints.py +26 -0
  60. package/runtime/python/okstra_ctl/paths.py +20 -0
  61. package/runtime/python/okstra_ctl/ports/__init__.py +8 -0
  62. package/runtime/python/okstra_ctl/ports/host.py +3 -0
  63. package/runtime/python/okstra_ctl/ports/host_model.py +60 -0
  64. package/runtime/python/okstra_ctl/registry/host_registry.py +5 -0
  65. package/runtime/python/okstra_ctl/render.py +217 -12
  66. package/runtime/python/okstra_ctl/report_finalize.py +44 -0
  67. package/runtime/python/okstra_ctl/run.py +368 -51
  68. package/runtime/python/okstra_ctl/session.py +16 -12
  69. package/runtime/python/okstra_ctl/team.py +11 -11
  70. package/runtime/python/okstra_ctl/worker_audit_check.py +26 -4
  71. package/runtime/python/okstra_ctl/worker_audit_ledger.py +59 -9
  72. package/runtime/python/okstra_ctl/worker_dispatch.py +104 -0
  73. package/runtime/python/okstra_ctl/worker_prompt_body.py +5 -38
  74. package/runtime/python/okstra_ctl/worker_prompt_contract.py +56 -3
  75. package/runtime/python/okstra_ctl/worker_prompt_headers.py +2 -2
  76. package/runtime/python/okstra_ctl/worker_prompt_policy.py +38 -1
  77. package/runtime/skills/okstra-code-review/SKILL.md +22 -3
  78. package/runtime/skills/okstra-run/SKILL.md +16 -1
  79. package/runtime/skills/okstra-schedule-gen/SKILL.md +15 -1
  80. package/runtime/templates/implementation-worker-preamble.md +0 -10
  81. package/runtime/templates/report-writer-prompt-preamble.md +0 -9
  82. package/runtime/templates/reports/settings.template.json +0 -11
  83. package/runtime/templates/worker-prompt-preamble.md +0 -10
  84. package/runtime/validators/lib/fixtures.sh +93 -0
  85. package/runtime/validators/lib/validate-assets.sh +0 -8
  86. package/runtime/validators/validate-run.py +182 -0
  87. package/src/cli-registry.mjs +14 -0
  88. package/src/commands/execute/agent-prompt.mjs +25 -0
  89. package/src/commands/execute/codex-dispatch.mjs +6 -63
  90. package/src/commands/execute/worker-dispatch.mjs +76 -0
  91. package/src/commands/lifecycle/doctor.mjs +18 -3
  92. package/src/commands/lifecycle/install.mjs +33 -15
  93. package/src/commands/lifecycle/uninstall.mjs +4 -3
  94. package/src/lib/install-assets.mjs +9 -0
  95. package/runtime/agents/workers/antigravity-worker.md +0 -259
  96. package/runtime/agents/workers/codex-worker.md +0 -259
  97. package/runtime/agents/workers/grok-worker.md +0 -259
  98. package/runtime/agents/workers/kimi-worker.md +0 -259
  99. package/runtime/prompts/coding-preflight/scripts/preedit-check.sh +0 -79
  100. package/runtime/templates/operating-standard.md +0 -22
  101. package/src/lib/worker-agent-render.mjs +0 -50
@@ -0,0 +1,796 @@
1
+ """Materialize and verify one auditable LLM invocation specification."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from datetime import datetime, timezone
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ from pathlib import PurePosixPath
10
+ import shutil
11
+ import sys
12
+ import tempfile
13
+ from typing import Any, Mapping, get_args
14
+
15
+ from .agent_invocation import (
16
+ AgentInstruction,
17
+ AgentInstructionSource,
18
+ AgentAudience,
19
+ AgentInvocationError,
20
+ AgentInvocationRequest,
21
+ AgentModelAssignment,
22
+ PreparedAgentInvocation,
23
+ agent_model_assignment_from_payload,
24
+ digest_duty_catalog,
25
+ materialize_standalone_result,
26
+ prepare_agent_invocation,
27
+ publish_standalone_completion,
28
+ verify_standalone_completion,
29
+ verify_agent_invocation,
30
+ )
31
+ from .application.resolve_assignment import resolve_assignment_runner
32
+ from .model_discovery import normalize_execution_for_dispatch
33
+ from .models import provider_default_model, resolve_model_metadata
34
+ from .path_hints import hydrate_active_run_context
35
+ from .ports.host_model import HostModelBindingRequest
36
+ from .registry.host_registry import default_host_registry
37
+ from .registry.provider_registry import default_provider_registry
38
+ from .worker_prompt_headers import WorkerPromptHeaderError, worker_prompt_headers
39
+ from .worker_prompt_policy import resolve_prompt_plan_for_manifest
40
+ from .dispatch_state import (
41
+ DispatchError,
42
+ link_agent_dispatch_result,
43
+ record_verified_agent_dispatch,
44
+ )
45
+
46
+
47
+ _AUDIENCES = frozenset(get_args(AgentAudience))
48
+
49
+
50
+ class AgentPromptCliError(RuntimeError):
51
+ """Raised when CLI input cannot become a valid invocation request."""
52
+
53
+
54
+ def _parser() -> argparse.ArgumentParser:
55
+ parser = argparse.ArgumentParser(prog="okstra agent-prompt")
56
+ commands = parser.add_subparsers(dest="command", required=True)
57
+ materialize = commands.add_parser("materialize")
58
+ _common_paths(materialize)
59
+ materialize.add_argument("--invocation-id", required=True)
60
+ materialize.add_argument("--audience", required=True)
61
+ materialize.add_argument("--instruction", required=True)
62
+ materialize.add_argument("--prompt", required=True)
63
+ materialize.add_argument("--run-manifest")
64
+ materialize.add_argument("--worker-id")
65
+ materialize.add_argument("--dispatch-kind")
66
+ materialize.add_argument("--assignment-ref")
67
+ materialize.add_argument("--result")
68
+ materialize.add_argument("--audit-source")
69
+ materialize.add_argument("--host-runtime")
70
+ materialize.add_argument("--provider")
71
+ materialize.add_argument("--model-role")
72
+ materialize.add_argument("--model", default="")
73
+ materialize.add_argument("--purpose")
74
+ materialize.add_argument(
75
+ "--replace-undispatched",
76
+ action="store_true",
77
+ help="rewrite a prompt this invocation id already wrote, allowed only "
78
+ "while no dispatch has referenced it — the exit for a prompt that "
79
+ "failed a pre-dispatch gate and never ran",
80
+ )
81
+ materialize.add_argument("--json", action="store_true")
82
+
83
+ verify = commands.add_parser("verify")
84
+ _common_paths(verify)
85
+ verify.add_argument("--run-manifest")
86
+ verify.add_argument("--metadata", required=True)
87
+ verify.add_argument("--json", action="store_true")
88
+
89
+ materialize_result = commands.add_parser("materialize-result")
90
+ _standalone_completion_args(materialize_result)
91
+ materialize_result.add_argument("--returned-body-file", required=True)
92
+
93
+ complete = commands.add_parser("complete")
94
+ _standalone_completion_args(complete)
95
+
96
+ verify_completion = commands.add_parser("verify-completion")
97
+ _common_paths(verify_completion)
98
+ verify_completion.add_argument("--purpose", required=True)
99
+ verify_completion.add_argument("--completion", required=True)
100
+ verify_completion.add_argument("--json", action="store_true")
101
+
102
+ record_dispatch = commands.add_parser("record-dispatch")
103
+ _common_paths(record_dispatch)
104
+ record_dispatch.add_argument("--run-manifest", required=True)
105
+ record_dispatch.add_argument("--metadata", required=True)
106
+ record_dispatch.add_argument(
107
+ "--enforcement-mode",
108
+ required=True,
109
+ choices=("core-pre-dispatch", "host-native-spec-link-gate"),
110
+ )
111
+ record_dispatch.add_argument("--json", action="store_true")
112
+
113
+ link_result = commands.add_parser("link-result")
114
+ _common_paths(link_result)
115
+ link_result.add_argument("--run-manifest", required=True)
116
+ link_result.add_argument("--dispatch-id", required=True)
117
+ link_result.add_argument("--result", required=True)
118
+ link_result.add_argument("--json", action="store_true")
119
+ return parser
120
+
121
+
122
+ def _common_paths(parser: argparse.ArgumentParser) -> None:
123
+ parser.add_argument("--project-root", required=True)
124
+
125
+
126
+ def _standalone_completion_args(parser: argparse.ArgumentParser) -> None:
127
+ _common_paths(parser)
128
+ parser.add_argument("--purpose", required=True)
129
+ parser.add_argument("--metadata", required=True)
130
+ parser.add_argument("--json", action="store_true")
131
+
132
+
133
+ def main(argv: list[str] | None = None) -> int:
134
+ try:
135
+ args = _parser().parse_args(argv)
136
+ if args.command == "materialize":
137
+ prepared = _materialize(args)
138
+ _emit(_prepared_payload(prepared, args.audience), args.json)
139
+ return 0
140
+ if args.command == "verify":
141
+ _verify(args)
142
+ _emit(
143
+ {"ok": True, "metadataPath": str(Path(args.metadata).resolve())},
144
+ args.json,
145
+ )
146
+ return 0
147
+ if args.command == "materialize-result":
148
+ _materialize_result(args)
149
+ return 0
150
+ if args.command == "complete":
151
+ _complete(args)
152
+ return 0
153
+ if args.command == "verify-completion":
154
+ _verify_completion(args)
155
+ return 0
156
+ if args.command == "record-dispatch":
157
+ _record_dispatch(args)
158
+ return 0
159
+ _link_result(args)
160
+ return 0
161
+ except (
162
+ AgentPromptCliError,
163
+ AgentInvocationError,
164
+ DispatchError,
165
+ WorkerPromptHeaderError,
166
+ OSError,
167
+ ValueError,
168
+ ) as exc:
169
+ print(f"error: {exc}", file=sys.stderr)
170
+ return 2
171
+
172
+
173
+ def _materialize(args: argparse.Namespace) -> PreparedAgentInvocation:
174
+ project_root = _project_root(args.project_root)
175
+ if args.run_manifest:
176
+ return _materialize_run(args, project_root)
177
+ return _materialize_standalone(args, project_root)
178
+
179
+
180
+ def _record_dispatch(args: argparse.Namespace) -> None:
181
+ project_root = _project_root(args.project_root)
182
+ record = record_verified_agent_dispatch(
183
+ project_root=project_root,
184
+ run_manifest_path=_project_input(
185
+ project_root, args.run_manifest, "run manifest"
186
+ ),
187
+ metadata_path=_project_input(
188
+ project_root, args.metadata, "agent invocation metadata"
189
+ ),
190
+ enforcement_mode=args.enforcement_mode,
191
+ )
192
+ _emit(record, args.json)
193
+
194
+
195
+ def _link_result(args: argparse.Namespace) -> None:
196
+ project_root = _project_root(args.project_root)
197
+ link = link_agent_dispatch_result(
198
+ project_root=project_root,
199
+ run_manifest_path=_project_input(
200
+ project_root, args.run_manifest, "run manifest"
201
+ ),
202
+ dispatch_id=args.dispatch_id,
203
+ result_path=_project_input(project_root, args.result, "agent result"),
204
+ )
205
+ _emit(link, args.json)
206
+
207
+
208
+ def _materialize_run(
209
+ args: argparse.Namespace,
210
+ project_root: Path,
211
+ ) -> PreparedAgentInvocation:
212
+ required = {
213
+ "worker-id": args.worker_id,
214
+ "dispatch-kind": args.dispatch_kind,
215
+ "assignment-ref": args.assignment_ref,
216
+ "result": args.result,
217
+ }
218
+ missing = [name for name, value in required.items() if not value]
219
+ if missing:
220
+ raise AgentPromptCliError(
221
+ f"run materialization requires: {', '.join('--' + name for name in missing)}"
222
+ )
223
+ forbidden = {
224
+ "host-runtime": args.host_runtime,
225
+ "provider": args.provider,
226
+ "model-role": args.model_role,
227
+ "model": args.model,
228
+ "purpose": args.purpose,
229
+ }
230
+ present = [name for name, value in forbidden.items() if value]
231
+ if present:
232
+ raise AgentPromptCliError(
233
+ f"run materialization forbids: {', '.join('--' + name for name in present)}"
234
+ )
235
+ manifest_path = _project_input(project_root, args.run_manifest, "run manifest")
236
+ manifest = _read_json_object(manifest_path, "run manifest")
237
+ contract = _mapping(manifest.get("agentContract"), "run agent contract")
238
+ authorized = _mapping(contract.get("authorizedPaths"), "authorized paths")
239
+
240
+ instruction_path = _authorized_path(
241
+ project_root,
242
+ args.instruction,
243
+ authorized.get("instructionRoots"),
244
+ "instruction",
245
+ must_exist=True,
246
+ )
247
+ prompt_path = _authorized_path(
248
+ project_root,
249
+ args.prompt,
250
+ authorized.get("promptRoots"),
251
+ "prompt",
252
+ must_exist=False,
253
+ )
254
+ result_path = _authorized_path(
255
+ project_root,
256
+ args.result,
257
+ authorized.get("resultRoots"),
258
+ "result",
259
+ must_exist=False,
260
+ )
261
+ audit_source_path = (
262
+ _authorized_path(
263
+ project_root,
264
+ args.audit_source,
265
+ authorized.get("resultRoots"),
266
+ "audit source",
267
+ must_exist=False,
268
+ )
269
+ if args.audit_source
270
+ else result_path
271
+ )
272
+ _validate_run_identity(
273
+ manifest,
274
+ worker_id=args.worker_id,
275
+ dispatch_kind=args.dispatch_kind,
276
+ assignment_ref=args.assignment_ref,
277
+ audience=args.audience,
278
+ )
279
+ assignments = _mapping(
280
+ manifest.get("invocationAssignments"),
281
+ "run invocation assignments",
282
+ )
283
+ if args.assignment_ref not in assignments:
284
+ raise AgentPromptCliError(
285
+ f"assignment reference is missing from run manifest: {args.assignment_ref}"
286
+ )
287
+ assignment = agent_model_assignment_from_payload(assignments[args.assignment_ref])
288
+ duty_root = _project_manifest_path(
289
+ project_root,
290
+ contract.get("dutyRootPath"),
291
+ "duty root",
292
+ must_exist=True,
293
+ )
294
+ if contract.get("catalogDigest") != digest_duty_catalog(duty_root):
295
+ raise AgentPromptCliError("run duty snapshot catalog digest does not match")
296
+ active_context_path = _project_manifest_path(
297
+ project_root,
298
+ manifest.get("activeRunContextPath"),
299
+ "active run context",
300
+ must_exist=True,
301
+ )
302
+ active_context = hydrate_active_run_context(
303
+ _read_json_object(active_context_path, "active run context")
304
+ )
305
+ prompt_rel = _relative(project_root, prompt_path)
306
+ result_rel = _relative(project_root, result_path)
307
+ audit_rel = _relative(project_root, audit_source_path)
308
+ anchor_lines = tuple(worker_prompt_headers(
309
+ project_root=project_root,
310
+ prompt_rel=prompt_rel,
311
+ result_rel=result_rel,
312
+ audit_source_rel=audit_rel,
313
+ worker_id=args.worker_id,
314
+ dispatch_kind=args.dispatch_kind,
315
+ manifest=manifest,
316
+ active_context=active_context,
317
+ ))
318
+ return prepare_agent_invocation(AgentInvocationRequest(
319
+ invocation_id=args.invocation_id,
320
+ worker_id=args.worker_id,
321
+ audience=args.audience,
322
+ assignment_ref=args.assignment_ref,
323
+ purpose=None,
324
+ assignment=assignment,
325
+ instruction=AgentInstruction(
326
+ anchor_lines=anchor_lines,
327
+ body=instruction_path.read_text(encoding="utf-8"),
328
+ source_paths=(AgentInstructionSource(
329
+ kind="project",
330
+ path=_relative(project_root, instruction_path),
331
+ ),),
332
+ ),
333
+ project_root=project_root,
334
+ run_manifest_path=manifest_path,
335
+ duty_root=duty_root,
336
+ prompt_path=prompt_path,
337
+ metadata_path=prompt_path.with_name(prompt_path.name + ".meta.json"),
338
+ dispatch_kind=args.dispatch_kind,
339
+ replace_undispatched=args.replace_undispatched,
340
+ ))
341
+
342
+
343
+ def _validate_run_identity(
344
+ manifest: Mapping[str, Any],
345
+ *,
346
+ worker_id: str,
347
+ dispatch_kind: str,
348
+ assignment_ref: str,
349
+ audience: str,
350
+ ) -> None:
351
+ expected: str
352
+ if assignment_ref == "lead":
353
+ expected = "lead"
354
+ if worker_id != "lead":
355
+ raise AgentPromptCliError("lead assignment requires worker ID 'lead'")
356
+ elif assignment_ref == "translator":
357
+ expected = "translator"
358
+ if worker_id != "translator":
359
+ raise AgentPromptCliError("translator assignment requires worker ID 'translator'")
360
+ elif assignment_ref.startswith("critic/"):
361
+ scope = assignment_ref.split("/", 1)[1]
362
+ expected = {"scope": "scope-critic", "acceptance": "acceptance-critic"}.get(
363
+ scope,
364
+ "",
365
+ )
366
+ if not expected or dispatch_kind != "critic":
367
+ raise AgentPromptCliError("critic assignment identity is invalid")
368
+ convergence = manifest.get("convergence")
369
+ critic = convergence.get("critic") if isinstance(convergence, Mapping) else None
370
+ provider = critic.get("provider") if isinstance(critic, Mapping) else None
371
+ if provider and provider != worker_id:
372
+ raise AgentPromptCliError("critic worker does not match manifest provider")
373
+ else:
374
+ try:
375
+ expected = resolve_prompt_plan_for_manifest(
376
+ manifest=manifest,
377
+ worker_id=worker_id,
378
+ dispatch_kind=dispatch_kind,
379
+ ).duty_audience
380
+ except ValueError as exc:
381
+ raise AgentPromptCliError(str(exc)) from exc
382
+ if audience != expected:
383
+ raise AgentPromptCliError(
384
+ f"audience {audience!r} does not match required audience {expected!r}"
385
+ )
386
+
387
+
388
+ def _materialize_standalone(
389
+ args: argparse.Namespace,
390
+ project_root: Path,
391
+ ) -> PreparedAgentInvocation:
392
+ required = {
393
+ "host-runtime": args.host_runtime,
394
+ "provider": args.provider,
395
+ "model-role": args.model_role,
396
+ "purpose": args.purpose,
397
+ }
398
+ missing = [name for name, value in required.items() if not value]
399
+ if missing:
400
+ raise AgentPromptCliError(
401
+ "standalone materialization requires: "
402
+ + ", ".join("--" + name for name in missing)
403
+ )
404
+ forbidden = {
405
+ "worker-id": args.worker_id,
406
+ "dispatch-kind": args.dispatch_kind,
407
+ "assignment-ref": args.assignment_ref,
408
+ "result": args.result,
409
+ "audit-source": args.audit_source,
410
+ }
411
+ present = [name for name, value in forbidden.items() if value]
412
+ if present:
413
+ raise AgentPromptCliError(
414
+ "standalone materialization forbids: "
415
+ + ", ".join("--" + name for name in present)
416
+ )
417
+ if not _is_slug(args.purpose) or not _is_slug(args.invocation_id):
418
+ raise AgentPromptCliError("standalone purpose and invocation ID must be slugs")
419
+ if args.audience not in _AUDIENCES:
420
+ raise AgentPromptCliError(f"unknown duty audience: {args.audience}")
421
+ root = project_root / ".okstra" / "agent-invocations" / args.purpose
422
+ if not root.is_dir():
423
+ raise AgentPromptCliError(f"standalone invocation root not found: {root}")
424
+ resolved_root = root.resolve(strict=True)
425
+ if not _is_relative_to(resolved_root, project_root):
426
+ raise AgentPromptCliError("standalone invocation root escapes project root")
427
+ root = resolved_root
428
+ expected_instruction = root / f"{args.invocation_id}.instructions.md"
429
+ expected_prompt = root / f"{args.invocation_id}.prompt.md"
430
+ instruction_path = _exact_path(args.instruction, expected_instruction, True, "instruction")
431
+ prompt_path = _exact_path(args.prompt, expected_prompt, False, "prompt")
432
+ assignment = _standalone_assignment(
433
+ host_runtime=args.host_runtime,
434
+ provider=args.provider,
435
+ model_role=args.model_role,
436
+ model=args.model,
437
+ )
438
+ duty_root = root / f"{args.invocation_id}.duty-contracts"
439
+ _snapshot_standalone_duties(duty_root)
440
+ return prepare_agent_invocation(AgentInvocationRequest(
441
+ invocation_id=args.invocation_id,
442
+ worker_id=None,
443
+ audience=args.audience,
444
+ assignment_ref=None,
445
+ purpose=args.purpose,
446
+ assignment=assignment,
447
+ instruction=AgentInstruction(
448
+ anchor_lines=(),
449
+ body=instruction_path.read_text(encoding="utf-8"),
450
+ source_paths=(AgentInstructionSource(
451
+ kind="project",
452
+ path=_relative(project_root, instruction_path),
453
+ ),),
454
+ ),
455
+ project_root=project_root,
456
+ run_manifest_path=None,
457
+ duty_root=duty_root,
458
+ prompt_path=prompt_path,
459
+ metadata_path=prompt_path.with_name(prompt_path.name + ".meta.json"),
460
+ dispatch_kind="standalone",
461
+ ))
462
+
463
+
464
+ def _standalone_assignment(
465
+ *, host_runtime: str, provider: str, model_role: str, model: str,
466
+ ) -> AgentModelAssignment:
467
+ provider_registry = default_provider_registry()
468
+ provider_spec = provider_registry.resolve(provider)
469
+ default_model = provider_default_model(provider, model_role)
470
+ if not default_model:
471
+ raise AgentPromptCliError(
472
+ f"provider {provider!r} has no default model for role {model_role!r}"
473
+ )
474
+ metadata = resolve_model_metadata(
475
+ provider=provider,
476
+ raw_value=model,
477
+ default_display=default_model,
478
+ default_execution=default_model,
479
+ )
480
+ host_adapter = default_host_registry(provider_registry).resolve(host_runtime)
481
+ runner = resolve_assignment_runner(
482
+ host=host_adapter.descriptor,
483
+ provider=provider_spec,
484
+ role=model_role,
485
+ ).runner
486
+ execution = (
487
+ normalize_execution_for_dispatch(
488
+ provider=provider,
489
+ execution=metadata.execution,
490
+ role=model_role,
491
+ )
492
+ if runner == "cli-wrapper"
493
+ else metadata.execution
494
+ )
495
+ host_model = host_adapter.host_model().resolve(HostModelBindingRequest(
496
+ host_runtime=host_runtime,
497
+ provider=provider,
498
+ model=metadata.display,
499
+ model_execution_value=execution,
500
+ runner=runner,
501
+ ))
502
+ return AgentModelAssignment(
503
+ provider=provider,
504
+ model=metadata.display,
505
+ model_execution_value=execution,
506
+ runner=runner,
507
+ host_runtime=host_runtime,
508
+ host_model_value=host_model,
509
+ )
510
+
511
+
512
+ def _snapshot_standalone_duties(destination: Path) -> None:
513
+ source = Path(__file__).resolve().parents[2] / "prompts" / "duties"
514
+ if not source.is_dir():
515
+ raise AgentPromptCliError(f"duty contract source not found: {source}")
516
+ if destination.exists():
517
+ if not destination.is_dir() or digest_duty_catalog(destination) != digest_duty_catalog(source):
518
+ raise AgentPromptCliError("standalone duty snapshot conflicts with existing files")
519
+ return
520
+ temporary = Path(tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent))
521
+ try:
522
+ shutil.copytree(source, temporary, dirs_exist_ok=True)
523
+ try:
524
+ os.rename(temporary, destination)
525
+ except FileExistsError:
526
+ if digest_duty_catalog(destination) != digest_duty_catalog(source):
527
+ raise AgentPromptCliError("standalone duty snapshot publication conflict")
528
+ finally:
529
+ if temporary.exists():
530
+ shutil.rmtree(temporary)
531
+
532
+
533
+ def _verify(args: argparse.Namespace) -> None:
534
+ project_root = _project_root(args.project_root)
535
+ metadata_path = _project_input(project_root, args.metadata, "metadata")
536
+ metadata = _read_json_object(metadata_path, "metadata")
537
+ contract_source = _mapping(metadata.get("contractSource"), "contract source")
538
+ mode = contract_source.get("mode")
539
+ expected_manifest: Path | None = None
540
+ expected_assignment: AgentModelAssignment | None = None
541
+ if mode == "run":
542
+ if not args.run_manifest:
543
+ raise AgentPromptCliError("run invocation verification requires --run-manifest")
544
+ expected_manifest = _project_input(project_root, args.run_manifest, "run manifest")
545
+ manifest = _read_json_object(expected_manifest, "run manifest")
546
+ assignments = _mapping(manifest.get("invocationAssignments"), "run assignments")
547
+ reference = metadata.get("assignmentRef")
548
+ if not isinstance(reference, str) or reference not in assignments:
549
+ raise AgentPromptCliError("assignment reference is missing from run manifest")
550
+ expected_assignment = agent_model_assignment_from_payload(assignments[reference])
551
+ elif mode == "standalone":
552
+ if args.run_manifest:
553
+ raise AgentPromptCliError("standalone invocation verification forbids --run-manifest")
554
+ else:
555
+ raise AgentPromptCliError("contract source mode is invalid")
556
+ errors = verify_agent_invocation(
557
+ metadata_path,
558
+ project_root=project_root,
559
+ expected_run_manifest_path=expected_manifest,
560
+ expected_assignment=expected_assignment,
561
+ )
562
+ if errors:
563
+ raise AgentPromptCliError("; ".join(errors))
564
+
565
+
566
+ def _materialize_result(args: argparse.Namespace) -> None:
567
+ project_root = _project_root(args.project_root)
568
+ metadata_path = _project_input(project_root, args.metadata, "metadata")
569
+ root = project_root / ".okstra" / "agent-invocations" / args.purpose
570
+ temporary_root = root / ".tmp"
571
+ returned_body_path = _project_input(
572
+ project_root,
573
+ args.returned_body_file,
574
+ "returned body",
575
+ )
576
+ if not temporary_root.is_dir() or not _is_relative_to(
577
+ returned_body_path,
578
+ temporary_root.resolve(strict=True),
579
+ ):
580
+ raise AgentPromptCliError(
581
+ "returned body file must be inside the standalone purpose .tmp directory"
582
+ )
583
+ result = materialize_standalone_result(
584
+ project_root=project_root,
585
+ purpose=args.purpose,
586
+ metadata_path=metadata_path,
587
+ returned_body=returned_body_path.read_bytes(),
588
+ )
589
+ _emit({
590
+ "ok": True,
591
+ "purpose": result.purpose,
592
+ "invocationId": result.invocation_id,
593
+ "metadataPath": str(result.prompt_metadata_path),
594
+ "resultPath": str(result.result_path),
595
+ "resultEnvelopeDigest": result.result_envelope_digest,
596
+ }, args.json)
597
+
598
+
599
+ def _complete(args: argparse.Namespace) -> None:
600
+ project_root = _project_root(args.project_root)
601
+ metadata_path = _project_input(project_root, args.metadata, "metadata")
602
+ completion = publish_standalone_completion(
603
+ project_root=project_root,
604
+ purpose=args.purpose,
605
+ metadata_path=metadata_path,
606
+ completed_at=datetime.now(timezone.utc),
607
+ )
608
+ _emit({
609
+ "ok": True,
610
+ "purpose": args.purpose,
611
+ "metadataPath": str(metadata_path),
612
+ "completionPath": str(completion),
613
+ }, args.json)
614
+
615
+
616
+ def _verify_completion(args: argparse.Namespace) -> None:
617
+ project_root = _project_root(args.project_root)
618
+ completion_path = _project_input(
619
+ project_root,
620
+ args.completion,
621
+ "completion",
622
+ )
623
+ verified = verify_standalone_completion(
624
+ completion_path,
625
+ project_root=project_root,
626
+ expected_purpose=args.purpose,
627
+ )
628
+ _emit({
629
+ "ok": True,
630
+ "purpose": verified.purpose,
631
+ "invocationId": verified.invocation_id,
632
+ "metadataPath": str(verified.prompt_metadata_path),
633
+ "resultPath": str(verified.result_path),
634
+ "completionPath": str(verified.completion_path),
635
+ "resultEnvelopeDigest": verified.result_envelope_digest,
636
+ "returnedBody": verified.returned_body,
637
+ }, args.json)
638
+
639
+
640
+ def _authorized_path(
641
+ project_root: Path,
642
+ raw_path: str,
643
+ raw_roots: object,
644
+ label: str,
645
+ *,
646
+ must_exist: bool,
647
+ ) -> Path:
648
+ if not isinstance(raw_roots, list) or not raw_roots:
649
+ raise AgentPromptCliError(f"run manifest has no authorized {label} roots")
650
+ path = _candidate(project_root, raw_path, must_exist=must_exist, label=label)
651
+ roots = [
652
+ _project_manifest_path(project_root, value, f"{label} root", must_exist=True)
653
+ for value in raw_roots
654
+ ]
655
+ if not any(_is_relative_to(path, root) for root in roots):
656
+ raise AgentPromptCliError(f"{label} path is outside authorized roots: {path}")
657
+ return path
658
+
659
+
660
+ def _candidate(project_root: Path, raw: str, *, must_exist: bool, label: str) -> Path:
661
+ candidate = Path(raw)
662
+ if not candidate.is_absolute():
663
+ candidate = project_root / candidate
664
+ try:
665
+ if must_exist or candidate.exists() or candidate.is_symlink():
666
+ return candidate.resolve(strict=True)
667
+ return candidate.parent.resolve(strict=True) / candidate.name
668
+ except OSError as exc:
669
+ raise AgentPromptCliError(f"{label} path is invalid: {candidate}") from exc
670
+
671
+
672
+ def _project_input(project_root: Path, raw: str, label: str) -> Path:
673
+ path = _candidate(project_root, raw, must_exist=True, label=label)
674
+ if not _is_relative_to(path, project_root):
675
+ raise AgentPromptCliError(f"{label} path escapes project root: {path}")
676
+ return path
677
+
678
+
679
+ def _project_manifest_path(
680
+ project_root: Path,
681
+ value: object,
682
+ label: str,
683
+ *,
684
+ must_exist: bool,
685
+ ) -> Path:
686
+ if not isinstance(value, str) or not value:
687
+ raise AgentPromptCliError(f"{label} path is invalid")
688
+ pure = PurePosixPath(value)
689
+ if pure.is_absolute() or any(part in {"", ".", ".."} for part in pure.parts):
690
+ raise AgentPromptCliError(f"{label} path is invalid")
691
+ path = _candidate(project_root, value, must_exist=must_exist, label=label)
692
+ if not _is_relative_to(path, project_root):
693
+ raise AgentPromptCliError(f"{label} path escapes project root: {path}")
694
+ return path
695
+
696
+
697
+ def _exact_path(raw: str, expected: Path, must_exist: bool, label: str) -> Path:
698
+ actual = (
699
+ Path(raw).resolve(strict=True)
700
+ if must_exist
701
+ else Path(raw).parent.resolve(strict=True) / Path(raw).name
702
+ )
703
+ expected_actual = (
704
+ expected.resolve(strict=True)
705
+ if must_exist
706
+ else expected.parent.resolve(strict=True) / expected.name
707
+ )
708
+ if actual != expected_actual:
709
+ raise AgentPromptCliError(f"{label} does not use canonical standalone path")
710
+ return actual
711
+
712
+
713
+ def _project_root(value: str) -> Path:
714
+ try:
715
+ return Path(value).resolve(strict=True)
716
+ except OSError as exc:
717
+ raise AgentPromptCliError(f"project root not found: {value}") from exc
718
+
719
+
720
+ def _relative(project_root: Path, path: Path) -> str:
721
+ try:
722
+ return path.relative_to(project_root).as_posix()
723
+ except ValueError as exc:
724
+ raise AgentPromptCliError(f"path escapes project root: {path}") from exc
725
+
726
+
727
+ def _read_json_object(path: Path, label: str) -> dict[str, Any]:
728
+ try:
729
+ value = json.loads(path.read_text(encoding="utf-8"))
730
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
731
+ raise AgentPromptCliError(f"{label} is invalid: {path}") from exc
732
+ if not isinstance(value, dict):
733
+ raise AgentPromptCliError(f"{label} must be a JSON object: {path}")
734
+ return value
735
+
736
+
737
+ def _mapping(value: object, label: str) -> Mapping[str, Any]:
738
+ if not isinstance(value, Mapping):
739
+ raise AgentPromptCliError(f"{label} is missing or invalid")
740
+ return value
741
+
742
+
743
+ def _is_relative_to(path: Path, root: Path) -> bool:
744
+ try:
745
+ path.relative_to(root)
746
+ except ValueError:
747
+ return False
748
+ return True
749
+
750
+
751
+ def _is_slug(value: str) -> bool:
752
+ if not value or value.startswith("-") or value.endswith("-"):
753
+ return False
754
+ return all(part.isalnum() and part.lower() == part for part in value.split("-"))
755
+
756
+
757
+ def _prepared_payload(
758
+ prepared: PreparedAgentInvocation,
759
+ audience: str,
760
+ ) -> dict[str, object]:
761
+ assignment = prepared.assignment
762
+ return {
763
+ "ok": True,
764
+ "invocationId": prepared.invocation_id,
765
+ "workerId": prepared.worker_id,
766
+ "assignmentRef": prepared.assignment_ref,
767
+ "audience": audience,
768
+ "promptPath": str(prepared.prompt_path),
769
+ "metadataPath": str(prepared.metadata_path),
770
+ "modelAssignment": {
771
+ "provider": assignment.provider,
772
+ "model": assignment.model,
773
+ "modelExecutionValue": assignment.model_execution_value,
774
+ "runner": assignment.runner,
775
+ "hostRuntime": assignment.host_runtime,
776
+ "hostModelValue": assignment.host_model_value,
777
+ },
778
+ "digests": {
779
+ "catalogDigest": prepared.catalog_digest,
780
+ "assignmentDigest": prepared.assignment_digest,
781
+ "dutyDigest": prepared.duty_digest,
782
+ "instructionDigest": prepared.instruction_digest,
783
+ "promptDigest": prepared.prompt_digest,
784
+ },
785
+ }
786
+
787
+
788
+ def _emit(payload: Mapping[str, object], as_json: bool) -> None:
789
+ if as_json:
790
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
791
+ else:
792
+ print(payload.get("promptPath") or payload.get("metadataPath") or "ok")
793
+
794
+
795
+ if __name__ == "__main__":
796
+ raise SystemExit(main())