@craft_eco/craft-mcp 0.1.34 → 0.1.35-beta.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 (113) hide show
  1. package/README.md +2 -2
  2. package/bin/craft-mcp.mjs +11 -2
  3. package/dist-server/core/http-utils.mjs +11 -0
  4. package/dist-server/game-workflow/asset-formats.mjs +1 -1
  5. package/dist-server/game-workflow/bundle-files.mjs +19 -0
  6. package/dist-server/game-workflow/bundle-template.mjs +5 -0
  7. package/dist-server/game-workflow/context-state.mjs +1 -1
  8. package/dist-server/game-workflow/draft-archive.mjs +61 -0
  9. package/dist-server/game-workflow/draft-binding-migration.mjs +73 -0
  10. package/dist-server/game-workflow/draft-uploads.mjs +258 -75
  11. package/dist-server/game-workflow/native-context.mjs +4 -1
  12. package/dist-server/game-workflow/project-bundles.mjs +17 -6
  13. package/dist-server/game-workflow/projects.mjs +4 -0
  14. package/dist-server/game-workflow/template-refresh.mjs +430 -0
  15. package/dist-server/integrations/distribution-targets.mjs +2 -0
  16. package/dist-server/integrations/files.mjs +30 -2
  17. package/dist-server/integrations/fixed-launcher.mjs +4 -4
  18. package/dist-server/integrations/install.mjs +5 -5
  19. package/dist-server/integrations/installation-state.mjs +6 -7
  20. package/dist-server/integrations/launcher-start.mjs +12 -8
  21. package/dist-server/integrations/opencode-config.mjs +1 -1
  22. package/dist-server/integrations/project-setup.mjs +0 -1
  23. package/dist-server/integrations/runtime-candidate.mjs +8 -12
  24. package/dist-server/integrations/runtime-gc.mjs +20 -21
  25. package/dist-server/integrations/runtime.mjs +7 -3
  26. package/dist-server/integrations/updates.mjs +64 -27
  27. package/dist-server/launcher.mjs +39 -14
  28. package/dist-server/mcp/login-page.mjs +2 -2
  29. package/dist-server/mcp/server.mjs +10 -12
  30. package/dist-server/mcp/update-session.mjs +3 -3
  31. package/dist-server/upstream/{craft-aigc.mjs → craft-platform.mjs} +40 -115
  32. package/dist-server/upstream/draft-audit.mjs +51 -0
  33. package/dist-server/upstream/draft-transport.mjs +184 -0
  34. package/package.json +3 -3
  35. package/resources/craft-update/SKILL.md +2 -0
  36. package/resources/targets/claude/js/js/bundle.json +15 -9
  37. package/resources/targets/claude/js/target.json +8 -6
  38. package/resources/targets/claude/js3d/js3d/bundle.json +21 -10
  39. package/resources/targets/claude/js3d/target.json +14 -7
  40. package/resources/targets/codebuddy/js/js/bundle.json +15 -9
  41. package/resources/targets/codebuddy/js/target.json +8 -6
  42. package/resources/targets/codebuddy/js3d/js3d/bundle.json +21 -10
  43. package/resources/targets/codebuddy/js3d/target.json +14 -7
  44. package/resources/targets/codex/js/js/bundle.json +15 -9
  45. package/resources/targets/codex/js/target.json +8 -6
  46. package/resources/targets/codex/js3d/js3d/bundle.json +21 -10
  47. package/resources/targets/codex/js3d/target.json +14 -7
  48. package/resources/targets/comate/js/js/bundle.json +15 -9
  49. package/resources/targets/comate/js/target.json +8 -6
  50. package/resources/targets/comate/js3d/js3d/bundle.json +21 -10
  51. package/resources/targets/comate/js3d/target.json +14 -7
  52. package/resources/targets/cursor/js/js/bundle.json +15 -9
  53. package/resources/targets/cursor/js/target.json +8 -6
  54. package/resources/targets/cursor/js3d/js3d/bundle.json +21 -10
  55. package/resources/targets/cursor/js3d/target.json +14 -7
  56. package/resources/targets/dsh/js/js/bundle.json +15 -9
  57. package/resources/targets/dsh/js/target.json +8 -6
  58. package/resources/targets/dsh/js3d/js3d/bundle.json +21 -10
  59. package/resources/targets/dsh/js3d/target.json +14 -7
  60. package/resources/targets/index.json +56 -56
  61. package/resources/targets/kimi/js/js/bundle.json +15 -9
  62. package/resources/targets/kimi/js/target.json +8 -6
  63. package/resources/targets/kimi/js3d/js3d/bundle.json +21 -10
  64. package/resources/targets/kimi/js3d/target.json +14 -7
  65. package/resources/targets/opencode/js/js/bundle.json +15 -9
  66. package/resources/targets/opencode/js/target.json +8 -6
  67. package/resources/targets/opencode/js3d/js3d/bundle.json +21 -10
  68. package/resources/targets/opencode/js3d/target.json +14 -7
  69. package/resources/targets/qoder/js/js/bundle.json +15 -9
  70. package/resources/targets/qoder/js/target.json +8 -6
  71. package/resources/targets/qoder/js3d/js3d/bundle.json +21 -10
  72. package/resources/targets/qoder/js3d/target.json +14 -7
  73. package/resources/targets/qoder-cn/js/js/bundle.json +15 -9
  74. package/resources/targets/qoder-cn/js/target.json +8 -6
  75. package/resources/targets/qoder-cn/js3d/js3d/bundle.json +21 -10
  76. package/resources/targets/qoder-cn/js3d/target.json +14 -7
  77. package/resources/targets/qwen/js/js/bundle.json +15 -9
  78. package/resources/targets/qwen/js/target.json +8 -6
  79. package/resources/targets/qwen/js3d/js3d/bundle.json +21 -10
  80. package/resources/targets/qwen/js3d/target.json +14 -7
  81. package/resources/targets/trae/js/js/bundle.json +15 -9
  82. package/resources/targets/trae/js/target.json +8 -6
  83. package/resources/targets/trae/js3d/js3d/bundle.json +21 -10
  84. package/resources/targets/trae/js3d/target.json +14 -7
  85. package/resources/targets/workbuddy/js/js/bundle.json +15 -9
  86. package/resources/targets/workbuddy/js/target.json +8 -6
  87. package/resources/targets/workbuddy/js3d/js3d/bundle.json +21 -10
  88. package/resources/targets/workbuddy/js3d/target.json +14 -7
  89. package/resources/targets/zcode/js/js/bundle.json +15 -9
  90. package/resources/targets/zcode/js/target.json +8 -6
  91. package/resources/targets/zcode/js3d/js3d/bundle.json +21 -10
  92. package/resources/targets/zcode/js3d/target.json +14 -7
  93. package/resources/templates/js/materialize_paths.json +9 -0
  94. package/resources/templates/js/project/package.json +1 -0
  95. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  96. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  97. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  98. package/resources/templates/js/project/runtime/lightgame/1.1.0/release.json +3 -2
  99. package/resources/templates/js/project/scripts/refresh-runtime.mjs +50 -0
  100. package/resources/templates/js3d/materialize_paths.json +9 -0
  101. package/resources/templates/js3d/project/package.json +4 -2
  102. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  103. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  104. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  105. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/release.json +3 -2
  106. package/resources/templates/js3d/project/scripts/refresh-runtime.mjs +50 -0
  107. package/resources/templates/js3d/project/scripts/skill-modules/gameplay-check/check.mjs +331 -0
  108. package/resources/templates/js3d/project/src/game/capability/core.ts +3 -0
  109. package/resources/templates/js3d/project/src/main.ts +23 -6
  110. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.d.mts +92 -0
  111. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.mjs +375 -0
  112. package/resources/templates/js3d/project/src/skill-modules/gameplay/installed.json +6 -0
  113. package/dist-server/game-workflow/local-context.mjs +0 -64
