@llman-sdd/core 0.10.0 → 0.10.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llman-sdd/core",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
4
4
  "description": "Pure domain logic for llman-sdd (config, gherkin specs, validation, templates)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,6 +29,7 @@
29
29
  "@cucumber/messages": "^34.2.1",
30
30
  "@statelyai/graph": "^2.6.0",
31
31
  "@toon-format/toon": "^4.1.1",
32
+ "ignore": "^7.0.12",
32
33
  "nunjucks": "^3.2.4",
33
34
  "xstate": "^5.33.2",
34
35
  "yaml": "^2.9.1",
@@ -19,6 +19,7 @@ import {
19
19
  frozenCardName,
20
20
  isFrozenCard,
21
21
  } from './frozenCard.ts';
22
+ import { collectFilteredEntries } from './ignoreChain.ts';
22
23
  import type { SevenZipPort } from './sevenzip.ts';
23
24
 
24
25
  export const FREEZE_ARCHIVE_NAME = 'freezed_changes.7z.archived';
@@ -65,6 +66,9 @@ export interface FreezeOpts {
65
66
  before?: string;
66
67
  keepRecent?: number;
67
68
  dryRun?: boolean;
69
+ /** r120: absolute paths of extra gitignore-format files (highest
70
+ * precedence in the layered evaluation; nonexistent file is an error). */
71
+ ignoreFiles?: string[];
68
72
  }
69
73
 
