okstra 0.168.0 → 0.169.0

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 (96) 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/prompts/duties/acceptance-critic.md +24 -0
  14. package/runtime/prompts/duties/acceptance-verifier.md +24 -0
  15. package/runtime/prompts/duties/analysis-worker.md +24 -0
  16. package/runtime/prompts/duties/code-reviewer.md +24 -0
  17. package/runtime/prompts/duties/common.md +35 -0
  18. package/runtime/prompts/duties/implementation-executor.md +24 -0
  19. package/runtime/prompts/duties/implementation-verifier.md +24 -0
  20. package/runtime/prompts/duties/lead.md +24 -0
  21. package/runtime/prompts/duties/report-writer.md +24 -0
  22. package/runtime/prompts/duties/reverification-worker.md +24 -0
  23. package/runtime/prompts/duties/schedule-verifier.md +24 -0
  24. package/runtime/prompts/duties/scope-critic.md +24 -0
  25. package/runtime/prompts/duties/translator.md +24 -0
  26. package/runtime/prompts/lead/convergence.md +51 -7
  27. package/runtime/prompts/lead/okstra-lead-contract.md +10 -20
  28. package/runtime/prompts/lead/plan-body-verification.md +16 -1
  29. package/runtime/prompts/lead/report-writer.md +20 -5
  30. package/runtime/prompts/lead/team-contract.md +13 -13
  31. package/runtime/prompts/profiles/_coding-conventions-preflight.md +1 -1
  32. package/runtime/prompts/profiles/_implementation-diff-review.md +1 -1
  33. package/runtime/prompts/profiles/_implementation-executor.md +1 -1
  34. package/runtime/prompts/profiles/implementation.md +4 -2
  35. package/runtime/python/okstra_ctl/adapters/hosts/antigravity/adapter.py +6 -0
  36. package/runtime/python/okstra_ctl/adapters/hosts/antigravity/relay.md +3 -2
  37. package/runtime/python/okstra_ctl/adapters/hosts/capability_adapter.py +8 -0
  38. package/runtime/python/okstra_ctl/adapters/hosts/claude-code/adapter.py +33 -0
  39. package/runtime/python/okstra_ctl/adapters/hosts/claude-code/relay.md +13 -12
  40. package/runtime/python/okstra_ctl/adapters/hosts/codex/adapter.py +6 -0
  41. package/runtime/python/okstra_ctl/adapters/hosts/codex/relay.md +3 -2
  42. package/runtime/python/okstra_ctl/adapters/hosts/external/adapter.py +2 -0
  43. package/runtime/python/okstra_ctl/adapters/hosts/external/relay.md +3 -3
  44. package/runtime/python/okstra_ctl/adapters/hosts/grok/adapter.py +6 -0
  45. package/runtime/python/okstra_ctl/adapters/hosts/grok/relay.md +2 -1
  46. package/runtime/python/okstra_ctl/adapters/hosts/kimi/adapter.py +6 -0
  47. package/runtime/python/okstra_ctl/adapters/hosts/kimi/relay.md +2 -1
  48. package/runtime/python/okstra_ctl/agent_invocation.py +1502 -0
  49. package/runtime/python/okstra_ctl/agent_prompt_cli.py +788 -0
  50. package/runtime/python/okstra_ctl/codex_dispatch.py +2 -107
  51. package/runtime/python/okstra_ctl/context_cost.py +46 -5
  52. package/runtime/python/okstra_ctl/dispatch_core.py +312 -37
  53. package/runtime/python/okstra_ctl/dispatch_state.py +461 -36
  54. package/runtime/python/okstra_ctl/doctor.py +90 -16
  55. package/runtime/python/okstra_ctl/entrypoints/hosts.py +87 -9
  56. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +214 -23
  57. package/runtime/python/okstra_ctl/path_hints.py +26 -0
  58. package/runtime/python/okstra_ctl/paths.py +20 -0
  59. package/runtime/python/okstra_ctl/ports/__init__.py +8 -0
  60. package/runtime/python/okstra_ctl/ports/host.py +3 -0
  61. package/runtime/python/okstra_ctl/ports/host_model.py +60 -0
  62. package/runtime/python/okstra_ctl/registry/host_registry.py +5 -0
  63. package/runtime/python/okstra_ctl/render.py +217 -12
  64. package/runtime/python/okstra_ctl/report_finalize.py +44 -0
  65. package/runtime/python/okstra_ctl/run.py +368 -51
  66. package/runtime/python/okstra_ctl/session.py +16 -12
  67. package/runtime/python/okstra_ctl/team.py +11 -11
  68. package/runtime/python/okstra_ctl/worker_dispatch.py +104 -0
  69. package/runtime/python/okstra_ctl/worker_prompt_body.py +5 -38
  70. package/runtime/python/okstra_ctl/worker_prompt_contract.py +32 -2
  71. package/runtime/python/okstra_ctl/worker_prompt_policy.py +38 -1
  72. package/runtime/skills/okstra-code-review/SKILL.md +22 -3
  73. package/runtime/skills/okstra-run/SKILL.md +16 -1
  74. package/runtime/skills/okstra-schedule-gen/SKILL.md +15 -1
  75. package/runtime/templates/implementation-worker-preamble.md +0 -10
  76. package/runtime/templates/report-writer-prompt-preamble.md +0 -9
  77. package/runtime/templates/reports/settings.template.json +0 -11
  78. package/runtime/templates/worker-prompt-preamble.md +0 -10
  79. package/runtime/validators/lib/fixtures.sh +93 -0
  80. package/runtime/validators/lib/validate-assets.sh +0 -8
  81. package/runtime/validators/validate-run.py +182 -0
  82. package/src/cli-registry.mjs +14 -0
  83. package/src/commands/execute/agent-prompt.mjs +25 -0
  84. package/src/commands/execute/codex-dispatch.mjs +6 -63
  85. package/src/commands/execute/worker-dispatch.mjs +76 -0
  86. package/src/commands/lifecycle/doctor.mjs +18 -3
  87. package/src/commands/lifecycle/install.mjs +33 -15
  88. package/src/commands/lifecycle/uninstall.mjs +4 -3
  89. package/src/lib/install-assets.mjs +9 -0
  90. package/runtime/agents/workers/antigravity-worker.md +0 -259
  91. package/runtime/agents/workers/codex-worker.md +0 -259
  92. package/runtime/agents/workers/grok-worker.md +0 -259
  93. package/runtime/agents/workers/kimi-worker.md +0 -259
  94. package/runtime/prompts/coding-preflight/scripts/preedit-check.sh +0 -79
  95. package/runtime/templates/operating-standard.md +0 -22
  96. package/src/lib/worker-agent-render.mjs +0 -50
