pi-stacked-context 0.0.0 → 1.0.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.
@@ -0,0 +1,190 @@
1
+ import path from "node:path";
2
+ import {
3
+ SettingsSecurityError,
4
+ createJsonFileStorageAdapter,
5
+ defineSettings,
6
+ resolveDefaultAgentDir,
7
+ resolveScopeFilePath,
8
+ } from "pi-extension-settings-tui";
9
+ import { createDiagnostic } from "../shared/diagnostics.js";
10
+ import type { Diagnostic, LoadedConfiguration } from "../shared/types.js";
11
+ import { createDefaultConfig } from "./defaults.js";
12
+ import type { ConfigurationLayer, ConfigurationSources } from "./schema.js";
13
+ import { mergeConfigurationLayers, parseConfigurationLayer } from "./schema.js";
14
+
15
+ export type SettingsScope = "global" | "project";
16
+
17
+ export interface SettingsLayerSnapshot {
18
+ readonly path: string;
19
+ readonly data: Record<string, unknown> | null;
20
+ readonly diagnostics: Diagnostic[];
21
+ }
22
+
23
+ /**
24
+ * Narrow port over the settings library. Layers are read on demand so the
25
+ * caller decides whether a project layer may be touched at all.
26
+ */
27
+ export interface SettingsPort {
28
+ readLayer(scope: SettingsScope): Promise<SettingsLayerSnapshot>;
29
+ }
30
+
31
+ export interface SettingsPortOptions {
32
+ readonly cwd: string;
33
+ readonly agentDir?: string;
34
+ }
35
+
36
+ export interface ConfigurationContext {
37
+ readonly cwd: string;
38
+ isProjectTrusted(): boolean;
39
+ }
40
+
41
+ /**
42
+ * Storage-only schema. It declares the spec paths and the two layers; the
43
+ * settings dialog adds its field map in a later milestone, and persistence
44
+ * stays owned by the library's hardened, atomic JSON store.
45
+ */
46
+ const settingsStorageSchema = defineSettings({
47
+ id: "stacked-context",
48
+ title: "Stacked Context",
49
+ description: "Layered configuration for the pi-stacked-context extension.",
50
+ settingsFile: "stacked-context/settings.json",
51
+ scopes: ["global", "project"],
52
+ fields: {},
53
+ });
54
+
55
+ export function createSettingsPort(options: SettingsPortOptions): SettingsPort {
56
+ const agentDir = path.resolve(options.agentDir ?? resolveDefaultAgentDir());
57
+ const cwd = path.resolve(options.cwd);
58
+ const adapter = createJsonFileStorageAdapter(settingsStorageSchema, { agentDir, cwd });
59
+
60
+ return {
61
+ async readLayer(scope) {
62
+ const settingsPath = resolveScopeFilePath(settingsStorageSchema, scope, { agentDir, cwd });
63
+ try {
64
+ const result = await adapter.readLayer(scope);
65
+ return { path: settingsPath, data: result.data, diagnostics: [] };
66
+ } catch (error) {
67
+ return {
68
+ path: settingsPath,
69
+ data: null,
70
+ diagnostics: [describeSettingsError(error, scope, settingsPath)],
71
+ };
72
+ }
73
+ },
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Builds the effective configuration from defaults, global settings, and the
79
+ * project settings of a trusted project. The project layer is never read for
80
+ * an untrusted project.
81
+ */
82
+ export async function loadConfiguration(
83
+ ctx: ConfigurationContext,
84
+ cwd: string,
85
+ port?: SettingsPort,
86
+ ): Promise<LoadedConfiguration> {
87
+ const resolvedCwd = path.resolve(cwd);
88
+ const trusted = ctx.isProjectTrusted();
89
+ const settingsPort = port ?? createSettingsPort({ cwd: resolvedCwd });
90
+ const diagnostics: Diagnostic[] = [];
91
+
92
+ const globalSnapshot = await readLayerSafely(settingsPort, "global");
93
+ diagnostics.push(...globalSnapshot.diagnostics);
94
+ const globalLayer = parseConfigurationLayer(globalSnapshot.data, "global", globalSnapshot.path);
95
+ diagnostics.push(...globalLayer.diagnostics);
96
+
97
+ let projectLayer: ConfigurationLayer = {};
98
+ let projectSettingsPath: string | undefined;
99
+ if (trusted) {
100
+ const projectSnapshot = await readLayerSafely(settingsPort, "project");
101
+ projectSettingsPath = projectSnapshot.path;
102
+ diagnostics.push(...projectSnapshot.diagnostics);
103
+ const parsedProject = parseConfigurationLayer(
104
+ projectSnapshot.data,
105
+ "project",
106
+ projectSnapshot.path,
107
+ );
108
+ diagnostics.push(...parsedProject.diagnostics);
109
+ projectLayer = parsedProject.layer;
110
+ } else {
111
+ diagnostics.push(
112
+ createDiagnostic(
113
+ "info",
114
+ "project-settings-untrusted",
115
+ "Project settings were not read because the project is not trusted.",
116
+ ),
117
+ );
118
+ }
119
+
120
+ const sources: ConfigurationSources = {
121
+ global: globalSnapshot.path,
122
+ ...(projectSettingsPath === undefined ? {} : { project: projectSettingsPath }),
123
+ };
124
+ const merged = mergeConfigurationLayers(
125
+ createDefaultConfig(),
126
+ globalLayer.layer,
127
+ projectLayer,
128
+ trusted,
129
+ sources,
130
+ );
131
+
132
+ return {
133
+ config: merged.config,
134
+ diagnostics: [...diagnostics, ...merged.diagnostics],
135
+ provenance: merged.provenance,
136
+ };
137
+ }
138
+
139
+ async function readLayerSafely(
140
+ port: SettingsPort,
141
+ scope: SettingsScope,
142
+ ): Promise<SettingsLayerSnapshot> {
143
+ try {
144
+ return await port.readLayer(scope);
145
+ } catch (error) {
146
+ const message = error instanceof Error ? error.message : "unknown error";
147
+ return {
148
+ path: `${scope} settings`,
149
+ data: null,
150
+ diagnostics: [
151
+ createDiagnostic(
152
+ "error",
153
+ "settings-unreadable",
154
+ `The ${scope} settings layer could not be read: ${message}`,
155
+ { sourcePath: `${scope} settings` },
156
+ ),
157
+ ],
158
+ };
159
+ }
160
+ }
161
+
162
+ function describeSettingsError(
163
+ error: unknown,
164
+ scope: SettingsScope,
165
+ settingsPath: string,
166
+ ): Diagnostic {
167
+ if (error instanceof SettingsSecurityError) {
168
+ return createDiagnostic(
169
+ "error",
170
+ "settings-rejected",
171
+ `${scope} settings at ${settingsPath} were rejected by the settings security policy: ${error.message}`,
172
+ { sourcePath: settingsPath },
173
+ );
174
+ }
175
+ if (error instanceof SyntaxError) {
176
+ return createDiagnostic(
177
+ "error",
178
+ "settings-malformed-json",
179
+ `${scope} settings at ${settingsPath} are not valid JSON; inherited values are used.`,
180
+ { sourcePath: settingsPath },
181
+ );
182
+ }
183
+ const message = error instanceof Error ? error.message : "unknown error";
184
+ return createDiagnostic(
185
+ "error",
186
+ "settings-unreadable",
187
+ `${scope} settings at ${settingsPath} could not be read: ${message}`,
188
+ { sourcePath: settingsPath },
189
+ );
190
+ }
@@ -0,0 +1,173 @@
1
+ import type { Dirent } from "node:fs";
2
+ import { readdir as nodeReaddir } from "node:fs";
3
+ import path from "node:path";
4
+ import { glob } from "tinyglobby";
5
+ import { BUILT_IN_IGNORE_PATHS } from "../config/defaults.js";
6
+ import { nativeErrorCode } from "../shared/diagnostics.js";
7
+ import {
8
+ appendSkillsSuffix,
9
+ comparePaths,
10
+ expandPathValue,
11
+ workspaceRelativePatternProblem,
12
+ } from "./paths.js";
13
+
14
+ export interface GlobalAdapterCandidate {
15
+ candidatePath: string | null;
16
+ missingVariable: string | null;
17
+ }
18
+
19
+ /**
20
+ * Read-one-directory port shaped like the `fdir` crawl call. The default is
21
+ * `node:fs`; tests override it to record or simulate crawl failures.
22
+ */
23
+ export type ReadDirectory = (
24
+ directory: string,
25
+ options: { withFileTypes: true },
26
+ callback: (error: NodeJS.ErrnoException | null, entries: Dirent[]) => void,
27
+ ) => void;
28
+
29
+ /** A directory the project crawl could not read, with its native error code. */
30
+ export interface UnreadableDirectory {
31
+ readonly directory: string;
32
+ readonly code: string | null;
33
+ }
34
+
35
+ /** A glob evaluation failure, as opposed to an unsafe configured pattern. */
36
+ export interface GlobFailure {
37
+ readonly message: string;
38
+ readonly code: string | null;
39
+ }
40
+
41
+ export interface ProjectAdapterMatchInput {
42
+ readonly pattern: string;
43
+ readonly workspaceRoot: string;
44
+ readonly ignorePatterns: readonly string[];
45
+ readonly readdir?: ReadDirectory | undefined;
46
+ }
47
+
48
+ export interface ProjectAdapterMatch {
49
+ readonly candidates: readonly string[];
50
+ readonly unsafePattern: string | null;
51
+ readonly failure: GlobFailure | null;
52
+ readonly unreadableDirectories: readonly UnreadableDirectory[];
53
+ }
54
+
55
+ /**
56
+ * Resolves a user-level adapter directory. User-level candidates are explicit
57
+ * allowlisted roots, so they may resolve through symlinks; the `skills`
58
+ * suffix is still appended with native path operations.
59
+ */
60
+ export function resolveGlobalAdapterCandidate(
61
+ value: string,
62
+ environment: NodeJS.ProcessEnv,
63
+ home: string,
64
+ ): GlobalAdapterCandidate {
65
+ const expanded = expandPathValue(value, environment, home);
66
+ if (expanded.missingVariable !== undefined) {
67
+ return { candidatePath: null, missingVariable: expanded.missingVariable };
68
+ }
69
+ return {
70
+ candidatePath: appendSkillsSuffix(path.resolve(expanded.path)),
71
+ missingVariable: null,
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Builds the glob ignore list: built-in directory names at any depth plus the
77
+ * additional workspace-relative directory patterns. Additional settings can
78
+ * only add ignores, never remove the built-in safety entries.
79
+ */
80
+ export function buildIgnorePatterns(additionalIgnorePaths: readonly string[]): string[] {
81
+ const patterns: string[] = [];
82
+ for (const name of BUILT_IN_IGNORE_PATHS) {
83
+ patterns.push(`**/${name}`, `**/${name}/**`);
84
+ }
85
+ for (const additionalPath of additionalIgnorePaths) {
86
+ if (workspaceRelativePatternProblem(additionalPath) !== null) {
87
+ continue;
88
+ }
89
+ patterns.push(additionalPath, `${additionalPath}/**`);
90
+ }
91
+ return patterns;
92
+ }
93
+
94
+ /** Describes the applied ignore policy without printing environment values. */
95
+ export function describeIgnorePolicy(additionalIgnorePaths: readonly string[]): string {
96
+ const configured = additionalIgnorePaths.filter(
97
+ (additionalPath) => workspaceRelativePatternProblem(additionalPath) === null,
98
+ );
99
+ return [...BUILT_IN_IGNORE_PATHS, ...configured].join(", ");
100
+ }
101
+
102
+ /**
103
+ * Matches one project adapter pattern below the workspace root. Patterns are
104
+ * anchored at the root regardless of cwd depth, directory symlinks are never
105
+ * traversed, and results stay native platform paths. Directories the crawl
106
+ * cannot read are reported with their native error code instead of being
107
+ * dropped silently.
108
+ */
109
+ export async function matchProjectAdapterCandidates(
110
+ input: ProjectAdapterMatchInput,
111
+ ): Promise<ProjectAdapterMatch> {
112
+ const unsafePattern = workspaceRelativePatternProblem(input.pattern);
113
+ if (unsafePattern !== null) {
114
+ return { candidates: [], unsafePattern, failure: null, unreadableDirectories: [] };
115
+ }
116
+
117
+ const unreadableDirectories: UnreadableDirectory[] = [];
118
+ const baseReaddir = input.readdir ?? nodeReaddir;
119
+ const recordingReaddir = ((
120
+ directory: string,
121
+ options: { withFileTypes: true },
122
+ callback: (error: NodeJS.ErrnoException | null, entries: Dirent[]) => void,
123
+ ): void => {
124
+ baseReaddir(directory, options, (error, entries) => {
125
+ if (error) {
126
+ unreadableDirectories.push({
127
+ directory: path.resolve(directory),
128
+ code: nativeErrorCode(error),
129
+ });
130
+ }
131
+ callback(error, entries ?? []);
132
+ });
133
+ }) as unknown as typeof nodeReaddir;
134
+
135
+ let matches: string[];
136
+ try {
137
+ matches = await glob(input.pattern, {
138
+ cwd: input.workspaceRoot,
139
+ absolute: true,
140
+ onlyDirectories: true,
141
+ followSymbolicLinks: false,
142
+ dot: true,
143
+ expandDirectories: false,
144
+ ignore: [...input.ignorePatterns],
145
+ fs: { readdir: recordingReaddir },
146
+ });
147
+ } catch (error) {
148
+ if (error instanceof Error) {
149
+ return {
150
+ candidates: [],
151
+ unsafePattern: null,
152
+ failure: { message: error.message, code: nativeErrorCode(error) },
153
+ unreadableDirectories: sortUnreadable(unreadableDirectories),
154
+ };
155
+ }
156
+ throw error;
157
+ }
158
+
159
+ const candidates: string[] = [];
160
+ for (const match of matches) {
161
+ candidates.push(appendSkillsSuffix(path.normalize(match)));
162
+ }
163
+ return {
164
+ candidates,
165
+ unsafePattern: null,
166
+ failure: null,
167
+ unreadableDirectories: sortUnreadable(unreadableDirectories),
168
+ };
169
+ }
170
+
171
+ function sortUnreadable(entries: UnreadableDirectory[]): UnreadableDirectory[] {
172
+ return entries.sort((left, right) => comparePaths(left.directory, right.directory));
173
+ }
@@ -0,0 +1,158 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ const ENVIRONMENT_PATTERN =
5
+ /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}|([A-Za-z_][A-Za-z0-9_]*))/g;
6
+
7
+ const DRIVE_PREFIX_PATTERN = /^[A-Za-z]:/;
8
+
9
+ export interface ExpandedPathValue {
10
+ path: string;
11
+ missingVariable?: string;
12
+ }
13
+
14
+ /**
15
+ * Workspace containment through `path.relative`, so sibling directories that
16
+ * merely share a string prefix are never treated as descendants.
17
+ */
18
+ export function isInside(root: string, target: string): boolean {
19
+ const relative = path.relative(root, target);
20
+ if (relative.length === 0 || path.isAbsolute(relative)) {
21
+ return false;
22
+ }
23
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`);
24
+ }
25
+
26
+ /**
27
+ * Resolves the home directory used for `$HOME` and `~`. Home is the
28
+ * environment `HOME` value when present so tests and shells stay hermetic on
29
+ * every platform, otherwise the operating-system home directory.
30
+ */
31
+ export function resolveHome(environment: NodeJS.ProcessEnv): string {
32
+ const configuredHome = environment.HOME;
33
+ if (configuredHome !== undefined && configuredHome.trim().length > 0) {
34
+ return path.resolve(configuredHome.trim());
35
+ }
36
+ return os.homedir();
37
+ }
38
+
39
+ /**
40
+ * Expands the documented `$NAME`, `${NAME}`, `${NAME:-default}`, and `~` forms.
41
+ * No shell is invoked: anything else is kept literally and simply fails to
42
+ * resolve as a directory.
43
+ */
44
+ export function expandPathValue(
45
+ value: string,
46
+ environment: NodeJS.ProcessEnv,
47
+ home: string,
48
+ ): ExpandedPathValue {
49
+ let missingVariable: string | undefined;
50
+ const replaced = value.replace(
51
+ ENVIRONMENT_PATTERN,
52
+ (match: string, bracedName?: string, fallback?: string, plainName?: string): string => {
53
+ const name = bracedName ?? plainName ?? "";
54
+ const configured = nonEmpty(environment[name]);
55
+ if (configured !== undefined) {
56
+ return configured;
57
+ }
58
+ if (name === "HOME") {
59
+ return home;
60
+ }
61
+ if (fallback !== undefined) {
62
+ return fallback;
63
+ }
64
+ missingVariable = missingVariable ?? name;
65
+ return match;
66
+ },
67
+ );
68
+ if (missingVariable !== undefined) {
69
+ return { path: replaced, missingVariable };
70
+ }
71
+ return { path: applyHomeShorthand(replaced, home) };
72
+ }
73
+
74
+ /**
75
+ * Appends exactly one `skills` segment. A directory already named `skills`
76
+ * is used as is, so `.claude` and `.claude/skills` are both accepted.
77
+ */
78
+ export function appendSkillsSuffix(directory: string): string {
79
+ return path.basename(directory) === "skills" ? directory : path.join(directory, "skills");
80
+ }
81
+
82
+ /** Platform-native identity key used for physical-path deduplication. */
83
+ export function pathKey(candidate: string): string {
84
+ return process.platform === "win32" ? candidate.toLowerCase() : candidate;
85
+ }
86
+
87
+ /** Deterministic code-unit ordering; it is not skill-name precedence. */
88
+ export function comparePaths(left: string, right: string): number {
89
+ if (left === right) {
90
+ return 0;
91
+ }
92
+ return left < right ? -1 : 1;
93
+ }
94
+
95
+ /**
96
+ * A marker name or scan boundary must narrow the names it matches. A pattern
97
+ * whose remaining text after removing the `*` and `?` wildcards has no letter
98
+ * or digit is a wildcard-only pattern such as `*`, `**`, `?*`, `[!.]*`, or
99
+ * `{,.*}*`, and it matches essentially every entry.
100
+ */
101
+ export function isWildcardOnlyGlob(pattern: string): boolean {
102
+ return !/[\p{L}\p{N}]/u.test(pattern.replace(/[*?]/g, ""));
103
+ }
104
+
105
+ /**
106
+ * Validates a workspace-relative glob used for project adapters and additional
107
+ * ignores. Absolute, drive, UNC, home-shorthand, parent-escaping, negated, and
108
+ * wildcard-only patterns are rejected so a project scan cannot leave its
109
+ * workspace or prune every directory.
110
+ */
111
+ export function workspaceRelativePatternProblem(pattern: string): string | null {
112
+ const candidate = pattern.trim();
113
+ if (candidate.length === 0) {
114
+ return "must not be empty";
115
+ }
116
+ if (candidate.includes("\0")) {
117
+ return "must not contain NUL bytes";
118
+ }
119
+ if (
120
+ path.isAbsolute(candidate) ||
121
+ DRIVE_PREFIX_PATTERN.test(candidate) ||
122
+ candidate.startsWith("\\\\") ||
123
+ candidate.startsWith("//")
124
+ ) {
125
+ return "must be relative to the workspace root";
126
+ }
127
+ if (candidate.startsWith("~")) {
128
+ return "must not start with a home shorthand";
129
+ }
130
+ if (candidate.startsWith("!")) {
131
+ return "must not start with a glob negation";
132
+ }
133
+ if (isWildcardOnlyGlob(candidate)) {
134
+ return "must contain literal path text, not only glob wildcards";
135
+ }
136
+ if (candidate.split(/[/\\]/).some((segment) => segment === "..")) {
137
+ return "must not escape the workspace root";
138
+ }
139
+ return null;
140
+ }
141
+
142
+ function applyHomeShorthand(value: string, home: string): string {
143
+ if (value === "~") {
144
+ return home;
145
+ }
146
+ if (value.startsWith("~/") || value.startsWith(`~${path.sep}`)) {
147
+ return path.join(home, value.slice(2));
148
+ }
149
+ return value;
150
+ }
151
+
152
+ function nonEmpty(value: string | undefined): string | undefined {
153
+ if (value === undefined) {
154
+ return undefined;
155
+ }
156
+ const trimmed = value.trim();
157
+ return trimmed.length > 0 ? trimmed : undefined;
158
+ }
@@ -0,0 +1,105 @@
1
+ import path from "node:path";
2
+ import { glob } from "tinyglobby";
3
+ import { isWildcardOnlyGlob } from "./paths.js";
4
+
5
+ const DRIVE_PREFIX_PATTERN = /^[A-Za-z]:/;
6
+
7
+ const MARKER_MATCH_OPTIONS = {
8
+ absolute: true,
9
+ onlyFiles: false,
10
+ onlyDirectories: false,
11
+ dot: true,
12
+ expandDirectories: false,
13
+ followSymbolicLinks: false,
14
+ } as const;
15
+
16
+ export interface WorkspaceRootResult {
17
+ root: string;
18
+ matchedPattern?: string;
19
+ }
20
+
21
+ /**
22
+ * Validates a root marker pattern. Markers identify a basename in an ancestor
23
+ * directory, so filesystem paths, separators, parent escapes, and wildcard-only
24
+ * patterns that match every entry are rejected.
25
+ */
26
+ export function rootPatternProblem(pattern: string): string | null {
27
+ const candidate = pattern.trim();
28
+ if (candidate.length === 0) {
29
+ return "must not be empty";
30
+ }
31
+ if (candidate.includes("\0")) {
32
+ return "must not contain NUL bytes";
33
+ }
34
+ if (candidate === "." || candidate === "..") {
35
+ return "must not be a relative path segment";
36
+ }
37
+ if (
38
+ path.isAbsolute(candidate) ||
39
+ DRIVE_PREFIX_PATTERN.test(candidate) ||
40
+ candidate.startsWith("\\\\") ||
41
+ candidate.startsWith("//")
42
+ ) {
43
+ return "must be a marker name, not a filesystem path";
44
+ }
45
+ if (candidate.includes("/") || candidate.includes("\\")) {
46
+ return "must not contain path separators";
47
+ }
48
+ if (isWildcardOnlyGlob(candidate)) {
49
+ return "is too broad to identify a workspace root";
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /**
55
+ * Selects the nearest ancestor directory that contains a configured marker.
56
+ * `.git` may be a file or a directory, and the search never continues above
57
+ * the selected root.
58
+ */
59
+ export async function findWorkspaceRoot(
60
+ cwd: string,
61
+ rootPatterns: readonly string[],
62
+ ): Promise<WorkspaceRootResult> {
63
+ const start = path.resolve(cwd);
64
+ if (rootPatterns.length === 0) {
65
+ return { root: start };
66
+ }
67
+
68
+ let directory = start;
69
+ while (true) {
70
+ const matchedPattern = await matchMarkerIn(directory, rootPatterns);
71
+ if (matchedPattern !== undefined) {
72
+ return { root: directory, matchedPattern };
73
+ }
74
+ const parent = path.dirname(directory);
75
+ if (parent === directory) {
76
+ return { root: start };
77
+ }
78
+ directory = parent;
79
+ }
80
+ }
81
+
82
+ async function matchMarkerIn(
83
+ directory: string,
84
+ rootPatterns: readonly string[],
85
+ ): Promise<string | undefined> {
86
+ for (const pattern of rootPatterns) {
87
+ if (rootPatternProblem(pattern) !== null) {
88
+ continue;
89
+ }
90
+ let matches: string[];
91
+ try {
92
+ matches = await glob(pattern, { ...MARKER_MATCH_OPTIONS, cwd: directory });
93
+ } catch (error) {
94
+ // An ancestor that cannot be read is a miss, not a reason to fail discovery.
95
+ if (error instanceof Error) {
96
+ continue;
97
+ }
98
+ throw error;
99
+ }
100
+ if (matches.length > 0) {
101
+ return pattern;
102
+ }
103
+ }
104
+ return undefined;
105
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,15 @@
1
- export default function piStackedContext(): void {
2
- // Placeholder 0.0.0 bootstrap. Resource discovery is implemented in later releases.
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { loadConfiguration } from "./config/settings.js";
3
+ import { discoverSkillRoots } from "./skills/discover.js";
4
+
5
+ /**
6
+ * Pi entry point. Startup and native `/reload` both emit `resources_discover`,
7
+ * so every pass recomputes configuration and candidates from disk.
8
+ */
9
+ export default function piStackedContext(pi: ExtensionAPI): void {
10
+ pi.on("resources_discover", async (event, ctx) => {
11
+ const configuration = await loadConfiguration(ctx, event.cwd);
12
+ const discovery = await discoverSkillRoots({ cwd: event.cwd, config: configuration.config });
13
+ return { skillPaths: [...discovery.skillPaths] };
14
+ });
3
15
  }
@@ -0,0 +1,35 @@
1
+ import type { ConfigLayer, Diagnostic, DiagnosticLevel } from "./types.js";
2
+
3
+ export interface DiagnosticDetails {
4
+ readonly layer?: ConfigLayer | undefined;
5
+ readonly sourcePath?: string | undefined;
6
+ readonly field?: string | undefined;
7
+ }
8
+
9
+ export function createDiagnostic(
10
+ level: DiagnosticLevel,
11
+ code: string,
12
+ message: string,
13
+ details?: DiagnosticDetails,
14
+ ): Diagnostic {
15
+ const diagnostic: Diagnostic = { level, code, message };
16
+ if (details?.layer !== undefined) {
17
+ diagnostic.layer = details.layer;
18
+ }
19
+ if (details?.sourcePath !== undefined) {
20
+ diagnostic.sourcePath = details.sourcePath;
21
+ }
22
+ if (details?.field !== undefined) {
23
+ diagnostic.field = details.field;
24
+ }
25
+ return diagnostic;
26
+ }
27
+
28
+ /** Native error code such as `EACCES`, when the thrown value carries one. */
29
+ export function nativeErrorCode(error: unknown): string | null {
30
+ if (error instanceof Error && "code" in error) {
31
+ const code: unknown = (error as { code?: unknown }).code;
32
+ return typeof code === "string" ? code : null;
33
+ }
34
+ return null;
35
+ }