@sanqianx/ai-coding-workflow 0.1.1 → 0.2.0

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/src/snapshots.js CHANGED
@@ -3,20 +3,30 @@
3
3
  // Code snapshots for the review/check pipeline (main plan §9.1).
4
4
  //
5
5
  // A snapshot captures the work tree the way a delivery actually looks:
6
- // tracked files at HEAD, tracked files with local modifications, AND the
7
- // explicitly included untracked source files. Each file keeps its path,
8
- // origin (head|modified|untracked), byte length and content hash; the
6
+ // tracked files at HEAD, tracked files with local modifications, tracked
7
+ // files deleted in the work tree, AND the explicitly included untracked
8
+ // source files. Each file keeps its path (POSIX form), origin
9
+ // (head|modified|deleted|untracked), byte length and content hash; the
9
10
  // snapshot id is a hash over the manifest, so the same tree yields the same
10
11
  // id and cached evidence stays reusable, while ANY change (even with HEAD
11
12
  // unchanged) yields a new id and invalidates prior receipts (T11).
13
+ //
14
+ // M0-B hardening: the manifest is ordered deterministically, origin is
15
+ // decided against the real Git blob hash (NOT a raw SHA-256 — that bug made
16
+ // every tracked file look 'modified'), and every anomaly the caller must
17
+ // know about — unreadable included files, paths escaping the repo, symlink
18
+ // targets outside the tree — raises instead of being silently skipped.
12
19
 
13
20
  const crypto = require('crypto');
14
21
  const fs = require('fs');
15
22
  const path = require('path');
16
23
  const { spawnSync } = require('child_process');
24
+ const { WorkflowError } = require('./errors');
17
25
 
18
26
  const SOURCE_EXTS = new Set(['.js', '.cjs', '.mjs', '.ts', '.jsx', '.tsx', '.cc', '.cpp', '.h', '.hpp', '.go', '.json', '.css', '.html']);
19
27
 
