@sabaiway/agent-workflow-kit 23.6.0 → 23.8.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.
@@ -15,9 +15,10 @@
15
15
  // Dependency-free, Node >= 22. No side effects on import; the only child process is a read-only git
16
16
  // query, so the read-graph purity suite stays true.
17
17
 
18
- import { lstatSync, readdirSync, readFileSync } from 'node:fs';
19
- import { join } from 'node:path';
18
+ import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
19
+ import { join, relative, sep } from 'node:path';
20
20
  import { spawnSync } from 'node:child_process';
21
+ import { createHash } from 'node:crypto';
21
22
  import { configFail, configPathFor, scopeFail } from './source-size-refusal.mjs';
22
23
  import { KIT_FOLDER_ROOT, WHOLE_TREE_ROOT } from './source-size-config.mjs';
23
24
  import { SPEC_STORE_ROOT, walkSpecStore } from './source-size/index.mjs';
@@ -51,27 +52,65 @@ const bufSegmentPrefix = (path, prefix) =>
51
52
  const bufEndsWith = (path, suffix) =>
52
53
  path.length >= suffix.length && path.subarray(path.length - suffix.length).equals(suffix);
53
54
 
54
- // The enumeration-error class (exit 2) also refuses every git LOCATION but a work tree, by its own
55
- // state name — a redirecting GIT_DIR would otherwise enumerate ANOTHER repository's index in
56
- // silence — and a runner that throws, which is an answer here, never a raw stack.
57
- export const enumerateIndex = (cwd, deps = {}) => {
55
+ const queryGit = (cwd, args, deps, what) => {
58
56
  const spawn = deps.spawn ?? spawnSync;
59
57
  const env = deps.env ?? process.env;
60
58
  const location = resolveGitLocation(cwd, { spawn, env });
61
59
  if (location.state !== 'work-tree') {
62
- throw configFail(`the git index could not be enumerated in ${cwd} (the git location is ${location.state}: ${location.cause}) — the declared scope is unknown, so nothing is judged`);
63
- }
64
- let result;
65
- try {
66
- result = spawn('git', ['ls-files', '-s', '-z'], { cwd, env: withGitPath(env), maxBuffer: GIT_MAX_BUFFER, windowsHide: true });
67
- } catch (err) {
68
- result = { error: err };
60
+ throw configFail(`${what} in ${cwd} (the git location is ${location.state}: ${location.cause}) — the declared scope is unknown, so nothing is judged`);
69
61
  }
62
+ const result = (() => {
63
+ try {
64
+ return spawn('git', args, { cwd, env: withGitPath(env), maxBuffer: GIT_MAX_BUFFER, windowsHide: true });
65
+ } catch (error) {
66
+ return { error };
67
+ }
68
+ })();
70
69
  if (result.error || result.status !== 0) {
71
70
  const why = result.error ? result.error.message : result.signal ? `git was killed by ${result.signal}` : `git exited ${result.status}`;
72
- throw configFail(`the git index could not be enumerated in ${cwd} (${why}) — the declared scope is unknown, so nothing is judged`);
71
+ throw configFail(`${what} in ${cwd} (${why}) — the declared scope is unknown, so nothing is judged`);
73
72
  }
74
- return parseIndexEntries(result.stdout);
73
+ return { stdout: result.stdout, top: location.top };
74
+ };
75
+
76
+ export const enumerateIndex = (cwd, deps = {}) => parseIndexEntries(
77
+ queryGit(cwd, ['ls-files', '-s', '-z'], deps, 'the git index could not be enumerated').stdout);
78
+
79
+ const WORK_TREE_ARGS = Object.freeze(['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all', '--no-renames']);
80
+ const UNTRACKED_STATUS = '??';
81
+ const INTENT_STATUS = ' A';
82
+ const WORK_TREE_UNCHANGED = ' ';
83
+ const SHA256_HEX_LENGTH = 64;
84
+ const hashBlob = (bytes, oid) => createHash(oid.length === SHA256_HEX_LENGTH ? 'sha256' : 'sha1')
85
+ .update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
86
+ const rulesOf = (config) => ({
87
+ roots: config.roots.map((rel) => ({ rel, buf: Buffer.from(rel, 'utf8') })),
88
+ excludes: config.exclude.map((rel) => Buffer.from(rel, 'utf8')),
89
+ extensions: config.extensions.map((extension) => Buffer.from(extension, 'utf8')),
90
+ });
91
+ const rootOf = ({ roots }, path) => roots.find((root) => root.rel === WHOLE_TREE_ROOT || bufSegmentPrefix(path, root.buf));
92
+ const isExcluded = ({ excludes }, path) => excludes.some((entry) => bufSegmentPrefix(path, entry));
93
+ const isExtended = ({ extensions }, path) => extensions.some((extension) => bufEndsWith(path, extension));
94
+
95
+ export const workTreeOf = (cwd, config, { scope, bytes, layout }, deps = {}) => {
96
+ const { stdout, top } = queryGit(cwd, WORK_TREE_ARGS, deps, "the git work tree's state could not be read");
97
+ const below = relative(realpathSync(top), realpathSync(cwd)).split(sep).join('/');
98
+ const prefix = below === '' ? Buffer.alloc(0) : Buffer.from(`${below}/`, 'utf8');
99
+ const entries = stdout.toString('latin1').split('\0').filter(Boolean)
100
+ .map((record) => ({ status: record.slice(0, 2), path: Buffer.from(record.slice(3), 'latin1') }))
101
+ .filter(({ path }) => path.subarray(0, prefix.length).equals(prefix))
102
+ .map((entry) => ({ ...entry, path: entry.path.subarray(prefix.length) }));
103
+ const rules = rulesOf(config);
104
+ const intents = new Set(entries.filter((entry) => entry.status === INTENT_STATUS).map((entry) => decodeStrict(entry.path)));
105
+ const untracked = entries.filter(({ status, path }) => status === UNTRACKED_STATUS
106
+ && rootOf(rules, path) !== undefined && !isExcluded(rules, path) && !bufSegmentPrefix(path, KIT_FOLDER)
107
+ && (isExtended(rules, path) || (layout && !bufSegmentPrefix(path, SPEC_STORE))))
108
+ .map(({ path }) => path.toString('utf8')).sort();
109
+ const changed = new Set(entries.filter(({ status }) => status !== UNTRACKED_STATUS && status[1] !== WORK_TREE_UNCHANGED)
110
+ .map((entry) => decodeStrict(entry.path)));
111
+ const differing = scope.files.filter((rel) => intents.has(rel)
112
+ || (changed.has(rel) && hashBlob(bytes.get(rel), scope.objectIds.get(rel)) !== scope.objectIds.get(rel)));
113
+ return { untracked, differing };
75
114
  };
76
115
 
77
116
  // resolveScope(cwd, config) → { files: [rel…] sorted, perRoot: Map<root, [rel…]>, layout: Map<root,
@@ -87,18 +126,23 @@ export const resolveScope = (cwd, config, deps = {}) => {
87
126
  if (unmerged.length > 0) {
88
127
  throw scopeFail(`the git index is UNMERGED (${unmerged.length} conflict-stage entr(ies)) — an ambiguous index cannot be judged; resolve the conflict, then re-run`);
89
128
  }
90
- const roots = config.roots.map((rel) => ({ rel, buf: Buffer.from(rel, 'utf8') }));
91
- const excludes = config.exclude.map((rel) => Buffer.from(rel, 'utf8'));
92
- const extensions = config.extensions.map((ext) => Buffer.from(ext, 'utf8'));
129
+ const rules = rulesOf(config);
130
+ const { excludes, extensions } = rules;
131
+ const excluded = config.exclude.map((entry, at) => {
132
+ const carried = entries.filter(({ path }) => bufSegmentPrefix(path, excludes[at]));
133
+ const count = carried.filter(({ path }) => rootOf(rules, path) !== undefined).length;
134
+ return { entry, count, carried: carried.length };
135
+ });
136
+ const objectIds = new Map();
93
137
  const perRoot = new Map(config.roots.map((rel) => [rel, []]));
94
138
  const layout = new Map(config.roots.map((rel) => [rel, []]));
95
139
  const files = [];
96
140
  const kitMatched = new Set();
97
141
  for (const entry of entries) {
98
- const root = roots.find((r) => r.rel === WHOLE_TREE_ROOT || bufSegmentPrefix(entry.path, r.buf));
142
+ const root = rootOf(rules, entry.path);
99
143
  if (!root) continue;
100
- if (excludes.some((ex) => bufSegmentPrefix(entry.path, ex))) continue;
101
- const extended = extensions.some((ext) => bufEndsWith(entry.path, ext));
144
+ if (isExcluded(rules, entry.path)) continue;
145
+ const extended = isExtended(rules, entry.path);
102
146
  if (bufSegmentPrefix(entry.path, KIT_FOLDER)) {
103
147
  if (extended) kitMatched.add(root.rel);
104
148
  continue;
@@ -115,10 +159,11 @@ export const resolveScope = (cwd, config, deps = {}) => {
115
159
  throw scopeFail(`an in-scope tracked path's NAME is not valid UTF-8 (bytes ${entry.path.toString('hex')}) — it cannot be addressed losslessly, so nothing is judged; rename it, or add its prefix to "exclude" in ${configPathFor(cwd)}`);
116
160
  }
117
161
  files.push(rel);
162
+ objectIds.set(rel, entry.sha);
118
163
  perRoot.get(root.rel).push(rel);
119
164
  }
120
165
  // A config declaring no extension judges no file, and the check says so instead of refusing.
121
- if (extensions.length === 0) return { files, perRoot, layout, emptyRoots: [], kitFolderRoots: [] };
166
+ if (extensions.length === 0) return { files, perRoot, layout, emptyRoots: [], kitFolderRoots: [], excluded, objectIds };
122
167
  // A scope the kit's own folder alone matches judges no line, and is no misdeclaration.
123
168
  if (files.length === 0 && kitMatched.size === 0) {
124
169
  throw scopeFail(`the declared scope matches ZERO tracked files (roots: ${config.roots.join(', ')}; extensions: ${config.extensions.join(', ')}) — an empty scope is a misdeclaration, never an empty green; either widen "roots" / "extensions" in ${configPathFor(cwd)}, or track a file the declared scope covers`);
@@ -126,7 +171,7 @@ export const resolveScope = (cwd, config, deps = {}) => {
126
171
  files.sort();
127
172
  for (const list of perRoot.values()) list.sort();
128
173
  const emptyRoots = [...perRoot].filter(([, list]) => list.length === 0).map(([rel]) => rel);
129
- return { files, perRoot, layout, emptyRoots, kitFolderRoots: emptyRoots.filter((rel) => kitMatched.has(rel)) };
174
+ return { files, perRoot, layout, emptyRoots, kitFolderRoots: emptyRoots.filter((rel) => kitMatched.has(rel)), excluded, objectIds };
130
175
  };
131
176
 
132
177
  // specStoreEntries(cwd) → the spec store's entries walked from disk, or null where it is absent. A
@@ -162,7 +207,7 @@ export const countBytes = (buf) => {
162
207
  // measureFile(cwd, rel) → { lines, maxLineBytes }. The judged bytes are the WORKTREE bytes of an
163
208
  // index-visible path; an in-scope file the checker cannot verify is exit 1 naming the exclude lane,
164
209
  // never a silent or green skip.
165
- export const measureFile = (cwd, rel, deps = {}) => {
210
+ export const measureFile = (cwd, rel, deps = {}, observe = () => {}) => {
166
211
  const read = deps.readFile ?? readFileSync;
167
212
  let buf;
168
213
  try {
@@ -173,5 +218,6 @@ export const measureFile = (cwd, rel, deps = {}) => {
173
218
  if (decodeStrict(buf) === null) {
174
219
  throw scopeFail(`${rel}: in-scope but not valid UTF-8 — its size cannot be judged; add its prefix to "exclude" in ${configPathFor(cwd)}`);
175
220
  }
221
+ observe(buf);
176
222
  return countBytes(buf);
177
223
  };