opencode-agent-harness 0.0.0-stage → 0.3.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +217 -0
- package/LICENSE +21 -0
- package/README.md +636 -2
- package/bin/agent-harness.js +3182 -0
- package/contrib/global-plugins/README.md +49 -0
- package/contrib/global-plugins/harness-freshness.ts +355 -0
- package/package.json +86 -4
- package/templates/.agents/AGENTS.md +148 -0
- package/templates/.agents/features/INDEX.md +10 -0
- package/templates/.agents/handoffs/README.md +87 -0
- package/templates/.agents/memory/dev-loop.md +59 -0
- package/templates/.agents/memory/domain-map.md +29 -0
- package/templates/.agents/memory/environments.md +35 -0
- package/templates/.agents/memory/flow-map.md +23 -0
- package/templates/.agents/memory/history.md +7 -0
- package/templates/.agents/memory/locations.md +14 -0
- package/templates/.agents/memory/model-routing.md +261 -0
- package/templates/.agents/memory/orchestration.md +183 -0
- package/templates/.agents/memory/owned-files.md +19 -0
- package/templates/.agents/memory/product-principles.md +37 -0
- package/templates/.agents/memory/quality-parameters.md +37 -0
- package/templates/.agents/memory/stack-versions.md +35 -0
- package/templates/.agents/memory/test-design-parameters.md +36 -0
- package/templates/.agents/nightly.json +17 -0
- package/templates/.agents/qa-plans/README.md +70 -0
- package/templates/.agents/qa-runs/README.md +21 -0
- package/templates/.agents/reviews/README.md +47 -0
- package/templates/.agents/rules/00-operating.md +199 -0
- package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
- package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
- package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
- package/templates/.agents/skills/docs/SKILL.md +140 -0
- package/templates/.agents/skills/features/SKILL.md +187 -0
- package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
- package/templates/.agents/skills/handoff/SKILL.md +85 -0
- package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
- package/templates/.agents/skills/planner/SKILL.md +112 -0
- package/templates/.agents/skills/product-manager/SKILL.md +115 -0
- package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
- package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
- package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
- package/templates/.agents/skills/system-architect/SKILL.md +42 -0
- package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
- package/templates/.github/workflows/ci.yml +148 -0
- package/templates/.github/workflows/deploy-uat.yml +95 -0
- package/templates/.github/workflows/nightly.yml +83 -0
- package/templates/.github/workflows/uat-health.yml +41 -0
- package/templates/.husky/pre-push +23 -0
- package/templates/.ignore +28 -0
- package/templates/.opencode/agents/data-engineer.md +37 -0
- package/templates/.opencode/agents/devops-engineer.md +37 -0
- package/templates/.opencode/agents/diagnostics-expert.md +37 -0
- package/templates/.opencode/agents/docs.md +37 -0
- package/templates/.opencode/agents/features.md +21 -0
- package/templates/.opencode/agents/frontend-engineer.md +37 -0
- package/templates/.opencode/agents/handoff.md +21 -0
- package/templates/.opencode/agents/mobile-engineer.md +37 -0
- package/templates/.opencode/agents/planner.md +34 -0
- package/templates/.opencode/agents/product-manager.md +29 -0
- package/templates/.opencode/agents/qa-architect.md +27 -0
- package/templates/.opencode/agents/qa-runner.md +17 -0
- package/templates/.opencode/agents/security-engineer.md +37 -0
- package/templates/.opencode/agents/system-architect.md +37 -0
- package/templates/.opencode/agents/ui-designer.md +37 -0
- package/templates/.opencode/commands/board.md +15 -0
- package/templates/.opencode/commands/checkpoint.md +25 -0
- package/templates/.opencode/commands/feature.md +56 -0
- package/templates/.opencode/commands/finish.md +36 -0
- package/templates/.opencode/commands/next.md +49 -0
- package/templates/.opencode/commands/report.md +55 -0
- package/templates/.opencode/commands/resume.md +39 -0
- package/templates/.opencode/commands/switch-model.md +34 -0
- package/templates/.opencode/commands/tidy.md +49 -0
- package/templates/.opencode/plugins/backlog-notify.ts +57 -0
- package/templates/.opencode/plugins/backlog.ts +272 -0
- package/templates/.opencode/plugins/checkpoint.ts +160 -0
- package/templates/.opencode/plugins/context-guard.ts +1164 -0
- package/templates/.opencode/plugins/diff.ts +85 -0
- package/templates/.opencode/plugins/gates.ts +71 -0
- package/templates/.opencode/plugins/job-notify.ts +241 -0
- package/templates/.opencode/plugins/orient.ts +67 -0
- package/templates/.opencode/plugins/session.ts +89 -0
- package/templates/.opencode/plugins/wait.ts +101 -0
- package/templates/.opencode/plugins/where.ts +70 -0
- package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
- package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
- package/templates/.vercelignore +16 -0
- package/templates/AGENTS.md +27 -0
- package/templates/BACKLOG.md +95 -0
- package/templates/docs/ci-cd-pipeline.md +81 -0
- package/templates/docs/gates.md +128 -0
- package/templates/docs/mcp-integrations.md +97 -0
- package/templates/docs/mobile-testing.md +555 -0
- package/templates/docs/nightly-testing.md +106 -0
- package/templates/docs/wsl-optimizations.md +290 -0
- package/templates/opencode.json +188 -0
- package/templates/scripts/agent-report.js +541 -0
- package/templates/scripts/agent-search.sh +117 -0
- package/templates/scripts/backlog.js +1924 -0
- package/templates/scripts/board-service.sh +214 -0
- package/templates/scripts/checkpoint.js +290 -0
- package/templates/scripts/finalize.js +416 -0
- package/templates/scripts/nightly.js +913 -0
- package/templates/scripts/orient.js +514 -0
- package/templates/scripts/qa/board-client.js +323 -0
- package/templates/scripts/qa/board-lib.js +96 -0
- package/templates/scripts/qa/board-sync.js +499 -0
- package/templates/scripts/qa/capacity-lib.js +916 -0
- package/templates/scripts/qa/check-backlog.js +434 -0
- package/templates/scripts/qa/check-capacity.js +85 -0
- package/templates/scripts/qa/check-ci-policy.js +164 -0
- package/templates/scripts/qa/check-concurrency.js +344 -0
- package/templates/scripts/qa/check-dispatch-config.js +296 -0
- package/templates/scripts/qa/check-docs.js +288 -0
- package/templates/scripts/qa/check-integrate.js +98 -0
- package/templates/scripts/qa/check-linger.js +160 -0
- package/templates/scripts/qa/check-prefix-stability.js +187 -0
- package/templates/scripts/qa/check-product.js +177 -0
- package/templates/scripts/qa/check-qa-plan.js +378 -0
- package/templates/scripts/qa/check-qa-scripts.js +85 -0
- package/templates/scripts/qa/check-quality.js +249 -0
- package/templates/scripts/qa/check-test-wiring.js +253 -0
- package/templates/scripts/qa/check-worktrees.js +93 -0
- package/templates/scripts/qa/ci-triage.js +346 -0
- package/templates/scripts/qa/ci-usage-lib.js +185 -0
- package/templates/scripts/qa/ci-wait-lib.js +294 -0
- package/templates/scripts/qa/command-classifier.js +552 -0
- package/templates/scripts/qa/context-guard-core.js +1618 -0
- package/templates/scripts/qa/diff.js +174 -0
- package/templates/scripts/qa/feature-scaffold.js +224 -0
- package/templates/scripts/qa/fixtures/backlog.md +104 -0
- package/templates/scripts/qa/governance.js +174 -0
- package/templates/scripts/qa/hash-file.js +32 -0
- package/templates/scripts/qa/lease-lib.js +263 -0
- package/templates/scripts/qa/merge-backlog.js +324 -0
- package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
- package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
- package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
- package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
- package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
- package/templates/scripts/qa/mobile-e2e/check-flows.js +568 -0
- package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
- package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
- package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
- package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
- package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
- package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
- package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
- package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
- package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
- package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
- package/templates/scripts/qa/models.allowlist.txt +32 -0
- package/templates/scripts/qa/provider-stats.js +878 -0
- package/templates/scripts/qa/run-clean.js +83 -0
- package/templates/scripts/qa/run-gates.js +213 -0
- package/templates/scripts/qa/run-loop.js +220 -0
- package/templates/scripts/qa/session-recon.js +512 -0
- package/templates/scripts/qa/store-lib.js +324 -0
- package/templates/scripts/qa/tool-lib.js +134 -0
- package/templates/scripts/qa/where.js +214 -0
- package/templates/scripts/qa/worktree-hygiene.js +217 -0
- package/templates/scripts/qa/wslconfig-merge.js +157 -0
- package/templates/scripts/serve.js +1328 -0
- package/templates/scripts/setup-nightly.sh +185 -0
- package/templates/scripts/setup-tmpfs.sh +374 -0
- package/templates/scripts/ship.js +586 -0
- package/templates/scripts/switch-reasoning-model.ps1 +101 -0
- package/templates/scripts/switch-reasoning-model.sh +104 -0
- package/templates/scripts/wait-for.js +342 -0
- package/templates/scripts/wsl-gpu.sh +180 -0
- package/templates/scripts/wsl-tune.sh +319 -0
|
@@ -0,0 +1,1618 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/* Context-guard core — pure, dependency-free state machine backing the
|
|
4
|
+
* `.opencode/plugins/context-guard.ts` plugin. Kept separate from the plugin so
|
|
5
|
+
* every rule is unit-testable with `node:test` (threshold parsing, band
|
|
6
|
+
* transitions, loop counting, byte-stable injected text, guard-event JSONL).
|
|
7
|
+
*
|
|
8
|
+
* The plugin owns all IO (files, opencode client); this module owns no globals
|
|
9
|
+
* and mutates only the state object it is handed. Thresholds are never
|
|
10
|
+
* hardcoded here as runtime truth: `parseThresholds` reads the project-owned
|
|
11
|
+
* `.agents/memory/orchestration.md` and falls back to the documented defaults.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const DEFAULT_TURNS = Object.freeze({
|
|
15
|
+
checkpoint_warning_turn: 50,
|
|
16
|
+
soft_turn_budget: 60,
|
|
17
|
+
compaction_target_turn: 60,
|
|
18
|
+
new_context_preference_turn: 80,
|
|
19
|
+
hard_safety_turn_limit: 100,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const DEFAULT_STUCK = Object.freeze({
|
|
23
|
+
same_failure_turns: 3,
|
|
24
|
+
identical_tool_calls: 3,
|
|
25
|
+
no_state_change_turns: 4,
|
|
26
|
+
// Startup grace (the 2026-10-16 field review): a session's first steps are
|
|
27
|
+
// orientation (reads/greps/shell), so the no-state nudge fired at turn 5 in
|
|
28
|
+
// 78/143 sessions before any code existed to change. Do not count a turn
|
|
29
|
+
// toward `no_state_change_turns` until the session is past this many turns.
|
|
30
|
+
no_state_grace_turns: 8,
|
|
31
|
+
inspect_rearm_every: 10,
|
|
32
|
+
gate_rerun_turns: 3,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const DEFAULT_REQUEST = Object.freeze({
|
|
36
|
+
observe: 50000,
|
|
37
|
+
warn: 80000,
|
|
38
|
+
checkpoint: 120000,
|
|
39
|
+
intervene: 160000,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/* Todo-list discipline. opencode's right-hand panel is driven ONLY by the
|
|
43
|
+
* built-in `todowrite` tool, so a session that never calls it shows no panel and
|
|
44
|
+
* one that calls it once shows a stale list. The guard cannot write the panel
|
|
45
|
+
* itself (the V2 plugin API exposes no todo store), so it nudges the two
|
|
46
|
+
* mechanical gaps the model leaves:
|
|
47
|
+
* - `use_after_calls`: enough material tool calls have run that the work is
|
|
48
|
+
* clearly multi-step, yet no todo list has ever been written;
|
|
49
|
+
* - `stale_after_calls`: a list exists but N material calls have run since its
|
|
50
|
+
* last rewrite (the panel is behind the work).
|
|
51
|
+
* Thresholds are material-call counts, not turns, so a long tool loop between
|
|
52
|
+
* two model steps still triggers. */
|
|
53
|
+
const DEFAULT_TODO = Object.freeze({
|
|
54
|
+
use_after_calls: 4,
|
|
55
|
+
stale_after_calls: 3,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
/* Band order is resolved by threshold VALUE (descending), not by a fixed list,
|
|
59
|
+
* so a project can retune `orchestration.md` without breaking the guard:
|
|
60
|
+
* `turnBand` returns the highest band the turn count has reached. */
|
|
61
|
+
const TURN_BANDS = [
|
|
62
|
+
["hard_safety_turn_limit", "hard"],
|
|
63
|
+
["new_context_preference_turn", "new-context"],
|
|
64
|
+
["compaction_target_turn", "checkpoint"],
|
|
65
|
+
["checkpoint_warning_turn", "warning"],
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
/* Severity order for combining signals. A band is "higher" when its rank is
|
|
69
|
+
* greater, so the strongest pressure — turn count OR request context — wins. */
|
|
70
|
+
const BAND_RANK = Object.freeze({ warning: 1, checkpoint: 2, "new-context": 3, hard: 4 });
|
|
71
|
+
|
|
72
|
+
const REQUEST_LEVELS = ["observe", "warn", "checkpoint", "intervene"];
|
|
73
|
+
|
|
74
|
+
/* Request-context pressure mapped onto the SAME bands as turns, so the nudge
|
|
75
|
+
* text is driven by whichever signal is louder. Turn count is a coarse proxy for
|
|
76
|
+
* transcript growth; request context is the real cost driver (~97% cache reads,
|
|
77
|
+
* so cost ≈ Σ context × turns). `observe` is telemetry only. */
|
|
78
|
+
const REQUEST_BAND = Object.freeze({
|
|
79
|
+
observe: null,
|
|
80
|
+
warn: "warning",
|
|
81
|
+
checkpoint: "checkpoint",
|
|
82
|
+
intervene: "new-context",
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
/* Injected text is CONSTANT per band — never interpolated with the turn count —
|
|
86
|
+
* so the appended system tail stays byte-stable and cache-friendly (the guard
|
|
87
|
+
* must not turn every request into a fresh cache write). */
|
|
88
|
+
const BAND_TEXT = Object.freeze({
|
|
89
|
+
warning:
|
|
90
|
+
"CONTEXT GUARD — checkpoint warning (ADVISORY, not a stop): the orchestrator is approaching its turn/context budget (`checkpoint_warning_turn` and the request-token levels in `.agents/memory/orchestration.md`). Keep working: finish the current phase step and continue the task — do NOT stop mid-phase or ask for permission to continue. Write ONE compact deterministic checkpoint to `.agents/handoffs/<feature-id>.md` at the next natural phase boundary. FINALIZATION CARVE-OUT: if implementation + verification are complete and only the finalization tail remains (docs/CHANGELOG, archive, commit, land, confirm CI), do NOT stop — run `npm run finalize -- --feature <id>` ONCE and let it run to completion; that single call archives, commits, lands the branch directly on main, and confirms green CI (the deploy runs after CI).",
|
|
91
|
+
checkpoint:
|
|
92
|
+
"CONTEXT GUARD — soft turn budget reached: checkpoint ONCE now — task id/feature/objective/phase, completed and active dispatches, files changed, contracts, known facts, decisions, risks, next_action — into `.agents/handoffs/<feature-id>.md`, then STOP this transcript at the current phase boundary; a fresh bounded context resumes from the checkpoint. Do not begin the next phase here, and do not write a second checkpoint in this transcript. FINALIZATION CARVE-OUT: if implementation + verification are complete and only the finalization tail remains (docs/CHANGELOG, archive, commit, land, confirm CI), do NOT stop — run `npm run finalize -- --feature <id>` ONCE and let it run to completion; that single call archives, commits, lands the branch directly on main, and confirms green CI (the deploy runs after CI).",
|
|
93
|
+
"new-context":
|
|
94
|
+
"CONTEXT GUARD — strong new-context preference: do not keep growing this transcript. Checkpoint once now, then continue only in a fresh bounded context that reads the checkpoint plus the current task — never the replayed transcript. If only the finalization tail remains, run `npm run finalize -- --feature <id>` once instead of stopping — it archives, commits, lands directly on main, and confirms CI.",
|
|
95
|
+
hard:
|
|
96
|
+
"CONTEXT GUARD — hard safety ceiling reached: stop starting new work, checkpoint once, and finish. A running tool call still completes — never kill it mid-operation. FINALIZATION CARVE-OUT: if only the finalization tail remains, run `npm run finalize -- --feature <id>` once and allow it to finish — it archives, commits, lands the branch directly on main, and confirms green CI. A landed change is a completed one; a red or unconfirmed CI is the blocker to record.",
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
/* Provenance banner prepended to every injected block. The guard is delivered as
|
|
100
|
+
* a synthetic user-role message (the only shape opencode forwards from the
|
|
101
|
+
* messages transform), so without an explicit banner the model can mistake the
|
|
102
|
+
* nudge for the human speaking. LibraryOS F-259: the model read the no-state
|
|
103
|
+
* nudge as "the user is asking for a status update" and stopped to ask for
|
|
104
|
+
* permission the `/next` command had already granted. Constant text, so the
|
|
105
|
+
* cached prefix stays byte-stable. */
|
|
106
|
+
const GUARD_PROVENANCE =
|
|
107
|
+
"AUTOMATED HARNESS NUDGE — this is NOT a user message and NOT a user request. It is mechanical context-budget guidance from the agent harness. Keep executing the current task; the real user's explicit instruction takes precedence over this nudge except at the hard safety ceiling.";
|
|
108
|
+
|
|
109
|
+
const LOOP_TEXT =
|
|
110
|
+
"CONTEXT GUARD — repeated identical tool call detected (`identical_tool_calls` in `.agents/memory/orchestration.md`). Do not repeat it again: change instructions, context, model, decomposition, or diagnostics — or report the blocker. A retry must materially change something.";
|
|
111
|
+
|
|
112
|
+
/* No-material-progress nudge. The F-256 pause showed the orchestrator writing
|
|
113
|
+
* five checkpoints while warned and then stopping mid-phase; a checkpoint with
|
|
114
|
+
* no code/state change is not progress. Armed when whole turns pass with no
|
|
115
|
+
* file/state mutation (`no_state_change_turns`). */
|
|
116
|
+
const NO_STATE_TEXT =
|
|
117
|
+
"CONTEXT GUARD — no material state change detected across several turns (`no_state_change_turns` in `.agents/memory/orchestration.md`). Stop re-reading or re-checkpointing and make a materially changing action NOW: edit code, run the failing gate with NEW diagnostics, change the decomposition/model, or gather new runtime evidence (a DB query, a runtime probe, a live reproduction) — investigation that produces new facts counts as progress. Continue the task; do not stop or ask for permission. Another checkpoint with no state change is not progress.";
|
|
118
|
+
|
|
119
|
+
/* Same-failure nudge. Distinct from `identical_tool_calls`: the failure is the
|
|
120
|
+
* same even when the arguments differ. Armed when the same failure signature
|
|
121
|
+
* repeats across tool calls (`same_failure_turns`). */
|
|
122
|
+
const FAILURE_TEXT =
|
|
123
|
+
"CONTEXT GUARD — the same failure is repeating (`same_failure_turns` in `.agents/memory/orchestration.md`). Do not retry the identical action: change instructions, context, model, decomposition, or diagnostics — or report the blocker. A second attempt must materially change something.";
|
|
124
|
+
|
|
125
|
+
/* Provider funds/quota failures are a hard stop in `.agents/memory/model-routing.md`:
|
|
126
|
+
* the harness must pause and wait for the user's top-up instead of degrading
|
|
127
|
+
* inline. The regex is deliberately narrow (balance/funds/credits/limits/402) so
|
|
128
|
+
* ordinary task failures never trigger the stop. */
|
|
129
|
+
const FUNDS_RE =
|
|
130
|
+
/insufficient (?:balance|funds|credits?)|out of (?:credits?|funds)|credit balance|(?:usage|quota) (?:limit|exceeded)|exceeded your (?:usage|quota)|payment required|status(?:Code)?["'\s:]*402/i;
|
|
131
|
+
|
|
132
|
+
/* The failure label is the concrete account to top up (`opencode/gpt-5.6-luna`,
|
|
133
|
+
* `deepseek/deepseek-v4-pro`), taken from the observed dispatch metadata — never
|
|
134
|
+
* guessed. `where` names the surface that observed it (tool/event). Both are
|
|
135
|
+
* interpolated only when known, so the unknown case stays byte-identical to the
|
|
136
|
+
* original generic rule. */
|
|
137
|
+
function fundsText(label, where) {
|
|
138
|
+
const who = label ? ` from \`${label}\`` : "";
|
|
139
|
+
const at = where ? ` (observed in ${where})` : "";
|
|
140
|
+
const announce = label
|
|
141
|
+
? `Announce the failing provider/model (\`${label}\`)`
|
|
142
|
+
: "Announce which provider/model failed";
|
|
143
|
+
return `PROVIDER GUARD — a provider funds/quota error was observed${who}${at} (insufficient balance / credits / usage limit). STOP now: do not retry this call, do NOT do the persona's work inline, and do not silently switch providers. ${announce} and the exact unfinished step, checkpoint the state to \`.agents/handoffs/<feature-id>.md\`, then end the turn and wait for the user's explicit top-up-complete / continue message before resuming.`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const FUNDS_TEXT = fundsText();
|
|
147
|
+
|
|
148
|
+
function fundsError(text) {
|
|
149
|
+
return FUNDS_RE.test(String(text || ""));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/* Only STRUCTURED failure evidence may arm the stop. Scanning the text of every
|
|
153
|
+
* successful tool result false-positives on the harness's own documents: the
|
|
154
|
+
* mandated session-start read of `.agents/memory/model-routing.md` — and any
|
|
155
|
+
* handoff/plan/rulebook that quotes the funds rule — contains the literal
|
|
156
|
+
* trigger phrases, which paused sessions (F-169, LibraryOS) that had never seen
|
|
157
|
+
* a provider failure. Genuine failures carry a signal:
|
|
158
|
+
* - `error` — a tool that reported failure: a dispatch whose subagent died
|
|
159
|
+
* with "Subagent failed (...): Insufficient balance", or any thrown tool
|
|
160
|
+
* error (observed shape: task metadata carries the failed model);
|
|
161
|
+
* - `bash` with a non-zero `metadata.exit` — the command failed, so a
|
|
162
|
+
* provider CLI's funds error is in its output.
|
|
163
|
+
* Everything else (read/grep/glob content, successful dispatches and commands)
|
|
164
|
+
* is context, never failure evidence. Returns the text to scan, or null. */
|
|
165
|
+
function fundsArmText(tool, output) {
|
|
166
|
+
if (output?.error) return String(output.error);
|
|
167
|
+
if (String(tool || "") === "bash" || String(tool || "") === "shell") {
|
|
168
|
+
const exit = output?.metadata?.exit;
|
|
169
|
+
if (Number.isFinite(exit) && exit !== 0) {
|
|
170
|
+
return typeof output?.output === "string" ? output.output : JSON.stringify(output ?? {});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/* `provider/model` label from an opencode assistant message (providerID/modelID)
|
|
177
|
+
* or a dispatch metadata model object (provider/model). Null when neither side
|
|
178
|
+
* is known, so a label is only ever reported from observed data. */
|
|
179
|
+
function modelLabel(info) {
|
|
180
|
+
if (!info || typeof info !== "object") return null;
|
|
181
|
+
const provider = info.providerID || info.provider;
|
|
182
|
+
const model = info.modelID || info.model;
|
|
183
|
+
if (provider && model) return `${provider}/${model}`;
|
|
184
|
+
if (model) return String(model);
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/* Identical repeats of these are legitimate and must not count as loops:
|
|
189
|
+
* todo list rewrites, user questions, dispatches (retries are governed by the
|
|
190
|
+
* bounded-retry ladder), batched calls, board listings, the session join-key
|
|
191
|
+
* lookup, and the documented serve.js health polling. */
|
|
192
|
+
const EXEMPT_TOOLS = new Set(["todowrite", "question", "task", "subagent", "batch", "backlog_list", "session_info"]);
|
|
193
|
+
|
|
194
|
+
const SERVE_POLL = /serve\.js\s+(list|status)\b/;
|
|
195
|
+
|
|
196
|
+
/* A tool call that MATERIALLY changes repository state (as opposed to a read,
|
|
197
|
+
* grep, test run, or dispatch). Used only by the no-state-change detector: a
|
|
198
|
+
* whole turn with none of these is spinning, and the recovery nudge fires. A
|
|
199
|
+
* `subagent` dispatch counts as material — a subagent that edits files is progress
|
|
200
|
+
* even though the orchestrator's own tool arguments changed nothing. */
|
|
201
|
+
const MATERIAL_TOOLS = new Set(["write", "edit", "patch", "multiedit", "apply_patch", "task", "subagent"]);
|
|
202
|
+
const MATERIAL_BASH_RE =
|
|
203
|
+
/(^|[^a-z])(git\s+(commit|push|apply|am|merge|rebase|cherry-pick|stash|add)\b)|\|\s*tee\b|\bsed\s+-i\b|\b(rm|mv|cp|mkdir|touch)\b|>>?\s*[^&\s]|\bnpm\s+(install|ci|i)\b/;
|
|
204
|
+
|
|
205
|
+
function isMaterial(tool, args) {
|
|
206
|
+
const name = String(tool || "").toLowerCase();
|
|
207
|
+
if (MATERIAL_TOOLS.has(name)) return true;
|
|
208
|
+
if (name === "bash" || name === "shell") return MATERIAL_BASH_RE.test(String(args?.command || ""));
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/* Parse the machine-read values out of `orchestration.md`. Only the table row
|
|
213
|
+
* SHAPES matter — `| \`key\` | 60 | ... |` for turn/stuck keys and
|
|
214
|
+
* `| warn | 80K | ... |` for request levels. Anything missing falls back to the
|
|
215
|
+
* documented defaults, so a hand-trimmed file still guards. */
|
|
216
|
+
function parseThresholds(text) {
|
|
217
|
+
const turns = { ...DEFAULT_TURNS };
|
|
218
|
+
const stuck = { ...DEFAULT_STUCK };
|
|
219
|
+
const request = { ...DEFAULT_REQUEST };
|
|
220
|
+
const todo = { ...DEFAULT_TODO };
|
|
221
|
+
for (const line of String(text || "").split(/\r?\n/)) {
|
|
222
|
+
const keyed = line.match(/^\|\s*`?([a-z_]+)`?\s*\|\s*(\d+)\s*\|/);
|
|
223
|
+
if (keyed) {
|
|
224
|
+
const value = Number(keyed[2]);
|
|
225
|
+
if (keyed[1] in turns) turns[keyed[1]] = value;
|
|
226
|
+
else if (keyed[1] in stuck) stuck[keyed[1]] = value;
|
|
227
|
+
else if (keyed[1] in todo) todo[keyed[1]] = value;
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
const level = line.match(/^\|\s*(observe|warn|checkpoint|intervene)\s*\|\s*(\d+)\s*K?\+?\s*\|/);
|
|
231
|
+
if (level) request[level[1]] = Number(level[2]) * 1000;
|
|
232
|
+
}
|
|
233
|
+
return { turns, stuck, request, todo };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function turnBand(turn, turns) {
|
|
237
|
+
const ordered = TURN_BANDS.map(([key, band]) => ({ band, at: turns ? turns[key] : undefined }))
|
|
238
|
+
.filter((b) => Number.isFinite(b.at))
|
|
239
|
+
.sort((a, b) => b.at - a.at);
|
|
240
|
+
for (const b of ordered) if (turn >= b.at) return b.band;
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function bandRank(band) {
|
|
245
|
+
return BAND_RANK[band] || 0;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function requestBand(level) {
|
|
249
|
+
return REQUEST_BAND[level] || null;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/* The band the session should act on: the stronger of the turn band and the
|
|
253
|
+
* request-context band. Either signal alone can trigger the nudge, so a small
|
|
254
|
+
* turn count with a bloated context is caught just as a long transcript is. */
|
|
255
|
+
function pressureBand(state, thresholds) {
|
|
256
|
+
const turn = turnBand(state?.turns, thresholds?.turns);
|
|
257
|
+
const req = requestBand(state?.requestLevel);
|
|
258
|
+
return bandRank(req) > bandRank(turn) ? req : turn;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function bandText(band) {
|
|
262
|
+
return BAND_TEXT[band] || null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/* The ordered guard texts a request should carry: the highest reached turn band,
|
|
266
|
+
* then the funds stop, then the loop-recovery rule. Pure, so the plugin stays a
|
|
267
|
+
* thin IO layer and the composition is unit-testable. Returns [] when there is
|
|
268
|
+
* nothing to say. */
|
|
269
|
+
function guardTexts(state, thresholds) {
|
|
270
|
+
const texts = [];
|
|
271
|
+
const band = pressureBand(state, thresholds);
|
|
272
|
+
if (band) {
|
|
273
|
+
const text = bandText(band);
|
|
274
|
+
if (text) texts.push(text);
|
|
275
|
+
}
|
|
276
|
+
if (state?.fundsPending) texts.push(state.fundsNotice || FUNDS_TEXT);
|
|
277
|
+
if (state?.failurePending) texts.push(FAILURE_TEXT);
|
|
278
|
+
if (state?.noStatePending) texts.push(NO_STATE_TEXT);
|
|
279
|
+
if (state?.loopPending) texts.push(LOOP_TEXT);
|
|
280
|
+
if (state?.inspectPending) texts.push(INSPECT_TEXT);
|
|
281
|
+
if (state?.readPending && READ_TEXTS[state.readPending]) texts.push(READ_TEXTS[state.readPending]);
|
|
282
|
+
if (state?.dumpPending) texts.push(DUMP_TEXT);
|
|
283
|
+
if (state?.editMissPending) texts.push(EDIT_MISS_TEXT);
|
|
284
|
+
if (state?.gateRerunPending) texts.push(GATE_RERUN_TEXT);
|
|
285
|
+
if (state?.todoPending && TODO_TEXTS[state.todoPending]) texts.push(TODO_TEXTS[state.todoPending]);
|
|
286
|
+
if (state?.waitPending) texts.push(WAIT_TEXT);
|
|
287
|
+
return texts;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/* The single block injected into the conversation TAIL (never the system prompt,
|
|
291
|
+
* so the cached prefix stays byte-stable). The provenance banner leads so the
|
|
292
|
+
* synthetic user-role message can never be mistaken for the human. Null when
|
|
293
|
+
* there is nothing to inject. */
|
|
294
|
+
function composeGuardText(state, thresholds) {
|
|
295
|
+
const texts = guardTexts(state, thresholds);
|
|
296
|
+
return texts.length ? [GUARD_PROVENANCE, ...texts].join("\n\n") : null;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function requestLevel(tokens, request) {
|
|
300
|
+
if (!Number.isFinite(tokens)) return null;
|
|
301
|
+
let level = null;
|
|
302
|
+
for (const name of REQUEST_LEVELS) {
|
|
303
|
+
if (Number.isFinite(request?.[name]) && tokens >= request[name]) level = name;
|
|
304
|
+
}
|
|
305
|
+
return level;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/* Request-context size the provider reports for an assistant message. Cache
|
|
309
|
+
* reads/writes are part of the request; output tokens are not. */
|
|
310
|
+
function requestTokensOf(message) {
|
|
311
|
+
const t = message?.tokens;
|
|
312
|
+
if (!t) return null;
|
|
313
|
+
const cache = t.cache || {};
|
|
314
|
+
return (t.input || 0) + (cache.read || 0) + (cache.write || 0);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/* Order-independent JSON so `{a:1,b:2}` and `{b:2,a:1}` are the same call. */
|
|
318
|
+
function stableStringify(value) {
|
|
319
|
+
if (value === undefined) return "null";
|
|
320
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
321
|
+
if (Array.isArray(value)) return "[" + value.map(stableStringify).join(",") + "]";
|
|
322
|
+
return (
|
|
323
|
+
"{" +
|
|
324
|
+
Object.keys(value)
|
|
325
|
+
.sort()
|
|
326
|
+
.map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]))
|
|
327
|
+
.join(",") +
|
|
328
|
+
"}"
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/* Short FNV-1a digest — the guard-event log stores a hash, never the raw args
|
|
333
|
+
* (commands can carry secrets and the log is read by later telemetry passes). */
|
|
334
|
+
function shortHash(text) {
|
|
335
|
+
let h = 0x811c9dc5;
|
|
336
|
+
for (let i = 0; i < text.length; i++) {
|
|
337
|
+
h ^= text.charCodeAt(i);
|
|
338
|
+
h = Math.imul(h, 0x01000193) >>> 0;
|
|
339
|
+
}
|
|
340
|
+
return h.toString(16).padStart(8, "0");
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function isLoopExempt(tool, args) {
|
|
344
|
+
const name = String(tool || "");
|
|
345
|
+
if (EXEMPT_TOOLS.has(name)) return true;
|
|
346
|
+
if (name === "bash" || name === "shell") {
|
|
347
|
+
const command = String(args?.command || "");
|
|
348
|
+
if (SERVE_POLL.test(command)) return true;
|
|
349
|
+
}
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function loopKey(tool, args) {
|
|
354
|
+
return String(tool || "") + ":" + stableStringify(args ?? {});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function createSessionState() {
|
|
358
|
+
return {
|
|
359
|
+
turns: 0,
|
|
360
|
+
assistantIds: new Set(),
|
|
361
|
+
band: null,
|
|
362
|
+
requestLevel: null,
|
|
363
|
+
requestTokens: null,
|
|
364
|
+
toolCounts: new Map(),
|
|
365
|
+
flaggedLoops: new Set(),
|
|
366
|
+
loopPending: false,
|
|
367
|
+
fundsPending: false,
|
|
368
|
+
fundsNotice: null,
|
|
369
|
+
// no-state-change detector
|
|
370
|
+
materialSeen: false,
|
|
371
|
+
noStateTurns: 0,
|
|
372
|
+
noStatePending: false,
|
|
373
|
+
// same-failure detector
|
|
374
|
+
lastFailureKey: null,
|
|
375
|
+
consecutiveFailures: 0,
|
|
376
|
+
failurePending: false,
|
|
377
|
+
failureFlagged: false,
|
|
378
|
+
// tool-choice / read / whole-tree hygiene (advisory one-shot nudges)
|
|
379
|
+
inspectPending: false,
|
|
380
|
+
inspectFlagged: false,
|
|
381
|
+
// inspect re-arm (D): count every inspection, re-arm the advisory after
|
|
382
|
+
// `inspect_rearm_every` further inspections or on a different head.
|
|
383
|
+
inspectCount: 0,
|
|
384
|
+
inspectFlaggedAt: 0,
|
|
385
|
+
inspectLastHead: null,
|
|
386
|
+
readSeen: new Set(),
|
|
387
|
+
readNotices: new Set(),
|
|
388
|
+
readPending: null,
|
|
389
|
+
dumpPending: false,
|
|
390
|
+
dumpFlagged: false,
|
|
391
|
+
// edit-miss (E): a failed edit/write/apply_patch on a guessed path
|
|
392
|
+
editMissPending: false,
|
|
393
|
+
editMissFlagged: false,
|
|
394
|
+
// gate re-run (F): same gate run repeatedly with no intervening edit
|
|
395
|
+
gateRuns: new Map(),
|
|
396
|
+
gateRerunPending: false,
|
|
397
|
+
gateRerunFlagged: new Set(),
|
|
398
|
+
// wait/poll advisory (B)
|
|
399
|
+
waitPending: false,
|
|
400
|
+
waitFlagged: false,
|
|
401
|
+
// structural tool blocks: the first pure inspection of each head / poll of
|
|
402
|
+
// each kind is blocked once per session (see inspectBlockText/pollBlockText).
|
|
403
|
+
blockedInspectHeads: new Set(),
|
|
404
|
+
blockedPollKinds: new Set(),
|
|
405
|
+
// session-start orientation injection: the one-call `orient --brief` block,
|
|
406
|
+
// injected into the cache-safe tail until the session's first material action
|
|
407
|
+
// (then cleared) so a resume/claim prologue re-derives nothing by hand.
|
|
408
|
+
orientPending: false,
|
|
409
|
+
orientText: null,
|
|
410
|
+
// todo-list discipline (opencode's `todowrite` panel). The guard never
|
|
411
|
+
// writes the panel (no plugin API for it) — it tracks the last list the model
|
|
412
|
+
// wrote and nudges "create" / "sync" / "close" when the panel falls behind.
|
|
413
|
+
materialCalls: 0,
|
|
414
|
+
todos: null, // normalized [{content,status,priority}] or null before the first write
|
|
415
|
+
todoUpdatedAtCalls: 0,
|
|
416
|
+
todoUsed: false,
|
|
417
|
+
todoMissingFlaggedAt: -1,
|
|
418
|
+
todoStaleFlaggedAt: -1,
|
|
419
|
+
todoInvalidFlaggedAt: -1,
|
|
420
|
+
todoCloseFlagged: false,
|
|
421
|
+
todoPending: null, // "missing" | "stale" | "invalid" | "close"
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/* Record an assistant message. `message.updated` fires repeatedly per message,
|
|
426
|
+
* so a NEW id is one orchestrator turn; a repeat of a seen id is not. Returns
|
|
427
|
+
* the transitions (band + request level + no-state) for the plugin to log —
|
|
428
|
+
* never the raw every-request state, so the JSONL only carries crossings.
|
|
429
|
+
*
|
|
430
|
+
* Token refresh runs on EVERY emit, including repeats of a seen id. opencode
|
|
431
|
+
* emits a tokenless (all-zero) `message.updated` first, then a later emit for
|
|
432
|
+
* the SAME id carrying the real usage; deduping the whole handler dropped that
|
|
433
|
+
* second emit, so `requestTokens` never left 0 and the request-token band was
|
|
434
|
+
* dead in production (0 `request` guard events ever). Turn counting and the
|
|
435
|
+
* no-state detector still run only on the first emit of an id.
|
|
436
|
+
*
|
|
437
|
+
* A new turn also FINALIZES the previous turn's materiality: its tool calls
|
|
438
|
+
* have all run by now, so `materialSeen` is authoritative for that turn. Whole
|
|
439
|
+
* turns without a material change arm the no-state nudge. */
|
|
440
|
+
function noteAssistant(state, message, thresholds) {
|
|
441
|
+
const out = {
|
|
442
|
+
newTurn: false,
|
|
443
|
+
turns: state.turns,
|
|
444
|
+
band: state.band,
|
|
445
|
+
bandChanged: false,
|
|
446
|
+
requestLevel: state.requestLevel,
|
|
447
|
+
requestChanged: false,
|
|
448
|
+
requestTokens: null,
|
|
449
|
+
noStateChanged: false,
|
|
450
|
+
noStatePending: state.noStatePending,
|
|
451
|
+
noStateTurns: state.noStateTurns,
|
|
452
|
+
todoPending: state.todoPending,
|
|
453
|
+
};
|
|
454
|
+
const id = message?.id;
|
|
455
|
+
if (!id) return out;
|
|
456
|
+
|
|
457
|
+
const seen = state.assistantIds.has(id);
|
|
458
|
+
if (!seen) {
|
|
459
|
+
const priorTurns = state.turns;
|
|
460
|
+
state.assistantIds.add(id);
|
|
461
|
+
state.turns += 1;
|
|
462
|
+
out.newTurn = true;
|
|
463
|
+
out.turns = state.turns;
|
|
464
|
+
|
|
465
|
+
if (priorTurns > 0) {
|
|
466
|
+
// Startup grace: the first steps of every session are orientation
|
|
467
|
+
// (read/grep/shell) with nothing to mutate yet, so counting them as
|
|
468
|
+
// "no material change" cried wolf at turn 5 in 78/143 sessions (measured
|
|
469
|
+
// 2026-10-16). Only a turn PAST the grace may start the streak.
|
|
470
|
+
const grace = Number.isFinite(thresholds?.stuck?.no_state_grace_turns)
|
|
471
|
+
? thresholds.stuck.no_state_grace_turns
|
|
472
|
+
: 8;
|
|
473
|
+
if (state.materialSeen) state.noStateTurns = 0;
|
|
474
|
+
else if (priorTurns > grace) state.noStateTurns += 1;
|
|
475
|
+
state.materialSeen = false;
|
|
476
|
+
const nsThreshold = Number.isFinite(thresholds?.stuck?.no_state_change_turns)
|
|
477
|
+
? thresholds.stuck.no_state_change_turns
|
|
478
|
+
: 4;
|
|
479
|
+
if (state.noStateTurns >= nsThreshold && !state.noStatePending) {
|
|
480
|
+
state.noStatePending = true;
|
|
481
|
+
out.noStateChanged = true;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
out.noStatePending = state.noStatePending;
|
|
485
|
+
out.noStateTurns = state.noStateTurns;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// Token refresh on every emit (first or repeat), then derive the combined
|
|
489
|
+
// pressure band so a context-token crossing is reflected on the same emit it
|
|
490
|
+
// is observed — not just the first, tokenless one.
|
|
491
|
+
const tokens = requestTokensOf(message);
|
|
492
|
+
if (tokens != null) state.requestTokens = tokens;
|
|
493
|
+
out.requestTokens = state.requestTokens;
|
|
494
|
+
const level = requestLevel(state.requestTokens, thresholds?.request);
|
|
495
|
+
if (level !== state.requestLevel) {
|
|
496
|
+
state.requestLevel = level;
|
|
497
|
+
out.requestLevel = level;
|
|
498
|
+
out.requestChanged = true;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const band = pressureBand(state, thresholds);
|
|
502
|
+
if (band !== state.band) {
|
|
503
|
+
state.band = band;
|
|
504
|
+
out.band = band;
|
|
505
|
+
out.bandChanged = true;
|
|
506
|
+
}
|
|
507
|
+
if (out.newTurn) out.todoPending = armTodoNudge(state, thresholds, state.band);
|
|
508
|
+
return out;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/* Count identical tool+args calls cumulatively per session ("the worst sessions
|
|
512
|
+
* ran the same tool 100-150x" is cumulative, not consecutive). The first breach
|
|
513
|
+
* of `identical_tool_calls` is flagged once; `loopPending` stays true while the
|
|
514
|
+
* identical call repeats and clears on the next materially different call, so
|
|
515
|
+
* the recovery rule is injected exactly while the loop persists. */
|
|
516
|
+
function noteToolCall(state, tool, args, stuck) {
|
|
517
|
+
const material = isMaterial(tool, args);
|
|
518
|
+
if (material) {
|
|
519
|
+
state.materialSeen = true;
|
|
520
|
+
state.materialCalls = (state.materialCalls || 0) + 1;
|
|
521
|
+
state.noStateTurns = 0;
|
|
522
|
+
state.noStatePending = false;
|
|
523
|
+
state.orientPending = false; // real work began — drop the session-start orient block
|
|
524
|
+
resetGateRuns(state); // a batched edit invalidates prior gate results
|
|
525
|
+
}
|
|
526
|
+
const exempt = isLoopExempt(tool, args);
|
|
527
|
+
if (exempt) {
|
|
528
|
+
return { counted: false, count: 0, loop: false, firstFlag: false, keyHash: null, material };
|
|
529
|
+
}
|
|
530
|
+
const key = loopKey(tool, args);
|
|
531
|
+
const count = (state.toolCounts.get(key) || 0) + 1;
|
|
532
|
+
state.toolCounts.set(key, count);
|
|
533
|
+
const threshold = Number.isFinite(stuck?.identical_tool_calls) ? stuck.identical_tool_calls : 3;
|
|
534
|
+
const loop = count >= threshold;
|
|
535
|
+
let firstFlag = false;
|
|
536
|
+
if (loop && !state.flaggedLoops.has(key)) {
|
|
537
|
+
state.flaggedLoops.add(key);
|
|
538
|
+
firstFlag = true;
|
|
539
|
+
}
|
|
540
|
+
state.loopPending = loop;
|
|
541
|
+
return { counted: true, count, loop, firstFlag, keyHash: shortHash(key), material };
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/* Track tool-call failures. Distinct from the identical-call counter: the same
|
|
545
|
+
* failure can repeat with different arguments. A success clears the streak; the
|
|
546
|
+
* first time the same failure signature reaches `same_failure_turns` the
|
|
547
|
+
* recovery nudge is armed (and reported once). Pure; the plugin supplies
|
|
548
|
+
* `failureText` from structured tool-result evidence. */
|
|
549
|
+
function noteToolResult(state, tool, args, ok, failureText, stuck) {
|
|
550
|
+
const out = { failed: !ok, count: 0, pending: false, firstFlag: false, keyHash: null };
|
|
551
|
+
if (ok) {
|
|
552
|
+
state.lastFailureKey = null;
|
|
553
|
+
state.consecutiveFailures = 0;
|
|
554
|
+
state.failurePending = false;
|
|
555
|
+
state.failureFlagged = false;
|
|
556
|
+
return out;
|
|
557
|
+
}
|
|
558
|
+
const key = String(tool || "") + ":" + shortHash(String(failureText || "").slice(0, 2000));
|
|
559
|
+
if (key === state.lastFailureKey) state.consecutiveFailures += 1;
|
|
560
|
+
else {
|
|
561
|
+
state.lastFailureKey = key;
|
|
562
|
+
state.consecutiveFailures = 1;
|
|
563
|
+
}
|
|
564
|
+
const threshold = Number.isFinite(stuck?.same_failure_turns) ? stuck.same_failure_turns : 3;
|
|
565
|
+
const pending = state.consecutiveFailures >= threshold;
|
|
566
|
+
out.count = state.consecutiveFailures;
|
|
567
|
+
out.keyHash = shortHash(key);
|
|
568
|
+
out.pending = pending;
|
|
569
|
+
if (pending && !state.failureFlagged) {
|
|
570
|
+
state.failureFlagged = true;
|
|
571
|
+
out.firstFlag = true;
|
|
572
|
+
}
|
|
573
|
+
state.failurePending = pending;
|
|
574
|
+
return out;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/* ------------------------------------------------------- todo-list discipline
|
|
578
|
+
*
|
|
579
|
+
* opencode's right-hand todo panel is rendered exclusively from the model's
|
|
580
|
+
* `todowrite` calls. The harness cannot write it (no todo API on the V2 plugin
|
|
581
|
+
* surface), so the only mechanical lever is a cache-safe tail nudge. Four
|
|
582
|
+
* constant texts, one per failure mode:
|
|
583
|
+
* - missing: multi-step work began with no list at all;
|
|
584
|
+
* - stale: material work continued but the list was never rewritten;
|
|
585
|
+
* - invalid: more than one item is `in_progress` (the panel can no longer
|
|
586
|
+
* show what is actually current);
|
|
587
|
+
* - close: the context is at a wrap-up band but items are still open.
|
|
588
|
+
* The texts are CONSTANT (never interpolated) so the cached prefix survives. */
|
|
589
|
+
const TODO_USE_TEXT =
|
|
590
|
+
"TODO GUARD — this is multi-step work but no todo list has been written, so the opencode todo panel is empty. Create it now with the `todowrite` tool: one item per discrete step, exactly ONE item `in_progress` (the step you are doing now), the rest `pending`. Keep the list in step, and mark each item `completed` immediately after its own verification step. Skip this only for genuinely single-step work.";
|
|
591
|
+
const TODO_STALE_TEXT =
|
|
592
|
+
"TODO GUARD — the todo panel is behind the work: several material steps have run since the list was last written. Rewrite it now with `todowrite`: mark finished items `completed`, exactly ONE current item `in_progress`, and add any newly discovered step as `pending`. A stale list is worse than no list.";
|
|
593
|
+
const TODO_INVALID_TEXT =
|
|
594
|
+
"TODO GUARD — the todo list has more than one `in_progress` item. Keep exactly ONE item `in_progress` (the step actually being worked now); mark the others `pending` or `completed` in the next `todowrite` call so the panel reflects real progress.";
|
|
595
|
+
const TODO_CLOSE_TEXT =
|
|
596
|
+
"TODO GUARD — the context is at a wrap-up band but the todo list still has open items. Before you checkpoint/report, close the list with `todowrite`: mark every finished item `completed` and leave only genuinely unfinished work `pending`/`in_progress` (with the blocker named). Do not hand back a task with completed work still shown as open.";
|
|
597
|
+
|
|
598
|
+
const TODO_TEXTS = Object.freeze({
|
|
599
|
+
missing: TODO_USE_TEXT,
|
|
600
|
+
stale: TODO_STALE_TEXT,
|
|
601
|
+
invalid: TODO_INVALID_TEXT,
|
|
602
|
+
close: TODO_CLOSE_TEXT,
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
const TODO_STATUSES = new Set(["pending", "in_progress", "completed", "cancelled"]);
|
|
606
|
+
|
|
607
|
+
/* Normalize a `todowrite` payload. Returns null for a shape that is not a list
|
|
608
|
+
* (never inventing a list from garbage); an empty array is a deliberate clear. */
|
|
609
|
+
function normalizeTodos(value) {
|
|
610
|
+
if (!Array.isArray(value)) return null;
|
|
611
|
+
return value
|
|
612
|
+
.filter((t) => t && typeof t === "object")
|
|
613
|
+
.map((t) => ({
|
|
614
|
+
content: String(t.content ?? t.text ?? "").trim(),
|
|
615
|
+
status: TODO_STATUSES.has(String(t.status)) ? String(t.status) : "pending",
|
|
616
|
+
priority: t.priority ?? null,
|
|
617
|
+
}))
|
|
618
|
+
.filter((t) => t.content.length > 0);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/* Record a `todowrite` call. Also called for an intentional empty list (a clear).
|
|
622
|
+
* Returns counts the plugin logs; nothing here can fail a tool call. */
|
|
623
|
+
function noteTodoWrite(state, args) {
|
|
624
|
+
const list = normalizeTodos(args?.todos);
|
|
625
|
+
if (list === null) return { recorded: false, count: 0, inProgress: 0, open: 0 };
|
|
626
|
+
state.todos = list;
|
|
627
|
+
state.todoUsed = true;
|
|
628
|
+
state.todoUpdatedAtCalls = state.materialCalls || 0;
|
|
629
|
+
state.todoPending = null;
|
|
630
|
+
state.todoCloseFlagged = false;
|
|
631
|
+
return {
|
|
632
|
+
recorded: true,
|
|
633
|
+
count: list.length,
|
|
634
|
+
inProgress: list.filter((t) => t.status === "in_progress").length,
|
|
635
|
+
open: list.filter((t) => t.status === "pending" || t.status === "in_progress").length,
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/* Decide whether a todo nudge should ride the next request. Called once per
|
|
640
|
+
* orchestrator turn (a new assistant message), after tool calls for the previous
|
|
641
|
+
* turn have run. Re-arms are bounded so a model that ignores the nudge is
|
|
642
|
+
* reminded again only after real further work, never on every turn. */
|
|
643
|
+
function armTodoNudge(state, thresholds, band) {
|
|
644
|
+
const cfg = thresholds?.todo || DEFAULT_TODO;
|
|
645
|
+
const useAfter = Number.isFinite(cfg.use_after_calls) ? cfg.use_after_calls : DEFAULT_TODO.use_after_calls;
|
|
646
|
+
const staleAfter = Number.isFinite(cfg.stale_after_calls) ? cfg.stale_after_calls : DEFAULT_TODO.stale_after_calls;
|
|
647
|
+
const calls = state.materialCalls || 0;
|
|
648
|
+
|
|
649
|
+
if (!state.todoUsed) {
|
|
650
|
+
// Re-arm after another full `useAfter` window of material work, so a model
|
|
651
|
+
// that skipped the first nudge is reminded again rather than left empty.
|
|
652
|
+
if (
|
|
653
|
+
calls >= useAfter &&
|
|
654
|
+
(state.todoMissingFlaggedAt < 0 || calls - state.todoMissingFlaggedAt >= useAfter)
|
|
655
|
+
) {
|
|
656
|
+
state.todoMissingFlaggedAt = calls;
|
|
657
|
+
state.todoPending = "missing";
|
|
658
|
+
}
|
|
659
|
+
return state.todoPending;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
const list = Array.isArray(state.todos) ? state.todos : [];
|
|
663
|
+
const open = list.filter((t) => t.status === "pending" || t.status === "in_progress").length;
|
|
664
|
+
const inProgress = list.filter((t) => t.status === "in_progress").length;
|
|
665
|
+
|
|
666
|
+
// An invalid list (two currents) is the strongest signal: the panel is lying.
|
|
667
|
+
if (
|
|
668
|
+
inProgress > 1 &&
|
|
669
|
+
(state.todoInvalidFlaggedAt < 0 || calls - state.todoInvalidFlaggedAt >= staleAfter)
|
|
670
|
+
) {
|
|
671
|
+
state.todoInvalidFlaggedAt = calls;
|
|
672
|
+
state.todoPending = "invalid";
|
|
673
|
+
return state.todoPending;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Wrap-up closure: the model is approaching a checkpoint/report boundary and
|
|
677
|
+
// still shows open items. Flag once per list revision (any todowrite resets).
|
|
678
|
+
if (bandRank(band) >= BAND_RANK.checkpoint && open > 0 && !state.todoCloseFlagged) {
|
|
679
|
+
state.todoCloseFlagged = true;
|
|
680
|
+
state.todoPending = "close";
|
|
681
|
+
return state.todoPending;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// Staleness: real work ran since the last rewrite. Re-arm per stale window.
|
|
685
|
+
if (
|
|
686
|
+
calls - (state.todoUpdatedAtCalls || 0) >= staleAfter &&
|
|
687
|
+
(state.todoStaleFlaggedAt < 0 || calls - state.todoStaleFlaggedAt >= staleAfter)
|
|
688
|
+
) {
|
|
689
|
+
state.todoStaleFlaggedAt = calls;
|
|
690
|
+
state.todoPending = "stale";
|
|
691
|
+
}
|
|
692
|
+
return state.todoPending;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/* One JSON object per line — the Phase B telemetry substrate, read without a
|
|
696
|
+
* sqlite dependency. `ts` leads so a plain `sort` works. */
|
|
697
|
+
function formatGuardEvent(event) {
|
|
698
|
+
return JSON.stringify({ ts: new Date().toISOString(), ...event }) + "\n";
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/* ---------------------------------------------------------------- location
|
|
702
|
+
*
|
|
703
|
+
* V2 loads a plugin instance per *location* (project directory), and the runtime
|
|
704
|
+
* routes a session's events to the instance that owns that session's location.
|
|
705
|
+
* A session whose location has no plugins falls back to the service's default
|
|
706
|
+
* instance, so an instance CAN receive events for a checkout that is not its own
|
|
707
|
+
* — measured 2026-10-16: a session rooted in `agent-harness` (no plugins) was
|
|
708
|
+
* leased and guard-logged inside `PublicVirtualLibrary` by LibraryOS's instance.
|
|
709
|
+
* Every per-session write must therefore confirm ownership first.
|
|
710
|
+
*
|
|
711
|
+
* Pure so the decision is unit-testable and can never drift from the plugin. */
|
|
712
|
+
|
|
713
|
+
/* Slash form, no trailing slash (a lone "/" stays "/"). */
|
|
714
|
+
function normalizeRootPath(p) {
|
|
715
|
+
const s = String(p == null ? "" : p).replace(/\\/g, "/").replace(/\/+$/, "").replace(/\/\.$/, "");
|
|
716
|
+
return s === "" ? "" : s;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/* Does an instance rooted at `root` own an event whose location is `eventDir`?
|
|
720
|
+
* An unknown location (missing/empty) is owned — a real event is never dropped
|
|
721
|
+
* on a gap in the envelope. Windows paths compare case-insensitively. */
|
|
722
|
+
function ownsLocation(root, eventDir) {
|
|
723
|
+
if (typeof eventDir !== "string" || eventDir.length === 0) return true;
|
|
724
|
+
const a = normalizeRootPath(root);
|
|
725
|
+
const b = normalizeRootPath(eventDir);
|
|
726
|
+
if (!a || !b) return true;
|
|
727
|
+
if (a === b) return true;
|
|
728
|
+
return /^[a-z]:\//i.test(a) && a.toLowerCase() === b.toLowerCase();
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// ------------------------------------------------------- branch-switch guard
|
|
732
|
+
/* A shared checkout's HEAD can be moved out from under a running session by
|
|
733
|
+
* another primary session in the SAME tree (`git checkout <branch>` /
|
|
734
|
+
* `git switch`). The session that was mid-task then commits and pushes on the
|
|
735
|
+
* wrong branch. LibraryOS 2026-09-18: session A's `docs/f-239-record-landing`
|
|
736
|
+
* was replaced by session B's `git checkout main`, and A's later bare
|
|
737
|
+
* `git commit` + `git push` landed directly on main. The plugin blocks a branch
|
|
738
|
+
* switch while another LIVE primary lease shares this checkout, forcing the
|
|
739
|
+
* second session to isolate (`backlog worktree <id> --open`) first.
|
|
740
|
+
*
|
|
741
|
+
* `branchSwitch` is the pure parser; the plugin owns the lease census and the
|
|
742
|
+
* throw. It scans only COMMAND POSITION git (never an argument to echo/grep)
|
|
743
|
+
* and treats any `--` as a path restore (`git checkout -- <paths>`), so the
|
|
744
|
+
* everyday file-restore forms never false-positive. It is deliberately
|
|
745
|
+
* conservative: a single positional without `--` (`git checkout main`,
|
|
746
|
+
* `git checkout .`) is treated as a HEAD move, because in a two-session tree
|
|
747
|
+
* even an in-place restore is a collision worth isolating for. */
|
|
748
|
+
const GIT_WRAPPERS = new Set(["sudo", "env", "nohup", "time", "command", "exec"]);
|
|
749
|
+
|
|
750
|
+
/* Flags whose presence makes `git checkout` a branch/HEAD move rather than a
|
|
751
|
+
* path restore. `-` is `git checkout -` (switch to the previous branch). */
|
|
752
|
+
const BRANCH_CHECKOUT_FLAGS = new Set([
|
|
753
|
+
"-b",
|
|
754
|
+
"-B",
|
|
755
|
+
"--orphan",
|
|
756
|
+
"--detach",
|
|
757
|
+
"--track",
|
|
758
|
+
"-t",
|
|
759
|
+
"--guess",
|
|
760
|
+
"--no-guess",
|
|
761
|
+
"-",
|
|
762
|
+
]);
|
|
763
|
+
|
|
764
|
+
/* `git checkout` flags that select working-tree PATHS/hunks/conflict sides, not a
|
|
765
|
+
* branch. `--ours`/`--theirs`/`--conflict` resolve a conflict in named files and
|
|
766
|
+
* `-p`/`--patch` selects hunks, so any of them makes the command a path restore
|
|
767
|
+
* and can never move HEAD. (`-m`/`--merge` are NOT here: they can accompany a
|
|
768
|
+
* real branch switch, so they stay conservative.) The F-316 false positive:
|
|
769
|
+
* `git checkout --ours BACKLOG.md` was blocked as "a branch switch to
|
|
770
|
+
* `BACKLOG.md`". */
|
|
771
|
+
const PATH_CHECKOUT_FLAGS = new Set(["--ours", "--theirs", "--conflict", "-p", "--patch"]);
|
|
772
|
+
|
|
773
|
+
const GIT_GLOBAL_WITH_ARG = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"]);
|
|
774
|
+
|
|
775
|
+
function tokenize(segment) {
|
|
776
|
+
const tokens = [];
|
|
777
|
+
const re = /"((?:\\.|[^"\\])*)"|'([^']*)'|([^\s]+)/g;
|
|
778
|
+
let m;
|
|
779
|
+
while ((m = re.exec(String(segment || "")))) tokens.push(m[1] ?? m[2] ?? m[3]);
|
|
780
|
+
return tokens;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function isRedirection(token) {
|
|
784
|
+
return /^\d*[<>]/.test(token) || token === "&>" || token === ">&";
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function basename(token) {
|
|
788
|
+
const parts = String(token || "").split(/[\\/]/);
|
|
789
|
+
return parts[parts.length - 1];
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/* The raw value of a repo-selecting global option (`-C <path>`, `--git-dir[=]`,
|
|
793
|
+
* `--work-tree[=]`), or null. Kept pure: the caller resolves it against the
|
|
794
|
+
* command cwd and classifies the enclosing checkout (a `--git-dir` pointing at a
|
|
795
|
+
* `.git` directory resolves to its repo root when the classifier walks up). */
|
|
796
|
+
function gitRepoSelector(tokens, at) {
|
|
797
|
+
const t = tokens[at];
|
|
798
|
+
if (t === "-C" || t === "--work-tree" || t === "--git-dir") return tokens[at + 1] || null;
|
|
799
|
+
const eq = /^--(git-dir|work-tree)=(.*)$/.exec(t);
|
|
800
|
+
return eq ? eq[2] || null : null;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/* The git subcommand in command position of one shell segment, or null. Env
|
|
804
|
+
* assignments and the common wrappers (`sudo git ...`) are skipped. Global
|
|
805
|
+
* options (`-C`, `--git-dir`, `--work-tree`, ...) are stepped over to find the
|
|
806
|
+
* subcommand, but the repo selector is captured as `target` so the caller can
|
|
807
|
+
* classify the checkout the command actually writes to (a `git -C <main>` from
|
|
808
|
+
* an unrelated cwd must not escape the guard). */
|
|
809
|
+
function gitSubcommand(tokens) {
|
|
810
|
+
let i = 0;
|
|
811
|
+
while (i < tokens.length) {
|
|
812
|
+
const base = basename(tokens[i]);
|
|
813
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i]) || GIT_WRAPPERS.has(base)) {
|
|
814
|
+
i++;
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
break;
|
|
818
|
+
}
|
|
819
|
+
if (i >= tokens.length || basename(tokens[i]) !== "git") return null;
|
|
820
|
+
let j = i + 1;
|
|
821
|
+
let target = null;
|
|
822
|
+
while (j < tokens.length) {
|
|
823
|
+
const t = tokens[j];
|
|
824
|
+
if (GIT_GLOBAL_WITH_ARG.has(t)) {
|
|
825
|
+
const sel = gitRepoSelector(tokens, j);
|
|
826
|
+
if (sel && !target) target = sel;
|
|
827
|
+
j += 2;
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
if (/^--(git-dir|work-tree|namespace|exec-path)=/.test(t)) {
|
|
831
|
+
const sel = gitRepoSelector(tokens, j);
|
|
832
|
+
if (sel && !target) target = sel;
|
|
833
|
+
j += 1;
|
|
834
|
+
continue;
|
|
835
|
+
}
|
|
836
|
+
if (t.startsWith("-")) {
|
|
837
|
+
j += 1;
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
return { subcommand: t, args: tokens.slice(j + 1), target };
|
|
841
|
+
}
|
|
842
|
+
return null;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function firstPositional(args) {
|
|
846
|
+
for (const a of args) {
|
|
847
|
+
if (a === "-") return "-";
|
|
848
|
+
if (a.startsWith("-") || isRedirection(a)) continue;
|
|
849
|
+
return a;
|
|
850
|
+
}
|
|
851
|
+
return null;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/* { ref } when the shell command moves the checked-out branch, else null. */
|
|
855
|
+
function branchSwitch(command) {
|
|
856
|
+
for (const segment of String(command || "").split(/\r?\n|&&|\|\||;|\|/)) {
|
|
857
|
+
const found = gitSubcommand(tokenize(segment));
|
|
858
|
+
if (!found) continue;
|
|
859
|
+
const { subcommand, args } = found;
|
|
860
|
+
if (subcommand === "switch") return { ref: firstPositional(args) };
|
|
861
|
+
if (subcommand !== "checkout") continue;
|
|
862
|
+
if (args.includes("--")) continue; // `... -- <path>` is a restore
|
|
863
|
+
// Conflict resolution / hunk selection always names working-tree paths
|
|
864
|
+
// (`--conflict=<mode>` too), so it can never move HEAD.
|
|
865
|
+
if (args.some((a) => PATH_CHECKOUT_FLAGS.has(a) || /^--conflict(=|$)/.test(a))) continue;
|
|
866
|
+
if (args.some((a) => BRANCH_CHECKOUT_FLAGS.has(a))) return { ref: firstPositional(args) };
|
|
867
|
+
const positionals = args.filter((a) => !a.startsWith("-") && !isRedirection(a));
|
|
868
|
+
if (positionals.length !== 1) continue; // 0 args lists status; 2+ is `<tree> <path>`
|
|
869
|
+
const only = positionals[0];
|
|
870
|
+
// `.`/`..`/`./x` are unambiguously paths, never branch names.
|
|
871
|
+
if (only === "." || only === ".." || only.startsWith("./") || only.startsWith("../")) continue;
|
|
872
|
+
return { ref: only };
|
|
873
|
+
}
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/* The error the plugin throws to abort the switch. Names the branch and the
|
|
878
|
+
* other live sessions so the fix (isolate) is mechanical. */
|
|
879
|
+
function branchSwitchText(ref, others) {
|
|
880
|
+
const target = ref ? `\`${ref}\`` : "another branch";
|
|
881
|
+
const who =
|
|
882
|
+
Array.isArray(others) && others.length
|
|
883
|
+
? others.map((s) => `\`${s}\``).join(", ")
|
|
884
|
+
: "another primary session";
|
|
885
|
+
return `SESSION GUARD — blocked a branch switch to ${target}: ${who} is live in the same checkout. Two primary sessions must not share one working tree — the switch would move HEAD under the other session, which could then commit/push on the wrong branch (the 2026-09-18 direct-push-to-main incident). Fix it one of two ways. (1) To switch branches, isolate first: run \`backlog worktree <feature-id> --open\` from the MAIN tree, then work in that worktree — or let the other session finish. (2) If you only meant to restore a working-tree file (not switch branches), this was a false alarm: re-run it as \`git restore <path>\` or \`git checkout -- <path>\` (the \`--\` form) and it will pass. The switch was NOT executed.`;
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// ------------------------------------------------------- main-checkout guard
|
|
889
|
+
/* `main` is board + shippable code only: every feature works in its own linked
|
|
890
|
+
* worktree, so a session rooted in the shared main checkout must isolate BEFORE
|
|
891
|
+
* it changes code. F-278 (LibraryOS 2026-09-22) was the counter-example: the
|
|
892
|
+
* change was implemented straight into `main`, then `finalize` refused on `main`
|
|
893
|
+
* and the branch switch that would have isolated it was blocked by the
|
|
894
|
+
* branch-switch guard while other live sessions shared the tree — the work was
|
|
895
|
+
* stranded. This classifier is the preventive half: the plugin resolves the
|
|
896
|
+
* target + worktree roots (IO) and throws when a code change or git mutation is
|
|
897
|
+
* aimed at the main checkout.
|
|
898
|
+
*
|
|
899
|
+
* "Code" excludes the harness's own metadata (`.agents/`, `.serve/`, `.git/`,
|
|
900
|
+
* `node_modules/`) and human docs (Markdown/text), so checkpoint / handoff /
|
|
901
|
+
* QA-plan / CHANGELOG maintenance on `main` stays allowed — only source, test,
|
|
902
|
+
* and config edits require a worktree. Pure, so it is unit-testable. */
|
|
903
|
+
const NON_CODE_SEGMENTS = new Set([".agents", ".serve", ".git", "node_modules"]);
|
|
904
|
+
const NON_CODE_EXT = new Set([".md", ".mdx", ".txt", ".rst"]);
|
|
905
|
+
const NON_CODE_BASENAMES = new Set(["BACKLOG.md", "README.md", "CHANGELOG.md"]);
|
|
906
|
+
|
|
907
|
+
function isCodePath(filePath) {
|
|
908
|
+
const p = String(filePath || "").replace(/\\/g, "/");
|
|
909
|
+
if (!p) return false;
|
|
910
|
+
const segments = p.split("/").filter(Boolean);
|
|
911
|
+
if (segments.some((s) => NON_CODE_SEGMENTS.has(s))) return false;
|
|
912
|
+
const base = segments[segments.length - 1] || "";
|
|
913
|
+
if (NON_CODE_BASENAMES.has(base)) return false;
|
|
914
|
+
const dot = base.lastIndexOf(".");
|
|
915
|
+
const ext = dot > 0 ? base.slice(dot).toLowerCase() : "";
|
|
916
|
+
return !NON_CODE_EXT.has(ext);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/* Git subcommands that write content or history into the current checkout.
|
|
920
|
+
* Read-only git (`status`/`fetch`/`log`/`diff`/`show`) and `worktree add` (the
|
|
921
|
+
* isolation primitive itself) are deliberately absent, so a session on `main`
|
|
922
|
+
* can still inspect and isolate. HEAD moves (`checkout`/`switch`) are owned by
|
|
923
|
+
* the branch-switch guard, so they are left out here to keep one rule per
|
|
924
|
+
* failure mode. */
|
|
925
|
+
const GIT_MUTATIONS = new Set([
|
|
926
|
+
"add", "commit", "push", "apply", "am", "merge", "rebase",
|
|
927
|
+
"cherry-pick", "revert", "reset", "clean", "rm", "mv", "stash",
|
|
928
|
+
]);
|
|
929
|
+
|
|
930
|
+
/* `GIT_MUTATIONS` subcommands that also have a read-only form. `git stash list`
|
|
931
|
+
* / `git stash show` only read the stash — `stash` is in the set for push/pop/
|
|
932
|
+
* drop, but the inspection shape must not read as a main-checkout mutation
|
|
933
|
+
* (measured: `git stash list` blocked as "a command that mutates this
|
|
934
|
+
* checkout"). The value is the set of read-only first positionals; a bare
|
|
935
|
+
* `git stash` (push) or an unknown subcommand stays a mutation (conservative). */
|
|
936
|
+
const GIT_READONLY_FORMS = { stash: new Set(["list", "show"]) };
|
|
937
|
+
|
|
938
|
+
function isReadOnlyGitForm(subcommand, args) {
|
|
939
|
+
const ro = GIT_READONLY_FORMS[subcommand];
|
|
940
|
+
if (!ro) return false;
|
|
941
|
+
const first = (args || []).find((a) => !a.startsWith("-"));
|
|
942
|
+
return !!first && ro.has(first);
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/* A redirect target that never lands in the working tree: discard/stdio, the
|
|
946
|
+
* OS temp dirs, and the gitignored `.serve/` runtime container. */
|
|
947
|
+
function isAllowedWriteTarget(target) {
|
|
948
|
+
const s = String(target || "").replace(/^["']|["']$/g, "");
|
|
949
|
+
if (s === "/dev/null" || s === "/dev/stdout" || s === "/dev/stderr") return true;
|
|
950
|
+
if (/^\/dev\/fd\//.test(s)) return true;
|
|
951
|
+
if (/^\/(tmp|var\/tmp)\//.test(s)) return true;
|
|
952
|
+
if (/(^|\/)\.serve\//.test(s)) return true;
|
|
953
|
+
return false;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/* Drop single/double quoted substrings before scanning for redirections, so a
|
|
957
|
+
* literal `->` or `>` inside an echo/grep argument is never read as a file
|
|
958
|
+
* write. */
|
|
959
|
+
function stripQuoted(text) {
|
|
960
|
+
return String(text || "").replace(/"(?:\\.|[^"\\])*"|'(?:[^']*)'/g, " ");
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/* Git subcommands whose positional args are path operands (`git add <paths>`),
|
|
964
|
+
* as opposed to history ops that name no paths (`git push`, `git rebase`). For
|
|
965
|
+
* `commit`/`reset` only post-`--` args are pathspecs; a bare trailing arg is
|
|
966
|
+
* ambiguous and stays pathless (conservative). */
|
|
967
|
+
const GIT_PATHSPEC_SUBCOMMANDS = new Set(["add", "rm", "mv", "apply"]);
|
|
968
|
+
|
|
969
|
+
/* Flags that consume the NEXT token as their value, so it must not be mistaken
|
|
970
|
+
* for a pathspec (`git commit -m "docs: fix"`). */
|
|
971
|
+
const GIT_VALUE_FLAGS = new Set([
|
|
972
|
+
"-m", "--message", "-F", "--file", "--author", "--date", "--reuse-message",
|
|
973
|
+
"-c", "-C", "--fixup", "--squash", "--template", "--pathspec-from-file",
|
|
974
|
+
"--exclude", "--chmod", "--src-prefix", "--dst-prefix", "--directory",
|
|
975
|
+
"--trailer", "--cleanup",
|
|
976
|
+
]);
|
|
977
|
+
|
|
978
|
+
/* The explicit pathspecs named by one git mutation. Empty means the op carries
|
|
979
|
+
* no static path info (a whole-index `commit`, a `push`, a `rebase`) and the
|
|
980
|
+
* caller must resolve the affected paths at runtime. */
|
|
981
|
+
function gitPathspecs(subcommand, args) {
|
|
982
|
+
const out = [];
|
|
983
|
+
let afterDash = false;
|
|
984
|
+
for (let i = 0; i < args.length; i++) {
|
|
985
|
+
const a = args[i];
|
|
986
|
+
if (afterDash) {
|
|
987
|
+
out.push(a);
|
|
988
|
+
continue;
|
|
989
|
+
}
|
|
990
|
+
if (a === "--") {
|
|
991
|
+
afterDash = true;
|
|
992
|
+
continue;
|
|
993
|
+
}
|
|
994
|
+
if (a.startsWith("-")) {
|
|
995
|
+
if (GIT_VALUE_FLAGS.has(a)) i += 1;
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
const partial = (subcommand === "commit" || subcommand === "reset") && (a.includes("/") || a.startsWith("."));
|
|
999
|
+
if (GIT_PATHSPEC_SUBCOMMANDS.has(subcommand) || partial) out.push(a);
|
|
1000
|
+
}
|
|
1001
|
+
return out;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/* The non-git content mutators (`sed -i`, `perl -i`, `patch`, `tee`, redirect)
|
|
1005
|
+
* whose target path is named in the command, now resolved against `isCodePath`
|
|
1006
|
+
* so an in-place edit to a docs/metadata file does not read as code. */
|
|
1007
|
+
function contentCodeMutation(tokens, cmd) {
|
|
1008
|
+
const head = tokens.find((t) => !isRedirection(t) && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(t));
|
|
1009
|
+
if (head) {
|
|
1010
|
+
const base = basename(head);
|
|
1011
|
+
const rest = tokens.slice(tokens.indexOf(head) + 1);
|
|
1012
|
+
const operands = rest.filter((t) => !t.startsWith("-"));
|
|
1013
|
+
// The FILE operand is the last positional (`sed [opts] script file`,
|
|
1014
|
+
// `perl [opts] code file`); a script-only invocation stays conservative.
|
|
1015
|
+
const target = operands[operands.length - 1];
|
|
1016
|
+
if (base === "sed" && rest.some((t) => /^-i/.test(t)) && (!target || isCodePath(target))) return true;
|
|
1017
|
+
if (base === "perl" && rest.some((t) => /^-[^\s]*i/.test(t)) && (!target || isCodePath(target))) return true;
|
|
1018
|
+
if (base === "patch") return true;
|
|
1019
|
+
if (base === "tee") {
|
|
1020
|
+
const teeTarget = rest.find((t) => !t.startsWith("-"));
|
|
1021
|
+
if (teeTarget && !isAllowedWriteTarget(teeTarget) && isCodePath(teeTarget)) return true;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
// A redirect into the tree is conservative code regardless of extension: it
|
|
1025
|
+
// is a build/command output, not the board/docs maintenance carve-out.
|
|
1026
|
+
// The lookbehind skips a `>` that is part of an arrow (`=>`) or comparison
|
|
1027
|
+
// (`>=`) — a JS one-liner passed through `npx tsx -e` was read as a redirect.
|
|
1028
|
+
// The target class stops at shell metacharacters so `2>/dev/null)` and
|
|
1029
|
+
// `>/dev/null;` resolve to the allowed `/dev/null`, not `/dev/null)`.
|
|
1030
|
+
const redir = /(?<![=<>!-])>>?\s*([^\s;&|(){}<>'"]+)/g;
|
|
1031
|
+
let m;
|
|
1032
|
+
while ((m = redir.exec(stripQuoted(cmd)))) {
|
|
1033
|
+
if (!isAllowedWriteTarget(m[1])) return true;
|
|
1034
|
+
}
|
|
1035
|
+
return false;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/* Structured view of a shell command: whether it writes source/config content,
|
|
1039
|
+
* and every git mutation with its explicit pathspecs + effective repo selector.
|
|
1040
|
+
* The plugin refines the pathless git ops (whole-index `commit`/`push`) against
|
|
1041
|
+
* the live index; the pure predicate below treats them conservatively. */
|
|
1042
|
+
/* Split one shell command into segments on UNQUOTED `;`, `&&`, `||`, `|`, or a
|
|
1043
|
+
* newline. A naive `.split(/[|;]/)` tears a quoted regex apart, so a grep whose
|
|
1044
|
+
* pattern contains `|git add|` fabricates a `git add` mutation (measured:
|
|
1045
|
+
* `grep -nE "function |commit|git add|archive" scripts/finalize.js` was blocked
|
|
1046
|
+
* as "a command that mutates this checkout"). Quote state is tracked so an
|
|
1047
|
+
* operator inside `"…"`/`'…'` is never a separator. */
|
|
1048
|
+
function splitSegments(cmd) {
|
|
1049
|
+
const segments = [];
|
|
1050
|
+
let buf = "";
|
|
1051
|
+
let quote = null;
|
|
1052
|
+
const s = String(cmd || "");
|
|
1053
|
+
for (let i = 0; i < s.length; i++) {
|
|
1054
|
+
const ch = s[i];
|
|
1055
|
+
if (quote) {
|
|
1056
|
+
buf += ch;
|
|
1057
|
+
if (quote === '"' && ch === "\\" && i + 1 < s.length) buf += s[++i];
|
|
1058
|
+
else if (ch === quote) quote = null;
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
if (ch === '"' || ch === "'") {
|
|
1062
|
+
quote = ch;
|
|
1063
|
+
buf += ch;
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
if (ch === "\n" || ch === "\r") {
|
|
1067
|
+
segments.push(buf);
|
|
1068
|
+
buf = "";
|
|
1069
|
+
continue;
|
|
1070
|
+
}
|
|
1071
|
+
if (ch === ";") {
|
|
1072
|
+
segments.push(buf);
|
|
1073
|
+
buf = "";
|
|
1074
|
+
continue;
|
|
1075
|
+
}
|
|
1076
|
+
if (ch === "|") {
|
|
1077
|
+
segments.push(buf);
|
|
1078
|
+
buf = "";
|
|
1079
|
+
if (s[i + 1] === "|") i += 1;
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
if (ch === "&" && s[i + 1] === "&") {
|
|
1083
|
+
segments.push(buf);
|
|
1084
|
+
buf = "";
|
|
1085
|
+
i += 1;
|
|
1086
|
+
continue;
|
|
1087
|
+
}
|
|
1088
|
+
buf += ch;
|
|
1089
|
+
}
|
|
1090
|
+
segments.push(buf);
|
|
1091
|
+
return segments;
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
function classifyCommand(command) {
|
|
1095
|
+
const cmd = String(command || "");
|
|
1096
|
+
const result = { contentCode: false, gitOps: [] };
|
|
1097
|
+
if (!cmd) return result;
|
|
1098
|
+
for (const segment of splitSegments(cmd)) {
|
|
1099
|
+
const tokens = tokenize(segment);
|
|
1100
|
+
const found = gitSubcommand(tokens);
|
|
1101
|
+
if (found && GIT_MUTATIONS.has(found.subcommand) && !isReadOnlyGitForm(found.subcommand, found.args)) {
|
|
1102
|
+
const paths = gitPathspecs(found.subcommand, found.args);
|
|
1103
|
+
result.gitOps.push({
|
|
1104
|
+
subcommand: found.subcommand,
|
|
1105
|
+
args: found.args,
|
|
1106
|
+
paths,
|
|
1107
|
+
target: found.target,
|
|
1108
|
+
pathless: paths.length === 0,
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
if (!result.contentCode && contentCodeMutation(tokens, segment)) result.contentCode = true;
|
|
1112
|
+
}
|
|
1113
|
+
return result;
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/* True when a shell command writes source/config content or git history in the
|
|
1117
|
+
* current checkout. A git op whose explicit pathspecs are ALL non-code (e.g.
|
|
1118
|
+
* `git add .agents/handoffs/F-1.md BACKLOG.md`) does NOT match — the docs
|
|
1119
|
+
* maintenance carve-out. A pathless op (`git commit`, `git push`) stays
|
|
1120
|
+
* conservatively true here; the plugin resolves it against the index. Narrow by
|
|
1121
|
+
* design: the board CLI, test runs, `gh`, and read-only git never match. */
|
|
1122
|
+
function isCodeMutationCommand(command) {
|
|
1123
|
+
const { contentCode, gitOps } = classifyCommand(command);
|
|
1124
|
+
return (
|
|
1125
|
+
contentCode ||
|
|
1126
|
+
gitOps.some((op) => op.pathless || op.paths.some((p) => isCodePath(p)))
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/* `pkill -f <pat>` (or `--full`) matches each process's FULL command line —
|
|
1131
|
+
* which includes the `bash -c '<command>'` shell that pkill itself runs in — so
|
|
1132
|
+
* a pattern that also appears in its own command text SIGTERMs the agent's own
|
|
1133
|
+
* shell and interrupts the turn (measured twice in one session, 2026-10-16;
|
|
1134
|
+
* once it also killed the shared opencode service). Returns the self-matching
|
|
1135
|
+
* pattern, or null. `pkill <name>` (no `-f`) matches only the short process
|
|
1136
|
+
* name and is unaffected. */
|
|
1137
|
+
function shellSelfKill(command) {
|
|
1138
|
+
const cmd = String(command || "");
|
|
1139
|
+
if (!/\bpkill\b/.test(cmd)) return null;
|
|
1140
|
+
for (const segment of cmd.split(/\r?\n|&&|\|\||;|\|/)) {
|
|
1141
|
+
if (!/\bpkill\b/.test(segment)) continue;
|
|
1142
|
+
const rest = segment.slice(segment.search(/\bpkill\b/));
|
|
1143
|
+
if (!/(^|\s)(?:-f|--full)(?:\s|=)/.test(rest)) continue;
|
|
1144
|
+
const m = rest.match(/(?:-f|--full)(?:=|\s+)(?:"([^"]*)"|'([^']*)'|(\S+))/);
|
|
1145
|
+
const raw = m ? m[1] ?? m[2] ?? m[3] ?? "" : "";
|
|
1146
|
+
if (!raw) continue;
|
|
1147
|
+
let hit;
|
|
1148
|
+
try {
|
|
1149
|
+
hit = new RegExp(raw).test(cmd);
|
|
1150
|
+
} catch {
|
|
1151
|
+
hit = cmd.includes(raw);
|
|
1152
|
+
}
|
|
1153
|
+
if (hit) return raw;
|
|
1154
|
+
}
|
|
1155
|
+
return null;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
const SELFKILL_TEXT = (pat) =>
|
|
1159
|
+
`\`pkill -f\` matches the FULL command line of every process, including the ` +
|
|
1160
|
+
`\`bash -c\` shell running it — so the pattern \`${pat}\` also matches this very ` +
|
|
1161
|
+
`command and would SIGTERM your own shell (the turn dies mid-step). Kill by the ` +
|
|
1162
|
+
`recorded PID instead (\`kill <pid>\`), or write the pattern so it cannot match ` +
|
|
1163
|
+
`its own line (e.g. \`port 4[7]44\`). \`pkill <name>\` (no \`-f\`) is unaffected.`;
|
|
1164
|
+
|
|
1165
|
+
/* The harness source checkout dogfooding its own guard (`agent-harness dogfood`)
|
|
1166
|
+
* keeps editing `templates/**` on main — its normal workflow — so the
|
|
1167
|
+
* main-checkout block is skipped there. The IO probe is injected so the core
|
|
1168
|
+
* stays pure: the plugin passes a real `fs.existsSync`; tests pass a stub. A
|
|
1169
|
+
* missing/broken probe never disables the guard. */
|
|
1170
|
+
const DOGFOOD_MARKER = ".harness-dogfood";
|
|
1171
|
+
function mainEditGuardEnabled(markerPath, exists) {
|
|
1172
|
+
if (!markerPath || typeof exists !== "function") return true;
|
|
1173
|
+
try {
|
|
1174
|
+
if (exists(markerPath)) return false;
|
|
1175
|
+
} catch {
|
|
1176
|
+
/* a broken probe must never disable the guard */
|
|
1177
|
+
}
|
|
1178
|
+
return true;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
/* The error the plugin throws to abort a code change aimed at the main
|
|
1182
|
+
* checkout. Names the target and the fix (isolate) so recovery is mechanical.
|
|
1183
|
+
* When the feature id is known, the exact command is printed — the F-291 recon
|
|
1184
|
+
* showed a bare error sends the agent hunting for the right invocation. */
|
|
1185
|
+
function mainEditText(kind, target, feature, opts) {
|
|
1186
|
+
const what = kind === "bash" ? "a command that mutates this checkout" : `an edit to \`${target}\``;
|
|
1187
|
+
const noun = kind === "bash" ? "command" : "edit";
|
|
1188
|
+
const cmd = feature
|
|
1189
|
+
? `\`node scripts/backlog.js worktree ${feature}\``
|
|
1190
|
+
: "`node scripts/backlog.js worktree <id>`";
|
|
1191
|
+
const idNote = feature
|
|
1192
|
+
? `isolate \`${feature}\` first from the main tree: ${cmd}`
|
|
1193
|
+
: `isolate FIRST from the main tree: ${cmd} (a human starting the worktree at a terminal adds \`--open\`)`;
|
|
1194
|
+
// F-12: a target in ANOTHER project's main checkout (e.g. a project session
|
|
1195
|
+
// editing the harness `templates/`) cannot be fixed by isolating THIS session —
|
|
1196
|
+
// worktree isolation is per-repo. Name the cross-repo route instead of the
|
|
1197
|
+
// misleading "isolate here" advice.
|
|
1198
|
+
const crossRepoNote = opts && opts.crossRepo
|
|
1199
|
+
? ` This path belongs to a DIFFERENT checkout than this session (a harness-owned file?): worktree isolation cannot cross repos. Fix it from a session rooted in that checkout — for the harness, start opencode in \`~/develop/agent-harness\` and edit \`templates/\` there — then re-deploy with \`agent-harness update <this-project>\`.`
|
|
1200
|
+
: "";
|
|
1201
|
+
return `SESSION GUARD — blocked ${what}: this session is in the shared MAIN checkout, where code + git history are off-limits before isolation (the F-278 shape: work done on main cannot be finalized — \`finalize\` refuses on main and the branch switch is blocked while other sessions share the tree). ${idNote}, then make the change inside that worktree (set \`workdir\` to it). Only board/.agents/docs maintenance is allowed on main.${crossRepoNote} The ${noun} was NOT executed.`;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// ------------------------------------------- tool-choice & read-hygiene guard
|
|
1205
|
+
/* Advisory (never blocking) steering for the highest-volume avoidable habits
|
|
1206
|
+
* measured over the 2026-09-16 → 09-29 WSL sessions: shell file-inspection where
|
|
1207
|
+
* the dedicated tools exist, whole-tree output dumps, and re-reading files that
|
|
1208
|
+
* are already in context. Every text is CONSTANT so the tail stays byte-stable;
|
|
1209
|
+
* the plugin arms each notice at most once per session and clears it after the
|
|
1210
|
+
* next injected request (`clearOneShot`). */
|
|
1211
|
+
|
|
1212
|
+
/* Shell heads the dedicated Read/Grep/Glob tools cover better. Matched in
|
|
1213
|
+
* COMMAND POSITION only, and only when the command has no pipe/redirect (a
|
|
1214
|
+
* pipeline is real shell work). `sed`/`awk` are included for the ranged-read
|
|
1215
|
+
* shape but excluded when `-i` makes them an in-place edit — that path belongs to
|
|
1216
|
+
* the main-checkout classifier. */
|
|
1217
|
+
const SHELL_INSPECT_TOOLS = new Set([
|
|
1218
|
+
"cat", "ls", "find", "grep", "rg", "egrep", "fgrep", "head", "tail",
|
|
1219
|
+
"wc", "stat", "file", "more", "less", "tree", "sed", "awk",
|
|
1220
|
+
]);
|
|
1221
|
+
const SHELL_WRAPPERS = new Set(["sudo", "command", "env", "nohup", "time", "exec"]);
|
|
1222
|
+
|
|
1223
|
+
/* The command-position program + its args in one shell segment, skipping env
|
|
1224
|
+
* assignments and common wrappers (`sudo cat ...`). Null when the segment is
|
|
1225
|
+
* empty or only wrappers. */
|
|
1226
|
+
function commandHead(tokens) {
|
|
1227
|
+
let i = 0;
|
|
1228
|
+
while (i < tokens.length) {
|
|
1229
|
+
const t = tokens[i];
|
|
1230
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || SHELL_WRAPPERS.has(basename(t))) {
|
|
1231
|
+
i++;
|
|
1232
|
+
continue;
|
|
1233
|
+
}
|
|
1234
|
+
break;
|
|
1235
|
+
}
|
|
1236
|
+
return i < tokens.length ? { head: basename(tokens[i]), args: tokens.slice(i + 1) } : null;
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
/* The inspection head (`cat`, `grep`, …) when the FIRST command of a command
|
|
1240
|
+
* line is a read-only shell inspection the dedicated tools cover, else null. The
|
|
1241
|
+
* first shell segment is what matters: `grep -rn foo lib/ 2>/dev/null` and
|
|
1242
|
+
* `ls -la | head` are still a shell inspection of the tree (the downstream pipe/
|
|
1243
|
+
* redirect is output shaping), while `git log | grep x` is not (grep is a filter,
|
|
1244
|
+
* not the command). A trailing redirect on the first segment is ignored. */
|
|
1245
|
+
function inspectCommand(command) {
|
|
1246
|
+
const cmd = String(command || "");
|
|
1247
|
+
if (!cmd) return null;
|
|
1248
|
+
const first = cmd.split(/\r?\n|&&|\|\||;|\|/)[0];
|
|
1249
|
+
const found = commandHead(tokenize(first).filter((t) => !isRedirection(t)));
|
|
1250
|
+
if (!found || !SHELL_INSPECT_TOOLS.has(found.head)) return null;
|
|
1251
|
+
if ((found.head === "sed" || found.head === "awk") && found.args.some((a) => /^-i/.test(a))) return null;
|
|
1252
|
+
return found.head;
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
/* Rewrite a single leading `cd <path> && rest` into an explicit bash `workdir`,
|
|
1256
|
+
* so the tree is carried by the tool's cwd parameter instead of a shell `cd`
|
|
1257
|
+
* (the WSL `cd`-chaining habit — 2,981 calls / 388 sessions). Only the
|
|
1258
|
+
* unambiguous shape is transformed: exactly one `cd <literal-path> &&` prefix and
|
|
1259
|
+
* no other `cd` in the remainder. A dynamic path (`$VAR`, backticks, `-`) or an
|
|
1260
|
+
* explicit `workdir` already present is left untouched. */
|
|
1261
|
+
function rerootBash(command) {
|
|
1262
|
+
const cmd = String(command || "");
|
|
1263
|
+
const m = cmd.match(/^\s*cd\s+("[^"]*"|'[^']*'|[^\s&;|]+)\s*&&\s*([\s\S]+)$/);
|
|
1264
|
+
if (!m) return null;
|
|
1265
|
+
let dir = m[1];
|
|
1266
|
+
if ((dir.startsWith('"') && dir.endsWith('"')) || (dir.startsWith("'") && dir.endsWith("'"))) {
|
|
1267
|
+
dir = dir.slice(1, -1);
|
|
1268
|
+
}
|
|
1269
|
+
const rest = m[2];
|
|
1270
|
+
if (!dir || dir === "-" || /[$`]/.test(dir)) return null;
|
|
1271
|
+
// Only a tree-anchored path is safe to lift into `workdir`: a relative `cd sub`
|
|
1272
|
+
// resolves against the current cwd, which the tool cannot reproduce from the
|
|
1273
|
+
// launch directory alone.
|
|
1274
|
+
if (!/^(?:~\/|\/|[A-Za-z]:[\\/]|\\\\)/.test(dir)) return null;
|
|
1275
|
+
if (/(^|[^A-Za-z0-9_])cd\s/.test(rest)) return null; // a second cd changes semantics
|
|
1276
|
+
return { workdir: dir, command: rest };
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
/* Pathological whole-tree scans that dump unbounded output. Narrow on purpose —
|
|
1280
|
+
* a bare `git diff`/`git status` is legitimate, so only `find` rooted at the
|
|
1281
|
+
* filesystem and `ls -R` are flagged. */
|
|
1282
|
+
function dumpCommand(command) {
|
|
1283
|
+
for (const segment of String(command || "").split(/\r?\n|&&|\|\||;|\|/)) {
|
|
1284
|
+
const found = commandHead(tokenize(segment).filter((t) => !isRedirection(t)));
|
|
1285
|
+
if (!found) continue;
|
|
1286
|
+
if (found.head === "find") {
|
|
1287
|
+
const root = found.args.find((a) => !a.startsWith("-"));
|
|
1288
|
+
if (root === "/" || /^\/(?:mnt|home|usr|etc|var|opt|srv|root)(?:\/|$)/.test(root || "")) return "find";
|
|
1289
|
+
}
|
|
1290
|
+
if (found.head === "ls" && found.args.some((a) => /^-.*R/.test(a) || a === "-R")) return "ls";
|
|
1291
|
+
}
|
|
1292
|
+
return null;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
const INSPECT_TEXT =
|
|
1296
|
+
"TOOL GUARD — read-only shell inspection detected. Use the dedicated tools instead of shell `cat`/`ls`/`grep`/`find`/`sed`: `Read` (targeted with `offset`/`limit`), `Grep`, and `Glob`. They honour the project `.ignore` rules, return bounded output, and keep the transcript small. Reserve the shell for real commands and pipelines.";
|
|
1297
|
+
|
|
1298
|
+
/* Structural escalation of INSPECT_TEXT. The 0.1.104 advisory did not move the
|
|
1299
|
+
* measured habit (shell file-inspection stayed ~33% of bash two weeks later), so
|
|
1300
|
+
* the FIRST pure inspection of each head in a primary session is BLOCKED once,
|
|
1301
|
+
* with the dedicated-tool instruction. The caller may opt out for the machine
|
|
1302
|
+
* with `AGENT_GUARD_TOOLBLOCK=0`; a downstream filter (`git log | grep`) is not a
|
|
1303
|
+
* pure inspection and never blocks. */
|
|
1304
|
+
function inspectBlockText(head) {
|
|
1305
|
+
return `TOOL BLOCK — \`${head}\` is a read-only shell inspection the dedicated tools already cover; this one is blocked. Retry with \`Read\` (targeted \`offset\`/\`limit\`), \`Grep\`, or \`Glob\` — they honour the project \`.ignore\`, bound the output, and keep the transcript small. Use the shell only for real commands and pipelines. (Disable this block with \`AGENT_GUARD_TOOLBLOCK=0\`.)`;
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
/* H-23 escalation (2026-10-16): the one-shot block above still left shell
|
|
1309
|
+
* file-inspection flat over 2 weeks, so a PURE, single-path `cat <file>` /
|
|
1310
|
+
* `ls [<dir>]` is blocked on EVERY occurrence — `Read <file>` / `Glob <dir>` is
|
|
1311
|
+
* an exact substitute with no shell semantics to preserve. Deliberately narrow:
|
|
1312
|
+
* the whole command must be that one command (no pipe, redirect, `&&`, or `;`),
|
|
1313
|
+
* cat takes exactly one path, ls at most one, and `ls -R` (a whole-tree dump) is
|
|
1314
|
+
* handled by `dumpCommand` instead. Returns the head ("cat"/"ls") or null. Pure. */
|
|
1315
|
+
function repeatInspectBlock(command) {
|
|
1316
|
+
const cmd = String(command || "").trim();
|
|
1317
|
+
if (!cmd) return null;
|
|
1318
|
+
// A pipeline/redirect/sequence is real shell work — never hard-block it.
|
|
1319
|
+
if (/[|><;&\n]/.test(cmd)) return null;
|
|
1320
|
+
const found = commandHead(tokenize(cmd).filter((t) => !isRedirection(t)));
|
|
1321
|
+
if (!found) return null;
|
|
1322
|
+
if (found.head !== "cat" && found.head !== "ls") return null;
|
|
1323
|
+
const positionals = found.args.filter((a) => !a.startsWith("-"));
|
|
1324
|
+
if (positionals.length > 1) return null; // `cat a b` / `ls a b` is a multi-target read
|
|
1325
|
+
if (found.head === "cat" && positionals.length !== 1) return null; // bare `cat` reads stdin
|
|
1326
|
+
if (found.head === "ls" && found.args.some((a) => /^-.*R/.test(a) || a === "--recursive")) return null;
|
|
1327
|
+
return found.head;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
const READ_TEXTS = Object.freeze({
|
|
1331
|
+
reread:
|
|
1332
|
+
"TOOL GUARD — you already read this file in this session. Do not re-read it whole; it is already in context. Re-read only a specific changed region with `offset`/`limit`, or use `Grep` to locate the needed lines.",
|
|
1333
|
+
whole:
|
|
1334
|
+
"TOOL GUARD — a large file was read whole. Search first (`Grep`/`Glob`), then read a targeted `offset`/`limit` range — never read a big file blind (`.agents/AGENTS.md` §5).",
|
|
1335
|
+
missing:
|
|
1336
|
+
"TOOL GUARD — that path does not exist (a guessed path). If you meant a session checkpoint, do NOT guess a filename: handoffs are `.agents/handoffs/<feature-id>.md` (named for the FEATURE id — never `next.md`/`pending.md`/`auto.md`), and the supported way to load one is the `checkpoint_resume` tool (or `/resume <feature-id>`). Otherwise `Glob` the real path (e.g. `Glob .agents/handoffs/*.md`) or read `.agents/memory/locations.md` (the canonical locations index) before reading again — never re-hunt or guess.",
|
|
1337
|
+
});
|
|
1338
|
+
|
|
1339
|
+
const DUMP_TEXT =
|
|
1340
|
+
"TOOL GUARD — this command scans the whole tree and dumps unbounded output (`find /`, `ls -R`). Bound it: target specific paths, use `Glob`/`git ls-files`, and keep large output out of context.";
|
|
1341
|
+
|
|
1342
|
+
// ------------------------------------------------------- wait/poll guard
|
|
1343
|
+
/* Hand-rolled polling is a measured waste: the 2026-09 LibraryOS recon found 98
|
|
1344
|
+
* `sleep` commands + 81 `gh` polls in 30 days (rising on device-heavy days). A
|
|
1345
|
+
* blind `sleep N` either wastes minutes or forces another poll; `gh run watch`
|
|
1346
|
+
* blocks but never returns a machine summary. The harness ships a real bounded
|
|
1347
|
+
* waiter (`npm run wait` / the `wait` tool, and `run-detached.sh --wait` for the
|
|
1348
|
+
* device matrix). This advisory names it once per session. Advisory only — a
|
|
1349
|
+
* `sleep` inside a legitimate command pipeline is not a poll. */
|
|
1350
|
+
const WAIT_TEXT =
|
|
1351
|
+
"TOOL GUARD — hand-rolled polling detected (`sleep N; grep log`, or `gh run watch`). Blocking in a loop wastes wall-clock and re-bills context per poll. Use the bounded waiter instead: the `wait` tool (or `npm run wait -- --job <record.json>` / `--ci [--commit <sha>]` / `--file <log> --grep <re>` / `--health <url>` / `--port <n>`), and `scripts/qa/mobile-e2e/run-detached.sh --wait` for a device matrix. It returns the moment the condition is met and a terminal status on timeout.";
|
|
1352
|
+
|
|
1353
|
+
/* A `sleep` command that is a poll: a `sleep` segment followed in the SAME
|
|
1354
|
+
* command by a log tail/grep or a `gh run watch|view|pr checks`. Pure. */
|
|
1355
|
+
function pollCommand(command) {
|
|
1356
|
+
const cmd = stripQuoted(String(command || ""));
|
|
1357
|
+
if (/\bgh\s+run\s+watch\b/.test(cmd)) return "gh-watch";
|
|
1358
|
+
if (!/\bsleep\b/.test(cmd)) return null;
|
|
1359
|
+
if (/\bgh\s+(run\s+(watch|view)|pr\s+(checks|view))\b/.test(cmd)) return "gh";
|
|
1360
|
+
if (/\b(tail|cat|grep|rg|head|sed|awk|less|journalctl)\b/.test(cmd)) return "sleep+log";
|
|
1361
|
+
// A bare `sleep N` with no companion read is still a poll when it is the
|
|
1362
|
+
// whole first segment (wait-and-pray before re-checking by hand).
|
|
1363
|
+
const first = cmd.split(/\r?\n|&&|\|\||;|\|/)[0].trim();
|
|
1364
|
+
if (/^sleep\b/.test(first)) return "sleep";
|
|
1365
|
+
return null;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
/* One-shot per session: the first poll-shaped call arms the advisory. */
|
|
1369
|
+
function notePollCall(state, command) {
|
|
1370
|
+
const kind = pollCommand(command);
|
|
1371
|
+
if (!kind) return { poll: false, kind: null, firstFlag: false };
|
|
1372
|
+
if (state.waitFlagged) return { poll: true, kind, firstFlag: false };
|
|
1373
|
+
state.waitFlagged = true;
|
|
1374
|
+
state.waitPending = true;
|
|
1375
|
+
return { poll: true, kind, firstFlag: true };
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
/* Structural twin of notePollCall: block the FIRST poll of each kind in a
|
|
1379
|
+
* primary session (once), naming the bounded waiter. Same opt-out as the
|
|
1380
|
+
* inspection block. */
|
|
1381
|
+
function pollBlockText(kind) {
|
|
1382
|
+
return `TOOL BLOCK — hand-rolled polling (\`${kind}\`) is blocked; it wastes wall-clock and re-bills context per poll. Use the bounded waiter: the \`wait\` tool (or \`npm run wait -- --job <record.json>\` / \`--ci [--commit <sha>]\` / \`--file <log> --grep <re>\` / \`--health <url>\` / \`--port <n>\`), or \`scripts/qa/mobile-e2e/run-detached.sh --wait\` for a device matrix. (Disable this block with \`AGENT_GUARD_TOOLBLOCK=0\`.)`;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
/* Whether the structural tool blocks are enabled for this machine. */
|
|
1386
|
+
function toolBlockEnabled(env) {
|
|
1387
|
+
return String((env || process.env).AGENT_GUARD_TOOLBLOCK || "") !== "0";
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
const READ_LARGE_BYTES = 20000;
|
|
1391
|
+
|
|
1392
|
+
/* First read of a path is silent; a second read of the SAME path in one session
|
|
1393
|
+
* arms the one-shot re-read nudge. `state.readSeen` is the session's read set. */
|
|
1394
|
+
function noteReadBefore(state, filePath) {
|
|
1395
|
+
const p = String(filePath || "");
|
|
1396
|
+
if (!p) return { reread: false, firstFlag: false };
|
|
1397
|
+
const reread = state.readSeen.has(p);
|
|
1398
|
+
state.readSeen.add(p);
|
|
1399
|
+
if (reread && !state.readNotices.has("reread")) {
|
|
1400
|
+
state.readNotices.add("reread");
|
|
1401
|
+
state.readPending = "reread";
|
|
1402
|
+
return { reread: true, firstFlag: true };
|
|
1403
|
+
}
|
|
1404
|
+
return { reread, firstFlag: false };
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
/* After a read: a failed read arms the guessed-path nudge; a successful
|
|
1408
|
+
* whole-file read of a large file arms the whole-file nudge. Each kind fires at
|
|
1409
|
+
* most once per session. */
|
|
1410
|
+
function noteReadAfter(state, args, output, largeBytes = READ_LARGE_BYTES) {
|
|
1411
|
+
const failed = !!output?.error || String(output?.status || "") === "error";
|
|
1412
|
+
if (failed) {
|
|
1413
|
+
if (!state.readNotices.has("missing")) {
|
|
1414
|
+
state.readNotices.add("missing");
|
|
1415
|
+
state.readPending = "missing";
|
|
1416
|
+
return { notice: "missing", firstFlag: true };
|
|
1417
|
+
}
|
|
1418
|
+
return { notice: null, firstFlag: false };
|
|
1419
|
+
}
|
|
1420
|
+
const ranged = args?.offset != null || args?.limit != null;
|
|
1421
|
+
const bytes = typeof output?.output === "string" ? output.output.length : 0;
|
|
1422
|
+
if (!ranged && bytes >= largeBytes && !state.readNotices.has("whole")) {
|
|
1423
|
+
state.readNotices.add("whole");
|
|
1424
|
+
state.readPending = "whole";
|
|
1425
|
+
return { notice: "whole", firstFlag: true };
|
|
1426
|
+
}
|
|
1427
|
+
return { notice: null, firstFlag: false };
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
/* Clear the one-shot hygiene notices after they have been injected once, so a
|
|
1431
|
+
* standing preference does not nag on every later request. */
|
|
1432
|
+
function clearOneShot(state) {
|
|
1433
|
+
state.inspectPending = false;
|
|
1434
|
+
state.readPending = null;
|
|
1435
|
+
state.dumpPending = false;
|
|
1436
|
+
state.editMissPending = false;
|
|
1437
|
+
state.gateRerunPending = false;
|
|
1438
|
+
state.todoPending = null;
|
|
1439
|
+
state.waitPending = false;
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
// --------------------------------------------------- inspect re-arm (D)
|
|
1443
|
+
/* The shell-inspection advisory used to fire at most ONCE per session; the recon
|
|
1444
|
+
* showed shell inspection still at 31-38% of bash after it shipped, so a single
|
|
1445
|
+
* one-shot nudge is not enough. Re-arm it after `inspect_rearm_every` (default
|
|
1446
|
+
* 10) FURTHER inspections, or immediately when a DIFFERENT shell head appears
|
|
1447
|
+
* (`cat` -> `grep`), so a returning habit gets a fresh, specific reminder without
|
|
1448
|
+
* nagging on every call. The text is constant (cache-safe). */
|
|
1449
|
+
const DEFAULT_INSPECT_REARM_EVERY = 10;
|
|
1450
|
+
|
|
1451
|
+
function noteInspect(state, head, rearmEvery) {
|
|
1452
|
+
if (!head) return { fire: false, count: state.inspectCount };
|
|
1453
|
+
state.inspectCount += 1;
|
|
1454
|
+
const every = Number.isFinite(rearmEvery) && rearmEvery > 0 ? rearmEvery : DEFAULT_INSPECT_REARM_EVERY;
|
|
1455
|
+
const differentHead = state.inspectLastHead != null && state.inspectLastHead !== head;
|
|
1456
|
+
state.inspectLastHead = head;
|
|
1457
|
+
const sinceFlag = state.inspectCount - state.inspectFlaggedAt;
|
|
1458
|
+
if (state.inspectFlaggedAt === 0 || differentHead || sinceFlag >= every) {
|
|
1459
|
+
state.inspectFlaggedAt = state.inspectCount;
|
|
1460
|
+
state.inspectPending = true;
|
|
1461
|
+
return { fire: true, count: state.inspectCount, differentHead };
|
|
1462
|
+
}
|
|
1463
|
+
return { fire: false, count: state.inspectCount };
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
// --------------------------------------------------- edit-miss guard (E)
|
|
1467
|
+
/* A failed `edit`/`write`/`apply_patch` is almost always a guessed or stale
|
|
1468
|
+
* path (the recon measured 38 failed edits + 11 failed apply_patch, and a broken
|
|
1469
|
+
* `.../.virtualLibrary/...` path was observed live). One-shot advisory: check the
|
|
1470
|
+
* locations index / Glob, never re-hunt. Constant text. */
|
|
1471
|
+
const EDIT_MISS_TEXT =
|
|
1472
|
+
"TOOL GUARD — an edit/write targeted a path that does not exist (a guessed or stale path). Check `.agents/memory/locations.md` (the canonical locations index) or use `Glob` to find the real path before editing again — never re-hunt or guess. If the file moved, locate it first, then edit the real path.";
|
|
1473
|
+
|
|
1474
|
+
function noteEditAfter(state, failed) {
|
|
1475
|
+
if (!failed) return { firstFlag: false };
|
|
1476
|
+
if (state.editMissFlagged) return { firstFlag: false };
|
|
1477
|
+
state.editMissFlagged = true;
|
|
1478
|
+
state.editMissPending = true;
|
|
1479
|
+
return { firstFlag: true };
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// --------------------------------------------------- gate re-run guard (F)
|
|
1483
|
+
/* Running the same gate repeatedly with no intervening edit ("edit -> gate ->
|
|
1484
|
+
* edit -> gate", or re-running an unchanged gate as a ritual) is a measured
|
|
1485
|
+
* waste (153 gate runs in two days; `tsc`/`test:quick` ~25x each). Track each
|
|
1486
|
+
* gate's run count; reset on a material edit. Arm when the SAME gate runs
|
|
1487
|
+
* `gate_rerun_turns` (default 3) times with zero edits since its previous run.
|
|
1488
|
+
* Constant text; one nudge per gate per session. */
|
|
1489
|
+
const GATE_RERUN_TEXT =
|
|
1490
|
+
"TOOL GUARD — the same gate is being re-run with no code change in between (`tsc`/`test:quick`/`lint`). Batch a coherent set of edits, THEN run the gate once (`.agents/rules/00-operating.md` §Gate batching). Prefer the cheapest covering tier (`gates --phase=quick`) over the full battery, and read the failing gate's output instead of re-running it blind. A re-run is warranted only after a real edit, a new failure, an integration/rebase, or when the dispatch requires it.";
|
|
1491
|
+
|
|
1492
|
+
const DEFAULT_GATE_RERUN_TURNS = 3;
|
|
1493
|
+
|
|
1494
|
+
/* Normalize a bash command to the gate it runs, or null when it is not a gate.
|
|
1495
|
+
* Only the project-level gates that the recon showed repeating. Pure. */
|
|
1496
|
+
function gateKey(command) {
|
|
1497
|
+
const cmd = String(command || "");
|
|
1498
|
+
if (/\btsc\b.*--noEmit|\bnpx\s+tsc\b/.test(cmd)) return "tsc";
|
|
1499
|
+
const m = cmd.match(/\bnpm\s+run\s+(test:[a-z-]+|lint[a-z:-]*|build)\b/);
|
|
1500
|
+
if (m) return m[1];
|
|
1501
|
+
if (/\beslint\b/.test(cmd)) return "eslint";
|
|
1502
|
+
return null;
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/* Record a gate run. Any material edit (via `noteToolCall`) resets all counters,
|
|
1506
|
+
* so a gate re-run after an edit never counts. Returns { fire, key, count }. */
|
|
1507
|
+
function noteGateRun(state, command, threshold) {
|
|
1508
|
+
const key = gateKey(command);
|
|
1509
|
+
if (!key) return { fire: false, key: null, count: 0 };
|
|
1510
|
+
const entry = state.gateRuns.get(key) || { count: 0, atFlag: 0 };
|
|
1511
|
+
entry.count += 1;
|
|
1512
|
+
state.gateRuns.set(key, entry);
|
|
1513
|
+
const t = Number.isFinite(threshold) && threshold > 0 ? threshold : DEFAULT_GATE_RERUN_TURNS;
|
|
1514
|
+
const sinceFlag = entry.count - entry.atFlag;
|
|
1515
|
+
if (!state.gateRerunFlagged.has(key) && sinceFlag >= t) {
|
|
1516
|
+
state.gateRerunFlagged.add(key);
|
|
1517
|
+
entry.atFlag = entry.count;
|
|
1518
|
+
state.gateRerunPending = true;
|
|
1519
|
+
return { fire: true, key, count: entry.count };
|
|
1520
|
+
}
|
|
1521
|
+
return { fire: false, key, count: entry.count };
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
/* A material edit resets the gate counters: the batched edit invalidates the
|
|
1525
|
+
* previous gate result, so the next run is legitimate. */
|
|
1526
|
+
function resetGateRuns(state) {
|
|
1527
|
+
state.gateRuns = new Map();
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
module.exports = {
|
|
1531
|
+
DEFAULT_TURNS,
|
|
1532
|
+
DEFAULT_STUCK,
|
|
1533
|
+
DEFAULT_REQUEST,
|
|
1534
|
+
DEFAULT_TODO,
|
|
1535
|
+
TODO_TEXTS,
|
|
1536
|
+
TODO_USE_TEXT,
|
|
1537
|
+
TODO_STALE_TEXT,
|
|
1538
|
+
TODO_INVALID_TEXT,
|
|
1539
|
+
TODO_CLOSE_TEXT,
|
|
1540
|
+
BAND_TEXT,
|
|
1541
|
+
GUARD_PROVENANCE,
|
|
1542
|
+
NO_STATE_TEXT,
|
|
1543
|
+
FAILURE_TEXT,
|
|
1544
|
+
LOOP_TEXT,
|
|
1545
|
+
FUNDS_TEXT,
|
|
1546
|
+
BAND_RANK,
|
|
1547
|
+
REQUEST_BAND,
|
|
1548
|
+
fundsText,
|
|
1549
|
+
fundsError,
|
|
1550
|
+
fundsArmText,
|
|
1551
|
+
modelLabel,
|
|
1552
|
+
parseThresholds,
|
|
1553
|
+
turnBand,
|
|
1554
|
+
bandRank,
|
|
1555
|
+
requestBand,
|
|
1556
|
+
pressureBand,
|
|
1557
|
+
bandText,
|
|
1558
|
+
guardTexts,
|
|
1559
|
+
composeGuardText,
|
|
1560
|
+
requestLevel,
|
|
1561
|
+
requestTokensOf,
|
|
1562
|
+
stableStringify,
|
|
1563
|
+
shortHash,
|
|
1564
|
+
isLoopExempt,
|
|
1565
|
+
isMaterial,
|
|
1566
|
+
loopKey,
|
|
1567
|
+
createSessionState,
|
|
1568
|
+
noteAssistant,
|
|
1569
|
+
noteToolCall,
|
|
1570
|
+
noteToolResult,
|
|
1571
|
+
normalizeTodos,
|
|
1572
|
+
noteTodoWrite,
|
|
1573
|
+
armTodoNudge,
|
|
1574
|
+
formatGuardEvent,
|
|
1575
|
+
branchSwitch,
|
|
1576
|
+
branchSwitchText,
|
|
1577
|
+
isCodePath,
|
|
1578
|
+
isCodeMutationCommand,
|
|
1579
|
+
classifyCommand,
|
|
1580
|
+
gitPathspecs,
|
|
1581
|
+
isAllowedWriteTarget,
|
|
1582
|
+
stripQuoted,
|
|
1583
|
+
mainEditText,
|
|
1584
|
+
shellSelfKill,
|
|
1585
|
+
SELFKILL_TEXT,
|
|
1586
|
+
DOGFOOD_MARKER,
|
|
1587
|
+
mainEditGuardEnabled,
|
|
1588
|
+
INSPECT_TEXT,
|
|
1589
|
+
READ_TEXTS,
|
|
1590
|
+
DUMP_TEXT,
|
|
1591
|
+
WAIT_TEXT,
|
|
1592
|
+
EDIT_MISS_TEXT,
|
|
1593
|
+
GATE_RERUN_TEXT,
|
|
1594
|
+
inspectBlockText,
|
|
1595
|
+
repeatInspectBlock,
|
|
1596
|
+
pollBlockText,
|
|
1597
|
+
toolBlockEnabled,
|
|
1598
|
+
pollCommand,
|
|
1599
|
+
notePollCall,
|
|
1600
|
+
noteInspect,
|
|
1601
|
+
noteEditAfter,
|
|
1602
|
+
gateKey,
|
|
1603
|
+
noteGateRun,
|
|
1604
|
+
resetGateRuns,
|
|
1605
|
+
DEFAULT_INSPECT_REARM_EVERY,
|
|
1606
|
+
DEFAULT_GATE_RERUN_TURNS,
|
|
1607
|
+
READ_LARGE_BYTES,
|
|
1608
|
+
SHELL_INSPECT_TOOLS,
|
|
1609
|
+
commandHead,
|
|
1610
|
+
inspectCommand,
|
|
1611
|
+
rerootBash,
|
|
1612
|
+
dumpCommand,
|
|
1613
|
+
noteReadBefore,
|
|
1614
|
+
noteReadAfter,
|
|
1615
|
+
clearOneShot,
|
|
1616
|
+
normalizeRootPath,
|
|
1617
|
+
ownsLocation,
|
|
1618
|
+
};
|