-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_tentacle_dispatch.py
More file actions
1844 lines (1617 loc) · 71.8 KB
/
_tentacle_dispatch.py
File metadata and controls
1844 lines (1617 loc) · 71.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Dispatch, runtime-bundle, recall, and profile helpers for tentacle.py."""
import ast
import json
import os
import re
import subprocess
import sys
import textwrap
from datetime import datetime, timezone
from pathlib import Path
from _tentacle_core import (
_DISPATCHED_MARKER_PATH,
_DISPATCHED_MARKER_TTL,
AGENT_PROFILE_REFERENCE_DIR,
AUTO_RECALL_END,
AUTO_RECALL_START,
)
from _tentacle_core import (
BRIEFING_PY as _DEFAULT_BRIEFING_PY,
)
from _tentacle_core import (
CHECKPOINT_RESTORE_PY as _DEFAULT_CHECKPOINT_RESTORE_PY,
)
from _tentacle_core import (
find_git_root as _default_find_git_root,
)
from _tentacle_core import (
get_tentacles_dir as _default_get_tentacles_dir,
)
from _tentacle_core import (
parse_todos as _default_parse_todos,
)
from _tentacle_goal import (
_goal_collect_prior_handoffs as _default_goal_collect_prior_handoffs,
)
from _tentacle_goal import (
_goal_load as _default_goal_load,
)
from _tentacle_goal import (
_goal_render_continuation_context as _default_goal_render_continuation_context,
)
if os.name == "nt":
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
POINTER_DISPATCH_MODE_NAME = "pointer_bundle"
FULL_CONTEXT_DISPATCH_MODE_NAME = "full_context_inline"
POINTER_PROMPT_REDUCTION_TARGET_PERCENT = 30.0
_runtime_BRIEFING_PY = _DEFAULT_BRIEFING_PY
_runtime_CHECKPOINT_RESTORE_PY = _DEFAULT_CHECKPOINT_RESTORE_PY
_runtime_HANDOFF_TRIAGE_STATUSES: frozenset[str] = frozenset()
_runtime_find_git_root = _default_find_git_root
_runtime_get_tentacles_dir = _default_get_tentacles_dir
_runtime_parse_todos = _default_parse_todos
_runtime_validate_tentacle_name = None
_runtime_worktree_prepare = None
_runtime_write_dispatched_subagent_marker = None
_runtime_get_marker_state = None
_runtime_goal_load = _default_goal_load
_runtime_goal_render_continuation_context = _default_goal_render_continuation_context
_runtime_goal_collect_prior_handoffs = _default_goal_collect_prior_handoffs
_runtime_fetch_recall_pack_json = None
_runtime_run_briefing_for_task = None
_runtime_load_latest_checkpoint_context = None
_runtime_build_runtime_bundle = None
def configure_dispatch_runtime(**deps: object) -> None:
"""Inject tentacle.py-owned helpers that the extracted dispatch seam calls."""
globals().update(deps)
def _runtime_path(value) -> Path:
"""Resolve an injected path or path-returning callable."""
return Path(value() if callable(value) else value)
def _run_briefing(query: str) -> str:
"""Run briefing.py with a text query and return compact output. Returns empty string on failure."""
briefing_py = _runtime_path(_runtime_BRIEFING_PY)
if not briefing_py.exists():
return ""
try:
result = subprocess.run(
[sys.executable, str(briefing_py), query, "--compact", "--limit", "3"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace", # P1-3: prevent UnicodeDecodeError on Windows cp1252
timeout=15,
)
output = result.stdout.strip()
if output and "No relevant" not in output and len(output) > 20:
return output
except (subprocess.TimeoutExpired, Exception):
pass
return ""
def _render_knowledge_evidence(
entries: list[dict],
*,
task_id: str = "",
file_matches: list[dict] | None = None,
) -> str:
"""Render deterministic compact evidence block for prompt injection."""
def _source_label(entry: dict) -> str:
src = entry.get("source_document") or {}
if not isinstance(src, dict):
return ""
doc_type = str(src.get("doc_type") or "").strip()
if not doc_type:
return ""
section = str(src.get("section") or "").strip()
seq = src.get("seq")
file_path = str(src.get("file_path") or "").strip()
title = str(src.get("title") or "").strip()
if doc_type == "checkpoint" and seq:
label = f"checkpoint #{seq}"
elif file_path:
label = f"{doc_type} / {Path(file_path).name}"
elif title:
label = f"{doc_type} / {title[:80]}"
else:
label = doc_type
if section:
label = f"{label} / {section}"
return label[:120]
refs = entries[:5]
if not refs:
return ""
lines = ["[KNOWLEDGE EVIDENCE]"]
if task_id:
lines.append(f"Task: {task_id}")
for e in refs:
eid = e.get("id", "?")
cat = e.get("category", "unknown")
title = e.get("title", "(no title)")
lines.append(f"- #{eid} [{cat}] {title}")
labels: list[str] = []
for e in refs:
label = _source_label(e)
if not label or label in labels:
continue
labels.append(label)
if len(labels) >= 2:
break
if labels:
lines.append(f"From: {'; '.join(labels)}")
file_paths: list[str] = []
for fm in file_matches or []:
path = str(fm.get("file_or_module", "")).strip()
if path and path not in file_paths:
file_paths.append(path)
if len(file_paths) >= 3:
break
if file_paths:
lines.append(f"Files: {', '.join(file_paths)}")
first_entry = refs[0]
first_id = first_entry.get("id", "?")
drilldowns = [f"query-session.py --detail {first_id}"]
first_related = first_entry.get("related_entry_ids")
if isinstance(first_related, list) and len(first_related) > 0:
drilldowns.append(f"query-session.py --related {first_id}")
if task_id:
drilldowns.append(f"query-session.py --task {task_id!r}")
if file_paths:
drilldowns.append(f"query-session.py {file_paths[0]!r}")
lines.append(f"Drilldown: {' | '.join(drilldowns)}")
return "\n".join(lines)
def _extract_pack_entries(pack_data: dict) -> list[dict]:
"""Extract ordered reference entries from briefing --pack payload."""
entries = pack_data.get("entries", {})
out = []
for category in ("mistake", "pattern", "decision", "tool"):
for entry in entries.get(category, []):
out.append(
{
"id": entry.get("id", "?"),
"category": entry.get("category", category),
"title": entry.get("title", "(no title)"),
"source_document": entry.get("source_document"),
"related_entry_ids": entry.get("related_entry_ids", []),
}
)
return out
def _run_briefing_for_task(task_id: str, fallback_query: str = "") -> str:
"""Load evidence block for task recall using task-json then pack fallback."""
recall_pack_data, recall_source_mode = _fetch_recall_pack_json(task_id, fallback_query=fallback_query)
return _render_recall_payload(task_id, recall_pack_data, recall_source_mode)
def _pack_payload_has_signal(pack_data: dict) -> bool:
"""Return True when a --pack payload carries actionable recall content."""
entries = pack_data.get("entries", {})
if any(entries.get(cat) for cat in ("mistake", "pattern", "decision", "tool")):
return True
for key in ("task_matches", "file_matches", "past_work", "risk"):
if pack_data.get(key):
return True
return bool(pack_data.get("next_open"))
def _render_recall_payload(task_id: str, recall_data: dict, source_mode: str | None) -> str:
"""Render a fetched recall payload into the bounded prose evidence block."""
if not recall_data or not source_mode:
return ""
if source_mode == "task_json":
tagged = recall_data.get("tagged_entries", [])
related = recall_data.get("related_entries", [])
if not (tagged or related):
return ""
task_entries = [
{
"id": e.get("id", "?"),
"category": e.get("category", "unknown"),
"title": e.get("title", "(no title)"),
"source_document": e.get("source_document"),
"related_entry_ids": e.get("related_entry_ids", []),
}
for e in [*tagged, *related]
]
return _render_knowledge_evidence(task_entries, task_id=task_id)
if source_mode == "pack":
pack_entries = _extract_pack_entries(recall_data)
return _render_knowledge_evidence(
pack_entries,
file_matches=recall_data.get("file_matches", []),
)
return ""
def _fetch_recall_pack_json(task_id: str, fallback_query: str = "") -> tuple[dict, str | None]:
"""Fetch machine-readable recall JSON for task_id from briefing.py.
Tries --task --json first (source_mode="task_json"), then --pack fallback
(source_mode="pack"). Returns ({}, None) when both sources are empty or
briefing.py is unavailable.
"""
briefing_py = _runtime_path(_runtime_BRIEFING_PY)
if not briefing_py.exists():
return {}, None
# Try task-json first
try:
result = subprocess.run(
[sys.executable, str(briefing_py), "--task", task_id, "--json"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=15,
)
if result.returncode == 0 and result.stdout.strip():
data = json.loads(result.stdout)
if data.get("tagged_entries") or data.get("related_entries"):
return data, "task_json"
except (subprocess.TimeoutExpired, json.JSONDecodeError, OSError):
pass
# Fallback to --pack
if fallback_query:
try:
result = subprocess.run(
[
sys.executable,
str(briefing_py),
fallback_query,
"--pack",
"--limit",
"3",
],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=15,
)
if result.returncode == 0 and result.stdout.strip():
data = json.loads(result.stdout)
if _pack_payload_has_signal(data):
return data, "pack"
except (subprocess.TimeoutExpired, json.JSONDecodeError, OSError):
pass
return {}, None
def _upsert_auto_recall_block(context_text: str, recall_content: str) -> str:
"""Insert/replace a single auto-managed recall block in CONTEXT.md."""
block = f"{AUTO_RECALL_START}\n{recall_content}\n{AUTO_RECALL_END}"
pattern = re.compile(
rf"{re.escape(AUTO_RECALL_START)}.*?{re.escape(AUTO_RECALL_END)}",
flags=re.DOTALL,
)
if pattern.search(context_text):
return pattern.sub(block, context_text, count=1)
prefix = "" if not context_text or context_text.endswith("\n") else "\n"
return f"{context_text}{prefix}\n{block}\n"
def _render_checkpoint_context(data: dict) -> str:
"""Render a concise checkpoint context block from checkpoint JSON.
Sources only real fields: seq, title, and a small subset of useful sections.
"""
seq = data.get("seq", "?")
title = data.get("title", "unknown")
sections = data.get("sections", {})
lines = [f"### Latest Checkpoint (#{seq}: {title})", ""]
for key in ("overview", "work_done", "next_steps"):
text = sections.get(key, "").strip()
if text:
snippet = text[:300] + ("…" if len(text) > 300 else "")
label = key.replace("_", " ").title()
lines.append(f"**{label}:** {snippet}")
lines.append("")
return "\n".join(lines).strip()
def _load_latest_checkpoint_context() -> str:
"""Load latest checkpoint and render a concise context block.
Returns empty string if no checkpoint exists or on any error.
"""
checkpoint_restore_py = _runtime_path(_runtime_CHECKPOINT_RESTORE_PY)
if not checkpoint_restore_py.exists():
return ""
try:
result = subprocess.run(
[
sys.executable,
str(checkpoint_restore_py),
"--export",
"latest",
"--format",
"json",
],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace", # P1-3
timeout=15,
)
if result.returncode != 0 or not result.stdout.strip():
return ""
data = json.loads(result.stdout)
return _render_checkpoint_context(data)
except (subprocess.TimeoutExpired, json.JSONDecodeError, Exception):
return ""
def _bundle_enabled(args) -> bool:
"""Return whether dispatch should materialize a runtime bundle.
The CLI parser defaults this to True for swarm/dispatch. Older direct
callers/tests that do not provide the attribute retain the historical
behavior.
"""
return bool(getattr(args, "bundle", False))
def _normalize_agent_profile_id(profile_id: str) -> str:
"""Return a safe profile slug for .agent.md lookup."""
slug = str(profile_id or "").strip()
if slug.endswith(".agent.md"):
slug = slug[: -len(".agent.md")]
elif slug.endswith(".md"):
slug = slug[: -len(".md")]
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]*", slug or ""):
raise ValueError("Agent profile id must be a slug containing only letters, numbers, underscores, and hyphens.")
return slug
def _parse_frontmatter_scalar(value: str):
"""Parse the scalar subset used by .agent.md frontmatter."""
raw = value.strip()
if raw == "":
return ""
if raw.startswith("[") and raw.endswith("]"):
try:
parsed = ast.literal_eval(raw)
except (SyntaxError, ValueError):
return raw
if isinstance(parsed, list):
return [str(item) for item in parsed]
return raw
if (raw.startswith("'") and raw.endswith("'")) or (raw.startswith('"') and raw.endswith('"')):
return raw[1:-1]
lower = raw.lower()
if lower == "true":
return True
if lower == "false":
return False
return raw
def _parse_agent_frontmatter(path: Path) -> dict:
"""Parse the YAML-frontmatter subset used by bundled agent profiles."""
text = path.read_text(encoding="utf-8", errors="replace")
lines = text.splitlines()
if not lines or lines[0].strip() != "---":
return {}
end_index = None
for idx in range(1, len(lines)):
if lines[idx].strip() == "---":
end_index = idx
break
if end_index is None:
return {}
data: dict = {}
frontmatter = lines[1:end_index]
i = 0
while i < len(frontmatter):
line = frontmatter[i]
stripped = line.strip()
if not stripped or stripped.startswith("#") or line.startswith((" ", "\t")):
i += 1
continue
if ":" not in line:
i += 1
continue
key, raw_value = line.split(":", 1)
key = key.strip()
value = raw_value.strip()
if not key:
i += 1
continue
if value in {"|", ">"}:
block_lines: list[str] = []
i += 1
while i < len(frontmatter):
block_line = frontmatter[i]
if block_line.strip() and not block_line.startswith((" ", "\t")):
break
block_lines.append(block_line[2:] if block_line.startswith(" ") else block_line.lstrip())
i += 1
data[key] = "\n".join(block_lines).rstrip()
continue
if value == "":
items: list = []
i += 1
while i < len(frontmatter):
item_line = frontmatter[i]
if item_line.strip() and not item_line.startswith((" ", "\t")):
break
item_stripped = item_line.strip()
if item_stripped.startswith("- "):
items.append(_parse_frontmatter_scalar(item_stripped[2:]))
i += 1
data[key] = items if items else ""
continue
data[key] = _parse_frontmatter_scalar(value)
i += 1
return data
def _agent_profile_candidates(profile_id: str, git_root: Path | None = None) -> list[Path]:
"""Return profile lookup candidates in project-first order."""
slug = _normalize_agent_profile_id(profile_id)
candidates: list[Path] = []
if git_root:
candidates.extend(
[
git_root / ".github" / "agents" / f"{slug}.agent.md",
git_root / ".github" / "agents" / f"{slug}.md",
]
)
candidates.extend(
[
AGENT_PROFILE_REFERENCE_DIR / f"{slug}.agent.md",
AGENT_PROFILE_REFERENCE_DIR / f"{slug}.md",
]
)
return candidates
def _load_agent_profile(profile_id: str, git_root: Path | None = None) -> dict:
"""Load a project or bundled agent profile from .agent.md frontmatter."""
slug = _normalize_agent_profile_id(profile_id)
candidates = _agent_profile_candidates(slug, git_root)
for candidate in candidates:
if not candidate.is_file():
continue
profile = _parse_agent_frontmatter(candidate)
if not profile:
raise ValueError(f"Agent profile file has no YAML frontmatter: {candidate}")
profile["profile_id"] = str(profile.get("profile_id") or slug)
profile["role"] = str(profile.get("role") or profile.get("name") or profile["profile_id"])
profile["agent_type"] = str(profile.get("agent_type") or profile["profile_id"])
profile["profile_path"] = str(candidate)
return profile
searched = ", ".join(str(path) for path in candidates)
raise FileNotFoundError(f"Agent profile '{slug}' not found. Searched: {searched}")
def _agent_profile_meta(profile: dict) -> dict:
"""Return the JSON-safe subset stored in tentacle meta.json."""
allowed = (
"profile_id",
"name",
"role",
"goal",
"domain",
"expertise",
"triggers",
"quality_gates",
"escalation_rules",
"anti_patterns",
"evidence_required",
"tools_denied",
"model",
"model_tier",
"agent_type",
"profile_path",
)
return {key: profile[key] for key in allowed if key in profile and profile[key] not in ("", [], None)}
def _resolve_agent_profile_from_meta(meta: dict) -> dict:
"""Resolve an embedded or referenced profile from tentacle metadata."""
embedded = meta.get("agent_profile")
if isinstance(embedded, dict) and embedded.get("profile_id"):
profile = dict(embedded)
profile["profile_id"] = str(profile["profile_id"])
profile["role"] = str(profile.get("role") or profile.get("name") or profile["profile_id"])
profile["agent_type"] = str(profile.get("agent_type") or profile["profile_id"])
return profile
profile_id = meta.get("agent_profile_id")
if profile_id:
return _load_agent_profile(str(profile_id), _runtime_find_git_root())
return {}
def _profile_list(profile: dict, key: str) -> list[str]:
"""Return a profile field as a clean list of strings."""
value = profile.get(key)
if isinstance(value, list):
return [str(item).strip() for item in value if str(item).strip()]
if isinstance(value, str):
lines = []
for raw_line in value.splitlines():
line = raw_line.strip()
if line.startswith("- "):
line = line[2:].strip()
if line:
lines.append(line)
return lines
return []
def _render_profile_list(title: str, items: list[str], *, limit: int | None = None) -> list[str]:
"""Render a titled bullet list when profile data is present."""
if not items:
return []
shown = items[:limit] if limit else items
lines = [f"### {title}", ""]
lines.extend(f"- {item}" for item in shown)
if limit and len(items) > limit:
lines.append(f"- ... plus {len(items) - limit} more")
lines.append("")
return lines
def _render_agent_profile_section(profile: dict | None, *, prompt: bool = False) -> str:
"""Render a specialist profile section for CONTEXT.md or dispatch prompts."""
if not profile:
return ""
heading = "### Specialist Profile" if prompt else "## Agent Profile"
lines = [heading, ""]
profile_id = profile.get("profile_id")
role = profile.get("role") or profile.get("name")
if profile_id:
lines.append(f"**Profile:** `{profile_id}`")
if role:
lines.append(f"**Role:** {role}")
if profile.get("domain"):
lines.append(f"**Domain:** {profile['domain']}")
if profile.get("model_tier") or profile.get("model"):
model_bits = []
if profile.get("model_tier"):
model_bits.append(f"tier `{profile['model_tier']}`")
if profile.get("model"):
model_bits.append(f"model `{profile['model']}`")
lines.append(f"**Runtime preference:** {', '.join(model_bits)}")
if profile.get("goal"):
goal = " ".join(str(profile["goal"]).split()) if prompt else str(profile["goal"]).strip()
lines.append("")
lines.append("**Goal:**")
lines.append(goal)
lines.append("")
list_limit = 6 if prompt else None
lines.extend(_render_profile_list("Expertise", _profile_list(profile, "expertise"), limit=list_limit))
lines.extend(_render_profile_list("Lifecycle Triggers", _profile_list(profile, "triggers"), limit=list_limit))
lines.extend(_render_profile_list("Quality Gates", _profile_list(profile, "quality_gates"), limit=list_limit))
lines.extend(_render_profile_list("Escalation Rules", _profile_list(profile, "escalation_rules"), limit=list_limit))
lines.extend(_render_profile_list("Anti-patterns", _profile_list(profile, "anti_patterns"), limit=list_limit))
lines.extend(
_render_profile_list(
"Evidence Required in Handoff", _profile_list(profile, "evidence_required"), limit=list_limit
)
)
lines.extend(_render_profile_list("Tools Denied", _profile_list(profile, "tools_denied"), limit=list_limit))
return "\n" + "\n".join(lines).rstrip() + "\n"
def _scope_items(meta: dict) -> list[str]:
raw_scope = meta.get("scope") or []
if isinstance(raw_scope, str):
return [raw_scope.strip()] if raw_scope.strip() else []
elif isinstance(raw_scope, list):
return [str(item) for item in raw_scope if str(item).strip()]
return []
def _scope_summary(meta: dict) -> str:
items = _scope_items(meta)
return ", ".join(items[:6]) if items else "See bundle/session-metadata.md"
def _context_excerpt(context: str, limit: int = 180) -> str:
lines = [line.strip() for line in context.splitlines() if line.strip()]
if not lines:
return "See bundle/session-metadata.md"
text = " ".join(lines)
if len(text) <= limit:
return text
return text[: limit - 1].rstrip() + "…"
def _render_dispatch_context(context: str, meta: dict, bundle_dir: Path | None) -> str:
"""Render token-lean context for dispatch prompts.
With a bundle, the file-backed artifact is authoritative; keep the inline
prompt small so sub-agents spend tokens on code, not duplicated context.
"""
if not bundle_dir:
return context.strip()
return textwrap.dedent(f"""\
Runtime bundle is authoritative; inline context is intentionally minimal.
Read first:
1. `{bundle_dir}/context-packet.md` ← unified context packet
2. `{bundle_dir}/manifest.json`
3. `{bundle_dir}/session-metadata.md`
4. `{bundle_dir}/recall-pack.json`
5. `{bundle_dir}/instructions.md` and relevant source files
Scope: {_scope_summary(meta)}
Context excerpt: {_context_excerpt(context)}
""").strip()
def _render_dispatch_live_briefing_section(briefing_text: str, *, bundled: bool) -> str:
"""Render the live-briefing section for bundled vs inline dispatch modes."""
if not briefing_text:
return ""
if bundled:
return "\n### Live Knowledge\n\nBundled in `briefing.md` and `recall-pack.json`; read those before editing.\n"
return f"\n{briefing_text}\n"
def _dispatch_context_mode(bundle_dir: Path | None) -> dict:
"""Describe the active dispatch mode in a JSON-safe structure."""
if bundle_dir is not None:
return {
"name": POINTER_DISPATCH_MODE_NAME,
"summary": "Pointer-based bundle (default)",
"details": (
"Read the Bundle Path files as authoritative context instead of duplicating the "
"full tentacle context inline."
),
"fallback_flag": "--no-bundle",
"default": True,
}
return {
"name": FULL_CONTEXT_DISPATCH_MODE_NAME,
"summary": "Full-context inline fallback (`--no-bundle`)",
"details": (
"This run duplicates the full tentacle context inline because the pointer-based bundle was disabled."
),
"fallback_flag": "--no-bundle",
"default": False,
}
def _render_dispatch_mode_section(mode: dict) -> str:
"""Render a human-readable dispatch-mode section for prompts."""
return textwrap.dedent(f"""\
### Dispatch Mode
**{mode["summary"]}**
{mode["details"]}
""")
def _render_swarm_prompt(
name: str,
pending: list[dict],
context_for_prompt: str,
*,
specialist_profile_section: str = "",
live_briefing_section: str = "",
dispatch_mode_section: str = "",
prompt_size_section: str = "",
bundle_section: str = "",
worktree_section: str = "",
) -> str:
"""Render the single-agent swarm/dispatch prompt."""
prompt = f"""## Tentacle: {name}
### Context
{context_for_prompt}
{specialist_profile_section}{live_briefing_section}{dispatch_mode_section}{prompt_size_section}{bundle_section}{worktree_section}
### Your Tasks (complete ALL)
"""
for t in pending:
prompt += f"- [ ] {t['text']}\n"
prompt += f"""
### Rules
- Complete all tasks above
- If a Bundle Path is present, read `manifest.json` first and use the bundle files as authoritative context
- Stay within the scoped files only — DO NOT modify files outside your declared scope
- **DO NOT run `git commit` or `git push`** — the orchestrator owns all git operations
- **DO NOT widen your scope** beyond the files listed above without explicit escalation to the orchestrator
- If a task cannot be completed within your scope, stop that task and write a scope escalation note to handoff before continuing
### Cross-review (required before handoff)
Before writing the handoff, do a self-cross-review:
1. Re-read every file you modified and confirm correctness against the task description
2. Verify no unintended changes outside your declared scope
3. Confirm all todos are complete or explicitly documented as blocked/escalated
### When done
Mark each completed todo:
`python3 ~/.copilot/tools/tentacle.py todo "{name}" done <index>`
Write a structured handoff with status and changed-file receipts:
`python3 ~/.copilot/tools/tentacle.py handoff "{name}" "<summary>" --status DONE --changed-file <file1> --changed-file <file2> --learn`
Status values: `DONE` (all tasks complete) | `BLOCKED` (external dependency) | `TOO_BIG` (scope too wide) | `AMBIGUOUS` (spec unclear) | `REGRESSED` (tests broke)
Add `--changed-file <path>` once per modified file. Omit if no files changed (e.g. BLOCKED with no edits).
"""
return prompt
def _dispatch_prompt_size_stats(
name: str,
pending: list[dict],
context: str,
meta: dict,
*,
bundled_live_briefing_section: str,
inline_live_briefing_section: str,
worktree_section: str,
bundle_dir: Path | None,
bundle_section: str,
agent_profile: dict | None = None,
) -> dict:
"""Compare pointer-mode prompt size against the full-context fallback."""
specialist_profile_section = _render_agent_profile_section(agent_profile, prompt=True)
full_context_prompt = _render_swarm_prompt(
name,
pending,
_render_dispatch_context(context, meta, None),
specialist_profile_section=specialist_profile_section,
live_briefing_section=inline_live_briefing_section,
worktree_section=worktree_section,
)
if bundle_dir is None:
return {
"comparison_available": False,
"active_prompt_chars": len(full_context_prompt),
"full_context_prompt_chars": len(full_context_prompt),
"reduction_vs_full_context_percent": 0.0,
"minimum_reduction_percent": POINTER_PROMPT_REDUCTION_TARGET_PERCENT,
"meets_minimum_reduction": None,
}
pointer_prompt = _render_swarm_prompt(
name,
pending,
_render_dispatch_context(context, meta, bundle_dir),
specialist_profile_section=specialist_profile_section,
live_briefing_section=bundled_live_briefing_section,
bundle_section=bundle_section,
worktree_section=worktree_section,
)
full_chars = max(len(full_context_prompt), 1)
reduction = round(max(0.0, (1 - (len(pointer_prompt) / full_chars)) * 100), 1)
return {
"comparison_available": True,
"active_prompt_chars": len(pointer_prompt),
"full_context_prompt_chars": len(full_context_prompt),
"reduction_vs_full_context_percent": reduction,
"minimum_reduction_percent": POINTER_PROMPT_REDUCTION_TARGET_PERCENT,
"meets_minimum_reduction": reduction >= POINTER_PROMPT_REDUCTION_TARGET_PERCENT,
}
def _render_dispatch_prompt_size_section(prompt_size: dict) -> str:
"""Render prompt-size evidence for dispatch prompts."""
if prompt_size.get("comparison_available"):
meets = "YES" if prompt_size.get("meets_minimum_reduction") else "NO"
return textwrap.dedent(f"""\
### Prompt Size
- Active prompt chars: `{prompt_size["active_prompt_chars"]}`
- Full-context fallback chars: `{prompt_size["full_context_prompt_chars"]}`
- Reduction vs full-context: `{prompt_size["reduction_vs_full_context_percent"]:.1f}%` (target: `>= {prompt_size["minimum_reduction_percent"]:.1f}%`)
- Meets target: `{meets}`
""")
return textwrap.dedent(f"""\
### Prompt Size
- Active prompt chars: `{prompt_size["active_prompt_chars"]}`
- Comparison inactive: this run is the full-context inline fallback.
""")
# ---------------------------------------------------------------------------
# SEAM: dispatch-bundle context packet helpers
# ---------------------------------------------------------------------------
_DEFAULT_CONTEXT_PACKET_TEMPLATE = """\
# Context Packet: {{tentacle_name}}
## Tentacle / Scope / Iteration Header
- **Tentacle:** {{tentacle_name}}
- **Scope:** {{scope}}
- **Iteration:** {{iteration}}
- **Status:** {{status}}
## Task Description
{{task_description}}
## Goal Context
{{goal_context}}
## Previous Handoffs
{{previous_handoffs}}
## Project Conventions
{{project_conventions}}
## Recall Pack
{{recall_pack}}
## Blocker Context
{{blocker_context}}
"""
def _apply_context_packet_template(template: str, subs: dict) -> str:
"""Replace {{key}} markers in *template* with values from *subs*.
Unknown keys are left as-is so custom templates with extra markers do not
crash. Uses a regex replace to avoid conflicts with Python f-string braces
that might appear in literal template content.
"""
def _replacer(m: re.Match) -> str:
return subs.get(m.group(1), m.group(0))
return re.sub(r"\{\{(\w+)\}\}", _replacer, template)
def _load_context_packet_template(git_root: "Path | None") -> str:
"""Load the project-level context-packet template if present.
Looks for ``.github/context-packet-template.md`` under *git_root*.
Falls back to ``_DEFAULT_CONTEXT_PACKET_TEMPLATE`` when the file is
absent or unreadable.
"""
if git_root:
override = git_root / ".github" / "context-packet-template.md"
if override.is_file():
try:
return override.read_text(encoding="utf-8", errors="replace")
except OSError:
pass
return _DEFAULT_CONTEXT_PACKET_TEMPLATE
def _blocker_context_from_meta(meta: dict, tentacle_dir: Path) -> str:
"""Return substantive blocker context when the latest handoff is non-DONE terminal.
Returns a stable ``None`` placeholder otherwise so the packet is
deterministic regardless of run order.
"""
terminal_status = meta.get("terminal_status")
if terminal_status not in _runtime_HANDOFF_TRIAGE_STATUSES:
return "None"
handoff_path = tentacle_dir / "handoff.md"
if not handoff_path.is_file():
return f"STATUS: {terminal_status} (see handoff.md — file not present)"
try:
text = handoff_path.read_text(encoding="utf-8", errors="replace").strip()
return text[:600] if len(text) > 600 else text
except OSError:
return f"STATUS: {terminal_status} (handoff.md unreadable)"
def _project_conventions_summary(instr_paths: "list[str]") -> str:
"""Summarize available instruction sources for the context packet."""
if not instr_paths:
return "No project instruction files detected.\nSee `bundle/briefing.md` for session-knowledge guidance."
shown = instr_paths[:6]
lines = [f"- Sources: {', '.join(shown)}"]
if len(instr_paths) > len(shown):
lines.append(f"- Additional instruction files: {len(instr_paths) - len(shown)}")
lines.append("- Full excerpts: `bundle/instructions.md`")
lines.append("- Session knowledge: `bundle/briefing.md`")
return "\n".join(lines)
def _recall_pack_summary(recall_pack_data: "dict | None", recall_source_mode: str | None) -> str:
"""Summarize the machine-readable recall pack for the context packet."""
if not recall_pack_data:
return "None — no recall pack data available."
lines: list[str] = []
if recall_source_mode:
lines.append(f"- Source mode: {recall_source_mode}")
tagged = recall_pack_data.get("tagged_entries")
if isinstance(tagged, list) and tagged:
lines.append(f"- Tagged entries: {len(tagged)}")
related = recall_pack_data.get("related_entries")
if isinstance(related, list) and related:
lines.append(f"- Related entries: {len(related)}")
entries = recall_pack_data.get("entries")
if isinstance(entries, dict):
populated = []
for key, value in entries.items():
if isinstance(value, list) and value:
populated.append(f"{key}={len(value)}")
if populated:
lines.append(f"- Entry buckets: {', '.join(populated[:6])}")
file_matches = recall_pack_data.get("file_matches")
if isinstance(file_matches, list) and file_matches:
lines.append(f"- File matches: {len(file_matches)}")
lines.append("- Full payload: `bundle/recall-pack.json`")
return "\n".join(lines)
def _build_context_packet(
name: str,
meta: dict,
tentacle_dir: Path,
context_text: str,
goal_context_text: str,
prior_handoffs: "list[dict]",
recall_pack_data: "dict | None",
recall_source_mode: str | None,
instr_paths: "list[str]",
git_root: "Path | None",
) -> str:
"""Render the context-packet.md content for a tentacle bundle.
Uses the project-level template when present
(``.github/context-packet-template.md``), falling back to the built-in
default. All substitution keys use ``{{variable_name}}`` markers so they
do not clash with Python f-string syntax.
"""
template = _load_context_packet_template(git_root)
# ── substitutions ────────────────────────────────────────────────────────
scope_str = _scope_summary(meta)