@@ -1,13 +1,32 @@
1
- import { checkedDraftFiles, checkedDraftSource, encodeCheckedDraftArchive } from './draft-archive.mjs';
1
+ import { createHash } from 'node:crypto';
2
+ import { promisify } from 'node:util';
3
+ import { gzip } from 'node:zlib';
4
+ import {
5
+ applyFilteredTextFiles,
6
+ checkedDraftFiles,
7
+ checkedDraftSource,
8
+ encodeCheckedDraftArchive,
9
+ } from './draft-archive.mjs';
2
10
  import { guardWork } from './work-scope.mjs';
3
11
  import path from 'node:path';
12
+ import { setTimeout as delay } from 'node:timers/promises';
4
13
  import { DraftBindings } from './draft-bindings.mjs';
14
+ import {
15
+ advanceLegacyMigration,
16
+ loadOrMigrateBinding,
17
+ resolveDraftTarget,
18
+ retireUnreviewedLegacyRecord,
19
+ } from './draft-binding-migration.mjs';
5
20
  import { draftUploadIdentity } from './draft-upload-identity.mjs';
6
21
  import { digest } from './request-store.mjs';
7
22
  import { validMcpProduceLocation } from '../core/production-source.mjs';
23
+ import { modelAuditErrorMessage } from '../upstream/draft-audit.mjs';
8
24
  import { assertSourceUploadLimit, validSourceMetadata } from '../upstream/draft-source.mjs';
9
25
  import { assertUploadSecurity, uploadSecurityPolicyVersion } from './upload-security.mjs';
10
26
 
