@commonlyai/cli 0.1.201 → 0.1.202

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.201",
3
+ "version": "0.1.202",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -2,14 +2,20 @@ import { Buffer } from 'node:buffer';
2
2
  import { createHash } from 'node:crypto';
3
3
  import {
4
4
  accessSync,
5
+ closeSync,
5
6
  constants,
7
+ fstatSync,
8
+ lstatSync,
6
9
  mkdtempSync,
10
+ openSync,
11
+ readFileSync,
12
+ readlinkSync,
7
13
  rmSync,
8
14
  statSync,
9
15
  writeFileSync,
10
16
  } from 'node:fs';
11
17
  import { tmpdir } from 'node:os';
12
- import { join, resolve } from 'node:path';
18
+ import { dirname, join, resolve } from 'node:path';
13
19
  import { spawnSync } from 'node:child_process';
14
20
 
15
21
  const GIT_HOOKS = [
@@ -77,6 +83,145 @@ const seatAddressId = (agentName, instanceId) => {
77
83
  // resolves the original hooks itself at commit time.
78
84
  const GIT_PROBE_TIMEOUT_MS = 5000;
79
85
 
86
+ const directoryOrNull = (path) => {
87
+ try {
88
+ return statSync(path).isDirectory() ? path : null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ };
93
+
94
+ // A regular file's text, or null. The open does not block, so a FIFO or a
95
+ // device where git keeps a file is refused instead of hanging the caller.
96
+ const readRegularFile = (path) => {
97
+ let fd = null;
98
+ try {
99
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
100
+ return fstatSync(fd).isFile() ? readFileSync(fd, 'utf8') : null;
101
+ } catch {
102
+ return null;
103
+ } finally {
104
+ if (fd !== null) closeSync(fd);
105
+ }
106
+ };
107
+
108
+ // One git config value: quotes group, a backslash escapes the next character,
109
+ // and an unquoted # or ; starts a comment. Whitespace around the value is
110
+ // dropped unless it is quoted.
111
+ const configValue = (raw) => {
112
+ let value = '';
113
+ let kept = 0;
114
+ let quoted = false;
115
+ for (let index = 0; index < raw.length; index += 1) {
116
+ const character = raw[index];
117
+ if (character === '\\' && index + 1 < raw.length) {
118
+ index += 1;
119
+ value += raw[index];
120
+ kept = value.length;
121
+ } else if (character === '"') {
122
+ quoted = !quoted;
123
+ } else if (!quoted && (character === '#' || character === ';')) {
124
+ break;
125
+ } else if (quoted || value || !/\s/.test(character)) {
126
+ value += character;
127
+ if (quoted) kept = value.length;
128
+ }
129
+ }
130
+ return value.slice(0, kept) + value.slice(kept).trimEnd();
131
+ };
132
+
133
+ // The last core.hooksPath in one config file, or null. `include` and
134
+ // conditional includes are not followed.
135
+ const configuredHooksPath = (configPath) => {
136
+ const text = readRegularFile(configPath);
137
+ if (text === null) return null;
138
+ let inCore = false;
139
+ let hooksPath = null;
140
+ for (const rawLine of text.split(/\r?\n/)) {
141
+ let line = rawLine.trim();
142
+ const section = /^\[\s*([A-Za-z0-9.-]+)\s*("[^"]*")?\s*\]/.exec(line);
143
+ if (section) {
144
+ inCore = section[1].toLowerCase() === 'core' && !section[2];
145
+ line = line.slice(section[0].length).trim();
146
+ }
147
+ const entry = inCore && /^hookspath\s*=(.*)$/i.exec(line);
148
+ if (entry) hooksPath = configValue(entry[1]);
149
+ }
150
+ return hooksPath || null;
151
+ };
152
+
153
+ // Git opens a git directory only if its HEAD names a ref or an object id and
154
+ // its common directory holds objects/ and refs/.
155
+ const isGitDirectory = (gitDir, commonDir) => {
156
+ if (!directoryOrNull(join(commonDir, 'objects')) || !directoryOrNull(join(commonDir, 'refs'))) {
157
+ return false;
158
+ }
159
+ const head = join(gitDir, 'HEAD');
160
+ try {
161
+ if (lstatSync(head).isSymbolicLink()) return readlinkSync(head).startsWith('refs/');
162
+ const line = (readRegularFile(head) ?? '').split('\n')[0];
163
+ return /^ref:\s*refs\//.test(line) || /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(line);
164
+ } catch {
165
+ return false;
166
+ }
167
+ };
168
+
169
+ // Git refuses a repository whose files another user owns, unless global
170
+ // safe.directory config allows it. That config is not read here, so such a
171
+ // repository yields no hooks, which is git's own answer without it.
172
+ const ownedByThisUser = (path) => {
173
+ if (typeof process.geteuid !== 'function') return false;
174
+ try {
175
+ return lstatSync(path).uid === process.geteuid();
176
+ } catch {
177
+ return false;
178
+ }
179
+ };
180
+
181
+ // The hooks directory a commit in `cwd` would use, read from the repository's
182
+ // own files without running git: core.hooksPath from the repository config,
183
+ // else the hooks folder of the common git directory (a linked worktree shares
184
+ // its main repository's). Global config and includes are not read. `~` expands
185
+ // against the HOME the probe gave git, as git itself would. The nearest .git
186
+ // must be a repository this user owns, or there are no hooks. Git would walk
187
+ // on past a .git directory that is not a repository, and this stops there.
188
+ const hooksPathFromGitFiles = (cwd, env) => {
189
+ let top = resolve(cwd);
190
+ let entry = join(top, '.git');
191
+ let entryStat = null;
192
+ for (;;) {
193
+ try {
194
+ entryStat = statSync(entry);
195
+ break;
196
+ } catch {
197
+ if (dirname(top) === top) return null;
198
+ top = dirname(top);
199
+ entry = join(top, '.git');
200
+ }
201
+ }
202
+ // Ownership is settled before any of the repository's files is read.
203
+ if (!ownedByThisUser(top) || !ownedByThisUser(entry)) return null;
204
+ let gitDir = entry;
205
+ if (entryStat.isFile()) {
206
+ const pointer = /^gitdir:\s*(.+?)\s*$/m.exec(readRegularFile(entry) ?? '');
207
+ if (!pointer) return null;
208
+ gitDir = resolve(top, pointer[1]);
209
+ if (!ownedByThisUser(gitDir)) return null;
210
+ }
211
+ // A main repository has no commondir file.
212
+ const commonDirFile = readRegularFile(join(gitDir, 'commondir'));
213
+ const commonDir = commonDirFile === null ? gitDir : resolve(gitDir, commonDirFile.trim());
214
+ if (!isGitDirectory(gitDir, commonDir)) return null;
215
+ const configured = configuredHooksPath(join(commonDir, 'config'));
216
+ if (!configured) return directoryOrNull(join(commonDir, 'hooks'));
217
+ if (configured === '~' || configured.startsWith('~/')) {
218
+ return env.HOME ? directoryOrNull(join(env.HOME, configured.slice(1))) : null;
219
+ }
220
+ // Git runs hooks from the top of the working tree, so a relative path
221
+ // resolves there.
222
+ return directoryOrNull(resolve(top, configured));
223
+ };
224
+
80
225
  const resolveOriginalHooksPath = (cwd, env) => {
81
226
  const result = spawnSync(
82
227
  'git',
@@ -90,13 +235,31 @@ const resolveOriginalHooksPath = (cwd, env) => {
90
235
  killSignal: 'SIGKILL',
91
236
  },
92
237
  );
93
- if (result.error || result.status !== 0 || !result.stdout?.trim()) return null;
94
- const hooksPath = resolve(result.stdout.trim());
95
- try {
96
- return statSync(hooksPath).isDirectory() ? hooksPath : null;
97
- } catch {
238
+ if (result.error?.code === 'ETIMEDOUT') {
239
+ // The open() that stalled git would stall this process too, and a
240
+ // synchronous read cannot be timed out, so nothing is read here. A git
241
+ // that cannot open the repository cannot commit in it either.
242
+ // eslint-disable-next-line no-console
243
+ console.warn(`[commit-attribution] git did not answer in ${GIT_PROBE_TIMEOUT_MS / 1000}s in ${cwd}, `
244
+ + 'so a confined seat is not granted this repository\'s hooks this turn');
98
245
  return null;
99
246
  }
247
+ if (result.error || result.status !== 0 || !result.stdout?.trim()) {
248
+ // A confined seat can only run the hooks it is granted. A hook it is not
249
+ // granted is skipped without a word, or refuses the commit where the jail
250
+ // can see the file but not run it. So read the hooks directory from the
251
+ // repository's files instead.
252
+ const fallback = hooksPathFromGitFiles(cwd, env);
253
+ if (fallback) {
254
+ const reason = result.error?.code || `exit ${result.status}`;
255
+ // eslint-disable-next-line no-console
256
+ console.warn(`[commit-attribution] git could not report the hooks directory (${reason}), `
257
+ + `so ${fallback} was read from the repository's files`);
258
+ }
259
+ return fallback;
260
+ }
261
+ // Only git's newline ends the line, since a path can end in a space.
262
+ return directoryOrNull(resolve(result.stdout.replace(/\r?\n$/, '')));
100
263
  };
101
264
 
102
265
  const resolveGitConfigCount = (env) => {
@@ -192,8 +355,8 @@ export const prepareCommitAttribution = ({
192
355
  COMMONLY_AGENT_GIT_CONFIG_BASE_COUNT: String(configIndex),
193
356
  COMMONLY_AGENT_HOOKS_PATH: hooksDirectory,
194
357
  // The sandbox adapters allow the workspace's existing hook files. The
195
- // proxy resolves the target repo's path at hook time; a confined seat may
196
- // fail closed if that repo's hook lies outside the workspace allowlist.
358
+ // proxy resolves the target repo's path at hook time, and a confined seat
359
+ // cannot run a hook outside what it was granted.
197
360
  ...(originalHooksPath ? { COMMONLY_AGENT_ORIGINAL_HOOKS_PATH: originalHooksPath } : {}),
198
361
  COMMONLY_AGENT_SEAT_NAME: cleanSingleLine(displayName || agentName, 'agent'),
199
362
  COMMONLY_AGENT_SEAT_ID: seatAddressId(agentName, instanceId),