70
74
  export interface FreezeRunResult {
@@ -96,6 +100,24 @@ export async function runFreeze(
96
100
  // Card = authoritative record that bodies are in the cold backup. Write
97
101
  // cards first; on `7z add` failure roll them back and keep the original dirs.
98
102
  const archiveAbs = join(rootAbs, ARCHIVE_DIR_REL, FREEZE_ARCHIVE_NAME);
103
+ const archiveBase = join(rootAbs, ARCHIVE_DIR_REL);
104
+
105
+ // r120: layered gitignore filtering runs before any mutation — user-file
106
+ // existence errors and the zero-files guard must leave the tree untouched.
107
+ const packed: string[] = [];
108
+ let excludedTotal = 0;
109
+ for (const c of candidates) {
110
+ const { files, excluded } = collectFilteredEntries(io, {
111
+ rootAbs,
112
+ candidateAbs: join(archiveBase, c),
113
+ userIgnoreFiles: opts.ignoreFiles ?? [],
114
+ });
115
+ if (files.length === 0) {
116
+ throw new Error(`candidate has no packable files after ignore filtering: ${c}`);
117
+ }
118
+ excludedTotal += excluded;
119
+ packed.push(...files.map((f) => `${c}/${f}`));
120
+ }
99
121
 
100
122
  const cards: Array<{ datedId: string; source: string }> = [];
101
123
  for (const c of candidates) {
@@ -116,7 +138,7 @@ export async function runFreeze(
116
138
  io.writeText(`${ARCHIVE_DIR_REL}/${frozenCardName(card.datedId)}`, card.source);
117
139
  }
118
140
  try {
119
- await sz.add(archiveAbs, join(rootAbs, ARCHIVE_DIR_REL), candidates);
141
+ await sz.add(archiveAbs, archiveBase, packed);
120
142
  } catch (error) {
121
143
  for (const card of cards) io.remove(`${ARCHIVE_DIR_REL}/${frozenCardName(card.datedId)}`);
122
144
  throw error;
@@ -124,12 +146,13 @@ export async function runFreeze(
124
146
  for (const c of candidates) {
125
147
  io.removeDir(`${ARCHIVE_DIR_REL}/${c}`);
126
148
  }
127
- return {
128
- candidates,
129
- lines: [
130
- `Froze ${candidates.length} archived changes into ./${ARCHIVE_DIR_REL}/${FREEZE_ARCHIVE_NAME}`,
131
- ],
132
- };
149
+ const lines = [
150
+ `Froze ${candidates.length} archived changes into ./${ARCHIVE_DIR_REL}/${FREEZE_ARCHIVE_NAME}`,
151
+ ];
152
+ if (excludedTotal > 0) {
153
+ lines.push(`Excluded ${excludedTotal} ignored file(s) via gitignore chain`);
154
+ }
155
+ return { candidates, lines };
133
156
  }
134
157
 
135
158
  /**
@@ -0,0 +1,167 @@
1
+ /**
2
+ * r120 freeze content filter: git-style layered .gitignore evaluation for
3
+ * `archive freeze` (review-freeze capability). For each candidate directory
4
+ * the packer walks the tree and keeps only files no ignore layer decides
5
+ * against: user-supplied `--ignore-file` layers first (highest precedence),
6
+ * then `.gitignore` files found while descending (deeper wins), then the
7
+ * ancestor chain from the candidate dir up to the discovered project root
8
+ * (nearest ancestor holding `.git`; the instance root when absent).
9
+ *
10
+ * Purity: filesystem access flows through the injected IgnoreChainIo; the
11
+ * `ignore` package is a pure pattern engine. All paths are absolute here;
12
+ * POSIX relativization happens per layer (anchoring base = the layer's own
13
+ * directory, exactly like git).
14
+ */
15
+ import { dirname, join, relative, sep } from 'node:path';
16
+
17
+ import * as ignoreModule from 'ignore';
18
+
19
+ import type { FsPort } from '../util/fsPort.ts';
20
+
21
+ type Ignore = ignoreModule.Ignore;
22
+
23
+ /**
24
+ * CJS `export =` interop: both Bun and Node surface the factory on
25
+ * `.default` while the ESM namespace itself is not callable — and under
26
+ * verbatimModuleSyntax tsc types the namespace import as a pure namespace,
27
+ * so the callable is recovered through a structural cast against the
28
+ * package's own `Ignore` interface.
29
+ */
30
+ const createIgnore = (ignoreModule as unknown as { default: () => Ignore }).default;
31
+
32
+ export type IgnoreChainIo = Pick<FsPort, 'exists' | 'listDir' | 'readText' | 'isDirectory'>;
33
+
34
+ export class IgnoreChainError extends Error {}
35
+
36
+ /** One `.gitignore`-style rule set; `base` is the anchoring directory. */
37
+ interface Layer {
38
+ base: string;
39
+ ig: Ignore;
40
+ }
41
+
42
+ export interface FilteredCandidate {
43
+ /** POSIX file paths relative to the candidate dir (7z entry base). */
44
+ files: string[];
45
+ /** Files excluded by ignore rules (pruned directories count recursively). */
46
+ excluded: number;
47
+ }
48
+
49
+ function toPosix(p: string): string {
50
+ return sep === '/' ? p : p.split(sep).join('/');
51
+ }
52
+
53
+ function relPosix(from: string, to: string): string {
54
+ return toPosix(relative(from, to));
55
+ }
56
+
57
+ /**
58
+ * Outermost ignore root: the nearest ancestor of `start` (inclusive) holding
59
+ * `.git` (a directory, or the file git uses for worktrees); when the tree is
60
+ * not inside a git repository the instance root `start` itself is the
61
+ * outermost layer (r120 fallback semantics).
62
+ */
63
+ export function discoverIgnoreRoot(io: IgnoreChainIo, start: string): string {
64
+ let cur = start;
65
+ for (;;) {
66
+ if (io.exists(join(cur, '.git'))) return cur;
67
+ const parent = dirname(cur);
68
+ if (parent === cur) return start;
69
+ cur = parent;
70
+ }
71
+ }
72
+
73
+ function loadLayer(io: IgnoreChainIo, base: string): Layer | null {
74
+ const path = join(base, '.gitignore');
75
+ if (!io.exists(path)) return null;
76
+ return { base, ig: createIgnore().add(io.readText(path)) };
77
+ }
78
+
79
+ /** First decisive layer wins: user files → deepest walk layer → ancestors. */
80
+ function decide(
81
+ user: readonly Layer[],
82
+ walk: readonly Layer[],
83
+ ancestors: readonly Layer[],
84
+ pathAbs: string,
85
+ isDir: boolean,
86
+ ): boolean {
87
+ const layers: Layer[] = [...user];
88
+ for (let i = walk.length - 1; i >= 0; i--) layers.push(walk[i]!);
89
+ layers.push(...ancestors);
90
+ for (const layer of layers) {
91
+ let rel = relPosix(layer.base, pathAbs);
92
+ // A .gitignore governs only its own subtree (git semantics); layers the
93
+ // path lies outside of cannot decide and must not be consulted.
94
+ if (rel === '' || rel === '..' || rel.startsWith('../')) continue;
95
+ if (isDir) rel = `${rel}/`;
96
+ const verdict = layer.ig.test(rel);
97
+ if (verdict.ignored || verdict.unignored) return verdict.ignored;
98
+ }
99
+ return false;
100
+ }
101
+
102
+ function countFiles(io: IgnoreChainIo, dirAbs: string): number {
103
+ let n = 0;
104
+ for (const name of io.listDir(dirAbs)) {
105
+ if (name === '.git') continue;
106
+ const abs = join(dirAbs, name);
107
+ n += io.isDirectory(abs) ? countFiles(io, abs) : 1;
108
+ }
109
+ return n;
110
+ }
111
+
112
+ export interface CollectFilteredOpts {
113
+ /** Instance root (absolute) — ignore-root discovery starts here. */
114
+ rootAbs: string;
115
+ /** Candidate change directory (absolute, under the instance root). */
116
+ candidateAbs: string;
117
+ /** Absolute paths of extra gitignore-format files (highest precedence,
118
+ * anchored at the candidate dir — extras describe per-change junk). */
119
+ userIgnoreFiles: string[];
120
+ }
121
+
122
+ export function collectFilteredEntries(
123
+ io: IgnoreChainIo,
124
+ opts: CollectFilteredOpts,
125
+ ): FilteredCandidate {
126
+ const user: Layer[] = [];
127
+ for (const file of opts.userIgnoreFiles) {
128
+ if (!io.exists(file)) {
129
+ throw new IgnoreChainError(`ignore file not found: ${file}`);
130
+ }
131
+ user.push({ base: opts.candidateAbs, ig: createIgnore().add(io.readText(file)) });
132
+ }
133
+
134
+ // Ancestor chain: candidate dir first (highest of the fixed layers), then
135
+ // each parent up to the discovered ignore root (outermost, last).
136
+ const outer = discoverIgnoreRoot(io, opts.rootAbs);
137
+ const ancestors: Layer[] = [];
138
+ for (let cur = opts.candidateAbs; ; cur = dirname(cur)) {
139
+ const layer = loadLayer(io, cur);
140
+ if (layer) ancestors.push(layer);
141
+ if (cur === outer) break;
142
+ const parent = dirname(cur);
143
+ if (parent === cur) break; // defensive: ignore root not an ancestor
144
+ }
145
+
146
+ const walk: Layer[] = [];
147
+ const files: string[] = [];
148
+ let excluded = 0;
149
+ const visit = (dirAbs: string): void => {
150
+ const layer = loadLayer(io, dirAbs);
151
+ if (layer) walk.push(layer);
152
+ for (const name of io.listDir(dirAbs).toSorted()) {
153
+ if (name === '.git') continue; // git never packs .git metadata (r120)
154
+ const abs = join(dirAbs, name);
155
+ const isDir = io.isDirectory(abs);
156
+ if (decide(user, walk, ancestors, abs, isDir)) {
157
+ excluded += isDir ? countFiles(io, abs) : 1;
158
+ continue;
159
+ }
160
+ if (isDir) visit(abs);
161
+ else files.push(relPosix(opts.candidateAbs, abs));
162
+ }
163
+ if (layer) walk.pop();
164
+ };
165
+ visit(opts.candidateAbs);
166
+ return { files, excluded };
167
+ }
@@ -82,10 +82,15 @@ function mount(mod: EmscriptenModule, seq: number, hostDir: string): string {
82
82
  return mountpoint;
83
83
  }
84
84
 
85
- /** 7z `l` listing: header/footer dashed rules around fixed-ish columns; our
86
- * entry names are space-free, so the name is column 6+. */
85
+ /** 7z `l` listing: header/footer dashed rules around fixed-ish columns.
86
+ * Column offsets come from the header row, NOT whitespace splitting — solid
87
+ * blocks leave the Compressed cell empty for every file after the block
88
+ * head, which collapses the column count and silently dropped those rows
89
+ * (surfaced by r120's explicit file lists; our entry names are space-free). */
87
90
  function parseListNames(lines: string[]): string[] {
88
91
  const names: string[] = [];
92
+ let nameCol = -1;
93
+ let attrCol = -1;
89
94
  let inTable = false;
90
95
  let rulesSeen = 0;
91
96
  for (const line of lines) {
@@ -95,14 +100,18 @@ function parseListNames(lines: string[]): string[] {
95
100
  if (rulesSeen === 3) break;
96
101
  continue;
97
102
  }
98
- if (inTable) {
99
- const parts = line.trim().split(/\s+/u);
100
- if (parts.length >= 6) {
101
- const attr = parts[2] ?? '';
102
- const name = parts.slice(5).join(' ');
103
- if (name !== '' && !attr.includes('D')) names.push(name);
103
+ if (!inTable) {
104
+ if (/\bDate\s+Time\s+Attr\b/u.test(line)) {
105
+ nameCol = line.lastIndexOf('Name');
106
+ attrCol = line.lastIndexOf('Attr');
104
107
  }
108
+ continue;
105
109
  }
110
+ if (nameCol < 0 || attrCol < 0 || line.trim() === '') continue;
111
+ // Attr cells are fixed-width 5 chars (e.g. `....A`, `D....`).
112
+ const attr = line.slice(attrCol, attrCol + 5);
113
+ const name = line.slice(nameCol).trim();
114
+ if (name !== '' && !attr.includes('D')) names.push(name);
106
115
  }
107
116
  return names;
108
117
  }
package/src/index.ts CHANGED
@@ -288,6 +288,14 @@ export {
288
288
  frozenCardName,
289
289
  isFrozenCard,
290
290
  } from './archive/frozenCard.ts';
291
+ export {
292
+ IgnoreChainError,
293
+ collectFilteredEntries,
294
+ discoverIgnoreRoot,
295
+ type CollectFilteredOpts,
296
+ type FilteredCandidate,
297
+ type IgnoreChainIo,
298
+ } from './archive/ignoreChain.ts';
291
299
  export {
292
300
  buildReview,
293
301
  renderReviewHtml,