27
+ const compressChunk = promisify(gzip);
28
+ const CHUNK_WIRE_OVERHEAD_BYTES = 64 * 1024;
29
+
11
30
  function prepareInput(record) {
12
31
  const input = record.prepare_input ?? { client_request_id:record.request_id, engine:record.engine,
13
32
  title:record.name.slice(0,40), bytes:record.bytes, sha256:record.sha256 };
@@ -19,7 +38,9 @@ function prepareInput(record) {
19
38
  return input;
20
39
  }
21
40
 
22
- const terminal = record => ['draft_ready','expired','superseded'].includes(record.state) || record.audit?.state === 'rejected';
41
+ const terminal = record => ['draft_ready','expired','superseded','title_rejected'].includes(record.state) ||
42
+ record.audit?.state === 'rejected' || ['rejected','error'].includes(record.content_audit?.state);
43
+ const processing = record => ['queued','auditing','retry_wait'].includes(record.content_audit?.state);
23
44
 
24
45
  function bindingBase(record) {
25
46
  const input = prepareInput(record);
@@ -43,6 +64,11 @@ function hasCurrentSecurityReview(record) {
43
64
  }
44
65
 
45
66
  function mergeReceipt(record, result) {
67
+ const prior = record.content_audit, current = result.content_audit;
68
+ if ((record.text_audit_protocol || prior) && !current) throw new Error('Craft 未返回约定的内容审核状态');
69
+ if (prior && (current?.revision < prior.revision || (processing(record) && (!current || current.state === 'not_started')) ||
70
+ (current?.revision === prior.revision && current.state !== prior.state) ||
71
+ (terminal(record) && current?.state !== prior.state))) throw new Error('Craft 返回了过期或矛盾的内容审核状态');
46
72
  if (record.audit && !result.audit && result.state !== 'expired') throw new Error('Craft 未返回已有上传检查的状态');
47
73
  if (result.state === 'draft_ready' && result.audit && result.audit.state !== 'passed') throw new Error('Craft 未确认上传检查通过');
48
74
  if (record.upload_id !== undefined && record.upload_id !== result.upload_id) throw new Error('Craft changed the upload ID for this request');
@@ -63,7 +89,16 @@ function mergeReceipt(record, result) {
63
89
  if (result.upload_mode !== record.prepare_input.upload_mode) throw new Error('Craft 后端尚未支持本次上传模式,请先部署新版后端');
64
90
  if (result.state === 'draft_ready' && (!Number.isSafeInteger(result.version_number) || result.version_number < 1)) throw new Error('Craft 未返回有效的上传版本号,请查询上传状态后重试');
65
91
  }
66
- return { ...record, ...result };
92
+ const updated = { ...record, ...result };
93
+ if (updated.dist_ready) delete updated.dist_chunks_received;
94
+ if (updated.source_ready) delete updated.source_chunks_received;
95
+ return updated;
96
+ }
97
+
98
+ function publicContentAudit(audit) {
99
+ if (!audit) return undefined;
100
+ return { protocol:audit.protocol, state:audit.state, revision:audit.revision,
101
+ ...(audit.location ? { location:audit.location } : {}), ...(modelAuditErrorMessage(audit) && {reason:audit.reason}) };
67
102
  }
68
103
 
69
104
  export function draftUploadView(record) {
@@ -72,27 +107,84 @@ export function draftUploadView(record) {
72
107
  const distReady = record.dist_ready === true || ready;
73
108
  const projectUrl = ready && sourceReady && record.platform && /^[a-zA-Z0-9_-]{1,128}$/.test(record.conversation_id ?? '')
74
109
  ? new URL(`/chat/${record.conversation_id}`,record.platform).href : undefined;
110
+ const maskedFiles = Array.isArray(record.masked_files) && record.masked_files.length ? record.masked_files : undefined;
75
111
  return { state:record.state, check_task_id:record.check_task_id ?? record.request_id, request_id:record.request_id,
76
112
  upload_mode:record.upload_mode ?? record.prepare_input?.upload_mode, request_key:record.request_key,
77
113
  version_number:record.version_number,
78
114
  upload_id:record.upload_id, conversation_id:record.conversation_id, version_id:record.version_id,
79
115
  dist_ready:distReady, source_ready:sourceReady, published:false,
80
116
  ...(record.audit ? { audit:record.audit } : {}),
117
+ ...(record.content_audit ? { content_audit:publicContentAudit(record.content_audit), processing:processing(record) } : {}),
118
+ ...(maskedFiles ? { masked_files:maskedFiles } : {}),
81
119
  ...(projectUrl ? { project_url:projectUrl } : {}),
82
120
  ...(record.external_manifest_sha256 ? { external_manifest_sha256:record.external_manifest_sha256 } : {}),
83
121
  next:projectUrl ? `Tell the user: uploaded ${record.version_number ? 'version v' + record.version_number : 'version ' + record.version_id}, project ${record.conversation_id}: ${projectUrl}. This is an upload, not a public release; preview and publish in Craft Web.` : ready
84
122
  ? 'This previous upload contains the build only. Run a new game check and upload the source and build to open it in Craft Web.'
123
+ : record.state === 'title_rejected' ? '项目标题未通过文本审核,请调整标题后重新检查并上传。'
124
+ : processing(record) ? '文件已上传,内容审核中。使用原 check_task_id、upload_mode 和 request_key 调用 craft_game_upload_status 查询。'
125
+ : record.content_audit?.state === 'rejected'
126
+ ? (maskedFiles
127
+ ? `包内文档(${maskedFiles.join('、')})触发内容审核,已自动将违禁词替换为 * 并写回本地文件。请告知用户检查修改结果,确认无误后重新运行 craft_game_check 并手动重新上传。`
128
+ : '包内内容未通过审核。如有 content_audit.location,可据此定位文件。请修改后重新检查并上传。')
129
+ : record.content_audit?.state === 'error' ? (modelAuditErrorMessage(record.content_audit) ?? '平台未能完成内容审核,本次上传已结束。')
85
130
  : record.audit?.state === 'rejected' ? '服务端上传检查未通过。根据 audit.findings 修复文件,重新运行 craft_game_check 后上传。当前文件未生成预览。'
86
131
  : terminal(record) ? 'Run a new game check and upload that result to start a new draft.'
87
132
  : 'Run craft_game_upload with the same check_task_id, upload_mode and request_key to resume this upload.' };
88
133
  }
89
134
 
135
+ const COMMIT_BUSY_BACKEND_CODE = 10016;
136
+ const DEFAULT_COMMIT_RETRY_DELAYS_MS = [1000, 2000, 4000];
137
+ const DEFAULT_CHUNK_RETRY_DELAYS_MS = [500, 1500];
138
+ const DEFAULT_AUDIT_POLL_INTERVAL_MS = 2000;
139
+ const DEFAULT_AUDIT_POLL_TIMEOUT_MS = 90_000;
140
+
141
+ function* iterateByteChunks(parts, chunkSize) {
142
+ let index = 0;
143
+ let pending = [];
144
+ let pendingBytes = 0;
145
+ for (const part of parts) {
146
+ let offset = 0;
147
+ while (offset < part.length) {
148
+ const take = Math.min(chunkSize - pendingBytes, part.length - offset);
149
+ if (pendingBytes === 0 && take === chunkSize) {
150
+ yield { index: index++, chunk: part.subarray(offset, offset + take) };
151
+ offset += take;
152
+ continue;
153
+ }
154
+ pending.push(part.subarray(offset, offset + take));
155
+ pendingBytes += take;
156
+ offset += take;
157
+ if (pendingBytes === chunkSize) {
158
+ yield { index: index++, chunk: pending.length === 1 ? pending[0] : Buffer.concat(pending, chunkSize) };
159
+ pending = [];
160
+ pendingBytes = 0;
161
+ }
162
+ }
163
+ }
164
+ if (pendingBytes > 0) {
165
+ yield { index: index++, chunk: pending.length === 1 ? pending[0] : Buffer.concat(pending, pendingBytes) };
166
+ }
167
+ }
168
+
169
+ function isRetryableChunkError(error) {
170
+ const detail = error?.detail;
171
+ if (!detail) return false;
172
+ return detail.failure_type === 'network' || detail.failure_type === 'timeout' ||
173
+ detail.backend_code === COMMIT_BUSY_BACKEND_CODE ||
174
+ (typeof detail.http_status === 'number' && detail.http_status >= 500);
175
+ }
176
+
90
177
  export class DraftUploads {
91
- constructor(platform, store, evidence, bindings) {
178
+ constructor(platform, store, evidence, bindings, options = {}) {
92
179
  this.platform = platform;
93
180
  this.store = store;
94
181
  this.evidence = evidence;
95
182
  this.bindings = bindings ?? new DraftBindings(path.join(path.dirname(store.directory),'draft-bindings'),store.workspace);
183
+ this.commitRetryDelays = options.commitRetryDelays ?? DEFAULT_COMMIT_RETRY_DELAYS_MS;
184
+ this.chunkRetryDelays = options.chunkRetryDelays ?? DEFAULT_CHUNK_RETRY_DELAYS_MS;
185
+ this.auditPollIntervalMs = options.auditPollIntervalMs ?? DEFAULT_AUDIT_POLL_INTERVAL_MS;
186
+ this.auditPollTimeoutMs = options.auditPollTimeoutMs ?? DEFAULT_AUDIT_POLL_TIMEOUT_MS;
187
+ this.onBound = options.onBound;
96
188
  }
97
189
 
98
190
  #scope(name,engine,owner) {
@@ -107,25 +199,11 @@ export class DraftUploads {
107
199
  async target(name, engine, owner, signal) {
108
200
  const scope = this.#scope(name,engine,owner);
109
201
  const binding = await this.bindings.read(scope);
110
- const history = binding ? binding.migration ?? [] : await this.#history(scope);
111
- let head = binding;
112
- for (let record of binding?.pending ? [binding.pending,...history] : history) {
113
- if (Object.entries(scope).some(([key,value])=>record[key] !== value)) throw new Error('Invalid draft binding history scope');
114
- // Build-only receipts can be missing the final commit response. Query their existing upload without migrating or submitting it.
115
- if (!terminal(record) && record.upload_id && !record.prepare_input?.source) {
116
- signal?.throwIfAborted();
117
- record = mergeReceipt(record,await this.platform.draftSession(owner)('status',{id:record.upload_id},signal));
118
- }
119
- if (record.state === 'draft_ready') { head = record; break; }
120
- if (!terminal(record)) {
121
- return {state:'recovery_required',appid:binding?.conversation_id,check_task_id:record.check_task_id ?? record.request_id,
122
- upload_mode:record.upload_mode ?? 'current_project',request_key:record.request_key,
123
- next:'Check the existing upload receipt and recover it before starting another upload.'};
124
- }
202
+ if (binding?.pending?.text_audit_protocol) {
203
+ const local = await this.#record(name,binding.pending.request_id,owner);
204
+ if (local?.upload_id && (local.content_audit?.revision ?? 0) >= (binding.pending.content_audit?.revision ?? 0)) binding.pending = local;
125
205
  }
126
- return head?.conversation_id
127
- ? {state:'bound',appid:head.conversation_id,conversation_id:head.conversation_id,version_id:head.version_id}
128
- : {state:'unbound',next:'An initial upload can create a cloud project. To update an existing appid, locate its bound local project first.'};
206
+ return resolveDraftTarget({ binding,store:this.store,scope,platform:this.platform,owner,signal,terminal,mergeReceipt });
129
207
  }
130
208
 
131
209
  async #record(name, id, owner) {
@@ -146,6 +224,17 @@ export class DraftUploads {
146
224
  return updated;
147
225
  }
148
226
 
227
+ async #prepare(record, request, signal) {
228
+ try {
229
+ return await this.#accept(record,await request('prepare',{input:prepareInput(record)},signal));
230
+ } catch (error) {
231
+ if (!record.text_audit_protocol || error.detail?.backend_code !== 50002) throw error;
232
+ const rejected = {...record, state:'title_rejected'};
233
+ await this.store.save(rejected);
234
+ return rejected;
235
+ }
236
+ }
237
+
149
238
  async #pending(scope, binding) {
150
239
  const saved = binding.pending;
151
240
  if (Object.entries(scope).some(([key,value])=>saved[key] !== value)) throw new Error('Invalid pending draft binding');
@@ -171,78 +260,168 @@ export class DraftUploads {
171
260
  delete binding.migration;
172
261
  }
173
262
  delete binding.pending;
174
- return this.bindings.save(scope,binding);
263
+ const saved = await this.bindings.save(scope,binding);
264
+ if (record.state === 'draft_ready') await this.onBound?.(scope,record.conversation_id);
265
+ return saved;
175
266
  }
176
267
 
177
268
  async #recover(record, request, signal, statusOnly) {
178
269
  if (terminal(record)) return record;
179
270
  signal?.throwIfAborted();
180
271
  if (record.upload_id) record = await this.#accept(record,await request('status',{ id:record.upload_id },signal));
181
- if (terminal(record) || statusOnly || !hasCurrentSecurityReview(record)) return record;
272
+ if (terminal(record) || processing(record) || statusOnly || !hasCurrentSecurityReview(record)) return record;
182
273
  if (!record.upload_id) {
183
274
  await guardWork();
184
- record = await this.#accept(record,await request('prepare',{ input:prepareInput(record) },signal));
275
+ record = await this.#prepare(record,request,signal);
185
276
  }
186
- if (record.state === 'uploaded') {
277
+ if (record.state === 'uploaded' && !processing(record) && !terminal(record)) {
187
278
  record = await this.#commit(record,request,signal);
188
279
  }
189
280
  return record;
190
281
  }
191
282
 
192
- async #commit(record, request, signal) {
283
+ async #uploadChunked(record, request, signal, { chunkKind, parts, totalBytes, chunkSize }) {
284
+ const total = Math.ceil(totalBytes / chunkSize);
285
+ const receivedKey = chunkKind === 'dist' ? 'dist_chunks_received' : 'source_chunks_received';
286
+ const readyKey = chunkKind === 'dist' ? 'dist_ready' : 'source_ready';
287
+ const received = new Set(record[receivedKey] ?? []);
288
+ for (const { index, chunk } of iterateByteChunks(parts, chunkSize)) {
289
+ if (received.has(index)) continue;
290
+ signal?.throwIfAborted();
291
+ const sha256 = createHash('sha256').update(chunk).digest('hex');
292
+ // Gzip each chunk on the wire so plain HTML/JS source slices do not trigger edge WAF rules.
293
+ const encodedChunk = await compressChunk(chunk, { maxOutputLength: chunk.byteLength + CHUNK_WIRE_OVERHEAD_BYTES });
294
+ for (let attempt = 0; ; attempt++) {
295
+ signal?.throwIfAborted();
296
+ await guardWork();
297
+ try {
298
+ record = await this.#accept(record, await request('upload-chunk', {
299
+ id: record.upload_id, chunkKind, index, total, sha256, chunk: encodedChunk, encoding: 'gzip',
300
+ }, signal));
301
+ break;
302
+ } catch (error) {
303
+ if (!isRetryableChunkError(error) || attempt >= this.chunkRetryDelays.length) throw error;
304
+ const waitMs = this.chunkRetryDelays[attempt];
305
+ if (waitMs > 0) await delay(waitMs, undefined, { signal });
306
+ }
307
+ }
308
+ if (record[readyKey] || terminal(record)) return record;
309
+ }
193
310
  signal?.throwIfAborted();
194
311
  await guardWork();
195
- record = await this.#accept(record,await request('commit',{id:record.upload_id},signal));
196
- if (!terminal(record)) throw new Error('Craft did not finish the draft version');
197
- return record;
312
+ return this.#accept(record, await request('complete-chunks', { id: record.upload_id, chunkKind, total }, signal));
198
313
  }
199
314
 
200
- async #history(scope) {
201
- const history = (await this.store.list()).filter(record=>
202
- Object.entries(scope).every(([key,value])=>record[key] === value) && !['expired','superseded'].includes(record.state));
203
- if (history.some(record=>!Number.isFinite(Date.parse(record.created_at)))) throw new Error('Invalid draft upload history timestamp');
204
- history.sort((a,b)=>Date.parse(b.created_at)-Date.parse(a.created_at));
205
- if (history.some((record,index)=>index && Date.parse(record.created_at) === Date.parse(history[index-1].created_at))) {
206
- throw new Error('Ambiguous draft upload history; cannot choose the original project');
315
+ async #commit(record, request, signal) {
316
+ for (let attempt = 0; ; attempt++) {
317
+ signal?.throwIfAborted();
318
+ await guardWork();
319
+ try {
320
+ record = await this.#accept(record,await request('commit',{id:record.upload_id},signal));
321
+ if (!terminal(record) && !processing(record)) throw new Error('Craft did not finish the draft version');
322
+ return record;
323
+ } catch (error) {
324
+ if (error?.detail?.backend_code !== COMMIT_BUSY_BACKEND_CODE || attempt >= this.commitRetryDelays.length) {
325
+ throw error;
326
+ }
327
+ const waitMs = this.commitRetryDelays[attempt];
328
+ if (waitMs > 0) await delay(waitMs,undefined,{ signal });
329
+ signal?.throwIfAborted();
330
+ await guardWork();
331
+ record = await this.#accept(record,await request('status',{id:record.upload_id},signal));
332
+ if (terminal(record) || processing(record)) return record;
333
+ if (record.state !== 'uploaded') throw new Error('Craft did not finish the draft version');
334
+ }
207
335
  }
208
- return history;
209
336
  }
210
337
 
211
338
  async #loadBinding(scope) {
212
- let binding = await this.bindings.read(scope);
213
- if (!binding) {
214
- // Persist the migration queue as well: a crash or profile switch must not lose older receipts.
215
- binding = await this.bindings.save(scope,{ schema:1,...scope,migration:await this.#history(scope) });
216
- }
217
- return binding;
339
+ return loadOrMigrateBinding(this.bindings,this.store,scope);
218
340
  }
219
341
 
220
342
  async #binding(scope, id, request, signal, statusOnly) {
221
343
  let binding = await this.#loadBinding(scope);
222
344
  for (;;) {
223
- if (!binding.pending && binding.migration?.length) {
224
- const record = binding.migration.shift();
225
- record.prepare_input = prepareInput(record);
226
- await this.store.save(record);
227
- binding.pending = record;
228
- await this.bindings.save(scope,binding);
229
- }
230
- if (!binding.pending) {
231
- if (binding.migration) { delete binding.migration; await this.bindings.save(scope,binding); }
232
- return binding;
233
- }
345
+ binding = await advanceLegacyMigration(this.bindings,this.store,scope,binding,prepareInput);
346
+ if (!binding.pending) return binding;
234
347
  const record = await this.#pending(scope,binding);
235
348
  if (record.request_id === id) return binding;
236
349
  let recovered = await this.#recover(record,request,signal,statusOnly);
237
- if (!statusOnly && !terminal(recovered) && !hasCurrentSecurityReview(recovered)) {
238
- recovered = { ...recovered,state:'superseded' };
239
- await this.store.save(recovered);
240
- }
350
+ if (processing(recovered)) throw new Error(`Previous upload is awaiting content review. Query craft_game_upload_status with check_task_id=${record.check_task_id ?? record.request_id}, upload_mode=${record.upload_mode ?? 'current_project'}${record.request_key ? ', request_key=' + record.request_key : ''}.`);
351
+ recovered = await retireUnreviewedLegacyRecord(this.store,recovered,{ statusOnly,terminal,hasCurrentSecurityReview });
241
352
  if (!terminal(recovered)) throw new Error(`Previous draft upload is unfinished; resume craft_game_upload with check_task_id=${record.check_task_id ?? record.request_id}, upload_mode=${record.upload_mode ?? 'current_project'}${record.request_key ? ', request_key=' + record.request_key : ''} before starting another upload`);
242
353
  binding = await this.#finish(scope,binding,recovered);
243
354
  }
244
355
  }
245
356
 
357
+ async #waitForAudit(record, request, signal) {
358
+ if (!processing(record) || !record.upload_id) return record;
359
+ const deadline = Date.now() + this.auditPollTimeoutMs;
360
+ while (processing(record) && Date.now() < deadline) {
361
+ const waitMs = Math.min(this.auditPollIntervalMs, Math.max(0, deadline - Date.now()));
362
+ if (waitMs > 0) await delay(waitMs, undefined, { signal });
363
+ signal?.throwIfAborted();
364
+ await guardWork();
365
+ record = await this.#accept(record, await request('status', { id: record.upload_id }, signal));
366
+ }
367
+ return record;
368
+ }
369
+
370
+ async #deliverUpload({ record, scope, binding, request, signal, chunkSize, archive, source, input, waitForAudit }) {
371
+ const run = async (kind, options) => {
372
+ signal.throwIfAborted();
373
+ await guardWork();
374
+ record = await this.#accept(record, await request(kind, options, signal));
375
+ };
376
+ signal?.throwIfAborted();
377
+ await guardWork();
378
+ record = await this.#prepare(record, request, signal);
379
+ if (record.text_audit_protocol && record.upload_id) {
380
+ binding.pending = record;
381
+ await this.bindings.save(scope, binding);
382
+ }
383
+ if (record.state === 'prepared' && !record.dist_ready) {
384
+ if (chunkSize && archive.bytes > chunkSize) {
385
+ record = await this.#uploadChunked(record, request, signal, { chunkKind: 'dist', parts: archive.parts, totalBytes: archive.bytes, chunkSize });
386
+ } else {
387
+ await run('upload', { id: record.upload_id, archive });
388
+ }
389
+ if (!record.dist_ready && !terminal(record)) throw new Error('Craft did not confirm the draft archive upload');
390
+ }
391
+ if (record.state === 'prepared' && !record.source_ready) {
392
+ if (chunkSize && source.length > chunkSize) {
393
+ record = await this.#uploadChunked(record, request, signal, { chunkKind: 'source', parts: [source], totalBytes: source.length, chunkSize });
394
+ } else {
395
+ await run('upload-source', { id: record.upload_id, source, sourceFormat: input.source.format });
396
+ }
397
+ if (!record.source_ready && !terminal(record)) throw new Error('Craft did not confirm the project source upload');
398
+ }
399
+ if (record.state === 'uploaded' && !terminal(record) && !processing(record)) record = await this.#commit(record, request, signal);
400
+ if (waitForAudit && processing(record)) record = await this.#waitForAudit(record, request, signal);
401
+ if (terminal(record) && binding.pending?.request_id === record.request_id) {
402
+ binding = await this.#finish(scope, binding, record);
403
+ }
404
+ return { record, binding };
405
+ }
406
+
407
+ async #applyAutoMask(record, options, signal) {
408
+ if (!options?.project || record?.content_audit?.state !== 'rejected' ||
409
+ !Array.isArray(record.content_audit.filtered_files) || !record.content_audit.filtered_files.length ||
410
+ record.masked_files) {
411
+ return record;
412
+ }
413
+ let appliedPaths;
414
+ try {
415
+ appliedPaths = await applyFilteredTextFiles(options.project, record.content_audit.filtered_files, signal);
416
+ } catch (error) {
417
+ if (error?.name === 'AbortError' || signal?.aborted) throw error;
418
+ return record;
419
+ }
420
+ const updated = { ...record, masked_files: appliedPaths };
421
+ await this.store.save(updated);
422
+ return updated;
423
+ }
424
+
246
425
  async upload(check, owner, signal, options) {
247
426
  const { name, task_id:checkId, result } = check;
248
427
  const { id, upload_mode, request_key } = draftUploadIdentity(checkId,options);
@@ -267,8 +446,19 @@ export class DraftUploads {
267
446
  if (record && terminal(record)) {
268
447
  const binding = await this.#loadBinding(scope);
269
448
  if (binding?.pending?.request_id === id) await this.#finish(scope,binding,record);
449
+ record = await this.#applyAutoMask(record,options,signal);
270
450
  return draftUploadView(record);
271
451
  }
452
+ if (record?.text_audit_protocol && record.upload_id) {
453
+ record = await this.#accept(record,await request('status',{id:record.upload_id},signal));
454
+ if (options?.project && processing(record)) record = await this.#waitForAudit(record,request,signal);
455
+ if (processing(record) || terminal(record)) {
456
+ const binding = await this.#loadBinding(scope);
457
+ if (binding.pending?.request_id === id && terminal(record)) await this.#finish(scope,binding,record);
458
+ record = await this.#applyAutoMask(record,options,signal);
459
+ return draftUploadView(record);
460
+ }
461
+ }
272
462
  if (record && !record.prepare_input?.source) throw new Error('This upload predates project source uploads. Run a new craft_game_check');
273
463
  const source = await checkedDraftSource(this.evidence,result.snapshot_id,result.source_snapshot,signal);
274
464
  const files = await checkedDraftFiles(this.evidence,result.snapshot_id,result.artifacts,signal);
@@ -282,6 +472,7 @@ export class DraftUploads {
282
472
  assertFrozenInputs(record,archive,result.source_snapshot);
283
473
  if (record && terminal(record)) {
284
474
  await this.#finish(scope,binding,record);
475
+ record = await this.#applyAutoMask(record,options,signal);
285
476
  return draftUploadView(record);
286
477
  }
287
478
  const input = record ? prepareInput(record) : { client_request_id:id, engine:result.engine, title:name.slice(0,40),
@@ -307,29 +498,21 @@ export class DraftUploads {
307
498
  previous_binding:{ conversation_id:binding.conversation_id,version_id:binding.version_id }, ...scope, bytes:input.bytes, sha256:input.sha256,
308
499
  state:'preparing',prepare_input:input });
309
500
  record.prepare_input ??= input;
501
+ if (!record.upload_id && limits.text_audit_protocol) record.text_audit_protocol = limits.text_audit_protocol;
310
502
  record.security_review = { policy_version:uploadSecurityPolicyVersion,
311
503
  source_sha256:result.source_snapshot.sha256, archive_sha256:archive.sha256 };
312
504
  // Save immutable target/base before any remote request, then make it recoverable across profiles.
313
505
  await this.store.save(record);
314
506
  binding.pending = record;
315
507
  await this.bindings.save(scope,binding);
316
- const run = async (kind, options) => {
317
- signal.throwIfAborted();
318
- await guardWork();
319
- record = await this.#accept(record,await request(kind,options,signal));
320
- };
321
508
  // Reconcile each frozen artifact before sending it again after a lost response.
322
- await run('prepare',{ input });
323
- if (record.state === 'prepared' && !record.dist_ready) {
324
- await run('upload',{ id:record.upload_id, archive });
325
- if (!record.dist_ready && !terminal(record)) throw new Error('Craft did not confirm the draft archive upload');
326
- }
327
- if (record.state === 'prepared' && !record.source_ready) {
328
- await run('upload-source',{ id:record.upload_id, source, sourceFormat:input.source.format });
329
- if (!record.source_ready && !terminal(record)) throw new Error('Craft did not confirm the project source upload');
330
- }
331
- if (record.state === 'uploaded' && !terminal(record)) record = await this.#commit(record,request,signal);
332
- if (terminal(record)) await this.#finish(scope,binding,record);
509
+ const delivered = await this.#deliverUpload({
510
+ record, scope, binding, request, signal,
511
+ chunkSize: limits.chunk_size_bytes,
512
+ archive, source, input,
513
+ waitForAudit: Boolean(options?.project),
514
+ });
515
+ record = await this.#applyAutoMask(delivered.record,options,signal);
333
516
  return draftUploadView(record);
334
517
  }
