@cratis/pi 7.170.3 → 7.170.5

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.
@@ -282,15 +282,46 @@ Rule numbers refer to the numbered list in [`../rules/general.md`](../rules/gene
282
282
  repository's dependency-manifest policy allows them (see below)
283
283
  - `.env`, `.env.*`, `*.env` — secrets
284
284
  - Agent controls: `.claude/settings.json`, `.claude/settings.local.json`, `.mcp.json`,
285
- `.pi/settings.json` and `.pi/extensions/**`
286
- - With `.cratis/ai.manifest.json` present, the installed `.cratis/ai/**`, `.claude/**` and `.pi/**`
287
- trees. Both addressed paths and symlink destinations are checked, including the Claude settings
288
- link to the hook template. The uninstalled Cratis/AI source repository is exempt from this
289
- agent-control category so its authored corpus and harness adapters remain editable.
285
+ `.pi/settings.json`, `.pi/extensions/**`, `.cratis/ai.manifest.json` and `.cratis/ai.json`
286
+ - The installed `.cratis/ai/**` corpus, including when its manifest is missing or unreadable.
287
+ Adapter paths in `.claude/**` and `.pi/**` are protected according to the manifest's
288
+ `Integrations` entries. Both addressed paths and symlink destinations are checked, including
289
+ the Claude settings link to the hook template. Without an installation manifest, authored
290
+ corpus and harness adapters remain editable only when Git `HEAD` records the authoring layout:
291
+ `Cratis.AI.slnx`, the guard source and the `@cratis/pi` package in `Source/Pi.Plugin`. Changing a
292
+ remote URL or adding uncommitted files does not establish this source-repository exception.
293
+ The two policy JSON files remain protected in the source repository.
290
294
 
291
295
  For agent controls, report the intended change rather than rewriting permissions or hooks.
292
296
  A person edits settings; `cratis ai update` replaces managed files using the CLI's filesystem
293
- operations, not agent Write/Edit calls. The shell-write guard scans the **whole command text**
297
+ operations, not agent Write/Edit calls. Before reference classification, the shell guard admits
298
+ only these standalone install/repair operations (Node must be available):
299
+
300
+ - Literal `cratis ai init`, `cratis ai update` or `cratis ai restore`, optionally followed only by
301
+ `--force` or `--dry-run`. Other arguments receive no exception. This invokes the CLI rather than
302
+ granting file-content writes.
303
+ - `ln -s`, `ln -sf` or `ln -sfn` with exactly a target and a link. The link must be below `.pi/`,
304
+ `.claude/`, `.cursor/`, `.opencode/` or `.github/` in the current repository. Resolve the target
305
+ relative to the link's directory: both its lexical path and its physical path (existing ancestors
306
+ resolved, including symlinks) must stay inside that repository's `.cratis/ai/`. The link's parent
307
+ must physically stay in its managed folder. A present `.cratis/ai.manifest.json` must contain an
308
+ exact `Integrations` link entry (`Path` and a string `Target`); missing/invalid entries or invalid
309
+ JSON refuse the repair. A missing manifest also refuses every link repair, even if the corpus
310
+ tree already exists; use the standalone installer commands instead. Both addressed and physical
311
+ link names are checked against the write guard's own `control_patterns`, read without executing
312
+ that guard. Hook, agent, guard, extension and workflow trees cannot be repaired with `ln`, even
313
+ when a manifest lists the link. Recognized repairs that fail validation are blocked outright,
314
+ rather than falling back to an uninstalled repository's more permissive reference policy.
315
+ Only links whose lexical or physical target lands in the corpus enter these repair checks.
316
+ Ordinary non-corpus links and calls outside Git retain the original reference policy; a
317
+ symlinked link parent or target alias cannot disguise a physical corpus target.
318
+ - These exceptions accept simple whole-word quoting, but no `cd` prefix, chaining, pipes,
319
+ redirects, substitutions, expansions, escapes, comments, globs or multiline shell constructs.
320
+ Existing directories cannot be replaced; an existing symlink to a directory requires `-sfn`
321
+ so `ln` cannot follow it and write into its target. File Write/Edit calls, including writes
322
+ through repaired links, remain protected as before.
323
+
324
+ All other commands retain the existing policy. The shell-write guard scans the **whole command text**
294
325
  for protected references, including nested strings, heredoc bodies and option values. It