@@ -11,6 +11,7 @@ from typing import Iterable
11
11
  from okstra_project import ResolverError, project_json_path, resolve_project_root
12
12
 
13
13
  from . import improvement_lenses, worktree_registry
14
+ from .models import provider_wrappers
14
15
  from .workers import resolve_profile_workers
15
16
  from .worktree import is_git_work_tree, main_worktree_path
16
17
 
@@ -40,6 +41,7 @@ def phase_diagnostics(
40
41
  cwd: str | Path,
41
42
  workspace_root: str | Path,
42
43
  home: str | Path,
44
+ host_runtime: str,
43
45
  ) -> dict[str, object]:
44
46
  """Return JSON-serialisable readiness checks for one lifecycle phase."""
45
47
  if phase not in SUPPORTED_PHASES:
@@ -57,7 +59,11 @@ def phase_diagnostics(
57
59
  checks.append(_profile_check(workspace, phase))
58
60
 
59
61
  if project_root is not None:
60
- checks.extend(_phase_checks(phase, project_root, workspace, home_path))
62
+ checks.extend(
63
+ _phase_checks(
64
+ phase, project_root, workspace, home_path, host_runtime
65
+ )
66
+ )
61
67
 
62
68
  return {
63
69
  "ok": all(check.ok for check in checks),
@@ -164,15 +170,18 @@ def _phase_checks(
164
170
  project_root: Path,
165
171
  workspace: Path,
166
172
  home: Path,
173
+ host_runtime: str,
167
174
  ) -> list[DoctorCheck]:
168
175
  if phase == "implementation":
169
- return _implementation_checks(project_root, workspace, home)
176
+ return _implementation_checks(
177
+ project_root, workspace, home, host_runtime
178
+ )
170
179
  if phase == "final-verification":
171
180
  return _final_verification_checks(workspace)
172
181
  if phase == "release-handoff":
173
182
  return _release_handoff_checks(project_root)
174
183
  if phase == "improvement-discovery":
175
- return _improvement_discovery_checks(workspace, home)
184
+ return _improvement_discovery_checks(workspace, home, host_runtime)
176
185
  return []
177
186
 
178
187
 
@@ -180,12 +189,13 @@ def _implementation_checks(
180
189
  project_root: Path,
181
190
  workspace: Path,
182
191
  home: Path,
192
+ host_runtime: str,
183
193
  ) -> list[DoctorCheck]:
184
194
  return [
185
195
  _git_work_tree_check(project_root),
186
196
  _git_worktree_support_check(project_root),
187
197
  _approved_plan_validator_check(),
188
- _worker_agents_check(home, workspace, "implementation"),
198
+ *_worker_dispatch_checks(home, workspace, "implementation", host_runtime),
189
199
  ]
190
200
 
191
201
 
@@ -213,10 +223,15 @@ def _release_handoff_checks(project_root: Path) -> list[DoctorCheck]:
213
223
  ]
214
224
 
215
225
 
216
- def _improvement_discovery_checks(workspace: Path, home: Path) -> list[DoctorCheck]:
226
+ def _improvement_discovery_checks(
227
+ workspace: Path,
228
+ home: Path,
229
+ host_runtime: str,
230
+ ) -> list[DoctorCheck]:
217
231
  return [
218
- _worker_agents_check(home, workspace, "improvement-discovery"),
219
- _file_check("antigravity worker agent", _agent_path(home, "antigravity")),
232
+ *_worker_dispatch_checks(
233
+ home, workspace, "improvement-discovery", host_runtime
234
+ ),
220
235
  _lens_whitelist_check(),
221
236
  ]
222
237
 
@@ -242,18 +257,77 @@ def _approved_plan_validator_check() -> DoctorCheck:
242
257
  return _ok("approved-plan validator", "okstra plan-validate is available")
243
258
 
244
259
 
245
- def _worker_agents_check(home: Path, workspace: Path, phase: str) -> DoctorCheck:
260
+ def _worker_dispatch_checks(
261
+ home: Path,
262
+ workspace: Path,
263
+ phase: str,
264
+ host_runtime: str,
265
+ ) -> list[DoctorCheck]:
246
266
  workers = resolve_profile_workers(_profile_path(workspace, phase))
247
267
  if not workers:
248
- return _ok("worker agents", "no worker agents required")
249
- missing = [worker for worker in workers if not _agent_path(home, worker).is_file()]
250
- roster = ",".join(workers)
251
- if missing:
252
- return _fail(
253
- "worker agents",
254
- f"missing {','.join(missing)}; profile requires {roster}",
268
+ return [_ok("worker dispatch", "no workers required")]
269
+ if not host_runtime:
270
+ return [_fail("worker dispatch", "resolved host runtime is required")]
271
+
272
+ native_provider = {
273
+ "claude-code": "claude",
274
+ "codex": "codex",
275
+ "antigravity": "antigravity",
276
+ "grok": "grok",
277
+ "kimi": "kimi",
278
+ }.get(host_runtime)
279
+ providers = ["claude" if worker == "report-writer" else worker for worker in workers]
280
+ checks: list[DoctorCheck] = []
281
+
282
+ if host_runtime == "claude-code":
283
+ native_agents = []
284
+ if "claude" in workers:
285
+ native_agents.append("claude")
286
+ if "report-writer" in workers:
287
+ native_agents.append("report-writer")
288
+ for agent in native_agents:
289
+ checks.append(
290
+ _file_check(
291
+ f"host-native agent: {agent}", _agent_path(home, agent)
292
+ )
293
+ )
294
+
295
+ cli_providers = sorted({
296
+ provider for provider in providers if provider != native_provider
297
+ })
298
+ if cli_providers:
299
+ dispatch_module = _first_file(
300
+ workspace / "scripts" / "okstra_ctl" / "worker_dispatch.py",
301
+ workspace / "python" / "okstra_ctl" / "worker_dispatch.py",
302
+ )
303
+ checks.append(
304
+ _file_check("worker-dispatch entrypoint", dispatch_module)
255
305
  )
256
- return _ok("worker agents", f"installed: {roster}")
306
+ wrappers = provider_wrappers("analyser")
307
+ for provider in cli_providers:
308
+ wrapper = wrappers.get(provider, "")
309
+ if not wrapper:
310
+ checks.append(
311
+ _fail(
312
+ f"CLI provider strategy: {provider}",
313
+ "provider registry has no analyser wrapper",
314
+ )
315
+ )
316
+ continue
317
+ path = _first_file(
318
+ workspace / "scripts" / wrapper,
319
+ workspace / "bin" / wrapper,
320
+ )
321
+ checks.append(_file_check(f"CLI provider strategy: {provider}", path))
322
+ if not checks:
323
+ checks.append(
324
+ _ok("worker dispatch", f"native host owns roster on {host_runtime}")
325
+ )
326
+ return checks
327
+
328
+
329
+ def _first_file(*paths: Path) -> Path:
330
+ return next((path for path in paths if path.is_file()), paths[0])
257
331
 
258
332
 
259
333
  def _worktree_registry_check() -> DoctorCheck:
@@ -9,6 +9,14 @@ from contextlib import contextmanager
9
9
  from dataclasses import asdict
10
10
  from pathlib import Path
11
11
 
12
+ from ..agent_invocation import (
13
+ AgentInvocationError,
14
+ AgentModelAssignment,
15
+ agent_model_assignment_from_payload,
16
+ verify_agent_invocation,
17
+ )
18
+ from ..dispatch_state import DispatchError, record_verified_agent_dispatch
19
+
12
20
  from ..application.start_run import start_run
13
21
  from ..application.resume_run import resume_run
14
22
  from ..domain.host import (
@@ -24,6 +32,7 @@ from ..domain.host import (
24
32
  ProviderUnavailable,
25
33
  )
26
34
  from ..registry.host_registry import HostAdapterRegistry, default_host_registry
35
+ from ..models import lead_launch_argv, lead_launch_spec
27
36
 
28
37
 
29
38
  _ENTRYPOINT_ERRORS = (
@@ -33,6 +42,7 @@ _ENTRYPOINT_ERRORS = (
33
42
  HostUnavailable,
34
43
  ProviderNotRegistered,
35
44
  ProviderUnavailable,
45
+ DispatchError,
36
46
  ValueError,
37
47
  )
38
48
 
@@ -252,9 +262,24 @@ def _launch_plan_payload(
252
262
  available_functions=frozenset(),
253
263
  interaction_surface="terminal",
254
264
  )
255
- project_root, request_argv = _launch_request(args, adapter.descriptor.id)
265
+ project_root, request_argv, dispatch_authority = _launch_request(
266
+ args, adapter.descriptor.id
267
+ )
256
268
  request = LeadStartRequest(project_root, "", request_argv)
257
269
  plan = start_run(request, context, adapter)
270
+ if dispatch_authority is not None:
271
+ run_manifest_path, metadata_path, _assignment = dispatch_authority
272
+ record_verified_agent_dispatch(
273
+ project_root=project_root,
274
+ run_manifest_path=run_manifest_path,
275
+ metadata_path=metadata_path,
276
+ enforcement_mode=(
277
+ "core-pre-dispatch"
278
+ if plan.mode == "spawn-process"
279
+ else "host-native-spec-link-gate"
280
+ ),
281
+ allow_native_core=plan.mode == "spawn-process",
282
+ )
258
283
  return {"ok": True, "_project_root": str(project_root), **asdict(plan)}
259
284
 
260
285
 
@@ -283,9 +308,13 @@ def _resume_plan_payload(
283
308
  def _launch_request(
284
309
  args: argparse.Namespace,
285
310
  canonical_host_id: str,
286
- ) -> tuple[Path, tuple[str, ...]]:
311
+ ) -> tuple[
312
+ Path,
313
+ tuple[str, ...],
314
+ tuple[Path, Path, AgentModelAssignment] | None,
315
+ ]:
287
316
  if not args.prepared_launch_json:
288
- return Path(args.project_root), ()
317
+ return Path(args.project_root), (), None
289
318
  try:
290
319
  prepared = json.loads(args.prepared_launch_json)
291
320
  except json.JSONDecodeError as exc:
@@ -295,14 +324,63 @@ def _launch_request(
295
324
  if prepared.get("leadRuntime") != canonical_host_id:
296
325
  raise ValueError("prepared launch runtime does not match selected host")
297
326
  project_root = prepared.get("projectRoot")
298
- request_argv = prepared.get("launchRequestArgv")
299
327
  if not isinstance(project_root, str) or not project_root:
300
328
  raise ValueError("prepared launch is missing projectRoot")
301
- if not isinstance(request_argv, list) or not all(
302
- isinstance(arg, str) for arg in request_argv
303
- ):
304
- raise ValueError("prepared launch is missing launchRequestArgv")
305
- return Path(project_root), tuple(request_argv)
329
+ root = Path(project_root)
330
+ run_manifest_value = prepared.get("runManifestPath")
331
+ metadata_value = prepared.get("leadPromptMetadataPath")
332
+ if not isinstance(run_manifest_value, str) or not run_manifest_value:
333
+ raise ValueError("prepared launch is missing runManifestPath")
334
+ if not isinstance(metadata_value, str) or not metadata_value:
335
+ raise ValueError("prepared launch is missing leadPromptMetadataPath")
336
+ run_manifest_path = Path(run_manifest_value)
337
+ metadata_path = Path(metadata_value)
338
+ try:
339
+ manifest = json.loads(run_manifest_path.read_text(encoding="utf-8"))
340
+ resources = manifest["resources"]
341
+ assignment = agent_model_assignment_from_payload(
342
+ manifest["invocationAssignments"]["lead"]
343
+ )
344
+ prompt_path = root / resources["leadExecutionPromptPath"]
345
+ canonical_metadata = root / resources["leadPromptMetadataPath"]
346
+ metadata = json.loads(canonical_metadata.read_text(encoding="utf-8"))
347
+ if metadata["prompt"]["path"] != resources["leadExecutionPromptPath"]:
348
+ raise KeyError("lead prompt resource does not match metadata")
349
+ except (OSError, json.JSONDecodeError, KeyError, TypeError, AgentInvocationError) as exc:
350
+ raise ValueError("lead invocation authority is incomplete") from exc
351
+ if metadata_path.resolve(strict=False) != canonical_metadata.resolve(strict=False):
352
+ raise ValueError("prepared lead metadata does not match run manifest")
353
+ if prepared.get("leadProvider") != assignment.provider:
354
+ raise ValueError("prepared lead provider does not match run manifest")
355
+ if prepared.get("leadModelExecutionValue") != assignment.model_execution_value:
356
+ raise ValueError("prepared lead model does not match run manifest")
357
+ errors = verify_agent_invocation(
358
+ metadata_path,
359
+ project_root=root,
360
+ expected_run_manifest_path=run_manifest_path,
361
+ expected_assignment=assignment,
362
+ expected_worker_id="lead",
363
+ expected_assignment_ref="lead",
364
+ expected_audience="lead",
365
+ )
366
+ if errors:
367
+ raise ValueError("lead invocation verification failed: " + "; ".join(errors))
368
+ session_id = prepared.get("leadSessionId")
369
+ if not isinstance(session_id, str):
370
+ raise ValueError("prepared launch is missing leadSessionId")
371
+ argv = lead_launch_argv(
372
+ assignment.provider,
373
+ model=assignment.model_execution_value,
374
+ session_id=session_id,
375
+ prompt=prompt_path.read_text(encoding="utf-8"),
376
+ )
377
+ launch = lead_launch_spec(assignment.provider)
378
+ prefix_size = 1 + len(launch.sandbox_waiver)
379
+ return (
380
+ root,
381
+ tuple(argv[prefix_size:]),
382
+ (run_manifest_path, canonical_metadata, assignment),
383
+ )
306
384
 
307
385
 
308
386
  def _write_null_launch_plan(payload: dict[str, object]) -> None:
@@ -11,6 +11,16 @@ from pathlib import Path
11
11
  from typing import Any, Callable, Literal, Mapping, Sequence
12
12
 
13
13
  from .final_report_paths import final_report_data_path
14
+ from .agent_invocation import (
15
+ AgentInstruction,
16
+ AgentInstructionSource,
17
+ AgentInvocationError,
18
+ AgentInvocationRequest,
19
+ agent_model_assignment_from_payload,
20
+ compose_agent_prompt,
21
+ prepare_agent_invocation,
22
+ verify_agent_invocation,
23
+ )
14
24
  from .path_hints import hydrate_active_run_context
15
25
  from .report_language import resolve_report_language
16
26
  from .worker_prompt_body import (
@@ -101,6 +111,30 @@ _CLARIFICATION_AUTHORITY_INTRO = (
101
111
  _CLARIFICATION_SOURCE_PREFIX = "Source:"
102
112
  _REQUIRED_PROMPT_RESOURCES_HEADING = "## Required prompt resources"
103
113
  _HTML_COMMENTS = re.compile(r"<!--.*?-->\n?", re.DOTALL)
114
+ _AGENT_CONTRACT_KEYS = {
115
+ "schemaVersion",
116
+ "dutyRootPath",
117
+ "catalogDigest",
118
+ "invocationReservationRootPath",
119
+ "allowedAudiences",
120
+ "authorizedPaths",
121
+ }
122
+ _MODEL_ASSIGNMENT_KEYS = {
123
+ "provider",
124
+ "model",
125
+ "modelExecutionValue",
126
+ "runner",
127
+ "hostRuntime",
128
+ "hostModelValue",
129
+ }
130
+ _RUN_INVOCATION_PATH_KEYS = {
131
+ "runManifestPath",
132
+ "workerPromptsDirectoryPath",
133
+ "leadInstructionsPath",
134
+ "leadExecutionPromptPath",
135
+ "leadPromptMetadataPath",
136
+ "invocationReservationRootPath",
137
+ }
104
138
 
105
139
 
106
140
  @dataclass(frozen=True)
@@ -198,6 +232,7 @@ def _load_materialization_context(
198
232
  )
199
233
  manifest_path = _resolve_input_path(project_root, request.run_manifest_path)
200
234
  manifest = _load_json_object(manifest_path, "run manifest")
235
+ _validate_invocation_manifest_authority(manifest)
201
236
  team_state = _load_referenced_json(project_root, manifest, "teamStatePath")
202
237
  active_context = hydrate_active_run_context(
203
238
  _load_referenced_json(
@@ -215,6 +250,39 @@ def _load_materialization_context(
215
250
  )
216
251
 
217
252
 
253
+ def _validate_invocation_manifest_authority(
254
+ manifest: Mapping[str, Any],
255
+ ) -> None:
256
+ has_contract = "agentContract" in manifest
257
+ has_assignments = "invocationAssignments" in manifest
258
+ if not has_contract and not has_assignments:
259
+ return
260
+ contract = manifest.get("agentContract")
261
+ assignments = manifest.get("invocationAssignments")
262
+ complete = (
263
+ isinstance(contract, Mapping)
264
+ and set(contract) == _AGENT_CONTRACT_KEYS
265
+ and contract.get("schemaVersion") == 1
266
+ and isinstance(assignments, Mapping)
267
+ and bool(assignments)
268
+ and all(
269
+ isinstance(item, Mapping)
270
+ and set(item) == _MODEL_ASSIGNMENT_KEYS
271
+ for item in assignments.values()
272
+ )
273
+ and all(
274
+ isinstance(manifest.get(key), str)
275
+ and bool(manifest.get(key))
276
+ for key in _RUN_INVOCATION_PATH_KEYS
277
+ )
278
+ )
279
+ if not complete:
280
+ raise InitialPromptMaterializationError(
281
+ "required_input_missing",
282
+ "new invocation manifest is incomplete",
283
+ )
284
+
285
+
218
286
  def _resolve_prompt_item(
219
287
  context: _MaterializationContext,
220
288
  worker: InitialPromptWorkerRequest,
@@ -312,12 +380,23 @@ def _render_prompt(
312
380
  context: _MaterializationContext,
313
381
  item: _PromptItem,
314
382
  ) -> str:
383
+ request = _agent_invocation_request(context, item)
384
+ if request is not None:
385
+ return compose_agent_prompt(request)
386
+ anchors, body = _render_prompt_parts(context, item)
387
+ return "\n".join([*anchors, *body]).rstrip() + "\n"
388
+
389
+
390
+ def _render_prompt_parts(
391
+ context: _MaterializationContext,
392
+ item: _PromptItem,
393
+ ) -> tuple[list[str], list[str]]:
315
394
  worker = item.worker
316
395
  state = _worker_state(context.team_state, worker.worker_id)
317
396
  prompt_rel = _project_relative(context.project_root, item.final_path)
318
397
  result_rel, audit_source_rel = _result_paths(context, state, worker.worker_id)
319
398
  try:
320
- lines = worker_prompt_headers(
399
+ anchors = worker_prompt_headers(
321
400
  project_root=context.project_root,
322
401
  prompt_rel=prompt_rel,
323
402
  result_rel=result_rel,
@@ -327,12 +406,12 @@ def _render_prompt(
327
406
  manifest=context.manifest,
328
407
  active_context=context.active_context,
329
408
  )
330
- lines.append(
409
+ anchors.append(
331
410
  f"**Prompt Delivery Mode:** {context.request.delivery_mode.value}"
332
411
  )
333
- lines.extend(_implementation_anchor_lines(context, item.plan))
334
- lines.extend(_prompt_body(context, state, worker, item.plan))
335
- lines.extend(_resource_lines(context, item))
412
+ anchors.extend(_implementation_anchor_lines(context, item.plan))
413
+ body = _prompt_body(context, state, worker, item.plan)
414
+ body.extend(_resource_lines(context, item))
336
415
  except InitialPromptMaterializationError:
337
416
  raise
338
417
  except Exception as exc:
@@ -340,7 +419,62 @@ def _render_prompt(
340
419
  "render_failed",
341
420
  f"cannot compose initial prompt for {worker.worker_id}: {exc}",
342
421
  ) from exc
343
- return "\n".join(lines).rstrip() + "\n"
422
+ return anchors, body
423
+
424
+
425
+ def _agent_invocation_request(
426
+ context: _MaterializationContext,
427
+ item: _PromptItem,
428
+ ) -> AgentInvocationRequest | None:
429
+ contract = context.manifest.get("agentContract")
430
+ if not isinstance(contract, Mapping):
431
+ return None
432
+ assignment_ref = f"initial/{item.worker.worker_id}"
433
+ assignments = context.manifest.get("invocationAssignments")
434
+ payload = assignments.get(assignment_ref) if isinstance(assignments, Mapping) else None
435
+ try:
436
+ assignment = agent_model_assignment_from_payload(payload)
437
+ except AgentInvocationError as exc:
438
+ raise InitialPromptMaterializationError(
439
+ "required_input_missing", str(exc)
440
+ ) from exc
441
+ if assignment.model_execution_value != item.worker.model:
442
+ raise InitialPromptMaterializationError(
443
+ "required_input_missing",
444
+ f"requested model does not match {assignment_ref}",
445
+ )
446
+ anchors, body = _render_prompt_parts(context, item)
447
+ source_paths = (
448
+ AgentInstructionSource(
449
+ "project",
450
+ _project_relative(context.project_root, context.request.run_manifest_path),
451
+ ),
452
+ AgentInstructionSource(
453
+ "project", _required_string(context.manifest, "activeRunContextPath")
454
+ ),
455
+ AgentInstructionSource(
456
+ "project", _required_string(context.manifest, "teamStatePath")
457
+ ),
458
+ )
459
+ return AgentInvocationRequest(
460
+ invocation_id=f"initial-{item.worker.worker_id}",
461
+ worker_id=item.worker.worker_id,
462
+ audience=item.plan.duty_audience,
463
+ assignment_ref=assignment_ref,
464
+ purpose=None,
465
+ assignment=assignment,
466
+ instruction=AgentInstruction(
467
+ anchor_lines=tuple(anchors),
468
+ body="\n".join(body).rstrip() + "\n",
469
+ source_paths=source_paths,
470
+ ),
471
+ project_root=context.project_root,
472
+ run_manifest_path=context.request.run_manifest_path,
473
+ duty_root=context.project_root / _required_string(contract, "dutyRootPath"),
474
+ prompt_path=item.final_path,
475
+ metadata_path=item.final_path.with_name(item.final_path.name + ".meta.json"),
476
+ dispatch_kind="initial",
477
+ )
344
478
 
345
479
 
346
480
  def _prompt_body(
@@ -366,7 +500,6 @@ def _prompt_body(
366
500
  context.active_context,
367
501
  worker.worker_id,
368
502
  worker.model,
369
- _worker_role(plan),
370
503
  plan,
371
504
  )
372
505
 
@@ -607,15 +740,30 @@ def _publish_or_reuse(
607
740
  ) -> _PublishedPrompt:
608
741
  if item.existed:
609
742
  return _published_prompt(item, existed=True)
610
- temp_path = _required_temp_path(item)
743
+ invocation = _agent_invocation_request(context, item)
744
+ if invocation is None:
745
+ temp_path = _required_temp_path(item)
746
+ try:
747
+ os.link(temp_path, item.final_path)
748
+ except FileExistsError:
749
+ _validate_existing_prompt(context, item)
750
+ return _published_prompt(item, existed=True)
751
+ except OSError as exc:
752
+ raise InitialPromptMaterializationError(
753
+ "publication_failed",
754
+ f"cannot publish initial prompt {item.final_path}: {exc}",
755
+ ) from exc
756
+ return _published_prompt(item, existed=False)
611
757
  try:
612
- os.link(temp_path, item.final_path)
613
- except FileExistsError:
614
- _validate_existing_prompt(context, item)
615
- return _published_prompt(item, existed=True)
616
- except OSError as exc:
758
+ prepare_agent_invocation(invocation)
759
+ except AgentInvocationError as exc:
760
+ reason: MaterializationReason = (
761
+ "existing_prompt_conflict"
762
+ if exc.reason == "existing_invocation_conflict"
763
+ else "publication_failed"
764
+ )
617
765
  raise InitialPromptMaterializationError(
618
- "publication_failed",
766
+ reason,
619
767
  f"cannot publish initial prompt {item.final_path}: {exc}",
620
768
  ) from exc
621
769
  return _published_prompt(item, existed=False)
@@ -625,6 +773,7 @@ def _validate_existing_prompt(
625
773
  context: _MaterializationContext,
626
774
  item: _PromptItem,
627
775
  ) -> None:
776
+ expects_invocation = isinstance(context.manifest.get("agentContract"), Mapping)
628
777
  text = _require_readable_prompt(
629
778
  item.final_path,
630
779
  item.worker.worker_id,
@@ -636,6 +785,10 @@ def _validate_existing_prompt(
636
785
  item.worker.worker_id,
637
786
  "initial",
638
787
  item.final_path,
788
+ metadata_path=_metadata_path(item.final_path) if expects_invocation else None,
789
+ expected_duty_audience=(
790
+ item.plan.duty_audience if expects_invocation else None
791
+ ),
639
792
  )
640
793
  basic_errors = validate_initial_prompt_records(
641
794
  manifest=context.manifest,
@@ -653,6 +806,10 @@ def _validate_existing_prompt(
653
806
  item.final_path,
654
807
  expected_model=item.worker.model,
655
808
  expected_delivery_mode=context.request.delivery_mode.value,
809
+ metadata_path=_metadata_path(item.final_path) if expects_invocation else None,
810
+ expected_duty_audience=(
811
+ item.plan.duty_audience if expects_invocation else None
812
+ ),
656
813
  )
657
814
  expected_errors = validate_initial_prompt_records(
658
815
  manifest=context.manifest,
@@ -665,6 +822,23 @@ def _validate_existing_prompt(
665
822
  reason,
666
823
  "existing initial prompt metadata: " + "; ".join(expected_errors),
667
824
  )
825
+ invocation = _agent_invocation_request(context, item)
826
+ if invocation is not None:
827
+ errors = verify_agent_invocation(
828
+ invocation.metadata_path,
829
+ project_root=context.project_root,
830
+ expected_run_manifest_path=context.request.run_manifest_path,
831
+ expected_assignment=invocation.assignment,
832
+ expected_invocation_id=invocation.invocation_id,
833
+ expected_worker_id=invocation.worker_id,
834
+ expected_assignment_ref=invocation.assignment_ref,
835
+ expected_audience=invocation.audience,
836
+ )
837
+ if errors:
838
+ raise InitialPromptMaterializationError(
839
+ "existing_prompt_invalid",
840
+ "existing initial prompt invocation: " + "; ".join(errors),
841
+ )
668
842
 
669
843
 
670
844
  def _validate_existing_clarification_metadata(
@@ -854,12 +1028,20 @@ def _item_record(
854
1028
  item: _PromptItem,
855
1029
  ) -> PromptRecord:
856
1030
  path = item.final_path if item.existed else _required_temp_path(item)
1031
+ expects_invocation = (
1032
+ item.existed
1033
+ and isinstance(context.manifest.get("agentContract"), Mapping)
1034
+ )
857
1035
  return PromptRecord(
858
1036
  item.worker.worker_id,
859
1037
  "initial",
860
1038
  path,
861
1039
  expected_model=item.worker.model,
862
1040
  expected_delivery_mode=context.request.delivery_mode.value,
1041
+ metadata_path=_metadata_path(item.final_path) if expects_invocation else None,
1042
+ expected_duty_audience=(
1043
+ item.plan.duty_audience if expects_invocation else None
1044
+ ),
863
1045
  )
864
1046
 
865
1047
 
@@ -867,15 +1049,24 @@ def _published_record(
867
1049
  context: _MaterializationContext,
868
1050
  prompt: _PublishedPrompt,
869
1051
  ) -> PromptRecord:
1052
+ expects_invocation = isinstance(context.manifest.get("agentContract"), Mapping)
870
1053
  return PromptRecord(
871
1054
  prompt.worker.worker_id,
872
1055
  "initial",
873
1056
  prompt.path,
874
1057
  expected_model=prompt.worker.model,
875
1058
  expected_delivery_mode=context.request.delivery_mode.value,
1059
+ metadata_path=_metadata_path(prompt.path) if expects_invocation else None,
1060
+ expected_duty_audience=(
1061
+ prompt.plan.duty_audience if expects_invocation else None
1062
+ ),
876
1063
  )
877
1064
 
878
1065
 
1066
+ def _metadata_path(prompt_path: Path) -> Path:
1067
+ return prompt_path.with_name(prompt_path.name + ".meta.json")
1068
+
1069
+
879
1070
  def _worker_prompt_path(
880
1071
  context: _MaterializationContext,
881
1072
  worker_id: str,
@@ -1094,14 +1285,6 @@ def _validate_worker_request(worker: InitialPromptWorkerRequest) -> None:
1094
1285
  )
1095
1286
 
1096
1287
 
1097
- def _worker_role(plan: PromptPlan) -> str:
1098
- if plan.audience == "implementation-executor":
1099
- return "executor"
1100
- if plan.audience == "implementation-verifier":
1101
- return "verifier"
1102
- return "worker"
1103
-
1104
-
1105
1288
  def _existing_metadata_reason(
1106
1289
  errors: Sequence[str],
1107
1290
  ) -> MaterializationReason:
@@ -1164,7 +1347,15 @@ def _required_temp_path(item: _PromptItem) -> Path:
1164
1347
 
1165
1348
 
1166
1349
  def _project_relative(project_root: Path, path: Path) -> str:
1167
- return path.relative_to(project_root).as_posix()
1350
+ # macOS commonly exposes the same temporary directory as both `/var/...`
1351
+ # and `/private/var/...`; project-root resolution already canonicalizes the
1352
+ # former. Resolve the candidate too so provenance does not reject an alias
1353
+ # for the same directory. `strict=False` is required for a prompt that has
1354
+ # not been published yet, while still resolving every existing parent and
1355
+ # therefore preserving the symlink-escape check in `relative_to`.
1356
+ return path.resolve(strict=False).relative_to(
1357
+ project_root.resolve(strict=True)
1358
+ ).as_posix()
1168
1359
 
1169
1360
 
1170
1361
  def _resolve_input_path(project_root: Path, path: Path) -> Path: