@punal_manalan/blender-project-harness 0.0.0-stage → 1.0.2

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 (91) hide show
  1. package/.kilo/agent/blender-grader.md +197 -0
  2. package/.kilo/agent/blender-worker.md +127 -0
  3. package/.kilo/blender-project-harness/config.example.json +71 -0
  4. package/.kilo/blender-project-harness/tools/harness/EXPECTED_FLOW.md +656 -0
  5. package/.kilo/blender-project-harness/tools/harness/blender-operations.mjs +882 -0
  6. package/.kilo/blender-project-harness/tools/harness/blender-operations.test.mjs +550 -0
  7. package/.kilo/blender-project-harness/tools/harness/blender.mjs +301 -0
  8. package/.kilo/blender-project-harness/tools/harness/blender.test.mjs +87 -0
  9. package/.kilo/blender-project-harness/tools/harness/cli.mjs +127 -0
  10. package/.kilo/blender-project-harness/tools/harness/documents.mjs +201 -0
  11. package/.kilo/blender-project-harness/tools/harness/download.mjs +94 -0
  12. package/.kilo/blender-project-harness/tools/harness/download.test.mjs +63 -0
  13. package/.kilo/blender-project-harness/tools/harness/engine.mjs +1866 -0
  14. package/.kilo/blender-project-harness/tools/harness/engine.test.mjs +2219 -0
  15. package/.kilo/blender-project-harness/tools/harness/intake.mjs +571 -0
  16. package/.kilo/blender-project-harness/tools/harness/intake.test.mjs +181 -0
  17. package/.kilo/blender-project-harness/tools/harness/package-lock.json +1227 -0
  18. package/.kilo/blender-project-harness/tools/harness/package.json +15 -0
  19. package/.kilo/blender-project-harness/tools/harness/plugin.mjs +550 -0
  20. package/.kilo/blender-project-harness/tools/harness/plugin.test.mjs +526 -0
  21. package/.kilo/blender-project-harness/tools/harness/proxy.mjs +222 -0
  22. package/.kilo/blender-project-harness/tools/harness/proxy.test.mjs +217 -0
  23. package/.kilo/blender-project-harness/tools/harness/scaffold.mjs +83 -0
  24. package/.kilo/blender-project-harness/tools/harness/scaffold.test.mjs +74 -0
  25. package/.kilo/blender-project-harness/tools/harness/server.mjs +24 -0
  26. package/.kilo/blender-project-harness/tools/harness/shell-policy.mjs +196 -0
  27. package/.kilo/blender-project-harness/tools/harness/shell-policy.test.mjs +68 -0
  28. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/ASSETS.md +29 -0
  29. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/DECISIONS.md +8 -0
  30. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/Goals/01-project-brief.md +71 -0
  31. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/Goals/README.md +17 -0
  32. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/INTAKE.md +8 -0
  33. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/README.md +57 -0
  34. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/REQUIREMENTS.md +64 -0
  35. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/REVIEW.md +29 -0
  36. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/References/README.md +18 -0
  37. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/Reviews/README.md +48 -0
  38. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/TASKSTRACKER.md +10 -0
  39. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/Tasks/README.md +4 -0
  40. package/.kilo/blender-project-harness/tools/harness/templates/project/Documents/WORKFLOW.md +36 -0
  41. package/.kilo/blender-project-harness/tools/harness/templates/project/README.md +130 -0
  42. package/.kilo/blender-project-harness/tools/harness/templates/project/assets/README.md +31 -0
  43. package/.kilo/blender-project-harness/tools/harness/templates/project/assets/audio/.gitkeep +0 -0
  44. package/.kilo/blender-project-harness/tools/harness/templates/project/assets/external/README.md +43 -0
  45. package/.kilo/blender-project-harness/tools/harness/templates/project/assets/external/SOURCE_TEMPLATE.md +18 -0
  46. package/.kilo/blender-project-harness/tools/harness/templates/project/assets/hdri/.gitkeep +0 -0
  47. package/.kilo/blender-project-harness/tools/harness/templates/project/assets/models/.gitkeep +0 -0
  48. package/.kilo/blender-project-harness/tools/harness/templates/project/assets/textures/.gitkeep +0 -0
  49. package/.kilo/blender-project-harness/tools/harness/templates/project/backups/.gitkeep +0 -0
  50. package/.kilo/blender-project-harness/tools/harness/templates/project/backups/README.md +5 -0
  51. package/.kilo/blender-project-harness/tools/harness/templates/project/exports/.gitkeep +0 -0
  52. package/.kilo/blender-project-harness/tools/harness/templates/project/exports/README.md +11 -0
  53. package/.kilo/blender-project-harness/tools/harness/templates/project/renders/README.md +7 -0
  54. package/.kilo/blender-project-harness/tools/harness/templates/project/renders/final/.gitkeep +0 -0
  55. package/.kilo/blender-project-harness/tools/harness/templates/project/renders/wip/.gitkeep +0 -0
  56. package/.kilo/blender-project-harness/tools/harness/templates/project/scenes/README.md +10 -0
  57. package/.kilo/blender-project-harness/tools/harness/templates/project/scripts/README.md +16 -0
  58. package/.kilo/blender-project-harness/tools/harness/test-fixture.mjs +91 -0
  59. package/.kilo/blender-project-harness/tools/harness/workspace.mjs +30 -0
  60. package/.kilo/blender-project-harness/tools/harness/workspace.test.mjs +31 -0
  61. package/.kilo/blender-project-harness/tools/test_blender_tools.py +427 -0
  62. package/.kilo/plugins/blender-workflow.js +3 -0
  63. package/.kilo/skills/blender-assets/SKILL.md +99 -0
  64. package/.kilo/skills/blender-mcp/SKILL.md +147 -0
  65. package/.kilo/skills/blender-mcp/references/README.md +22 -0
  66. package/.kilo/skills/blender-mcp/references/animation.md +83 -0
  67. package/.kilo/skills/blender-mcp/references/bpy.md +97 -0
  68. package/.kilo/skills/blender-mcp/references/level-design.md +53 -0
  69. package/.kilo/skills/blender-mcp/references/materials.md +80 -0
  70. package/.kilo/skills/blender-mcp/references/retopology.md +104 -0
  71. package/.kilo/skills/blender-mcp/references/rigging.md +123 -0
  72. package/.kilo/skills/blender-mcp/references/scene.md +72 -0
  73. package/.kilo/skills/blender-project-goal/SKILL.md +115 -0
  74. package/.kilo/skills/blender-project-grading/SKILL.md +184 -0
  75. package/.kilo/skills/blender-project-readme/SKILL.md +46 -0
  76. package/.kilo/skills/blender-project-requirements/SKILL.md +84 -0
  77. package/.kilo/skills/blender-project-scaffold/SKILL.md +59 -0
  78. package/.kilo/skills/blender-project-workflow/SKILL.md +96 -0
  79. package/.kilo/skills/blender-subagents/SKILL.md +204 -0
  80. package/.kilo/skills/blender-workflow-harness/SKILL.md +187 -0
  81. package/AGENTS.md +234 -0
  82. package/Blender/README.md +30 -0
  83. package/CHANGELOG.md +22 -0
  84. package/LICENSE +21 -0
  85. package/README.md +368 -2
  86. package/THIRD_PARTY_NOTICES.md +51 -0
  87. package/bin/blender-project-harness.mjs +4 -0
  88. package/installer/cli.mjs +116 -0
  89. package/installer/install.mjs +325 -0
  90. package/installer/install.test.mjs +134 -0
  91. package/package.json +58 -6
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "blender-workflow-harness",
3
+ "version": "1.0.2",
4
+ "private": true,
5
+ "type": "module",
6
+ "engines": { "node": ">=22" },
7
+ "scripts": {
8
+ "test": "node --test *.test.mjs",
9
+ "doctor": "node cli.mjs doctor"
10
+ },
11
+ "dependencies": {
12
+ "@modelcontextprotocol/sdk": "1.29.0",
13
+ "zod": "3.25.76"
14
+ }
15
+ }
@@ -0,0 +1,550 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { z } from 'zod';
5
+ import { Harness, contained, deny, git, modelRole, normalizeGoal, stable } from './engine.mjs';
6
+ import { describeDocumentFormats } from './documents.mjs';
7
+ import { MAX_BATCH, OPERATION_NAMES, PRIMITIVES, operationBatchCode } from './blender-operations.mjs';
8
+ import { projectPathInCommand, shellPolicy, unsafeBlenderShell } from './shell-policy.mjs';
9
+
10
+ const READ_ONLY = new Set(['read', 'glob', 'grep', 'list', 'webfetch', 'websearch', 'skill', 'todowrite', 'todoread', 'board_read', 'board_post', 'agent_manager_models', 'kilo_local_recall', 'schedule_wakeup', 'cron_create', 'cron_list', 'cron_delete', 'background_process']);
11
+ const ORCHESTRATOR_ONLY = new Set(['schedule_wakeup', 'cron_create', 'cron_list', 'cron_delete', 'background_process']);
12
+ const BLENDER_READ = new Set(['blender_get_addon_status', 'blender_get_scene_info', 'blender_harness_scene_info', 'blender_look', 'blender_search_assets', 'blender_disable_telemetry', 'blender_record_trajectory_feedback']);
13
+ const GRADER_BLENDER_READ = new Set(['blender_look']);
14
+ const WORKER_BLENDER_READ = new Set(['blender_get_addon_status', 'blender_get_scene_info', 'blender_harness_scene_info', 'blender_look']);
15
+ const PUBLIC_ACTIONS = new Set(['status', 'launch', 'stop', 'begin', 'extend', 'finalize', 'bootstrap-document', 'bootstrap-commit', 'intake', 'download', 'document', 'self-review', 'review', 'commit', 'approval', 'checkpoint', 'grader-ticket', 'grader-fail', 'recover', 'escalate', 'reregister', 'pause', 'reclaim', 'preserve']);
16
+ const SHELL_APPROVAL_TTL_MS = 10 * 60_000;
17
+ const SHELL_TOKEN = /\[HARNESS_SHELL:([a-f0-9-]{36})\]/i;
18
+ const successful = (output) => output && !output.isError && !output.metadata?.error && !/^Error\b/.test(output.output ?? '');
19
+ const BOOTSTRAP_DOCUMENTS = [
20
+ 'README.md',
21
+ 'Documents/README.md',
22
+ 'Documents/REQUIREMENTS.md',
23
+ 'Documents/WORKFLOW.md',
24
+ 'Documents/REVIEW.md',
25
+ 'Documents/ASSETS.md',
26
+ 'Documents/DECISIONS.md',
27
+ 'Documents/INTAKE.md',
28
+ 'Documents/TASKSTRACKER.md',
29
+ 'Documents/Tasks/README.md',
30
+ 'Documents/Goals/README.md',
31
+ 'Documents/Goals/<NN>-<slug>.md',
32
+ 'Documents/References/README.md',
33
+ 'Documents/References/<name>.md',
34
+ 'Documents/Reviews/README.md',
35
+ 'assets/**/*.md',
36
+ 'renders/README.md',
37
+ 'exports/README.md',
38
+ 'scenes/README.md',
39
+ 'scripts/README.md',
40
+ 'backups/README.md',
41
+ ];
42
+ const capabilities = () => ({
43
+ operations: [...OPERATION_NAMES],
44
+ primitives: [...PRIMITIVES],
45
+ bootstrapDocuments: [...BOOTSTRAP_DOCUMENTS],
46
+ documentFormats: describeDocumentFormats(),
47
+ actions: [
48
+ { name: 'status', actor: 'orchestrator', phase: 'any', payload: '{project?:string}' },
49
+ { name: 'bootstrap-document', actor: 'orchestrator', phase: 'before registration', payload: '{project,path,content}' },
50
+ { name: 'bootstrap-commit', actor: 'orchestrator', phase: 'before registration', payload: '{project,message}' },
51
+ { name: 'intake', actor: 'orchestrator', phase: 'scan or open change', payload: '{project,files?,folders?,kind?,source?,generated?,scan?}' },
52
+ { name: 'download', actor: 'orchestrator', phase: 'before or during production', payload: '{project?,url,filename?,maxBytes?}' },
53
+ { name: 'prepare', actor: 'orchestrator', phase: 'before registration', payload: '{project,goal,scene}' },
54
+ { name: 'reregister', actor: 'orchestrator', phase: 'paused project', payload: '{reason}' },
55
+ { name: 'launch|stop', actor: 'orchestrator', phase: 'active goal', payload: '{}' },
56
+ { name: 'begin', actor: 'orchestrator', phase: 'active goal', payload: '{outcome,objects,paths,milestone?,requirements?,scenes?,sceneRequirements?,revision?}' },
57
+ { name: 'extend', actor: 'orchestrator', phase: 'open change', payload: '{objects?,paths,scenes?,sceneRequirements?}' },
58
+ { name: 'finalize', actor: 'orchestrator', phase: 'open change', payload: '{}' },
59
+ { name: 'ticket', actor: 'orchestrator', phase: 'open change', payload: '{operation:apply|save|seal|wip,payload}' },
60
+ { name: 'document', actor: 'orchestrator', phase: 'open change', payload: '{path,content}' },
61
+ { name: 'self-review|review|grader-ticket|grader-fail', actor: 'orchestrator', phase: 'sealed change', payload: 'see docs' },
62
+ { name: 'commit|checkpoint|approval', actor: 'orchestrator', phase: 'reviewed change', payload: 'see docs' },
63
+ { name: 'recover|escalate|pause|reclaim|preserve', actor: 'orchestrator', phase: 'recovery', payload: '{reopen?}, escalation fields, {reason}, {project,reason}, or {reason} for a sealed tooling block' },
64
+ ],
65
+ limits: { appliesBeforeCheckpoint: 20, hardApplyCap: 20, maxChangeObjects: 20, maxChangeScenes: 32, ticketTtlMinutes: 10, minutesWithoutApply: 15, wipEveryApplies: 3, maxRounds: 'configured 1-4', batchOperations: MAX_BATCH },
66
+ commitPolicy: 'Project documents are created with bootstrap-document/document. Every successful apply batch commits atomically; the review produces the final commit. A non-scene change containing only documentation, source-only scripts, references, or assets commits and checkpoints without apply, seal, or review. A failed or expired change may use commit {mode:"wip"} then checkpoint; a sealed tooling block uses preserve {reason} then checkpoint. Manual project git add or git commit is blocked.',
67
+ shellPolicy: 'Read-only and trusted harness commands run directly. Any other non-project shell command requires a warning acknowledgement: repeat the exact command with description "Reason: ... [HARNESS_SHELL:<id>]". The command and reason are committed atomically under <project>/Documents/Commands/ or root Commands/; command output is never captured or committed. Blender launches, project mutations, and command substitution stay blocked.',
68
+ documentPolicy: 'Use blender_document action read for structured title/field/section access and action write for declared writes. Registration documents (REQUIREMENTS, WORKFLOW, REVIEW, and the active goal) are frozen after prepare; close the change and call reregister {reason}, bootstrap-document, bootstrap-commit, then prepare to replace them. Direct read/edit is permitted but discouraged; review reports are written only through the document tool.',
69
+ documentTool: { actions: ['read', 'write', 'ledger'], read: '{project?,path,section?}', write: '{project?,path,content}', ledger: '{project?}' },
70
+ });
71
+
72
+ function jsonPayload(value, label = 'payload') {
73
+ if (value === undefined || value === null || value === '') return {};
74
+ if (typeof value === 'string') {
75
+ if (!value.trim()) return {};
76
+ if (value === '[object Object]') deny(`${label} arrived as [object Object]; pass a JSON object or a JSON string`);
77
+ try { value = JSON.parse(value); } catch (error) { deny(`${label} is not valid JSON: ${error.message}`); }
78
+ }
79
+ if (!value || typeof value !== 'object' || Array.isArray(value)) deny(`${label} must be a JSON object or a JSON string containing an object`);
80
+ return value;
81
+ }
82
+
83
+ function kiloGoal(info) {
84
+ const metadata = info?.metadata ?? {};
85
+ let raw = metadata['kilo.goal'] ?? metadata?.kilo?.goal ?? metadata?.goal;
86
+ if (typeof raw === 'string') {
87
+ try { raw = JSON.parse(raw); } catch { return null; }
88
+ }
89
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
90
+ const status = typeof raw.status === 'string' ? raw.status.toLowerCase() : typeof raw.state === 'string' ? raw.state.toLowerCase() : null;
91
+ if (!status) return null;
92
+ const reason = raw.reason ?? raw.report?.reason ?? raw.lastReport?.reason ?? raw.last_report?.reason;
93
+ return {
94
+ status,
95
+ active: status === 'active',
96
+ reason: typeof reason === 'string' && reason.trim() ? reason.trim().slice(0, 1000) : null,
97
+ objective: typeof raw.objective === 'string' ? raw.objective.slice(0, 1000) : null,
98
+ };
99
+ }
100
+
101
+ function withKiloGoal(result, info) {
102
+ if (!result || typeof result !== 'object' || Array.isArray(result)) return result;
103
+ const goal = kiloGoal(info);
104
+ if (!goal) return result;
105
+ result.kiloGoal = goal;
106
+ if (['blocked', 'paused'].includes(goal.status)
107
+ && (result.goalActive || ['goal', 'goal_report'].includes(result.nextStep?.action))) {
108
+ result.nextStep = {
109
+ phase: 'resume-goal',
110
+ actor: 'orchestrator',
111
+ action: 'goal',
112
+ command: 'goal {action:"resume"}',
113
+ reason: `Kilo marks the goal ${goal.status}; resume it before the next workflow step or goal_report.`,
114
+ };
115
+ result.next = result.nextStep.reason;
116
+ }
117
+ return result;
118
+ }
119
+
120
+ function reconcileGoal(harness, session, info) {
121
+ const goal = kiloGoal(info);
122
+ if (!goal) return goal;
123
+ harness.transaction((s) => {
124
+ const p = Object.values(s.projects).find((item) => item.orchestrator === session);
125
+ if (!p || p.complete) return;
126
+ if (goal.status === 'active' && !p.goalActive) {
127
+ p.goalActive = true;
128
+ p.paused = null;
129
+ p.goalSync = { source: 'kilo', status: goal.status, at: new Date().toISOString() };
130
+ } else if (['paused', 'blocked', 'complete'].includes(goal.status) && p.goalActive) {
131
+ p.goalActive = false;
132
+ p.goalSync = { source: 'kilo', status: goal.status, at: new Date().toISOString() };
133
+ }
134
+ });
135
+ return goal;
136
+ }
137
+
138
+ function shellReason(description) {
139
+ if (typeof description !== 'string') return '';
140
+ return description.replace(SHELL_TOKEN, ' ').replace(/^\s*(?:reason|why)\s*:\s*/i, '').replace(/\s+/g, ' ').trim().slice(0, 1000);
141
+ }
142
+
143
+ function shellPendingDir(harness) {
144
+ return path.join(harness.home, 'shell-approvals');
145
+ }
146
+
147
+ function shellApprovalTarget(project, id) {
148
+ return project ? `${project}/Documents/Commands/${id}.md` : `Commands/${id}.md`;
149
+ }
150
+
151
+ function pendingShellRecords(dir) {
152
+ if (!fs.existsSync(dir)) return [];
153
+ return fs.readdirSync(dir).filter((name) => name.endsWith('.json')).map((name) => {
154
+ try { return JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')); } catch { return null; }
155
+ }).filter(Boolean);
156
+ }
157
+
158
+ function writePendingShell(dir, record) {
159
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
160
+ fs.writeFileSync(path.join(dir, `${record.id}.json`), JSON.stringify(record, null, 2) + '\n', { mode: 0o600 });
161
+ }
162
+
163
+ function shellApprovalError(message) {
164
+ throw new Error(message);
165
+ }
166
+
167
+ function guardShell(harness, session, project, command, args = {}) {
168
+ const policy = shellPolicy(command);
169
+ if (policy.kind === 'deny') deny(policy.reason);
170
+ if (policy.kind === 'read-only' || policy.kind === 'trusted') return;
171
+ if (projectPathInCommand(command)) deny('project files are harness-owned; use blender_workflow bootstrap-commit or commit, never shell mutation');
172
+ if (harness.developmentMode(session)) return;
173
+ const dir = shellPendingDir(harness);
174
+ const description = args.description ?? '';
175
+ const reasoning = shellReason(description);
176
+ const token = String(description).match(SHELL_TOKEN)?.[1];
177
+ if (!token) {
178
+ const existing = pendingShellRecords(dir).find((record) => record.status === 'pending' && record.session === session
179
+ && record.project === project && record.command === command && Date.now() - Date.parse(record.created) < SHELL_APPROVAL_TTL_MS);
180
+ const record = existing ?? {
181
+ id: crypto.randomUUID(),
182
+ status: 'pending',
183
+ session,
184
+ project,
185
+ command,
186
+ reasoning,
187
+ cwd: args.workdir ?? harness.root,
188
+ created: new Date().toISOString(),
189
+ approvedAt: null,
190
+ };
191
+ if (reasoning) record.reasoning = reasoning;
192
+ writePendingShell(dir, record);
193
+ const target = shellApprovalTarget(project, record.id);
194
+ shellApprovalError([
195
+ `Shell approval required: "${command}" is not a read-only or trusted harness command. Nothing ran.`,
196
+ 'This is a warning gate, not a workflow block.',
197
+ `Re-run the exact command with description "Reason: <one sentence why this is safe and necessary> [HARNESS_SHELL:${record.id}]".`,
198
+ `The command and reasoning are committed atomically to ${target} when approved; command output is never captured or committed.`,
199
+ ].join(' '));
200
+ }
201
+ const file = path.join(dir, `${token}.json`);
202
+ if (!fs.existsSync(file)) deny('unknown shell approval id; start the warning flow again');
203
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'));
204
+ if (record.status !== 'pending') deny('shell approval id was already used');
205
+ if (record.session !== session || record.project !== project || record.command !== command) deny('shell approval id is bound to a different session, project, or command');
206
+ if (Date.now() - Date.parse(record.created) > SHELL_APPROVAL_TTL_MS) deny('shell approval id expired; start the warning flow again');
207
+ if (reasoning.length < 8) shellApprovalError(`Shell approval requires a reason of at least 8 characters. Re-run the exact command with description "Reason: <why this is safe and necessary> [HARNESS_SHELL:${record.id}]".`);
208
+ record.status = 'approved';
209
+ record.reasoning = reasoning;
210
+ record.approvedAt = new Date().toISOString();
211
+ harness.commitShellApproval(session, record.project, record);
212
+ fs.rmSync(file, { force: true });
213
+ }
214
+
215
+ export function createHooks(harness, client) {
216
+ const questions = new Map();
217
+ const taskArgs = new Map();
218
+ async function identity(id) {
219
+ // PluginInput.client is SDK v1, whose request shape differs from SDK v2.
220
+ const result = await client.session.get({ path: { id }, query: { directory: harness.root }, throwOnError: true });
221
+ if (!result.data?.id || result.data.id !== id) deny('session identity unavailable');
222
+ return result.data;
223
+ }
224
+ async function childAssignment(session) {
225
+ const info = await identity(session);
226
+ if (!info.parentID) return null;
227
+ const messages = await client.session.messages({ path: { id: session }, query: { limit: 100 }, throwOnError: true });
228
+ if (!Array.isArray(messages.data)) deny('child session messages unavailable');
229
+ const first = messages.data.find((m) => m.info?.role === 'user' && m.parts?.some((p) => p.type === 'text' && p.text?.trim()));
230
+ const user = first?.info;
231
+ const prompt = first?.parts?.filter((p) => p.type === 'text' && !p.synthetic && !p.ignored).map((p) => p.text).join('\n');
232
+ const assistant = messages.data.findLast((m) => m.info?.role === 'assistant' && !m.info.summary)?.info;
233
+ if (user?.agent === 'blender-worker') {
234
+ if (!assistant) deny('worker runtime model metadata unavailable');
235
+ const cfg = harness.workerConfig();
236
+ if (!modelRole(cfg, assistant)) deny('worker runtime model does not match configured worker or backup');
237
+ return { worker: true, info };
238
+ }
239
+ if (user?.agent !== 'blender-grader' || !prompt?.includes('HARNESS_GRADER:')) deny('only assigned worker or grader children allowed during production');
240
+ const existing = harness.transaction((s) => harness.graderAssignment(s, session));
241
+ if (!assistant) deny('grader runtime model metadata unavailable');
242
+ if (!existing) harness.bindGrader(info.parentID, session, prompt, { providerID: assistant.providerID, modelID: assistant.modelID, variant: assistant.variant });
243
+ return info;
244
+ }
245
+ function stateFor(session) {
246
+ return harness.transaction((s) => Object.values(s.projects).find((p) => p.orchestrator === session) ?? null);
247
+ }
248
+ async function statusFor(session) {
249
+ const info = await identity(session);
250
+ reconcileGoal(harness, session, info);
251
+ return withKiloGoal(harness.command(session, 'status'), info);
252
+ }
253
+ function editPaths(tool, args) {
254
+ if (tool === 'apply_patch') {
255
+ const text = args.patchText ?? args.patch ?? '';
256
+ const paths = [...text.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)].map((m) => m[1]);
257
+ if (!paths.length) deny('cannot classify patch paths');
258
+ return paths;
259
+ }
260
+ const file = args.filePath ?? args.file_path ?? args.path;
261
+ if (typeof file !== 'string') deny('cannot classify file write');
262
+ return [file];
263
+ }
264
+ function relative(file) {
265
+ const full = path.resolve(harness.root, file);
266
+ if (!full.startsWith(harness.root + path.sep)) deny('production access outside workspace');
267
+ const name = path.relative(harness.root, full).replaceAll('\\', '/');
268
+ contained(harness.root, name, true);
269
+ return name;
270
+ }
271
+ return {
272
+ tool: {
273
+ blender_workflow: {
274
+ description: 'Mandatory Blender workflow gate. capabilities, status, bootstrap-document, bootstrap-commit, intake, download, prepare, reregister, launch, stop, begin, extend, finalize, document, ticket, grader-ticket, grader-fail, self-review, review, commit, approval, checkpoint, recover, escalate, preserve. payload is a JSON object or JSON string. Follow status.nextStep for the exact next call. Project documents and commits are harness-owned; never invoke Blender or legacy scripts from the shell.',
275
+ args: { action: z.string(), payload: z.union([z.string(), z.record(z.unknown())]).default('{}') },
276
+ async execute(args, context) {
277
+ const session = await identity(context.sessionID);
278
+ if (session.parentID) deny('workflow control belongs to root orchestrator');
279
+ reconcileGoal(harness, context.sessionID, session);
280
+ const payload = jsonPayload(args.payload);
281
+ let result;
282
+ if (args.action === 'capabilities') result = capabilities();
283
+ else if (args.action === 'bootstrap-document') result = harness.bootstrapDocument(context.sessionID, payload);
284
+ else if (args.action === 'bootstrap-commit') result = harness.bootstrapCommit(context.sessionID, payload);
285
+ else if (args.action === 'intake') result = harness.intake(context.sessionID, payload);
286
+ else if (args.action === 'download') result = await harness.download(context.sessionID, payload);
287
+ else if (args.action === 'prepare') result = harness.prepare(context.sessionID, payload);
288
+ else if (args.action === 'ticket') {
289
+ const p = stateFor(context.sessionID);
290
+ if (!p) deny('no registered project for this session; call blender_workflow prepare and complete its registration question first');
291
+ if (payload.operation === 'apply') operationBatchCode(payload.payload, p.change?.objects ?? []);
292
+ else if (stable(payload.payload) !== '{}') deny('save/seal/wip payload must be empty object');
293
+ result = harness.issue(context.sessionID, payload.operation, payload.payload);
294
+ } else {
295
+ if (!PUBLIC_ACTIONS.has(args.action)) deny('internal workflow action unavailable');
296
+ result = args.action === 'recover' ? harness.recover(context.sessionID, payload)
297
+ : args.action === 'launch' ? await harness.launch(context.sessionID)
298
+ : args.action === 'stop' ? await harness.stop(context.sessionID)
299
+ : harness.command(context.sessionID, args.action, payload);
300
+ }
301
+ return JSON.stringify(withKiloGoal(result, session), null, 2);
302
+ },
303
+ },
304
+ blender_document: {
305
+ description: 'Structured project-document access. action read returns title, metadata fields, section index and format diagnostics; pass section to read one section. action write creates or updates a declared document or the assigned grader report and rejects invalid format/structure. action ledger returns the harness-owned task rows and summary. payload is a JSON object or JSON string. Use this instead of raw full-file reads and direct edits.',
306
+ args: { action: z.string(), payload: z.union([z.string(), z.record(z.unknown())]).default('{}') },
307
+ async execute(args, context) {
308
+ const payload = jsonPayload(args.payload);
309
+ if (args.action === 'read') return JSON.stringify(harness.documentRead(context.sessionID, payload, (await identity(context.sessionID)).parentID ?? null), null, 2);
310
+ if (args.action === 'write') return JSON.stringify(harness.documentWrite(context.sessionID, payload), null, 2);
311
+ if (args.action === 'ledger') return JSON.stringify(harness.documentLedger(context.sessionID, payload), null, 2);
312
+ deny('document action must be read, write, or ledger');
313
+ },
314
+ },
315
+ },
316
+ async 'tool.execute.before'(input, output) {
317
+ if (harness.developmentMode(input.sessionID)) return;
318
+ const tool = input.tool.replace(/^functions\./, '');
319
+ const args = output.args ?? {};
320
+ if (/execute_blender_code|import_asset|generate_3d/.test(tool)) deny('raw Blender mutation disabled; use ticketed harness_execute');
321
+ if (tool === 'blender_harness_execute') {
322
+ const session = await identity(input.sessionID);
323
+ if (session.parentID) {
324
+ const child = await childAssignment(input.sessionID);
325
+ if (!child?.worker || args.operation !== 'apply') deny('worker may execute assigned apply operations only');
326
+ harness.authorize(session.parentID, args.token, args.operation, args.payload);
327
+ harness.bindWorkerByToken(session.parentID, input.sessionID, args.token);
328
+ return;
329
+ }
330
+ if (args.operation === 'apply') deny('orchestrator delegates apply operations to blender-worker; save and seal stay orchestrator-owned');
331
+ harness.authorize(input.sessionID, args.token, args.operation, args.payload);
332
+ return;
333
+ }
334
+ if (tool === 'blender_document') {
335
+ const session = await identity(input.sessionID);
336
+ if (session.parentID) {
337
+ const child = await childAssignment(input.sessionID);
338
+ if (!child) deny('document access requires an assigned child');
339
+ if (child.worker) {
340
+ if (args.action === 'write') deny('workers cannot write documents');
341
+ return;
342
+ }
343
+ harness.graderStep(input.sessionID, 'blender_document', args);
344
+ return;
345
+ }
346
+ return;
347
+ }
348
+ const session = await identity(input.sessionID);
349
+ if (!session.parentID) reconcileGoal(harness, input.sessionID, session);
350
+ const p = stateFor(input.sessionID);
351
+ if (session.parentID && harness.transaction((s) => Object.values(s.projects).some((p) => p.orchestrator === session.parentID))) {
352
+ const child = await childAssignment(input.sessionID);
353
+ if (child?.worker) {
354
+ if (ORCHESTRATOR_ONLY.has(tool) || ['write', 'edit', 'apply_patch', 'bash', 'task', 'agent_manager', 'question', 'goal', 'goal_report'].includes(tool)
355
+ || (tool.startsWith('blender_') && !WORKER_BLENDER_READ.has(tool))
356
+ || (!READ_ONLY.has(tool) && !WORKER_BLENDER_READ.has(tool) && !tool.startsWith('context7_'))) deny('worker child is read-only and cannot use this tool');
357
+ return;
358
+ }
359
+ if (ORCHESTRATOR_ONLY.has(tool)) deny('graders cannot use scheduler or process tools');
360
+ const assignment = harness.graderStep(input.sessionID, tool, args);
361
+ if (['write', 'edit', 'apply_patch'].includes(tool)) {
362
+ deny('grader document writes use blender_document only; direct edit is denied');
363
+ } else if (['read', 'glob', 'grep'].includes(tool)) {
364
+ const candidate = args.filePath ?? args.path;
365
+ if (candidate) {
366
+ const name = relative(candidate);
367
+ if (tool !== 'read') deny('grader searches unavailable; read exact assigned spec/evidence files');
368
+ const allowed = harness.transaction((s) => {
369
+ const { p } = harness.graderAssignment(s, input.sessionID);
370
+ return new Set([...Object.keys(p.records.specs), ...Object.keys(p.change.evidence), assignment.report,
371
+ `${p.project}/Documents/Reviews/${p.change.round}/manifest.json`, 'AGENTS.md',
372
+ '.kilo/agent/blender-grader.md', '.kilo/skills/blender-project-grading/SKILL.md']);
373
+ });
374
+ if (!allowed.has(name)) deny('grader read outside frozen assignment or peer report access');
375
+ } else deny('grader read requires exact path');
376
+ } else if (GRADER_BLENDER_READ.has(tool)) {
377
+ const assignmentState = harness.transaction((s) => harness.graderAssignment(s, input.sessionID));
378
+ if (!assignmentState?.p?.change?.evidence) deny('grader evidence is unavailable');
379
+ if (tool === 'blender_look') {
380
+ const image = args.image;
381
+ if (typeof image !== 'string') deny('grader look requires exact frozen evidence image');
382
+ const full = path.resolve(harness.root, image);
383
+ const relative = full.startsWith(harness.root + path.sep) ? path.relative(harness.root, full).replaceAll('\\', '/') : null;
384
+ if (!relative || !Object.hasOwn(assignmentState.p.change.evidence, relative)) deny('grader look limited to frozen evidence image');
385
+ }
386
+ } else if (!READ_ONLY.has(tool) && !tool.startsWith('context7_')) deny('grader tool outside read-only scope');
387
+ return;
388
+ }
389
+ if (tool === 'question') questions.set(input.callID, structuredClone(args));
390
+ if (!p) {
391
+ if (ORCHESTRATOR_ONLY.has(tool)) deny('scheduler and process tools require a registered active goal');
392
+ if (tool.startsWith('blender_') && !BLENDER_READ.has(tool) && tool !== 'blender_workflow') deny('production tool requires a registered project; run blender_workflow prepare and complete its registration question first');
393
+ if (['write', 'edit', 'apply_patch'].includes(tool)) {
394
+ const files = editPaths(tool, args).map(relative);
395
+ if (files.some((f) => path.resolve(harness.root, f).startsWith(harness.home))) deny('harness state is runtime-owned; never write it directly');
396
+ const blocked = files.filter((f) => /^Blender\/[^/]+\//.test(f));
397
+ if (blocked.length) deny(`project files are harness-owned: ${blocked.join(', ')}. Before registration use blender_workflow bootstrap-document for markdown and bootstrap-commit for the exact scaffold; scaffold the folder with node .kilo/blender-project-harness/tools/harness/cli.mjs scaffold. Do not write project files directly.`);
398
+ }
399
+ if (tool === 'bash') {
400
+ const command = args.command ?? '';
401
+ if (unsafeBlenderShell(command)) deny('launch and stop Blender through blender_workflow launch/stop; shell Blender commands and legacy scripts are retired');
402
+ if (/^git add\b/.test(command)) {
403
+ const broad = /(?:^|\s)(?:-A|--all|-u|--update|-p|--patch|-i|--interactive|\.|:\/|\*)(?:\s|$)/.test(command);
404
+ if (projectPathInCommand(command) || (broad && fs.existsSync(path.join(harness.root, 'Blender')))) deny('project commits use blender_workflow bootstrap-commit before registration and blender_workflow commit after registration');
405
+ }
406
+ if (/^git commit\b/.test(command)) {
407
+ if (/(?:^|\s)(?:-a\w*|--all|--include|-i)\b/.test(command) || projectPathInCommand(command)) deny('project commits use blender_workflow bootstrap-commit before registration and blender_workflow commit after registration');
408
+ const staged = git(harness.root, ['diff', '--cached', '--name-only']).split(/\r?\n/).filter(Boolean);
409
+ if (staged.some((name) => name.startsWith('Blender/'))) deny('project commits use blender_workflow bootstrap-commit before registration and blender_workflow commit after registration');
410
+ }
411
+ guardShell(harness, input.sessionID, null, command, args);
412
+ }
413
+ return;
414
+ }
415
+ if (tool === 'agent_manager') return;
416
+ if (tool === 'background_process') {
417
+ const command = args.command ?? '';
418
+ if (typeof command !== 'string' || !command.trim()) deny('background process requires one command');
419
+ if (unsafeBlenderShell(command)) deny('launch and stop Blender through blender_workflow launch/stop');
420
+ if (args.workdir && path.resolve(args.workdir) !== harness.root) deny('background process workdir must be the workspace root');
421
+ if (/^git (?:add|commit)\b/i.test(command)) deny('production commits use blender_workflow commit');
422
+ guardShell(harness, input.sessionID, p.project, command, args);
423
+ return;
424
+ }
425
+ if (tool === 'blender_workflow' || tool === 'question' || READ_ONLY.has(tool) || BLENDER_READ.has(tool) || tool.startsWith('context7_')) return;
426
+ if (tool === 'goal') {
427
+ if (args.action === 'start' && normalizeGoal(args.objective) !== normalizeGoal(p.records.goalText)) deny('goal objective must equal registered prompt');
428
+ harness.fresh(p, { allowRosterDrift: true }); return;
429
+ }
430
+ if (tool === 'goal_report') {
431
+ const goal = kiloGoal(session);
432
+ if (goal && ['blocked', 'paused'].includes(goal.status)) deny(`Kilo marks the goal ${goal.status}; run goal {action:"resume"} before goal_report`);
433
+ if (args.status === 'complete') {
434
+ const missing = [];
435
+ if (p.change) missing.push('open change');
436
+ if (!['PASS', 'DOCUMENT'].includes(p.history.at(-1)?.verdict)) missing.push('applicable PASS/DOCUMENT checkpoint');
437
+ if (!p.lastRender) missing.push('inspected sealed render');
438
+ else if (harness.hash(p.lastRender.path) !== p.lastRender.hash) missing.push('unchanged inspected render');
439
+ if (!p.history.some((item) => item.final && item.verdict === 'PASS')) missing.push('final full-spec PASS');
440
+ if (missing.length) deny(`completion blocked by ${missing.join(', ')}; fix the checkpoint, then run goal {action:"resume"} before goal_report`);
441
+ harness.assertCommitted(p.project, harness.snapshot(p.project));
442
+ }
443
+ return;
444
+ }
445
+ if (tool === 'task') {
446
+ if (args.background) deny('production delegation must be foreground');
447
+ if (args.subagent_type === 'blender-worker') {
448
+ if (!p.goalActive || !args.prompt?.trim()) deny('worker delegation requires an active goal and a task prompt');
449
+ if (/HARNESS_GRADER:/.test(args.prompt)) deny('worker task cannot carry a grader marker');
450
+ harness.workerConfig();
451
+ return;
452
+ }
453
+ if (args.subagent_type !== 'blender-grader' || !/HARNESS_GRADER:[a-f0-9-]{36}/.test(args.prompt ?? '')) deny('production delegation requires foreground assigned grader');
454
+ if (!/saved scene SHA-256 [a-f0-9]{64}/.test(args.prompt ?? '') || !/Evidence key: [a-f0-9]{64}/.test(args.prompt ?? '')) {
455
+ deny('grader task must use the exact grader-ticket prompt including the saved scene SHA-256 and evidence key');
456
+ }
457
+ const token = args.prompt.match(/HARNESS_GRADER:([a-f0-9-]{36})/)[1];
458
+ if (!p.change?.inspected || !Object.values(p.change.graders).some((g) => g.token === token)) deny('grader ticket missing');
459
+ taskArgs.set(input.callID, args); return;
460
+ }
461
+ if (['write', 'edit', 'apply_patch'].includes(tool)) {
462
+ const c = p.change;
463
+ const names = editPaths(tool, args).map(relative);
464
+ if (names.every((f) => f.startsWith('.temp/'))) {
465
+ harness.fresh(p, { allowRosterDrift: true });
466
+ return;
467
+ }
468
+ if (!c) deny('no open bounded change; call blender_workflow begin with one outcome, exact object names, and exact project-relative paths before writing project files');
469
+ const allowed = new Set(c.paths);
470
+ if (names.some((f) => Object.hasOwn(p.records.specs, f) || f === `${p.project}/Documents/REVIEW.md`)) deny('registration documents are frozen after registration; restore the committed version and stop for explicit re-registration');
471
+ if (names.some((f) => f === `${p.project}/Documents/TASKSTRACKER.md` || f.startsWith(`${p.project}/Documents/Tasks/`))) deny('the task tracker is harness-owned; ticket issue and completion update it');
472
+ if (names.some((f) => f.startsWith(`${p.project}/Documents/Reviews/`))) deny('review artifacts are harness-owned; use review, self-review, or grader tools');
473
+ if (names.some((f) => !allowed.has(f) || /\.blend$|\/manifest\.json$|\/_evidence\/|\/REPORT\.md$|\.(png|jpg|exr)$/i.test(f))) deny('write outside the declared change scope or targets runtime-owned evidence/report paths; add the exact path to blender_workflow begin paths, or stop writing it');
474
+ if (names.some((f) => f.startsWith(`${p.project}/`) && /\.md$/i.test(f) && !fs.existsSync(path.resolve(harness.root, f)))) deny('new documents require blender_document write or blender_workflow document after declaring the exact path');
475
+ harness.fresh(p);
476
+ return;
477
+ }
478
+ if (tool === 'bash') {
479
+ const command = args.command ?? '';
480
+ if (unsafeBlenderShell(command)) deny('launch and stop Blender through blender_workflow launch/stop; shell Blender commands and legacy scripts are retired');
481
+ if (args.workdir && path.resolve(args.workdir) !== harness.root) deny('production Git/launch commands require workspace root');
482
+ if (/^git add\b/i.test(command)) {
483
+ const broad = /(?:^|\s)(?:-A|--all|-u|--update|-p|--patch|-i|--interactive|\.|:\/|\*)(?:\s|$)/.test(command);
484
+ if (projectPathInCommand(command) || broad) deny('project commits use blender_workflow bootstrap-commit before registration and blender_workflow commit after registration');
485
+ }
486
+ if (/^git commit\b/i.test(command)) {
487
+ if (/(?:^|\s)(?:-a\w*|--all|--include|-i)\b/.test(command)) deny('project commits use blender_workflow commit');
488
+ const staged = git(harness.root, ['diff', '--cached', '--name-only']).split(/\r?\n/).filter(Boolean);
489
+ if (staged.some((name) => name.startsWith('Blender' + '/'))) deny('project commits use blender_workflow commit');
490
+ }
491
+ const workspaceCommand = /^git (?:add|commit)\b/i.test(command);
492
+ guardShell(harness, input.sessionID, workspaceCommand ? null : p.project, command, args);
493
+ return;
494
+ }
495
+ deny(`unclassified production tool: ${tool}`);
496
+ },
497
+ async 'tool.execute.after'(input, output) {
498
+ if (harness.developmentMode(input.sessionID)) return;
499
+ const tool = input.tool.replace(/^functions\./, '');
500
+ if (tool === 'question') {
501
+ const args = questions.get(input.callID); questions.delete(input.callID);
502
+ if (args && !output.metadata?.dismissed && output.metadata?.answers) harness.question(input.sessionID, args, output.metadata.answers);
503
+ }
504
+ const p = stateFor(input.sessionID);
505
+ if (!p) return;
506
+ if (tool === 'goal' && successful(output)) {
507
+ if (['start', 'resume'].includes(input.args.action)) harness.command(input.sessionID, 'goal-active', { objective: input.args.action === 'start' ? input.args.objective : undefined });
508
+ else if (['pause', 'clear'].includes(input.args.action)) harness.command(input.sessionID, 'goal-inactive');
509
+ }
510
+ if (tool === 'goal_report' && input.args.status === 'complete' && successful(output)) harness.command(input.sessionID, 'goal-complete');
511
+ if (tool === 'blender_look' && input.args.image) {
512
+ const imageResult = output.content?.some((c) => c.type === 'image') || output.attachments?.some((a) => a.mime?.startsWith('image/'));
513
+ harness.inspect(input.sessionID, path.resolve(harness.root, input.args.image), Boolean(successful(output) && imageResult));
514
+ }
515
+ if (tool === 'task' && taskArgs.has(input.callID)) {
516
+ const args = taskArgs.get(input.callID); taskArgs.delete(input.callID);
517
+ const child = output.metadata?.sessionId ?? output.metadata?.sessionID ?? output.output?.match(/task(?:_id| id)[=:"\s]+(ses_[A-Za-z0-9]+)/)?.[1];
518
+ const token = args?.prompt?.match(/HARNESS_GRADER:([a-f0-9-]{36})/)?.[1];
519
+ if (!child || !successful(output)) {
520
+ if (token) harness.failGraderByToken(input.sessionID, token, output.output ?? 'grader task failed before child session');
521
+ else deny('grader task result lacks child session ID');
522
+ } else {
523
+ harness.collectGrader(input.sessionID, child);
524
+ }
525
+ } else if (tool === 'task' && input.args?.subagent_type === 'blender-worker') {
526
+ const child = output.metadata?.sessionId ?? output.metadata?.sessionID ?? output.output?.match(/task(?:_id| id)[=:"\s]+(ses_[A-Za-z0-9]+)/)?.[1];
527
+ if (successful(output) && child) {
528
+ harness.bindWorker(input.sessionID, child, input.args?.prompt ?? '');
529
+ } else {
530
+ const token = input.args?.prompt?.match(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i)?.[0];
531
+ if (token) harness.failWorkerByToken(input.sessionID, token, output.output ?? 'worker task failed before completion');
532
+ }
533
+ }
534
+ if (successful(output) && typeof output.output === 'string') output.output += `\n\nWorkflow: ${JSON.stringify(await statusFor(input.sessionID))}`;
535
+ },
536
+ async 'experimental.chat.system.transform'(input, output) {
537
+ if (harness.developmentMode(input.sessionID)) return;
538
+ if (!input.sessionID) return;
539
+ const p = stateFor(input.sessionID);
540
+ if (p) output.system.push(`Runtime workflow state: ${JSON.stringify(await statusFor(input.sessionID))}. Use blender_workflow; never bypass missing gates.`);
541
+ },
542
+ async 'experimental.session.compacting'(input, output) {
543
+ if (harness.developmentMode(input.sessionID)) return;
544
+ const p = stateFor(input.sessionID);
545
+ if (p) output.context.push(`Durable Blender workflow: ${JSON.stringify(await statusFor(input.sessionID))}. Continue current phase; do not repeat goal start or begin.`);
546
+ },
547
+ };
548
+ }
549
+
550
+ export async function server(context) { return createHooks(new Harness(context.worktree), context.client); }