28
+ const realpath = fs.realpathSync.native || fs.realpathSync;
29
+
20
30
  function git(repoPath, args) {
21
31
  const result = spawnSync('git', ['-C', repoPath, ...args], { encoding: 'utf8', windowsHide: true });
22
32
  if (result.status !== 0) throw Object.assign(new Error(`git ${args[0]} failed: ${(result.stderr || '').slice(0, 200)}`), { code: 'GIT_FAILED' });
@@ -25,6 +35,32 @@ function git(repoPath, args) {
25
35
 
26
36
  function hashBytes(buffer) { return crypto.createHash('sha256').update(buffer).digest('hex'); }
27
37
 
38
+ /** The Git blob object id of a buffer — the real comparison target for HEAD. */
39
+ function blobOid(buffer) {
40
+ return crypto.createHash('sha1').update(`blob ${buffer.length}\0`).update(buffer).digest('hex');
41
+ }
42
+
43
+ function toPosix(relativePath) { return relativePath.split(path.sep).join('/'); }
44
+
45
+ /** Fail closed when a path escapes the repository root (incl. symlink hops). */
46
+ function resolveInside(repoReal, relativePath, label) {
47
+ if (typeof relativePath !== 'string' || !relativePath) throw new WorkflowError('EXECUTION_FAILED', `${label} is required.`, { reason: 'snapshot-path-missing' });
48
+ if (path.isAbsolute(relativePath) || relativePath.split(/[\\/]/).includes('..')) {
49
+ throw new WorkflowError('EXECUTION_FAILED', `${label} escapes the repository root: ${relativePath}`, { reason: 'snapshot-path-escape', path: relativePath });
50
+ }
51
+ const absolute = path.join(repoReal, relativePath);
52
+ let real;
53
+ try { real = realpath(absolute); } catch (error) {
54
+ if (error && error.code === 'ENOENT') return { absolute, missing: true, real: null };
55
+ throw new WorkflowError('EXECUTION_FAILED', `${label} is not readable: ${relativePath}`, { reason: 'snapshot-unreadable', path: relativePath });
56
+ }
57
+ const rel = path.relative(repoReal, real);
58
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
59
+ throw new WorkflowError('EXECUTION_FAILED', `${label} resolves outside the repository root (symlink/junction): ${relativePath}`, { reason: 'snapshot-symlink-escape', path: relativePath });
60
+ }
61
+ return { absolute, missing: false, real };
62
+ }
63
+
28
64
  function isSourceFile(relativePath, includePatterns) {
29
65
  if (includePatterns && includePatterns.length) return includePatterns.some(p => relativePath.startsWith(p.replace(/\/$/, '') + '/') || relativePath === p);
30
66
  return SOURCE_EXTS.has(path.extname(relativePath));
@@ -33,9 +69,11 @@ function isSourceFile(relativePath, includePatterns) {
33
69
  /**
34
70
  * Materialize a snapshot record for a repository. `options.included` lists
35
71
  * untracked files the delivery explicitly pulls in (runbook §9.1: candidates
36
- * must not silently drop untracked sources).
72
+ * must not silently drop untracked sources). Unreadable included files,
73
+ * escaping paths and links leaving the tree are ERRORS, never skips.
37
74
  */
38
75
  function captureSnapshot(repoPath, options = {}) {
76
+ const repoReal = realpath(repoPath);
39
77
  const manifest = [];
40
78
  const lsTree = git(repoPath, ['ls-files', '-z']);
41
79
  const tracked = lsTree.split('\0').filter(Boolean);
@@ -44,30 +82,53 @@ function captureSnapshot(repoPath, options = {}) {
44
82
  const lsHead = git(repoPath, ['ls-tree', '-r', 'HEAD', '--format=%(objectname)%x09%(path)', '-z']);
45
83
  for (const entry of lsHead.split('\0').filter(Boolean)) {
46
84
  const [oid, p] = entry.split('\t');
47
- if (p) headOids.set(p, oid);
85
+ if (p) headOids.set(toPosix(p), oid);
48
86
  }
49
87
  }
50
- const modified = new Set(git(repoPath, ['status', '--porcelain', '-z']).split('\0')
51
- .filter(Boolean)
52
- .map(line => line.slice(3).replace(/"/g, '')));
88
+ const statusLines = git(repoPath, ['status', '--porcelain', '-z']).split('\0').filter(Boolean);
89
+ const modified = new Set();
90
+ const deleted = new Set();
91
+ for (const line of statusLines) {
92
+ const code = line.slice(0, 2);
93
+ const entry = line.slice(3).replace(/"/g, '');
94
+ if (!entry) continue;
95
+ if (code.trim() === 'D' || code.includes('D')) deleted.add(toPosix(entry.split(' -> ')[0]));
96
+ else modified.add(toPosix(entry.split(' -> ')[0]));
97
+ }
53
98
  for (const relativePath of tracked) {
54
- if (!isSourceFile(relativePath, options.includePatterns)) continue;
55
- if (options.exclude && options.exclude.includes(relativePath)) continue;
56
- const absolute = path.join(repoPath, relativePath);
99
+ const posixPath = toPosix(relativePath);
100
+ if (!isSourceFile(posixPath, options.includePatterns)) continue;
101
+ if (options.exclude && options.exclude.includes(posixPath)) continue;
102
+ const probe = resolveInside(repoReal, relativePath, 'tracked file');
103
+ if (probe.missing || deleted.has(posixPath)) {
104
+ // Deleted in the work tree: the delivery state must say so — a silent
105
+ // skip would let a broken build look like a clean tree.
106
+ manifest.push({ path: posixPath, origin: 'deleted', bytes: null, hash: null });
107
+ continue;
108
+ }
57
109
  let content;
58
- try { content = fs.readFileSync(absolute); } catch { continue; } // deleted in worktree
110
+ try { content = fs.readFileSync(probe.real); } catch {
111
+ throw new WorkflowError('EXECUTION_FAILED', `tracked file is not readable: ${posixPath}`, { reason: 'snapshot-unreadable', path: posixPath });
112
+ }
59
113
  const workHash = hashBytes(content);
60
- const origin = modified.has(relativePath) ? 'modified' : (headOids.get(relativePath) === workHash ? 'head' : 'modified');
61
- manifest.push({ path: relativePath, origin, bytes: content.length, hash: workHash });
114
+ // origin 'head' only when the content is BYTE-IDENTICAL to the HEAD blob.
115
+ const origin = headOids.get(posixPath) === blobOid(content) ? 'head' : 'modified';
116
+ manifest.push({ path: posixPath, origin, bytes: content.length, hash: workHash });
62
117
  }
118
+ const trackedPosix = new Set(tracked.map(toPosix));
63
119
  for (const relativePath of options.included || []) {
64
- if (tracked.includes(relativePath)) continue;
65
- const absolute = path.join(repoPath, relativePath);
120
+ const probe = resolveInside(repoReal, relativePath, 'included untracked file');
121
+ if (probe.missing) {
122
+ throw new WorkflowError('EXECUTION_FAILED', `included untracked file is missing: ${relativePath}`, { reason: 'snapshot-included-missing', path: toPosix(relativePath) });
123
+ }
124
+ if (trackedPosix.has(toPosix(relativePath))) continue;
66
125
  let content;
67
- try { content = fs.readFileSync(absolute); } catch { continue; }
68
- manifest.push({ path: relativePath, origin: 'untracked', bytes: content.length, hash: hashBytes(content) });
126
+ try { content = fs.readFileSync(probe.real); } catch {
127
+ throw new WorkflowError('EXECUTION_FAILED', `included untracked file is not readable: ${relativePath}`, { reason: 'snapshot-unreadable', path: toPosix(relativePath) });
128
+ }
129
+ manifest.push({ path: toPosix(relativePath), origin: 'untracked', bytes: content.length, hash: hashBytes(content) });
69
130
  }
70
- manifest.sort((a, b) => a.path.localeCompare(b.path));
131
+ manifest.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
71
132
  const id = crypto.createHash('sha256').update(JSON.stringify(manifest)).digest('hex').slice(0, 32);
72
133
  return { snapshotId: `snap_${id}`, files: manifest, fileCount: manifest.length, capturedAt: new Date().toISOString(), head: headCommit(repoPath) };
73
134
  }
@@ -81,4 +142,4 @@ function evidenceKey({ snapshotId, baselineId, policyHash, toolchainHash, accept
81
142
  return crypto.createHash('sha256').update(JSON.stringify({ snapshotId, baselineId, policyHash, toolchainHash, acceptanceRevision })).digest('hex');
82
143
  }
83
144
 
84
- module.exports = { captureSnapshot, evidenceKey, hashBytes };
145
+ module.exports = { captureSnapshot, evidenceKey, hashBytes, blobOid };
package/src/store.js CHANGED
@@ -110,8 +110,12 @@ class WorkflowStore {
110
110
  team: null,
111
111
  members: {},
112
112
  projects: {}, // projectId -> settings (enabled, review flags, checks)
113
+ projectRoots: {}, // projectId -> { canonicalGitRoot, ... } (M0-A trusted mapping)
113
114
  tasks: {}, // taskId -> task record
114
115
  sessionBindings: {},
116
+ reviewJobs: {}, // reviewJobId -> review job (M0-B: reserved before checks run)
117
+ reviewerConfig: null, // M1-A trusted reviewer runtime config (provider/entry/allowedModels)
118
+ checkReceipts: {}, // receiptId -> persisted receipt
115
119
  requests: {}, // requestId -> { payloadHash, result, revision, at }
116
120
  inbox: {}, // inboxId -> raw event (pre-projection journal events)
117
121
  outbox: [], // pending side effects, drained after persist
@@ -132,6 +136,24 @@ class WorkflowStore {
132
136
  if (parsed.schema !== STATE_SCHEMA) {
133
137
  throw new WorkflowError('DATA_CORRUPT', 'Workflow state has an unsupported schema.', { found: parsed.schema, expected: STATE_SCHEMA });
134
138
  }
139
+ // Read-time defaults: aggregates written by older versions predate
140
+ // newer keys; every mutation below assumes these containers exist
141
+ // (contract §6: apply defaults when reading, keep unknown fields).
142
+ parsed.requests ??= {};
143
+ parsed.inbox ??= {};
144
+ parsed.outbox ??= [];
145
+ parsed.cursors ??= {};
146
+ parsed.consumers ??= {};
147
+ parsed.changes ??= [];
148
+ parsed.changeSeq ??= 0;
149
+ parsed.sessionBindings ??= {};
150
+ parsed.tasks ??= {};
151
+ parsed.members ??= {};
152
+ parsed.projects ??= {};
153
+ parsed.projectRoots ??= {};
154
+ parsed.reviewJobs ??= {};
155
+ parsed.checkReceipts ??= {};
156
+ parsed.reviewerConfig ??= null;
135
157
  return parsed;
136
158
  } catch (error) {
137
159
  if (error instanceof WorkflowError) throw error;