295
326
  removes simple quoting/escapes, checks case-insensitive spellings, and asks the write guard's
296
327
  `--references` batch mode to classify candidate paths relative to the hook cwd. Original
@@ -0,0 +1,174 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ // Non-applicable commands fall back to reference checks; recognized invalid repairs fail closed.
5
+ import assert from 'node:assert/strict';
6
+ import { execFileSync } from 'node:child_process';
7
+ import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, statSync } from 'node:fs';
8
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
9
+
10
+ const managedFolders = ['.pi', '.claude', '.cursor', '.opencode', '.github'];
11
+
12
+ function literalWords(command) {
13
+ // No shell operators, expansions, escapes, comments, globs or multiline constructs, even in quotes.
14
+ if (/[\x00-\x1f\x7f$`\\;|&<>(){}*?!#~\[\]]/.test(command)) return [];
15
+ // Require whitespace between whole words: do not interpret concatenated quote fragments.
16
+ if (!/^ *(?:(?:'[^']*'|"[^"]*"|[^\s'"]+)(?: +|$))*$/.test(command)) return [];
17
+ return command.match(/'[^']*'|"[^"]*"|[^\s'"]+/g) ?? [];
18
+ }
19
+
20
+ function unquote(word) {
21
+ return /^["']/.test(word) ? word.slice(1, -1) : word;
22
+ }
23
+
24
+ function inside(path, directory) {
25
+ const suffix = relative(directory, path);
26
+ if (isAbsolute(suffix)) return false;
27
+ return !['', '..'].includes(suffix.split(sep)[0]);
28
+ }
29
+
30
+ function addressedTarget(link, target) {
31
+ return isAbsolute(target) ? target : `${dirname(link)}/${target}`;
32
+ }
33
+
34
+ function physicalPath(path, depth = 0) {
35
+ if (depth >= 40) throw new Error('Symlink resolution limit');
36
+ // Follow each symlink before '..', even when its destination does not exist yet.
37
+ let physical = sep;
38
+ for (const component of path.split(sep).filter(Boolean)) {
39
+ const candidate = resolve(physical, component);
40
+ physical = lstatIfPresent(candidate)?.isSymbolicLink()
41
+ ? physicalPath(addressedTarget(candidate, readlinkSync(candidate)), depth + 1)
42
+ : candidate;
43
+ }
44
+ return physical;
45
+ }
46
+
47
+ function lstatIfPresent(path) {
48
+ try { return lstatSync(path); }
49
+ catch (error) {
50
+ if (error.code === 'ENOENT') return undefined;
51
+ throw error;
52
+ }
53
+ }
54
+
55
+ function controlPatterns() {
56
+ // Read the write guard's literal policy, never execute/source it or maintain a second copy.
57
+ const source = readFileSync(new URL('./cratis-guard-writes.sh', import.meta.url), 'utf8');
58
+ const definition = source.match(/^control_patterns=\((.*)\)$/m)?.[1] ?? '';
59
+ const words = definition.match(/'[a-z0-9_./*-]+'/g) ?? [];
60
+ if (!words.length || words.join(' ') !== definition) throw new Error('Unsupported control policy');
61
+ return words.map(unquote);
62
+ }
63
+
64
+ function matchesControl(name, pattern) {
65
+ const expression = pattern.split('*').map(part => part.replaceAll('.', '\\.')).join('.*');
66
+ return new RegExp(`^${expression}(?:/.*)?$`).test(name) || pattern.startsWith(`${name}/`);
67
+ }
68
+
69
+ function controlLink(root, link) {
70
+ const names = [link, physicalPath(link)].map(path => relative(root, path).toLowerCase());
71
+ const patterns = controlPatterns();
72
+ // Repairs are also forbidden in executable/agent-definition trees, even if a manifest lists them.
73
+ const executableTree = /(?:^|\/)(?:hooks|agents|guards|extensions|workflows)(?:\/|$)/;
74
+ return names.some(name => executableTree.test(name) || patterns.some(pattern => matchesControl(name, pattern)));
75
+ }
76
+
77
+ function managedEntry(root, link) {
78
+ const manifest = resolve(root, '.cratis/ai.manifest.json');
79
+ if (!existsSync(manifest)) return false;
80
+ const { Integrations } = JSON.parse(readFileSync(manifest, 'utf8'));
81
+ return Array.isArray(Integrations) && Integrations.some(entry =>
82
+ entry?.Path === relative(root, link) && typeof entry.Target === 'string');
83
+ }
84
+
85
+ function linkOperands(words) {
86
+ if (words.length !== 4) return undefined;
87
+ if (!/^ln -(?:s|sf|sfn)$/.test(words.slice(0, 2).join(' '))) return undefined;
88
+ const [target, name] = words.slice(2).map(unquote);
89
+ if ([target, name].some(operand => !operand || operand.startsWith('-'))) return undefined;
90
+ if (unsafeLinkName(name)) return undefined;
91
+ return { target, name, flag: words[1] };
92
+ }
93
+
94
+ function unsafeLinkName(name) {
95
+ // A trailing slash or '/.' forces directory traversal even with ln -n.
96
+ return name.endsWith('/') || basename(name) === '.' || name.split('/').includes('..');
97
+ }
98
+
99
+ function parentInFolder(root, link, folder) {
100
+ const parent = physicalPath(dirname(link));
101
+ const managedFolder = resolve(realpathSync(root), folder);
102
+ return parent === managedFolder || inside(parent, managedFolder);
103
+ }
104
+
105
+ function atOrInside(path, directory) {
106
+ return path === directory || inside(path, directory);
107
+ }
108
+
109
+ function corpusRepair(root, link, target) {
110
+ const addressed = addressedTarget(link, target);
111
+ const corpus = resolve(root, '.cratis/ai');
112
+ return atOrInside(resolve(addressed), corpus) || atOrInside(physicalPath(addressed), corpus);
113
+ }
114
+
115
+ function corpusTarget(root, link, target) {
116
+ const addressed = addressedTarget(link, target);
117
+ if (!inside(resolve(addressed), resolve(root, '.cratis/ai'))) return false;
118
+ return inside(physicalPath(addressed), resolve(root, '.cratis/ai'));
119
+ }
120
+
121
+ function replaceableDestination(link, flag) {
122
+ const existing = lstatIfPresent(link);
123
+ if (existing?.isDirectory()) return false;
124
+ if (!existing?.isSymbolicLink()) return true;
125
+ if (!existsSync(link)) return true;
126
+ // Without -n, ln follows a destination symlink to a directory and writes inside its target.
127
+ return !statSync(link).isDirectory() || flag === '-sfn';
128
+ }
129
+
130
+ function repositoryRoot(cwd) {
131
+ try {
132
+ const repository = execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
133
+ return realpathSync(repository);
134
+ } catch { return undefined; }
135
+ }
136
+
137
+ function validateRepair(root, link, folder, { target, flag }) {
138
+ try {
139
+ assert(!controlLink(root, link), 'Agent control link');
140
+ assert(managedEntry(root, link), 'Unmanaged link');
141
+ assert(parentInFolder(root, link, folder), 'Redirected link parent');
142
+ assert(corpusTarget(root, link, target), 'Non-corpus target');
143
+ assert(replaceableDestination(link, flag), 'Directory destination');
144
+ } catch {
145
+ // Once identified as a corpus repair, unreadable/invalid policy or paths must not permit fallback.
146
+ assert.fail('Corpus repair validation failed');
147
+ }
148
+ }
149
+
150
+ function repairLink(cwd, words) {
151
+ const operands = linkOperands(words);
152
+ if (!operands) return false;
153
+ const root = repositoryRoot(cwd);
154
+ if (!root) return false;
155
+ // Git reports the physical root on macOS; align the cwd alias without resolving the link itself.
156
+ const link = resolve(realpathSync(cwd), operands.name);
157
+ const folder = managedFolders.find(folder => inside(link, resolve(root, folder)));
158
+ if (!folder) return false;
159
+ if (!corpusRepair(root, link, operands.target)) return false;
160
+ validateRepair(root, link, folder, operands);
161
+ return true;
162
+ }
163
+
164
+ function admitted(cwd, command) {
165
+ const words = literalWords(command);
166
+ if (['cratis ai init', 'cratis ai update', 'cratis ai restore'].includes(words.slice(0, 3).join(' '))) {
167
+ assert(words.slice(3).every(word => ['--force', '--dry-run'].includes(word)), 'Unsupported installer arguments');
168
+ return true;
169
+ }
170
+ return repairLink(cwd, words);
171
+ }
172
+
173
+ try { process.exitCode = admitted(process.argv[2], process.argv[3]) ? 0 : 1; }
174
+ catch (error) { process.exitCode = error instanceof assert.AssertionError ? 2 : 1; }
@@ -33,6 +33,21 @@ cwd="" command_text="" parser_status=""
33
33
  cwd="${cwd:-$PWD}"
34
34
  [ "${#command_text}" -le 131072 ] || parser_failed
35
35
 
36
+ # Only standalone corpus installer/repair invocations may bypass reference classification.
37
+ # The helper accepts a deliberately smaller language than the shell, never shell evaluation.
38
+ if [[ "$command_text" =~ ^[[:space:]]*(cratis|ln)[[:space:]] ]] && command -v node >/dev/null 2>&1; then
39
+ repair_status=0
40
+ node "$script_directory/cratis-guard-shell-writes-repair.mjs" "$cwd" "$command_text" || repair_status=$?
41
+ case "$repair_status" in
42
+ 0) exit 0 ;;
43
+ 1) ;; # Not an installer/repair exception: preserve the ordinary reference policy.
44
+ *)
45
+ printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: managed link repair was refused; use the installer or report the intended change.' >&2
46
+ exit 2
47
+ ;;
48
+ esac
49
+ fi
50
+
36
51
  IFS= read -r -d '' program <<'AWK' || true
37
52
  function candidate(s) {
38
53
  if (checking_marker) return
@@ -187,7 +187,7 @@ origin_matches() {
187
187
  # One policy vocabulary for normal Write/Edit and whole-command reference checks.
188
188
  manifest_patterns=(package.json Directory.Packages.props global.json NuGet.config yarn.lock package-lock.json pnpm-lock.yaml packages.lock.json)
189
189
  environment_patterns=('.env' '.env.*' '*.env')
190
- control_patterns=('.claude/settings.json' '.claude/settings.local.json' '.mcp.json' '.pi/settings.json' '.pi/extensions/*')
190
+ control_patterns=('.claude/settings.json' '.claude/settings.local.json' '.mcp.json' '.pi/settings.json' '.pi/extensions/*' '.cratis/ai.manifest.json' '.cratis/ai.json')
191
191
 
192
192
  # Glob-language intersection, not expansion/eval. A star has an epsilon transition and
193
193
  # a character loop. The product automaton accepts iff the two patterns share a spelling.
@@ -209,16 +209,17 @@ function tokens(s, side, i, c, j, k, t, copy, jumps, first, closing) {
209
209
  if (gsub(/\[/, "[", copy) > 64) exit 2
210
210
  first = index(s, "{")
211
211
  for (k = length(s); k > first; k--) if (substr(s, k, 1) == "}") { closing = k; break }
212
- if (first && closing) {
212
+ if (first && closing && s != "{}") {
213
213
  if (index(substr(s, first, closing - first + 1), "/")) exit 2
214
214
  if (substr(s, first, closing - first + 1) ~ /[$`'"\\]/) exit 2
215
215
  if (substr(s, 1, first - 1) substr(s, closing + 1) ~ /[^a-z0-9._\/*?,+=:@%-]/) exit 2
216
- s = substr(s, 1, first) substr(s, closing)
216
+ s = substr(s, 1, first - 1) "*" substr(s, closing + 1)
217
217
  }
218
218
  }
219
219
  for (i = 1; i <= length(s); i++) {
220
220
  c = substr(s, i, 1); t = c; j = i
221
- if (c == "{") {
221
+ # Only a standalone empty brace argument is literal; path placeholders can expand.
222
+ if (c == "{" && s != "{}") {
222
223
  j = index(substr(s, i), "}")
223
224
  if (j) { j = i + j - 1; t = "*" } else j = i
224
225
  if (side == 1 && index(substr(s, i, j - i + 1), "/")) exit 2
@@ -292,6 +293,8 @@ control_match() {
292
293
  local value="$1" reference_pattern="$reference_pattern" pattern LC_ALL=C
293
294
  shift
294
295
  if names_match "$value" "$@"; then return 0; fi
296
+ # Do not turn a standalone placeholder into a path by appending descendants.
297
+ [ "$value" != '{}' ] || return 1
295
298
  [ "$reference_mode" = 1 ] || return 1
296
299
  if [ "$reference_pattern" = 0 ]; then
297
300
  shopt -s nocasematch
@@ -305,6 +308,23 @@ control_match() {
305
308
  }
306
309
 
307
310
  # ── 4. Agent controls and installed managed trees ─────────────────────────────
311
+ # Authoring requires committed framework source, not a mutable remote URL or new files.
312
+ authored_cache_root=""
313
+ authored_cache_status=1
314
+ authored_corpus_repository() {
315
+ if [ "$authored_cache_root" != "$1" ]; then
316
+ authored_cache_root="$1"
317
+ authored_cache_status=1
318
+ if git -C "$1" cat-file -e HEAD:Cratis.AI.slnx 2>/dev/null &&
319
+ git -C "$1" cat-file -e HEAD:.cratis/ai/hooks/scripts/cratis-guard-writes.sh 2>/dev/null &&
320
+ git -C "$1" show HEAD:Source/Pi.Plugin/package.json 2>/dev/null |
321
+ jq -e -s 'length == 1 and .[0].name == "@cratis/pi" and .[0].type == "module"' >/dev/null 2>&1; then
322
+ authored_cache_status=0
323
+ fi
324
+ fi
325
+ return "$authored_cache_status"
326
+ }
327
+
308
328
  agent_control_target() {
309
329
  local target="$1" directory policy_root target_rel managed pattern
310
330
  dir_of "$target"
@@ -319,9 +339,14 @@ agent_control_target() {
319
339
  policy_root="$directory"
320
340
  relative_to "$target" "$policy_root"
321
341
  target_rel="$REPLY"
322
- if [ -f "$policy_root/.cratis/ai.manifest.json" ]; then
342
+ # Policy files remain controls even in the authored corpus repository.
343
+ if control_match "$target_rel" '.cratis/ai.manifest.json' '.cratis/ai.json'; then return 0; fi
344
+ if [ ! -f "$policy_root/.cratis/ai.manifest.json" ] && authored_corpus_repository "$policy_root"; then
345
+ return 1
346
+ fi
347
+ if [ -f "$policy_root/.cratis/ai.manifest.json" ] || [ -d "$policy_root/.cratis/ai" ]; then
323
348
  if control_match "$target_rel" '.cratis/ai/*'; then return 0; fi
324
- if control_match "$target_rel" '.claude/*' '.pi/*'; then
349
+ if [ -f "$policy_root/.cratis/ai.manifest.json" ] && control_match "$target_rel" '.claude/*' '.pi/*'; then
325
350
  # Integration paths, not corpus Files, establish adapter ownership.
326
351
  managed="$(jq -r '
327
352
  (.Integrations // []) | if type != "array" then empty else
@@ -335,12 +360,6 @@ agent_control_target() {
335
360
  if control_match "$target_rel" "$pattern"; then return 0; fi
336
361
  done <<<"$managed"
337
362
  fi
338
- else
339
- # The corpus is authored source in Cratis/AI, not a managed installation.
340
- repository_origin "$policy_root"
341
- if origin_matches '^(https://github\.com/|git@github\.com:|ssh://git@github\.com(:[0-9]+)?/)cratis/ai(\.git)?/?$'; then
342
- return 1
343
- fi
344
363
  fi
345
364
  control_match "$target_rel" "${control_patterns[@]}"
346
365
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.170.3",
3
+ "version": "7.170.5",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [