@tea-agent/loop-agent 0.22.0 → 0.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/AGENTS.md +42 -108
  2. package/CHANGELOG.md +68 -0
  3. package/README.md +7 -4
  4. package/dist/application/context-usage/skill-resolution-stats.js +263 -0
  5. package/dist/application/dag/generate-task-dag.js +17 -3
  6. package/dist/cli/command-definitions.js +8 -7
  7. package/dist/cli/program.js +17 -15
  8. package/dist/commands/doctor.js +269 -18
  9. package/dist/commands/init.js +101 -86
  10. package/dist/commands/stats.js +40 -11
  11. package/dist/shared/operator/capabilities.js +11 -1
  12. package/dist/worker/console/app-data.js +4 -0
  13. package/dist/worker/console/chat/instruction-skills.js +217 -0
  14. package/dist/worker/console/chat/model-resolver.js +106 -0
  15. package/dist/worker/console/chat/pi-runtime.js +605 -0
  16. package/dist/worker/console/chat/resource-loader.js +66 -0
  17. package/dist/worker/console/chat/routes.js +357 -0
  18. package/dist/worker/console/chat/session-store.js +238 -0
  19. package/dist/worker/console/chat/tool-adapter.js +238 -0
  20. package/dist/worker/console/chat/tools.js +171 -0
  21. package/dist/worker/console/server.js +55 -0
  22. package/dist/worker/console/static/assets/index-DVl7Jxt5.js +25 -0
  23. package/dist/worker/console/static/assets/index-lVcIr9Ju.css +1 -0
  24. package/dist/worker/console/static/index.html +2 -2
  25. package/dist/worker/feature/profile-schema.js +1 -1
  26. package/dist/workflows/dag/init-hybrid.js +69 -21
  27. package/dist/workflows/dag/node-execution.js +38 -1
  28. package/dist/workflows/dag/output-protocol.js +89 -0
  29. package/dist/workflows/dag/prompt.js +35 -1
  30. package/dist/workflows/dag/recovery-recommendation.js +45 -0
  31. package/dist/workflows/dag/report.js +28 -1
  32. package/dist/workflows/dag/rerun-task.js +1 -1
  33. package/dist/workflows/dag/scheduler.js +9 -0
  34. package/dist/workflows/dag/types.js +12 -0
  35. package/dist/workflows/dag/validate.js +55 -0
  36. package/docs/README.md +73 -156
  37. package/docs/architecture/README.md +3 -2
  38. package/docs/architecture/dag-execution.md +2 -2
  39. package/docs/architecture/evolution.md +14 -12
  40. package/docs/architecture/system-overview.md +1 -1
  41. package/docs/architecture/worker-and-feature.md +3 -3
  42. package/docs/governance/README.md +15 -0
  43. package/docs/{harness-methodology-debugging.md → governance/harness-methodology-debugging.md} +27 -3
  44. package/docs/init-surface.manifest.json +22 -4
  45. package/docs/operations/README.md +12 -0
  46. package/docs/{local-development-environment.md → operations/local-development-environment.md} +1 -1
  47. package/docs/skills/vetted-skill-registry.md +23 -3
  48. package/docs/templates/README.md +55 -0
  49. package/docs/templates/evaluation/agents-map-slim-v1.candidate.json +9 -0
  50. package/docs/templates/evaluation/agents-map-slim-v1.md +87 -0
  51. package/docs/templates/evaluation/agents-map-verbose-v0.candidate.json +9 -0
  52. package/docs/templates/evaluation/agents-map-verbose-v0.md +153 -0
  53. package/docs/templates/hybrid-dag.json +1 -1
  54. package/docs/templates/progress-log.md +9 -2
  55. package/harness.json +5 -5
  56. package/package.json +5 -5
  57. package/scripts/kb-bootstrap-init-skeleton.sh +2 -2
  58. package/skills/agent-worker/SKILL.md +1 -1
  59. package/skills/grill-with-docs/SKILL.md +44 -52
  60. package/skills/grill-with-docs/adr-format.md +37 -26
  61. package/skills/grill-with-docs/context-format.md +18 -26
  62. package/skills/loop-agent/SKILL.md +28 -112
  63. package/skills/loop-agent/references/command-reference.md +9 -3
  64. package/skills/loop-agent/references/harness-policy.md +3 -3
  65. package/skills/loop-agent/references/hybrid-dag.md +1 -1
  66. package/skills/loop-agent/references/orchestrator-and-interventions.md +1 -1
  67. package/skills/loop-agent/references/task-workflow.md +2 -0
  68. package/skills/systematic-debugging/SKILL.md +20 -4
  69. package/skills/test-driven-development/SKILL.md +10 -3
  70. package/dist/worker/console/static/assets/index-CUDke82y.js +0 -18
  71. package/dist/worker/console/static/assets/index-wSEksVSO.css +0 -1
  72. /package/docs/{harness-methodology-tdd.md → governance/harness-methodology-tdd.md} +0 -0
  73. /package/docs/{harness-methodology-verification.md → governance/harness-methodology-verification.md} +0 -0
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Operator Chat — instruction skills whitelist (design §7.5 / plan D1).
3
+ *
4
+ * Hard rules (plan D1):
5
+ * - skills are READ-ONLY text context injected into the Chat system prompt;
6
+ * - skills are NEVER registered as executable tools;
7
+ * - the whitelist is a COMPILE-TIME constant (no runtime dir scan, no env override);
8
+ * - arbitrary pi extension / package tool / user-level ~/.pi/agent skill is
9
+ * never discovered or loaded (V12);
10
+ * - project `.agents/skills/` (init projection) is NOT injected (prevents
11
+ * target-repo injecting write instructions).
12
+ *
13
+ * Only the loop-agent repo's own audited skills are eligible. Workflow-specific
14
+ * skills are conditional on taskKind/workflow and loaded on demand (not in MVP
15
+ * operator-context default set).
16
+ */
17
+ import { readFile } from "node:fs/promises";
18
+ import path from "node:path";
19
+ /**
20
+ * Operator-context instruction skills (plan D1, "operator-context 允许").
21
+ * These are read-only methodology skills. Loaded as text context for every
22
+ * Chat session by default.
23
+ *
24
+ * MUST stay a compile-time constant. Adding a skill requires an ADR / plan note.
25
+ */
26
+ export const OPERATOR_CHAT_ALLOWED_INSTRUCTION_SKILLS = Object.freeze([
27
+ "grill-me",
28
+ "systematic-debugging",
29
+ "code-review-core",
30
+ "codebase-scout",
31
+ "verification-before-completion",
32
+ "requesting-code-review",
33
+ "analyze-product-requirements",
34
+ "analyze-product-dependencies",
35
+ "using-git-worktrees",
36
+ ]);
37
+ /**
38
+ * Meta / governance skills that must NEVER be injected into Chat context
39
+ * (plan D1 "元 / 治理 skill"). Injecting these would let Chat rewrite its own
40
+ * governance. Listed explicitly so accidental allowlist edits are caught.
41
+ */
42
+ export const OPERATOR_CHAT_DENIED_INSTRUCTION_SKILLS = Object.freeze([
43
+ "loop-agent",
44
+ "agent-worker",
45
+ "init-capability-evolution",
46
+ "ai-engineering-context",
47
+ "grill-with-docs",
48
+ ]);
49
+ /**
50
+ * Workflow-specific skills (plan D1 "workflow-specific 允许(条件)").
51
+ * Only injected when the corresponding taskKind / workflow is active.
52
+ * NOT loaded by default in MVP Chat.
53
+ */
54
+ export const OPERATOR_CHAT_WORKFLOW_CONDITIONAL_SKILLS = Object.freeze([
55
+ "frontend-implementation",
56
+ "frontend-review",
57
+ "frontend-verification",
58
+ "frontend-design-review",
59
+ "test-driven-development",
60
+ "webapp-testing",
61
+ "playwright-cli",
62
+ "playwright-cli-case-generator",
63
+ "browser-tools",
64
+ ]);
65
+ const ALLOWED = new Set(OPERATOR_CHAT_ALLOWED_INSTRUCTION_SKILLS.map((s) => s.toLowerCase()));
66
+ const DENIED = new Set(OPERATOR_CHAT_DENIED_INSTRUCTION_SKILLS.map((s) => s.toLowerCase()));
67
+ const CONDITIONAL = new Set(OPERATOR_CHAT_WORKFLOW_CONDITIONAL_SKILLS.map((s) => s.toLowerCase()));
68
+ export function isOperatorChatInstructionSkillAllowed(name) {
69
+ return ALLOWED.has(name.trim().toLowerCase());
70
+ }
71
+ export function isOperatorChatInstructionSkillDenied(name) {
72
+ return DENIED.has(name.trim().toLowerCase());
73
+ }
74
+ export function isOperatorChatInstructionSkillConditional(name) {
75
+ return CONDITIONAL.has(name.trim().toLowerCase());
76
+ }
77
+ export function classifyInstructionSkill(name, options) {
78
+ const n = name.trim().toLowerCase();
79
+ if (DENIED.has(n)) {
80
+ return { ok: false, reason: "denied-governance", name };
81
+ }
82
+ if (ALLOWED.has(n)) {
83
+ return { ok: true, kind: "operator-context", name };
84
+ }
85
+ if (CONDITIONAL.has(n)) {
86
+ const active = options?.activeWorkflowSkills ?? [];
87
+ const activeLower = new Set(active.map((s) => s.toLowerCase()));
88
+ if (activeLower.has(n)) {
89
+ // Conditional skill is allowed only when explicitly activated by workflow.
90
+ // For MVP, conditional skills are not auto-injected; callers must opt in.
91
+ return { ok: false, reason: "conditional-not-active", name };
92
+ }
93
+ return { ok: false, reason: "conditional-not-active", name };
94
+ }
95
+ return { ok: false, reason: "unknown", name };
96
+ }
97
+ /**
98
+ * Parse a SKILL.md frontmatter description (first `description:` line) and
99
+ * return the body text (frontmatter stripped). Tolerant of missing frontmatter.
100
+ */
101
+ export function parseSkillFrontmatter(raw) {
102
+ let description = "";
103
+ let bodyText = raw;
104
+ const hasFrontmatter = raw.trimStart().startsWith("---");
105
+ if (hasFrontmatter) {
106
+ const lines = raw.split(/\r?\n/);
107
+ // find closing ---
108
+ let closeIdx = -1;
109
+ for (let i = 1; i < lines.length; i++) {
110
+ if (lines[i].trim() === "---") {
111
+ closeIdx = i;
112
+ break;
113
+ }
114
+ }
115
+ if (closeIdx > 0) {
116
+ const fm = lines.slice(1, closeIdx).join("\n");
117
+ bodyText = lines.slice(closeIdx + 1).join("\n").trim();
118
+ const descMatch = fm.match(/^description:\s*(.+)$/m);
119
+ if (descMatch) {
120
+ description = descMatch[1].trim().replace(/^["']|["']$/g, "");
121
+ }
122
+ }
123
+ }
124
+ else {
125
+ bodyText = raw.trim();
126
+ }
127
+ return { description, bodyText };
128
+ }
129
+ /**
130
+ * Load the operator-context instruction skills from the loop-agent repo's own
131
+ * `skills/` directory and return their text bodies for system-prompt injection.
132
+ *
133
+ * Security: only names in OPERATOR_CHAT_ALLOWED_INSTRUCTION_SKILLS are read;
134
+ * any other path is rejected before filesystem access (safe-side).
135
+ *
136
+ * @param skillsDir absolute path to the loop-agent repo `skills/` directory
137
+ * (source repo / npm pack asset, NOT target project `.agents/skills/`).
138
+ * @param names override list (tests); defaults to the full allowlist.
139
+ */
140
+ export async function loadOperatorChatInstructionSkills(skillsDir, names) {
141
+ const selected = names ?? OPERATOR_CHAT_ALLOWED_INSTRUCTION_SKILLS;
142
+ const loaded = [];
143
+ const failures = [];
144
+ const skipped = [];
145
+ for (const rawName of selected) {
146
+ const name = rawName.trim();
147
+ if (!isOperatorChatInstructionSkillAllowed(name)) {
148
+ skipped.push(name);
149
+ continue;
150
+ }
151
+ // Defense in depth: reject path traversal / governance skills even if
152
+ // an attacker managed to mutate the allowlist at runtime.
153
+ if (isOperatorChatInstructionSkillDenied(name)) {
154
+ skipped.push(name);
155
+ continue;
156
+ }
157
+ const skillPath = path.join(skillsDir, name, "SKILL.md");
158
+ const resolved = path.resolve(skillPath);
159
+ const resolvedSkillsDir = path.resolve(skillsDir);
160
+ if (!resolved.startsWith(resolvedSkillsDir + path.sep)) {
161
+ failures.push({
162
+ name,
163
+ message: "path escapes skills directory",
164
+ });
165
+ continue;
166
+ }
167
+ try {
168
+ const raw = await readFile(resolved, "utf8");
169
+ const { description, bodyText } = parseSkillFrontmatter(raw);
170
+ loaded.push({
171
+ name,
172
+ description,
173
+ bodyText,
174
+ charCount: bodyText.length,
175
+ });
176
+ }
177
+ catch (error) {
178
+ failures.push({
179
+ name,
180
+ message: error instanceof Error ? error.message : String(error),
181
+ });
182
+ }
183
+ }
184
+ return { loaded, failures, skipped };
185
+ }
186
+ /** Hard cap on total injected instruction-skill chars (token budget guard). */
187
+ export const OPERATOR_CHAT_INSTRUCTION_CHAR_BUDGET = 24_000;
188
+ /**
189
+ * Compose the system-prompt fragment listing loaded instruction skills.
190
+ * Each skill is rendered as a bounded text block. If total chars exceed the
191
+ * budget, later skills are truncated (operator-context set is small enough
192
+ * that truncation should not trigger in practice, but the cap is enforced).
193
+ */
194
+ export function composeInstructionSkillsPrompt(skills, budget = OPERATOR_CHAT_INSTRUCTION_CHAR_BUDGET) {
195
+ if (skills.length === 0)
196
+ return "";
197
+ const lines = [
198
+ "## Operator methodology context (read-only instruction skills)",
199
+ "",
200
+ "These skills are READ-ONLY context. You may reference their methodology when reasoning, but you CANNOT execute them. All actions must go through the registered operator tools.",
201
+ "",
202
+ ];
203
+ let used = 0;
204
+ for (const skill of skills) {
205
+ const header = `\n### ${skill.name}${skill.description ? ` — ${skill.description}` : ""}\n`;
206
+ const remaining = budget - used - header.length;
207
+ if (remaining <= 0) {
208
+ lines.push(`_[${skill.name}: omitted, char budget exhausted]_`);
209
+ break;
210
+ }
211
+ const slice = skill.bodyText.slice(0, Math.max(0, remaining));
212
+ lines.push(header);
213
+ lines.push(slice);
214
+ used += header.length + slice.length;
215
+ }
216
+ return lines.join("\n");
217
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Operator Chat — default model resolver (no hardcoded model).
3
+ *
4
+ * Resolves the Chat default model from the repo harness.json `executors.pi.MED`
5
+ * tier, then finds a concrete provider by searching the Pi SDK's
6
+ * `snapshot.available` model list (preferring providers whose model entry is
7
+ * backed by credentials).
8
+ *
9
+ * Rationale: harness.json only stores a modelId per tier (e.g. "gpt-5.5"), not
10
+ * a provider. The Pi SDK `getModel(provider, modelId)` requires a provider, so
11
+ * we search `available` for entries whose `id` matches the modelId and pick the
12
+ * first whose provider resolves to a configured/credentialled source. This
13
+ * mirrors how the user's wizard-local / configured providers surface models.
14
+ *
15
+ * This module is deliberately framework-light: it takes a repoRoot + an
16
+ * optional model-list snapshot and returns a `{provider, modelId}` descriptor.
17
+ * The Pi runtime layer turns that into a concrete SDK model via getModel.
18
+ */
19
+ import { readFile } from "node:fs/promises";
20
+ import path from "node:path";
21
+ /** Tier keys in harness executors.pi that may override the default. */
22
+ const EXECUTOR_TIERS = ["LOW", "MED", "HIGH"];
23
+ /**
24
+ * Read executors.pi.<tier> from the repo harness.json. Returns undefined when
25
+ * harness.json is absent or the tier is unset / "default" sentinel.
26
+ *
27
+ * Default tier = MED (matches DAG executor model matrix convention).
28
+ */
29
+ export async function readHarnessPiModelTier(repoRoot, tier = "MED") {
30
+ try {
31
+ const raw = await readFile(path.join(repoRoot, "harness.json"), "utf-8");
32
+ const manifest = JSON.parse(raw);
33
+ const pi = manifest.executors?.pi;
34
+ if (!pi)
35
+ return undefined;
36
+ const tierValue = pi[tier];
37
+ if (tierValue && tierValue !== "default")
38
+ return tierValue;
39
+ const defaultModel = pi.defaultModel;
40
+ if (defaultModel && defaultModel !== "default")
41
+ return defaultModel;
42
+ return undefined;
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ /**
49
+ * Search the SDK's available-model list for entries matching a modelId.
50
+ *
51
+ * Matching rule: an entry matches when its `id` equals the modelId OR equals
52
+ * `<provider>/<modelId>` (SDK lists both bare and provider-prefixed ids).
53
+ *
54
+ * Provider preference (in order):
55
+ * 1. Bare-id entries (`id === modelId`) — these are the user's own provider
56
+ * config (e.g. wizard-local registering `gpt-5.5`), preferred over
57
+ * aggregator reseller entries (`openai/gpt-5.5` from openrouter).
58
+ * 2. Among matches, prefer those flagged hasCredentials=true (provider is
59
+ * in the SDK's configuredProviders set).
60
+ * 3. Stable list order otherwise.
61
+ */
62
+ export function findProviderForModelId(modelId, available) {
63
+ const matches = available.filter((m) => {
64
+ if (m.id === modelId)
65
+ return true;
66
+ if (m.id === `${m.provider}/${modelId}`)
67
+ return true;
68
+ const slash = m.id.lastIndexOf("/");
69
+ if (slash >= 0 && m.id.slice(slash + 1) === modelId)
70
+ return true;
71
+ return false;
72
+ });
73
+ if (matches.length === 0)
74
+ return undefined;
75
+ // Score: bare-id (0) beats prefixed (1); then hasCredentials wins; then order.
76
+ const score = (m) => {
77
+ let s = 0;
78
+ if (m.id !== modelId)
79
+ s += 1; // prefixed id is less preferred
80
+ if (m.hasCredentials !== true)
81
+ s += 2; // no credentials is less preferred
82
+ return s;
83
+ };
84
+ return [...matches].sort((a, b) => score(a) - score(b))[0];
85
+ }
86
+ /**
87
+ * Resolve the Chat default model descriptor. Returns undefined when no model
88
+ * can be resolved (harness unset + no snapshot match).
89
+ *
90
+ * @param repoRoot repo with harness.json
91
+ * @param available SDK snapshot.available (already mapped to AvailableModelEntry)
92
+ * @param options.tier harness tier to read (default MED)
93
+ */
94
+ export async function resolveDefaultChatModel(repoRoot, available, options) {
95
+ const modelId = await readHarnessPiModelTier(repoRoot, options?.tier ?? "MED");
96
+ if (!modelId)
97
+ return undefined;
98
+ const entry = findProviderForModelId(modelId, available);
99
+ if (!entry)
100
+ return undefined;
101
+ return {
102
+ provider: entry.provider,
103
+ modelId,
104
+ label: entry.name,
105
+ };
106
+ }