335
518
 
@@ -7,6 +7,7 @@ import { digest } from './bundle-files.mjs';
7
7
  import { hosts } from '../integrations/hosts.mjs';
8
8
  import { atomicJson } from './request-store.mjs';
9
9
  import { projectArtPreviewsCurrent, prepareArtPreviews } from './project-art-previews.mjs';
10
+ import { inspectManagedTemplatePaths } from './template-refresh.mjs';
10
11
 
11
12
  export const contextLayoutSchema = 5;
12
13
  // Schema 4 used one physical Buddy directory. Never validate a historical lock
@@ -43,7 +44,7 @@ async function hashes(root,relative='') {
43
44
  }
44
45
 
45
46
  // Preserve relative paths used by knowledge links, executable skills and SDK hooks.
46
- export function nativeContextFile(name,engine) {
47
+ function nativeContextFile(name,engine) {
47
48
  if(name.startsWith(engine+'/context/')) return name.slice((engine+'/context/').length);
48
49
  if(name==='craft-game-maker/SKILL.md') return 'workflow.md';
49
50
  if(name===`craft-game-maker/${engine}.md`) return 'guide.md';
@@ -84,6 +85,8 @@ export async function resolveNativeContext(project,current,lock) {
84
85
  const expected=nativeFileHashes(current.bundle);
85
86
  if(checked.integrity!=='valid' || checked.manifest.bundle_id!==binding.bundle_id || checked.manifest.source_revision!==binding.source_revision || !isDeepStrictEqual(checked.manifest.files,expected)) throw new Error('Project context integrity check failed: '+(checked.reason??'binding or manifest mismatch')+'; run craft_game_prepare mode=resume');
86
87
  if(!isDeepStrictEqual(checked.manifest.art_previews,current.bundle.art_previews) || !await projectArtPreviewsCurrent(project,current.bundle.art_previews)) throw new Error('Project art previews require restoration; run craft_game_prepare mode=resume');
88
+ const templateCheck=await inspectManagedTemplatePaths(project,current.bundle);
89
+ if(templateCheck.status!=='valid') throw new Error('Project managed template files require synchronization: '+(templateCheck.reason??'mismatch')+'; run craft_game_prepare mode=resume');
87
90
  const selected=nativeSelection(project,current);
88
91
  selected.context.hosts=Object.fromEntries(Object.entries(lock.active_hosts).map(([directory,host])=>[host,path.join(project,directory)]));
89
92
  selected.context.user_rules=path.join(project,'.craft/user-rules.md');
@@ -9,10 +9,12 @@ import { hosts } from '../integrations/hosts.mjs';
9
9
  import { compareVersions } from '../integrations/version-policy.mjs';
10
10
  import { copyBundleArtPreviews, previewHash } from './art-previews.mjs';
11
11
  import { projectArtPreviewsCurrent, retireArtPreviews } from './project-art-previews.mjs';
12
+ import { inspectManagedTemplatePaths, materializePathsFile, syncManagedTemplateFiles } from './template-refresh.mjs';
12
13
  import { isDeepStrictEqual } from 'node:util';
13
- import { localContextPath } from './local-context.mjs';
14
14
  import { contextLayoutSchema, schema4Hosts, nativeContextPath, nativeFileHashes, inspectNativeContext, materializeNativeContext, preflightNativeContext, recoverNativeContext, recoverLegacyNativeContexts, retireLegacyContext, resolveNativeContext } from './native-context.mjs';
15
15
 
16
+ const legacyLocalContextPath = (host,engine,id)=>`.craft/contexts/${host}/${engine}/${id}`;
17
+
16
18
  export const contextLock = '.craft/context-lock.json';
17
19
  export async function readContextLock(project, engine) {
18
20
  let lock;
@@ -28,7 +30,7 @@ export async function readContextLock(project, engine) {
28
30
  !lock.compatibility || typeof lock.compatibility !== 'object' || Array.isArray(lock.compatibility) ||
29
31
  !lock.contexts || typeof lock.contexts !== 'object' || Array.isArray(lock.contexts) || !Object.keys(lock.contexts).length ||
30
32
  Object.entries(lock.contexts).some(([host,value])=>!Object.hasOwn(hosts,host) || (lock.schema===4 && !schema4Hosts.includes(host)) || !validEntry(value) ||
31
- (value.path !== undefined && value.path !== (lock.schema >= 4 ? nativeContextPath(host,lock.schema) : localContextPath(host,engine,value.bundle_id)))) ||
33
+ (value.path !== undefined && value.path !== (lock.schema >= 4 ? nativeContextPath(host,lock.schema) : legacyLocalContextPath(host,engine,value.bundle_id)))) ||
32
34
  (lock.schema >= 3 && lock.policy !== 'follow-installed') ||
33
35
  (lock.schema >= 4 && (!lock.active_hosts || Array.isArray(lock.active_hosts) || Object.entries(lock.active_hosts).some(([directory,host])=>!Object.hasOwn(hosts,host) || nativeContextPath(host,lock.schema)!==directory || !lock.contexts[host]))))) throw new Error('Invalid project context lock or engine mismatch; restore the project lock from version control');
34
36
  return lock;
@@ -76,7 +78,10 @@ export async function planContextRelease(resources, bundle, lock, project) {
76
78
  // Regular status reads stop at the lock and release index. An explicit disk
77
79
  // check also catches edited peer files or publication interrupted before lock commit.
78
80
  const previews=new Set();
81
+ let templateRefreshPending=false, templateRefreshReason;
79
82
  if(project) {
83
+ const templateCheck=await inspectManagedTemplatePaths(project,bundle);
84
+ if(templateCheck.status!=='valid') {templateRefreshPending=true;templateRefreshReason=templateCheck.reason;}
80
85
  const names=Object.keys(targets);
81
86
  const manifests=await Promise.all(names.map(async name=>{
82
87
  const released=name===host ? bundle : JSON.parse(await readFile(path.join(resources,'targets',name,engine,engine,'bundle.json'),'utf8'));
@@ -102,9 +107,10 @@ export async function planContextRelease(resources, bundle, lock, project) {
102
107
  }
103
108
  }
104
109
  let versionStatus='unknown';
105
- if(lock?.contexts) versionStatus=pendingHosts.length ? 'update_available' : 'matches_installed';
110
+ if(lock?.contexts) versionStatus=(pendingHosts.length || templateRefreshPending) ? 'update_available' : 'matches_installed';
106
111
  if(conflictingHosts.length) versionStatus='requires_newer_runtime';
107
- return {targets,pending_hosts:pendingHosts,conflicting_hosts:conflictingHosts,version_status:versionStatus,previews:[...previews].sort()};
112
+ return {targets,pending_hosts:pendingHosts,conflicting_hosts:conflictingHosts,version_status:versionStatus,previews:[...previews].sort(),
113
+ ...(project ? {template_refresh_pending:templateRefreshPending,...(templateRefreshReason ? {template_refresh_reason:templateRefreshReason} : {})} : {})};
108
114
  }
109
115
 
110
116
  export function assertContextRelease(plan) {
@@ -143,6 +149,9 @@ export class ProjectBundles {
143
149
  const from = name.startsWith(projectPrefix) ? path.join(template,name.slice(projectPrefix.length)) : path.join(resources,name);
144
150
  await cp(from,path.join(staging,name),{dereference:false});
145
151
  }
152
+ if (bundle.template_refresh_paths?.length) {
153
+ await cp(path.join(path.dirname(template),materializePathsFile),path.join(staging,engine,materializePathsFile),{dereference:false});
154
+ }
146
155
  await copyBundleArtPreviews(resources,staging,bundle);
147
156
  await verifyBundle(staging,engine,bundle.id);
148
157
  try { await rename(staging,target); }
@@ -207,7 +216,7 @@ export class ProjectBundles {
207
216
  if (existing?.schema === 1) {
208
217
  const legacy = await verifyBundle(source.legacyResources,engine,existing.bundle_id);
209
218
  if (legacy.schema !== 1 || legacy.source_revision !== existing.source_revision) throw new Error('Legacy lock cannot select a host-specific context');
210
- } else if (existing && !isDeepStrictEqual(existing.compatibility,current.bundle.compatibility)) throw new Error('New context is incompatible with the project; migrate and validate its engine runtime before syncing');
219
+ }
211
220
  const plan=await planContextRelease(source.legacyResources,current.bundle,existing,project);
212
221
  assertContextRelease(plan);
213
222
  await guard();
@@ -258,6 +267,7 @@ export class ProjectBundles {
258
267
  contexts[host]={bundle_id:peer.bundle.id,source_revision:peer.bundle.source_revision,version:peer.bundle.version,path:peerLocal.relative};
259
268
  installed[host]=peerLocal;
260
269
  }
270
+ const templateSync=await syncManagedTemplateFiles(project,current,guard);
261
271
  const local=installed[this.host];
262
272
  const orderedContexts=Object.fromEntries(Object.entries(contexts).sort(([a],[b])=>a.localeCompare(b)));
263
273
  const lock = {schema:contextLayoutSchema,policy:'follow-installed',engine,compatibility:current.bundle.compatibility,
@@ -282,9 +292,10 @@ export class ProjectBundles {
282
292
  const backup=await retireLegacyContext(project,host,engine,value.bundle_id);
283
293
  if(backup) migrated.push({host,backup});
284
294
  }
285
- const sync = {policy:'follow-installed',location:'project',status:changed || local.materialized ? 'updated' : 'current',
295
+ const sync = {policy:'follow-installed',location:'project',status:changed || local.materialized || templateSync.updated ? 'updated' : 'current',
286
296
  updated_hosts:Object.keys(installed).filter(host=>installed[host].materialized),
287
297
  version:current.bundle.version,bundle_id:current.bundle.id,directory:local.selected.resources,
298
+ ...(templateSync.updated ? {template_refresh:{paths:templateSync.paths,updated_files:templateSync.updated_files,removed_files:templateSync.removed_files,...(templateSync.backup ? {backup:templateSync.backup} : {})}} : {}),
288
299
  ...(existing?.schema===4 ? {layout_migration:{from:4,to:contextLayoutSchema,previous_active_hosts:existing.active_hosts}} : {}),
289
300
  ...(previous && previous.bundle_id !== current.bundle.id ? {previous_bundle_id:previous.bundle_id} : {}),...(local.backup ? {backup:local.backup} : {}),...(migrated.length ? {migrated} : {})};
290
301
  local.selected.context.sync = sync;
@@ -99,6 +99,10 @@ export class Projects {
99
99
  const version_status=release?.version_status??'unknown';
100
100
  const layoutSchema=lock?.schema===4 ? 4 : contextLayoutSchema;
101
101
  const native=installed.host ? await inspectNativeContext(project,this.ide,engine,{full,schema:layoutSchema}) : {integrity:'unchecked'};
102
+ if(full && release?.template_refresh_pending && native.integrity==='valid') {
103
+ native.integrity='modified';
104
+ native.reason=release.template_refresh_reason;
105
+ }
102
106
  let incompatible;
103
107
  try {await checkProjectCompatibility(project,installed.bundle);} catch(error) {incompatible=error.message;}
104
108
  if(full && installed.host && lock?.schema===contextLayoutSchema && version_status==='matches_installed' && native.integrity==='valid') {