@stmcw1/dacw 0.0.0-stage → 1.0.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.
package/dist/runner.js ADDED
@@ -0,0 +1,324 @@
1
+ import { spawn, ChildProcess } from 'child_process';
2
+ import * as path from 'path';
3
+ import * as fsSync from 'fs';
4
+ import { StringDecoder } from 'string_decoder';
5
+ export class Runner {
6
+ workspaceDir;
7
+ MAX_OUTPUT_CHARS = 50_000;
8
+ HARD_LIMIT_CHARS = 100_000;
9
+ KILL_GRACE_MS = 2_000;
10
+ EXIT_GRACE_MS = 1_500;
11
+ ALLOWED_CMDS = [
12
+ 'npm',
13
+ 'pnpm',
14
+ 'yarn',
15
+ 'npx',
16
+ 'node',
17
+ 'python',
18
+ 'python3',
19
+ 'pytest',
20
+ 'cargo',
21
+ 'go'
22
+ ];
23
+ static CMD_META = /[&|<>^%!"\r\n]/;
24
+ static SHIM_CLI = {
25
+ npm: [
26
+ 'node_modules',
27
+ 'npm',
28
+ 'bin',
29
+ 'npm-cli.js'
30
+ ],
31
+ npx: [
32
+ 'node_modules',
33
+ 'npm',
34
+ 'bin',
35
+ 'npx-cli.js'
36
+ ],
37
+ pnpm: [
38
+ 'node_modules',
39
+ 'pnpm',
40
+ 'bin',
41
+ 'pnpm.cjs'
42
+ ],
43
+ yarn: [
44
+ 'node_modules',
45
+ 'yarn',
46
+ 'bin',
47
+ 'yarn.js'
48
+ ]
49
+ };
50
+ constructor(workspaceDir){
51
+ this.workspaceDir = path.resolve(workspaceDir);
52
+ }
53
+ resolveCommandPath(bareName) {
54
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(bareName)) {
55
+ return {
56
+ ok: false,
57
+ reason: `拒绝非裸命令名:${bareName}`
58
+ };
59
+ }
60
+ const isWin = process.platform === 'win32';
61
+ const candidates = isWin ? [
62
+ `${bareName}.cmd`,
63
+ `${bareName}.exe`
64
+ ] : [
65
+ bareName
66
+ ];
67
+ const pathDirs = (process.env.PATH || '').split(isWin ? ';' : ':').map((d)=>d.trim().replace(/^"|"$/g, '')).filter((d)=>d.length > 0);
68
+ for (const dir of pathDirs){
69
+ if (this.isInsideWorkspace(dir)) continue;
70
+ for (const cand of candidates){
71
+ const full = path.join(dir, cand);
72
+ try {
73
+ fsSync.accessSync(full, fsSync.constants.X_OK);
74
+ return {
75
+ ok: true,
76
+ absPath: path.resolve(full)
77
+ };
78
+ } catch {}
79
+ }
80
+ }
81
+ return {
82
+ ok: false,
83
+ reason: `PATH 上未找到命令“${bareName}”(工作区已从搜索范围排除)`
84
+ };
85
+ }
86
+ isInsideWorkspace(target) {
87
+ const resolved = path.resolve(target);
88
+ const a = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
89
+ const b = process.platform === 'win32' ? this.workspaceDir.toLowerCase() : this.workspaceDir;
90
+ return a === b || a.startsWith(b + path.sep);
91
+ }
92
+ trimTail(s, max) {
93
+ if (s.length <= max) return s;
94
+ let cut = s.slice(-max);
95
+ const c = cut.charCodeAt(0);
96
+ if (c >= 0xDC00 && c <= 0xDFFF) cut = cut.slice(1);
97
+ return cut;
98
+ }
99
+ run(command, args, timeoutMs = 60000) {
100
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
101
+ timeoutMs = 60000;
102
+ }
103
+ const cmdBase = command.replace(/\.(cmd|exe|bat)$/i, '').toLowerCase();
104
+ if (!this.ALLOWED_CMDS.includes(cmdBase)) {
105
+ return Promise.resolve({
106
+ success: false,
107
+ exitCode: null,
108
+ output: `[安全拦截] 运行机拒绝执行未授权命令:${command}`,
109
+ timedOut: false,
110
+ truncated: false
111
+ });
112
+ }
113
+ const resolution = this.resolveCommandPath(cmdBase);
114
+ if (!resolution.ok) {
115
+ return Promise.resolve({
116
+ success: false,
117
+ exitCode: null,
118
+ output: `[安全拦截] ${resolution.reason}`,
119
+ timedOut: false,
120
+ truncated: false
121
+ });
122
+ }
123
+ const isWin = process.platform === 'win32';
124
+ const useCmdShim = isWin && resolution.absPath.toLowerCase().endsWith('.cmd');
125
+ if (useCmdShim && args.some((a)=>Runner.CMD_META.test(a))) {
126
+ return Promise.resolve({
127
+ success: false,
128
+ exitCode: null,
129
+ output: `[安全拦截] 参数包含 cmd 元字符,拒绝执行:${args.join(' ')}`,
130
+ timedOut: false,
131
+ truncated: false
132
+ });
133
+ }
134
+ const childEnv = {
135
+ PATH: process.env.PATH || '',
136
+ SYSTEMROOT: process.env.SYSTEMROOT || '',
137
+ SYSTEMDRIVE: process.env.SYSTEMDRIVE || '',
138
+ COMSPEC: process.env.COMSPEC || path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'cmd.exe'),
139
+ TEMP: process.env.TEMP || process.env.TMP || '',
140
+ TMP: process.env.TMP || process.env.TEMP || '',
141
+ APPDATA: process.env.APPDATA || '',
142
+ USERPROFILE: process.env.USERPROFILE || process.env.HOME || '',
143
+ HOME: process.env.HOME || process.env.USERPROFILE || '',
144
+ CARGO_HOME: process.env.CARGO_HOME || path.join(process.env.USERPROFILE || process.env.HOME || '', '.cargo'),
145
+ LANG: 'en_US.UTF-8',
146
+ LC_ALL: 'en_US.UTF-8',
147
+ PYTHONIOENCODING: 'utf-8'
148
+ };
149
+ return new Promise((resolve)=>{
150
+ let child;
151
+ try {
152
+ if (useCmdShim) {
153
+ const cliParts = Runner.SHIM_CLI[cmdBase];
154
+ const cliJs = cliParts ? path.join(path.dirname(resolution.absPath), ...cliParts) : null;
155
+ const nodeRes = cliJs && fsSync.existsSync(cliJs) ? this.resolveCommandPath('node') : null;
156
+ if (cliJs && nodeRes && nodeRes.ok) {
157
+ child = spawn(nodeRes.absPath, [
158
+ cliJs,
159
+ ...args
160
+ ], {
161
+ cwd: this.workspaceDir,
162
+ env: childEnv,
163
+ shell: false,
164
+ windowsHide: true,
165
+ stdio: [
166
+ 'ignore',
167
+ 'pipe',
168
+ 'pipe'
169
+ ]
170
+ });
171
+ } else {
172
+ return resolve({
173
+ success: false,
174
+ exitCode: null,
175
+ output: `[安全拦截] 无法安全执行 ${cmdBase}:找不到底层的 JS 入口或 node 命令。为防工作区注入,已拒绝 cmd.exe 回退。`,
176
+ timedOut: false,
177
+ truncated: false
178
+ });
179
+ }
180
+ } else {
181
+ child = spawn(resolution.absPath, args, {
182
+ cwd: this.workspaceDir,
183
+ env: childEnv,
184
+ shell: false,
185
+ detached: process.platform !== 'win32',
186
+ windowsHide: true,
187
+ stdio: [
188
+ 'ignore',
189
+ 'pipe',
190
+ 'pipe'
191
+ ]
192
+ });
193
+ }
194
+ } catch (syncErr) {
195
+ return resolve({
196
+ success: false,
197
+ exitCode: null,
198
+ output: `[运行机错误] spawn 同步失败:${syncErr?.message}`,
199
+ timedOut: false,
200
+ truncated: false
201
+ });
202
+ }
203
+ let output = '';
204
+ let truncated = false;
205
+ let timedOut = false;
206
+ let settled = false;
207
+ let spawnError = null;
208
+ let exitCode = null;
209
+ let exitSignal = null;
210
+ let exitGraceTimer = null;
211
+ let killGraceTimer = null;
212
+ const stdoutDecoder = new StringDecoder('utf8');
213
+ const stderrDecoder = new StringDecoder('utf8');
214
+ let lineOpen = false;
215
+ const appendLog = (data, decoder, tag)=>{
216
+ if (output.length >= this.HARD_LIMIT_CHARS) {
217
+ truncated = true;
218
+ return;
219
+ }
220
+ const text = decoder.write(data);
221
+ if (text.length === 0) return;
222
+ const lines = text.split('\n');
223
+ for(let i = 0; i < lines.length; i++){
224
+ if (i > 0) {
225
+ output += '\n';
226
+ lineOpen = false;
227
+ }
228
+ const line = lines[i];
229
+ if (line.length === 0) continue;
230
+ if (!lineOpen) {
231
+ output += tag;
232
+ lineOpen = true;
233
+ }
234
+ output += line;
235
+ }
236
+ if (output.length > this.HARD_LIMIT_CHARS) {
237
+ output = this.trimTail(output, this.MAX_OUTPUT_CHARS);
238
+ truncated = true;
239
+ }
240
+ };
241
+ child.stdout?.on('data', (d)=>appendLog(d, stdoutDecoder, '[out] '));
242
+ child.stderr?.on('data', (d)=>appendLog(d, stderrDecoder, '[err] '));
243
+ const killTree = ()=>{
244
+ if (typeof child.pid !== 'number') return;
245
+ if (process.platform === 'win32') {
246
+ const tk = spawn('taskkill', [
247
+ '/pid',
248
+ String(child.pid),
249
+ '/f',
250
+ '/t'
251
+ ], {
252
+ stdio: 'ignore',
253
+ windowsHide: true
254
+ });
255
+ tk.on('error', ()=>{
256
+ try {
257
+ child.kill('SIGKILL');
258
+ } catch {}
259
+ });
260
+ } else {
261
+ try {
262
+ process.kill(-child.pid, 'SIGKILL');
263
+ } catch {
264
+ try {
265
+ child.kill('SIGKILL');
266
+ } catch {}
267
+ }
268
+ }
269
+ };
270
+ const finalize = ()=>{
271
+ if (settled) return;
272
+ settled = true;
273
+ if (mainTimer) clearTimeout(mainTimer);
274
+ if (exitGraceTimer) clearTimeout(exitGraceTimer);
275
+ if (killGraceTimer) clearTimeout(killGraceTimer);
276
+ if (spawnError) {
277
+ resolve({
278
+ success: false,
279
+ exitCode: null,
280
+ output: `[运行机错误] ${spawnError.message}`,
281
+ timedOut: false,
282
+ truncated: false
283
+ });
284
+ return;
285
+ }
286
+ let finalOutput = output;
287
+ if (finalOutput.length > this.MAX_OUTPUT_CHARS) {
288
+ finalOutput = this.trimTail(finalOutput, this.MAX_OUTPUT_CHARS);
289
+ }
290
+ if (truncated) finalOutput = '...[输出超出上限,前部已丢弃]\n' + finalOutput;
291
+ if (timedOut) {
292
+ finalOutput += `\n[执行超时 ${timeoutMs}ms,运行机已强杀进程树;exitCode=${exitCode ?? 'null'}, signal=${exitSignal ?? 'none'}]`;
293
+ }
294
+ resolve({
295
+ success: !timedOut && exitCode === 0,
296
+ exitCode,
297
+ output: finalOutput,
298
+ timedOut,
299
+ truncated
300
+ });
301
+ };
302
+ const mainTimer = setTimeout(()=>{
303
+ timedOut = true;
304
+ killTree();
305
+ killGraceTimer = setTimeout(finalize, this.KILL_GRACE_MS);
306
+ }, timeoutMs);
307
+ child.on('exit', (code, signal)=>{
308
+ exitCode = code;
309
+ exitSignal = signal;
310
+ exitGraceTimer = setTimeout(finalize, this.EXIT_GRACE_MS);
311
+ });
312
+ child.on('close', (code)=>{
313
+ if (exitCode === null && code !== null) exitCode = code;
314
+ finalize();
315
+ });
316
+ child.on('error', (err)=>{
317
+ if (typeof child.pid !== 'number' && !spawnError) {
318
+ spawnError = err;
319
+ finalize();
320
+ }
321
+ });
322
+ });
323
+ }
324
+ }
@@ -0,0 +1,149 @@
1
+ import * as fs from 'fs/promises';
2
+ import * as path from 'path';
3
+ import * as crypto from 'crypto';
4
+ export class StateManager {
5
+ stateDir;
6
+ stateFilePath;
7
+ taskId;
8
+ macSecret;
9
+ writeChain = Promise.resolve();
10
+ authoritative = null;
11
+ tmpSeq = 0;
12
+ constructor(stateDir, rawTaskId, workspaceDir, macSecret){
13
+ const safeTaskId = rawTaskId.replace(/[^a-zA-Z0-9_\-]/g, '_');
14
+ const idHash = crypto.createHash('sha256').update(String(rawTaskId) + '\n' + String(workspaceDir)).digest('hex').slice(0, 8);
15
+ this.taskId = safeTaskId;
16
+ this.macSecret = macSecret ?? null;
17
+ this.stateDir = path.resolve(stateDir);
18
+ this.stateFilePath = path.join(this.stateDir, `state_${safeTaskId}_${idHash}.json`);
19
+ }
20
+ macOf(body) {
21
+ if (this.macSecret !== null) {
22
+ return crypto.createHmac('sha256', this.macSecret).update(body).digest('hex');
23
+ }
24
+ return crypto.createHash('sha256').update(body).digest('hex');
25
+ }
26
+ checksumOf(state) {
27
+ const { taskId, round, status, taskPrompt, writtenFiles, testResult, reviewResult, lastError } = state;
28
+ const body = JSON.stringify({
29
+ taskId,
30
+ round,
31
+ status,
32
+ taskPrompt,
33
+ writtenFiles,
34
+ testResult,
35
+ reviewResult,
36
+ lastError
37
+ });
38
+ return this.macOf(body);
39
+ }
40
+ async persist(state) {
41
+ await fs.mkdir(this.stateDir, {
42
+ recursive: true,
43
+ mode: 0o700
44
+ });
45
+ const payload = {
46
+ version: 1,
47
+ ...state,
48
+ checksum: this.checksumOf(state)
49
+ };
50
+ const tmpPath = `${this.stateFilePath}.${process.pid}.${Date.now()}.${this.tmpSeq++}.tmp`;
51
+ const fh = await fs.open(tmpPath, 'w', 0o600);
52
+ try {
53
+ await fh.writeFile(JSON.stringify(payload, null, 2), 'utf8');
54
+ await fh.sync();
55
+ } finally{
56
+ await fh.close();
57
+ }
58
+ let renameErr = null;
59
+ for(let attempt = 0; attempt < 3; attempt++){
60
+ try {
61
+ await fs.rename(tmpPath, this.stateFilePath);
62
+ renameErr = null;
63
+ break;
64
+ } catch (e) {
65
+ renameErr = e;
66
+ if (e?.code !== 'EPERM' && e?.code !== 'EACCES') break;
67
+ await new Promise((r)=>setTimeout(r, 50 * (attempt + 1)));
68
+ }
69
+ }
70
+ if (renameErr !== null) {
71
+ await fs.unlink(tmpPath).catch(()=>{});
72
+ throw renameErr;
73
+ }
74
+ try {
75
+ const dh = await fs.open(this.stateDir, 'r');
76
+ try {
77
+ await dh.sync();
78
+ } finally{
79
+ await dh.close();
80
+ }
81
+ } catch {}
82
+ }
83
+ async readFromDisk() {
84
+ const raw = await fs.readFile(this.stateFilePath, 'utf8');
85
+ const parsed = JSON.parse(raw);
86
+ if (parsed.version !== 1) {
87
+ throw new Error(`[状态管理器] 状态文件格式版本不匹配:期望 1,收到 ${String(parsed.version)}`);
88
+ }
89
+ const { checksum, version, ...state } = parsed;
90
+ void version;
91
+ if (typeof checksum !== 'string' || checksum !== this.checksumOf(state)) {
92
+ throw new Error('[状态管理器] 状态文件校验失败(被外部篡改或密钥不匹配)');
93
+ }
94
+ return state;
95
+ }
96
+ enqueue(job) {
97
+ const next = this.writeChain.then(job, job);
98
+ this.writeChain = next.then(()=>undefined, ()=>undefined);
99
+ return next;
100
+ }
101
+ async init(taskPrompt) {
102
+ return this.enqueue(async ()=>{
103
+ const initial = {
104
+ taskId: this.taskId,
105
+ round: 1,
106
+ status: 'RUNNING',
107
+ taskPrompt,
108
+ writtenFiles: null,
109
+ testResult: null,
110
+ reviewResult: null,
111
+ lastError: null
112
+ };
113
+ await this.persist(initial);
114
+ this.authoritative = initial;
115
+ return initial;
116
+ });
117
+ }
118
+ async load() {
119
+ if (this.authoritative) return this.authoritative;
120
+ return this.enqueue(async ()=>{
121
+ if (this.authoritative) return this.authoritative;
122
+ try {
123
+ const s = await this.readFromDisk();
124
+ this.authoritative = s;
125
+ return s;
126
+ } catch (e) {
127
+ if (e?.code === 'ENOENT') return null;
128
+ throw e;
129
+ }
130
+ });
131
+ }
132
+ async update(mutator) {
133
+ return this.enqueue(async ()=>{
134
+ if (!this.authoritative) {
135
+ throw new Error('[状态管理器] 状态未初始化,禁止 update(应先 init 或 load 恢复)');
136
+ }
137
+ const draft = {
138
+ ...this.authoritative
139
+ };
140
+ await mutator(draft);
141
+ if (draft.round < this.authoritative.round) {
142
+ throw new Error(`[状态管理器] 拒绝过期写入:round ${draft.round} < 当前 ${this.authoritative.round}`);
143
+ }
144
+ await this.persist(draft);
145
+ this.authoritative = draft;
146
+ return draft;
147
+ });
148
+ }
149
+ }
package/icon.svg ADDED
@@ -0,0 +1,20 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-label="DACW">
2
+ <defs>
3
+ <linearGradient id="dacw-bg" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#2f3a4f"/>
5
+ <stop offset="1" stop-color="#15202f"/>
6
+ </linearGradient>
7
+ <linearGradient id="dacw-shield" x1="0" y1="0" x2="0" y2="1">
8
+ <stop offset="0" stop-color="#7cb6ff"/>
9
+ <stop offset="1" stop-color="#4f7cff"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect width="64" height="64" rx="14" fill="url(#dacw-bg)"/>
13
+ <path d="M32 8 L52 15 L52 31 C52 42 44 51 32 56 C20 51 12 42 12 31 L12 15 Z"
14
+ fill="none" stroke="url(#dacw-shield)" stroke-width="3.5" stroke-linejoin="round"/>
15
+ <path d="M25 24 L18.5 32 L25 40" fill="none" stroke="#e8f1ff" stroke-width="3"
16
+ stroke-linecap="round" stroke-linejoin="round"/>
17
+ <path d="M39 24 L45.5 32 L39 40" fill="none" stroke="#e8f1ff" stroke-width="3"
18
+ stroke-linecap="round" stroke-linejoin="round"/>
19
+ <path d="M35 20 L29 44" fill="none" stroke="#8fd3a8" stroke-width="3" stroke-linecap="round"/>
20
+ </svg>
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "DACW — Defensive Agent Coding Workflow",
4
+ "description": "Writer → deterministic runner → separate reviewer → human gate. The dacw_run tool writes, tests and audits code in an isolated workspace; nothing is merged without human review."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "DACW — 防御性智能体编程工作流",
4
+ "description": "写手 → 确定性运行机 → 独立审查者 → 人工闸门。dacw_run 工具在隔离工作区里写代码、跑测试、做审查;未经人工确认不会合入任何代码。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@stmcw1/dacw",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Defensive Agent Coding Workflow (DACW) as a DSH Host plugin: an AI writer proposes code, a deterministic runner tests it, a separate reviewer audits it, and a human gate decides the merge.",
5
+ "keywords": [
6
+ "dacw",
7
+ "dsh",
8
+ "deepseek-harness",
9
+ "coding-agent",
10
+ "agent-workflow",
11
+ "code-review",
12
+ "ai",
13
+ "plugin"
14
+ ],
15
+ "homepage": "https://github.com/stmcw1/DACW#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/stmcw1/DACW.git"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/stmcw1/DACW/issues"
22
+ },
23
+ "author": "stmcw1 <stmcw@163.com>",
24
+ "license": "MIT",
25
+ "private": false,
26
+ "type": "module",
27
+ "exports": {
28
+ ".": "./dist/plugin.js",
29
+ "./locale/*.json": "./locale/*.json",
30
+ "./icon": "./icon.svg"
31
+ },
32
+ "files": [
33
+ "dist/index.js",
34
+ "dist/plugin.js",
35
+ "dist/runner.js",
36
+ "dist/state_manager.js",
37
+ "cordis.patch.yml",
38
+ "locale/*.json",
39
+ "icon.svg",
40
+ "README.md",
41
+ "README_EN.md",
42
+ "SAFETY.md",
43
+ "SAFETY_EN.md",
44
+ "LICENSE"
45
+ ],
46
+ "engines": {
47
+ "node": ">=22.13"
48
+ },
49
+ "scripts": {
50
+ "build": "node build.mjs",
51
+ "prepack": "node build.mjs",
52
+ "pretest": "node build.mjs",
53
+ "test": "node selftest.mjs"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "dsh": {
59
+ "bundle": {
60
+ "patch": "./cordis.patch.yml"
61
+ }
62
+ }
63
+ }