@fro.bot/systematic 3.18.10 → 3.20.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.
@@ -1,3 +1,4 @@
1
+ import { CONFIG_PROTECTED_FIELD_PATHS, type ConfigProtectedFieldPath } from './config-protected-fields.js';
1
2
  import { type RoutingTarget } from './routing-resolver.js';
2
3
  export interface BootstrapConfig {
3
4
  enabled: boolean;
@@ -10,22 +11,75 @@ export interface WorkflowGuardConfig {
10
11
  }
11
12
  export type OverlayConfig = Record<string, unknown>;
12
13
  export type OverlayConfigMap = Record<string, OverlayConfig>;
14
+ /**
15
+ * Which FILE-level source contributed the winning value for one routing
16
+ * field -- distinct from `RoutingFieldSource.level`/`.form` in
17
+ * `routing-resolver.ts`, which describe SHAPE provenance (agent vs
18
+ * category, block vs flat), not file provenance. Reuses `ConfigSourceKind`
19
+ * for the non-profile cases (a plain agents/categories overlay entry from
20
+ * that trust level) and adds the three profile-bundle variants, since a
21
+ * bundle's own trust level (which file defined `profiles.<name>`) is a
22
+ * genuinely different fact from an ordinary same-trust overlay -- most
23
+ * importantly, `'project-profile'` is the only origin an advisory
24
+ * (project-sourced) bundle can ever produce, and is exactly the tag
25
+ * `config show` needs to make "the project bundle applied something"
26
+ * distinguishable from "the project bundle got fully absorbed by user
27
+ * config" (every field's origin reads `'user'`, never `'project-profile'`).
28
+ */
29
+ export type RoutingValueOrigin = ConfigSourceKind | 'user-profile' | 'custom-profile' | 'project-profile';
30
+ /**
31
+ * Per-leaf file-provenance for the exact set of fields
32
+ * `routing-resolver.ts` ever reads off a merged agent/category overlay
33
+ * value: the two flat fields (`model`, `variant`) and the four
34
+ * harness-block fields (`opencode.model`, `opencode.variant`, `pi.model`,
35
+ * `pi.thinking`). Deliberately NOT a generic recursive mirror of
36
+ * `OverlayConfig`'s shape -- routing is the only consumer, and a generic
37
+ * tree would have to track every overlay field (`mode`, `color`, `steps`,
38
+ * `hidden`, `disable`, `skills`, `permission`, ...) for no benefit, since
39
+ * none of those ever feed routing resolution.
40
+ *
41
+ * A leaf is `undefined` when no source in the merge chain has ever set
42
+ * that field as an OWN property for this key -- distinct from the field
43
+ * being unresolved at the routing layer (which can also happen when a
44
+ * lower-precedence layer, e.g. category, is shadowed by a higher one, e.g.
45
+ * agent, that DOES have an origin here).
46
+ */
47
+ export interface RoutingFieldOrigins {
48
+ readonly model?: RoutingValueOrigin;
49
+ readonly variant?: RoutingValueOrigin;
50
+ readonly opencodeModel?: RoutingValueOrigin;
51
+ readonly opencodeVariant?: RoutingValueOrigin;
52
+ readonly piModel?: RoutingValueOrigin;
53
+ readonly piThinking?: RoutingValueOrigin;
54
+ }
13
55
  export interface SourcedOverlayConfig {
14
56
  value: OverlayConfig;
15
57
  sourcePath: string;
16
58
  keyPath: string;
59
+ /**
60
+ * Per-routing-field file provenance for `value`, updated in lockstep
61
+ * with `value` at every merge step (see `resolveOverlayEntryOrigin`) --
62
+ * attached to the value that actually won, never derived after the fact
63
+ * from `sourcePath` (which is last-writer-wins across the WHOLE entry,
64
+ * not per field; see that field's doc comment for the trap this avoids).
65
+ * Optional and possibly `{}` for overlay maps this file's merge doesn't
66
+ * populate origins for (`pi_subagents`, and `routing-resolver.ts`'s
67
+ * `toSourcedOverlayMap` placeholder adapter for already-flattened
68
+ * inputs) -- routing resolution treats a missing leaf as "no known
69
+ * origin", never as an error.
70
+ */
71
+ origins?: RoutingFieldOrigins;
17
72
  }
18
73
  export interface SourcedOverlayConfigMap {
19
74
  agents: Record<string, SourcedOverlayConfig>;
20
75
  categories: Record<string, SourcedOverlayConfig>;
21
76
  }
22
77
  export declare const CONFIG_AUTHORITY_FIELD_PATHS: readonly ['bootstrap.enabled', 'bootstrap.file', 'skills_as_commands', 'workflow_guard.debug', 'workflow_guard.mode'];
23
- export declare const CONFIG_PROTECTED_FIELD_PATHS: readonly ['workflow_guard', 'profiles', 'agents.*.model', 'agents.*.permission', 'agents.*.skills', 'agents.*.variant', 'agents.*.opencode', 'agents.*.pi', 'categories.*.model', 'categories.*.permission', 'categories.*.skills', 'categories.*.variant', 'categories.*.opencode', 'categories.*.pi'];
78
+ export { CONFIG_PROTECTED_FIELD_PATHS, type ConfigProtectedFieldPath };
24
79
  export type ConfigSourceKind = 'custom' | 'project' | 'user';
25
80
  export type ConfigSourcePresence = 'absent' | 'invalid' | 'present';
26
81
  export type ConfigSourceErrorCode = 'parse-failed' | 'read-failed' | 'schema-invalid' | 'source-invalid';
27
82
  export type ConfigAuthorityFieldPath = (typeof CONFIG_AUTHORITY_FIELD_PATHS)[number];
28
- export type ConfigProtectedFieldPath = (typeof CONFIG_PROTECTED_FIELD_PATHS)[number];
29
83
  export interface ConfigSourceMetadata {
30
84
  readonly errorCode?: ConfigSourceErrorCode;
31
85
  readonly kind: ConfigSourceKind;
@@ -44,12 +98,14 @@ export interface ConfigProtectedFieldMetadata {
44
98
  * The source kind that supplied the winning `profile` selector value, or
45
99
  * `null` when no source set `profile` at all (case 1 of the selection table
46
100
  * in plan 2026-09-04-002-feat-model-config-profiles, Unit 2). This names
47
- * whichever source's value won the `custom ?? project ?? user` selector
48
- * lookup -- including when that value turned out to name a missing bundle
49
- * and the loader fell back to the user's own default (see
50
- * {@link ConfigObservationMetadata.profileFallback}).
101
+ * whichever source's value won the `SYSTEMATIC_PROFILE ?? custom ?? project
102
+ * ?? user` selector lookup -- including when that value turned out to name
103
+ * a missing bundle and the loader fell back to the user's own default (see
104
+ * {@link ConfigObservationMetadata.profileFallback}). `'environment'` is
105
+ * distinct from `ConfigSourceKind` deliberately: it names an env var
106
+ * override, never a config file, and must never be mistaken for one.
51
107
  */
52
- export type ProfileSelectorSource = ConfigSourceKind | null;
108
+ export type ProfileSelectorSource = ConfigSourceKind | 'environment' | null;
53
109
  /**
54
110
  * Present when the winning `profile` selector named a bundle absent from
55
111
  * the user source's `profiles` map. `usedDefault` names the user's own
@@ -82,6 +138,30 @@ export interface SourceAwareConfigResult {
82
138
  * the post-merge qualifier check, without recomputing it.
83
139
  */
84
140
  piSubagentsOverlays: SourcedOverlayConfigMap;
141
+ /**
142
+ * The (non-canonical) `path` of the file that defined the active
143
+ * profile's bundle content -- `profileSelection.bundleSource.path`,
144
+ * verbatim -- or `null` when no profile is active. Deliberately lives
145
+ * here and NOT on `ConfigObservationMetadata`: `capability-snapshot.ts`
146
+ * runs loader metadata through `assertAllowedKeys`, a hardcoded-allowlist
147
+ * gate that THROWS on any unknown key (see its doc comment), and only
148
+ * `.metadata` -- never the rest of `SourceAwareConfigResult` -- is an
149
+ * input to the capability snapshot. Adding a field to
150
+ * `ConfigObservationMetadata` would silently break `systematic
151
+ * capabilities` (`runCapabilities` catches the throw and prints
152
+ * "Capabilities diagnostic unavailable", naming no cause) exactly the way
153
+ * a hand-duplicated `CONFIG_PROTECTED_FIELD_PATHS` literal in
154
+ * `capability-snapshot.ts` once silently did, before that duplication was
155
+ * removed in favor of the shared `config-protected-fields.ts` module (see
156
+ * that module's doc comment for the incident record). Consumers
157
+ * (`systematic config show`) read `loaded.activeProfileSourcePath`
158
+ * directly, never `loaded.metadata.activeProfileSourcePath`. Uses `path`
159
+ * (matching `getConfigPaths`/`Configuration locations`'s non-canonical
160
+ * values), not `canonicalPath` -- printing the canonical path would
161
+ * disagree with the `Configuration locations` block a few lines above it
162
+ * for a symlinked config directory.
163
+ */
164
+ activeProfileSourcePath: string | null;
85
165
  }
86
166
  export interface PiSubagentsOverlayMap {
87
167
  categories?: OverlayConfigMap;
@@ -97,6 +177,7 @@ export interface SystematicConfig {
97
177
  categories?: OverlayConfigMap;
98
178
  pi_subagents?: PiSubagentsOverlayMap;
99
179
  skills_as_commands: boolean;
180
+ allow_project_profiles: boolean;
100
181
  }
101
182
  export declare const DEFAULT_CONFIG: SystematicConfig;
102
183
  /**
@@ -166,4 +247,3 @@ export declare function getConfigPaths(projectDir: string, options?: ConfigPathO
166
247
  customConfig?: string | undefined;
167
248
  customDir?: string | undefined;
168
249
  };
169
- export {};
@@ -13,7 +13,7 @@
13
13
  * (`src/lib/config.ts`), which has the `warningSink` this module deliberately
14
14
  * does not.
15
15
  */
16
- import type { OverlayConfigMap, PiSubagentsOverlayMap, SourcedOverlayConfig, SourcedOverlayConfigMap } from './config.js';
16
+ import type { OverlayConfigMap, PiSubagentsOverlayMap, RoutingValueOrigin, SourcedOverlayConfig, SourcedOverlayConfigMap } from './config.js';
17
17
  export type Harness = 'opencode' | 'pi';
18
18
  /**
19
19
  * One resolution target: a bundled agent's bare file-stem key plus its
@@ -32,10 +32,22 @@ export interface RoutingTarget {
32
32
  * `form` is `'legacy-pi-subagents'` only for a `pi` harness qualifier
33
33
  * resolved from the deprecated `pi_subagents.<agents|categories>.<key>.thinking`
34
34
  * location (R5) — `model` and `variant` never resolve from there.
35
+ *
36
+ * `level`/`form` are SHAPE provenance -- which key shape won (agent vs
37
+ * category, block vs flat) -- not FILE provenance. `origin` is the FILE
38
+ * provenance: which trust level/profile-bundle actually contributed the
39
+ * winning value, read from `SourcedOverlayConfig.origins` at the same leaf
40
+ * `level`/`form` identify (see `config.ts`'s `RoutingFieldOrigins` for how
41
+ * that's tracked through the merge). `undefined` for a legacy-pi-subagents
42
+ * source (that map isn't merge-tracked for origins -- profile bundles
43
+ * can't set `pi_subagents` fields at all) or when the caller supplied
44
+ * overlays via `toSourcedOverlayMap`'s placeholder adapter, which carries
45
+ * no real origins.
35
46
  */
36
47
  export interface RoutingFieldSource {
37
48
  readonly level: 'agent' | 'category';
38
49
  readonly form: 'block' | 'flat' | 'legacy-pi-subagents';
50
+ readonly origin?: RoutingValueOrigin;
39
51
  }
40
52
  export interface RoutingResolution {
41
53
  /**
package/dist/pi.js CHANGED
@@ -9657,7 +9657,7 @@ function createSystematicConfigSchema(opts) {
9657
9657
  examples: [{ review: { model: "anthropic/claude-opus-5" } }, {}]
9658
9658
  }),
9659
9659
  profiles: record(string2(), createProfileBundleSchema(agentNames, qualifiedAgentIds)).default({}).meta({
9660
- description: "Named routing-only overlay bundles, selectable by name via the profile field. Only valid in user config or OPENCODE_CONFIG_DIR config — a project config may select a profile but may not define this field.",
9660
+ description: "Named routing-only overlay bundles, selectable by name via the profile field. Valid in user config and OPENCODE_CONFIG_DIR config. A project config may always select a profile, but may only define this field when the user sets allow_project_profiles; a project-defined bundle is advisory and fills only routing the user has not set.",
9661
9661
  examples: [
9662
9662
  {
9663
9663
  personal: {
@@ -9670,6 +9670,10 @@ function createSystematicConfigSchema(opts) {
9670
9670
  ]
9671
9671
  }),
9672
9672
  profile: profileSchema,
9673
+ allow_project_profiles: trustProtected(boolean2().meta({
9674
+ description: "Allow a repository's project config to define its own `profiles` map. User-owned only — only valid in user config or OPENCODE_CONFIG_DIR config; a project config setting this field has it ignored (a project cannot grant itself a permission it does not already have). Defaults to false.",
9675
+ examples: [true, false]
9676
+ })).default(false),
9673
9677
  disabled_skills: array(_enum([...skillNames, ...removedSkillNames])).default([]).meta({
9674
9678
  description: "Array of bundled skill names to disable globally. Unknown skill names are rejected at parse time.",
9675
9679
  examples: [["ce:plan", "ce:review"]]
@@ -9744,8 +9748,8 @@ function toSourcedPiSubagentsOverlays(map) {
9744
9748
  categories: toSourcedOverlayMap(map?.categories)
9745
9749
  };
9746
9750
  }
9747
- function lookupAgentOverlay(overlays, target) {
9748
- return getOverlayValue(overlays.agents, target.agentKey) ?? getOverlayValue(overlays.agents, `${target.category}/${target.agentKey}`);
9751
+ function lookupAgentOverlayEntry(overlays, target) {
9752
+ return overlays.agents[target.agentKey] ?? overlays.agents[`${target.category}/${target.agentKey}`];
9749
9753
  }
9750
9754
  function readBlockField(overlay, blockKey, field) {
9751
9755
  if (overlay === undefined)
@@ -9778,23 +9782,31 @@ function resolveField(candidates) {
9778
9782
  }
9779
9783
  return { value: undefined, source: undefined };
9780
9784
  }
9781
- function resolveModel(agentOverlay, categoryOverlay, harness) {
9785
+ function resolveModel(agentOverlay, agentOrigins, categoryOverlay, categoryOrigins, harness) {
9782
9786
  const { value, source } = resolveField([
9783
9787
  {
9784
9788
  value: readBlockField(agentOverlay, harness, "model"),
9785
- source: { level: "agent", form: "block" }
9789
+ source: { level: "agent", form: "block", origin: agentOrigins?.piModel }
9786
9790
  },
9787
9791
  {
9788
9792
  value: readFlatField(agentOverlay, "model"),
9789
- source: { level: "agent", form: "flat" }
9793
+ source: { level: "agent", form: "flat", origin: agentOrigins?.model }
9790
9794
  },
9791
9795
  {
9792
9796
  value: readBlockField(categoryOverlay, harness, "model"),
9793
- source: { level: "category", form: "block" }
9797
+ source: {
9798
+ level: "category",
9799
+ form: "block",
9800
+ origin: categoryOrigins?.piModel
9801
+ }
9794
9802
  },
9795
9803
  {
9796
9804
  value: readFlatField(categoryOverlay, "model"),
9797
- source: { level: "category", form: "flat" }
9805
+ source: {
9806
+ level: "category",
9807
+ form: "flat",
9808
+ origin: categoryOrigins?.model
9809
+ }
9798
9810
  }
9799
9811
  ]);
9800
9812
  const narrowedValue = narrowModelValue(value);
@@ -9813,13 +9825,23 @@ function readOpencodeLayerField(agentOverlay, categoryOverlay, layer, field) {
9813
9825
  const overlay = layer.level === "agent" ? agentOverlay : categoryOverlay;
9814
9826
  return layer.form === "block" ? readBlockField(overlay, "opencode", field) : readFlatField(overlay, field);
9815
9827
  }
9816
- function resolveOpencodeModelAndVariant(agentOverlay, categoryOverlay) {
9828
+ function readOpencodeLayerOrigin(agentOrigins, categoryOrigins, layer, field) {
9829
+ const origins = layer.level === "agent" ? agentOrigins : categoryOrigins;
9830
+ if (field === "model") {
9831
+ return layer.form === "block" ? origins?.opencodeModel : origins?.model;
9832
+ }
9833
+ return layer.form === "block" ? origins?.opencodeVariant : origins?.variant;
9834
+ }
9835
+ function resolveOpencodeModelAndVariant(agentOverlay, agentOrigins, categoryOverlay, categoryOrigins) {
9817
9836
  const modelLayerIndex = OPENCODE_MODEL_VARIANT_LAYERS.findIndex((layer) => readOpencodeLayerField(agentOverlay, categoryOverlay, layer, "model") !== undefined);
9818
9837
  const modelLayer = modelLayerIndex === -1 ? undefined : OPENCODE_MODEL_VARIANT_LAYERS[modelLayerIndex];
9819
9838
  const rawModel = modelLayer === undefined ? undefined : readOpencodeLayerField(agentOverlay, categoryOverlay, modelLayer, "model");
9820
9839
  const model = narrowModelValue(rawModel);
9821
9840
  const hasModel = model !== undefined;
9822
- const modelSource = hasModel ? OPENCODE_MODEL_VARIANT_LAYERS[modelLayerIndex] : undefined;
9841
+ const modelSource = hasModel && modelLayer !== undefined ? {
9842
+ ...modelLayer,
9843
+ origin: readOpencodeLayerOrigin(agentOrigins, categoryOrigins, modelLayer, "model")
9844
+ } : undefined;
9823
9845
  let qualifier;
9824
9846
  let qualifierSource;
9825
9847
  if (model !== null) {
@@ -9828,22 +9850,33 @@ function resolveOpencodeModelAndVariant(agentOverlay, categoryOverlay) {
9828
9850
  const narrowed = narrowQualifierValue(readOpencodeLayerField(agentOverlay, categoryOverlay, layer, "variant"));
9829
9851
  if (narrowed !== undefined) {
9830
9852
  qualifier = narrowed;
9831
- qualifierSource = layer;
9853
+ qualifierSource = {
9854
+ ...layer,
9855
+ origin: readOpencodeLayerOrigin(agentOrigins, categoryOrigins, layer, "variant")
9856
+ };
9832
9857
  break;
9833
9858
  }
9834
9859
  }
9835
9860
  }
9836
9861
  return { model, modelSource, qualifier, qualifierSource };
9837
9862
  }
9838
- function resolvePiThinking(agentOverlay, categoryOverlay, piSubagentsOverlays, target) {
9863
+ function resolvePiThinking(agentOverlay, agentOrigins, categoryOverlay, categoryOrigins, piSubagentsOverlays, target) {
9839
9864
  const blockResolution = resolveField([
9840
9865
  {
9841
9866
  value: readBlockField(agentOverlay, "pi", "thinking"),
9842
- source: { level: "agent", form: "block" }
9867
+ source: {
9868
+ level: "agent",
9869
+ form: "block",
9870
+ origin: agentOrigins?.piThinking
9871
+ }
9843
9872
  },
9844
9873
  {
9845
9874
  value: readBlockField(categoryOverlay, "pi", "thinking"),
9846
- source: { level: "category", form: "block" }
9875
+ source: {
9876
+ level: "category",
9877
+ form: "block",
9878
+ origin: categoryOrigins?.piThinking
9879
+ }
9847
9880
  }
9848
9881
  ]);
9849
9882
  const legacyAgentThinking = getOverlayValue(piSubagentsOverlays.agents, target.agentKey)?.thinking;
@@ -9873,10 +9906,14 @@ function resolvePiThinking(agentOverlay, categoryOverlay, piSubagentsOverlays, t
9873
9906
  }
9874
9907
  function resolveRouting(input) {
9875
9908
  const { overlays, piSubagentsOverlays, target, harness } = input;
9876
- const agentOverlay = lookupAgentOverlay(overlays, target);
9877
- const categoryOverlay = getOverlayValue(overlays.categories, target.category);
9909
+ const agentEntry = lookupAgentOverlayEntry(overlays, target);
9910
+ const categoryEntry = overlays.categories[target.category];
9911
+ const agentOverlay = agentEntry?.value;
9912
+ const categoryOverlay = categoryEntry?.value;
9913
+ const agentOrigins = agentEntry?.origins;
9914
+ const categoryOrigins = categoryEntry?.origins;
9878
9915
  if (harness === "opencode") {
9879
- const resolution = resolveOpencodeModelAndVariant(agentOverlay, categoryOverlay);
9916
+ const resolution = resolveOpencodeModelAndVariant(agentOverlay, agentOrigins, categoryOverlay, categoryOrigins);
9880
9917
  return {
9881
9918
  model: resolution.model,
9882
9919
  qualifier: resolution.qualifier,
@@ -9888,8 +9925,8 @@ function resolveRouting(input) {
9888
9925
  harness
9889
9926
  };
9890
9927
  }
9891
- const modelResolution = resolveModel(agentOverlay, categoryOverlay, harness);
9892
- const qualifierResolution = resolvePiThinking(agentOverlay, categoryOverlay, piSubagentsOverlays, target);
9928
+ const modelResolution = resolveModel(agentOverlay, agentOrigins, categoryOverlay, categoryOrigins, harness);
9929
+ const qualifierResolution = resolvePiThinking(agentOverlay, agentOrigins, categoryOverlay, categoryOrigins, piSubagentsOverlays, target);
9893
9930
  return {
9894
9931
  model: modelResolution.value,
9895
9932
  qualifier: qualifierResolution.value,
@@ -9946,7 +9983,8 @@ var DEFAULT_CONFIG = {
9946
9983
  agents: {},
9947
9984
  categories: {},
9948
9985
  pi_subagents: { categories: {}, agents: {} },
9949
- skills_as_commands: true
9986
+ skills_as_commands: true,
9987
+ allow_project_profiles: false
9950
9988
  };
9951
9989
  var PROTECTED_OVERLAY_FIELD_PATHS = {
9952
9990
  agents: {
@@ -9966,7 +10004,10 @@ var PROTECTED_OVERLAY_FIELD_PATHS = {
9966
10004
  pi: "categories.*.pi"
9967
10005
  }
9968
10006
  };
9969
- var PROJECT_PROTECTED_FIELDS = new Set(["workflow_guard", "profiles"]);
10007
+ var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set([
10008
+ "workflow_guard",
10009
+ "allow_project_profiles"
10010
+ ]);
9970
10011
  var MAX_DIAGNOSTIC_TEXT = 200;
9971
10012
  var MAX_STRIP_WARNINGS = 20;
9972
10013
  var DIAGNOSTIC_ELLIPSIS = "…";
@@ -10159,7 +10200,7 @@ ${formatted.map((entry) => ` - ${entry}`).join(`
10159
10200
  issues
10160
10201
  });
10161
10202
  }
10162
- function loadConfigSource(filePath, trust, invalidSource, warningSink) {
10203
+ function loadConfigSource(filePath, trust, invalidSource, warningSink, allowProjectProfiles) {
10163
10204
  try {
10164
10205
  const rawConfig = loadJsoncFile(filePath);
10165
10206
  if (!rawConfig) {
@@ -10168,8 +10209,8 @@ function loadConfigSource(filePath, trust, invalidSource, warningSink) {
10168
10209
  source: null
10169
10210
  };
10170
10211
  }
10171
- const protectedFields = collectProjectProtectedFields(rawConfig, trust);
10172
- const topLevelStripped = trust === "project" ? stripProjectProtectedFields(rawConfig) : rawConfig;
10212
+ const protectedFields = collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles);
10213
+ const topLevelStripped = trust === "project" ? stripProjectProtectedFields(rawConfig, allowProjectProfiles) : rawConfig;
10173
10214
  const config = trust === "project" ? stripProjectSecurityOverlayFields(topLevelStripped, filePath, warningSink) : topLevelStripped;
10174
10215
  const result = SystematicConfigSchema.safeParse(config);
10175
10216
  if (!result.success) {
@@ -10220,7 +10261,14 @@ function resolveConfigSourcePath(filePath) {
10220
10261
  return path3.resolve(filePath);
10221
10262
  }
10222
10263
  }
10223
- function collectProjectProtectedFields(rawConfig, trust) {
10264
+ function emitTopLevelProtectedFieldWarning(projectSource, fieldPath, messageTemplate, sink) {
10265
+ if (!projectSource?.protectedFields.some((field) => field.fieldPath === fieldPath)) {
10266
+ return;
10267
+ }
10268
+ const safePath = sanitizeDiagnosticText(projectSource.path);
10269
+ sink(`[systematic] ${messageTemplate.replace("%PATH%", safePath)}`);
10270
+ }
10271
+ function collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles) {
10224
10272
  if (trust !== "project")
10225
10273
  return [];
10226
10274
  return [
@@ -10231,13 +10279,20 @@ function collectProjectProtectedFields(rawConfig, trust) {
10231
10279
  sourceKind: "project"
10232
10280
  }
10233
10281
  ] : [],
10234
- ...Object.hasOwn(rawConfig, "profiles") ? [
10282
+ ...!allowProjectProfiles && Object.hasOwn(rawConfig, "profiles") ? [
10235
10283
  {
10236
10284
  fieldPath: "profiles",
10237
10285
  outcome: "blocked",
10238
10286
  sourceKind: "project"
10239
10287
  }
10240
10288
  ] : [],
10289
+ ...Object.hasOwn(rawConfig, "allow_project_profiles") ? [
10290
+ {
10291
+ fieldPath: "allow_project_profiles",
10292
+ outcome: "blocked",
10293
+ sourceKind: "project"
10294
+ }
10295
+ ] : [],
10241
10296
  ...collectOverlayProtectedFields(rawConfig.agents, "agents"),
10242
10297
  ...collectOverlayProtectedFields(rawConfig.categories, "categories")
10243
10298
  ];
@@ -10254,11 +10309,14 @@ function collectProtectedOverlayValue(value, mapKey) {
10254
10309
  sourceKind: "project"
10255
10310
  }));
10256
10311
  }
10257
- function stripProjectProtectedFields(rawConfig) {
10312
+ function stripProjectProtectedFields(rawConfig, allowProjectProfiles) {
10258
10313
  const config = { ...rawConfig };
10259
- for (const field of PROJECT_PROTECTED_FIELDS) {
10314
+ for (const field of PROJECT_ALWAYS_PROTECTED_FIELDS) {
10260
10315
  delete config[field];
10261
10316
  }
10317
+ if (!allowProjectProfiles) {
10318
+ delete config.profiles;
10319
+ }
10262
10320
  return config;
10263
10321
  }
10264
10322
  function stripProjectSecurityOverlayFields(rawConfig, filePath, warningSink) {
@@ -10318,6 +10376,9 @@ var NO_PROFILE_SELECTION = {
10318
10376
  bundleSource: null
10319
10377
  };
10320
10378
  function resolveProfileSelector(input) {
10379
+ const envProfile = process.env.SYSTEMATIC_PROFILE?.trim();
10380
+ if (envProfile)
10381
+ return { value: envProfile, source: "environment" };
10321
10382
  const candidates = [
10322
10383
  ["custom", input.customConfig?.profile],
10323
10384
  ["project", input.projectConfig?.profile],
@@ -10342,12 +10403,21 @@ function lookupProfileBundle(input, name) {
10342
10403
  return { bundle, definingSource: input.userSource };
10343
10404
  }
10344
10405
  }
10406
+ if (input.allowProjectProfiles && input.projectSource) {
10407
+ const bundle = input.projectSource.config.profiles?.[name];
10408
+ if (bundle !== undefined) {
10409
+ return { bundle, definingSource: input.projectSource };
10410
+ }
10411
+ }
10345
10412
  return;
10346
10413
  }
10347
10414
  function trustedDefaultProfileName(input) {
10348
10415
  const userDefault = input.userConfig?.profile;
10349
10416
  return typeof userDefault === "string" ? userDefault : undefined;
10350
10417
  }
10418
+ function selectorSourceLabel(source) {
10419
+ return source === "environment" ? "SYSTEMATIC_PROFILE" : `${source} config`;
10420
+ }
10351
10421
  function resolveActiveProfile(input) {
10352
10422
  const selection = resolveProfileSelector(input);
10353
10423
  if (selection === null)
@@ -10375,7 +10445,7 @@ function resolveActiveProfile(input) {
10375
10445
  const trustedDefault = trustedDefaultProfileName(input);
10376
10446
  const fallbackLookup = trustedDefault !== undefined && trustedDefault !== requested ? lookupProfileBundle(input, trustedDefault) : undefined;
10377
10447
  if (fallbackLookup !== undefined && trustedDefault !== undefined) {
10378
- input.warningSink(`[systematic] profile "${sanitizeDiagnosticText(requested)}" (selected by ${selection.source} config) is not defined in \`profiles\`; falling back to your default profile "${sanitizeDiagnosticText(trustedDefault)}". See ${PROFILE_DOCS_URL} for how to define a profile.`);
10448
+ input.warningSink(`[systematic] profile "${sanitizeDiagnosticText(requested)}" (selected by ${selectorSourceLabel(selection.source)}) is not defined in \`profiles\`; falling back to your default profile "${sanitizeDiagnosticText(trustedDefault)}". See ${PROFILE_DOCS_URL} for how to define a profile.`);
10379
10449
  return {
10380
10450
  activeProfile: trustedDefault,
10381
10451
  profileSelectorSource: selection.source,
@@ -10384,7 +10454,7 @@ function resolveActiveProfile(input) {
10384
10454
  bundleSource: fallbackLookup.definingSource
10385
10455
  };
10386
10456
  }
10387
- const sourceNote = selection.source === "user" ? "" : ` (selected by ${selection.source} config)`;
10457
+ const sourceNote = selection.source === "user" ? "" : ` (selected by ${selectorSourceLabel(selection.source)})`;
10388
10458
  const alsoMissingNote = trustedDefault !== undefined && trustedDefault !== requested ? ` Your default profile "${sanitizeDiagnosticText(trustedDefault)}" is also not defined in \`profiles\`.` : trustedDefault === undefined ? " No default profile is configured (`profile` in your user config)." : "";
10389
10459
  input.warningSink(`[systematic] profile "${sanitizeDiagnosticText(requested)}"${sourceNote} is not defined in \`profiles\`; using base configuration (no profile).${alsoMissingNote} See ${PROFILE_DOCS_URL} for how to define a profile.`);
10390
10460
  return {
@@ -10444,6 +10514,19 @@ function buildAliasSuccessNotice(input) {
10444
10514
  warningSink(`[systematic] project config (${sanitizeDiagnosticText(projectConfigPath)}) and custom config (${sanitizeDiagnosticText(aliasedCustomConfigPath)}) resolve to the same file; protected fields stripped from the project pass (security-overlay fields, \`profiles\`, \`workflow_guard\`) apply through the custom-trust pass instead.`);
10445
10515
  };
10446
10516
  }
10517
+ function loadUserAndCustomSources(paths, invalidSource, warningSink) {
10518
+ const user = loadConfigSource(paths.userConfig, "user", invalidSource, warningSink, false);
10519
+ const custom = paths.customConfig ? loadConfigSource(paths.customConfig, "custom", invalidSource, warningSink, false) : {
10520
+ metadata: { kind: "custom", presence: "absent" },
10521
+ source: null
10522
+ };
10523
+ const allowProjectProfiles = custom.source?.config.allow_project_profiles ?? user.source?.config.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles;
10524
+ return { user, custom, allowProjectProfiles };
10525
+ }
10526
+ function buildOverlaySources(profileEntry, bundleSourceTrust, userSource, projectSource, customSource) {
10527
+ const ordered = profileEntry !== null && bundleSourceTrust === "project" ? [profileEntry, userSource, projectSource, customSource] : [userSource, profileEntry, projectSource, customSource];
10528
+ return ordered.filter((source) => source !== null);
10529
+ }
10447
10530
  function loadConfigWithSources(projectDir, options) {
10448
10531
  const includeProject = options?.includeProject ?? true;
10449
10532
  const invalidSource = options?.invalidSource ?? "throw";
@@ -10452,21 +10535,16 @@ function loadConfigWithSources(projectDir, options) {
10452
10535
  const aliasedCustomConfigPath = resolveAliasedCustomConfigPath(paths, includeProject);
10453
10536
  const projectStrip = createAliasStripTracker(warningSink, aliasedCustomConfigPath);
10454
10537
  const boundedProjectStrip = createBoundedStripWarningSink(projectStrip.sink);
10455
- const user = loadConfigSource(paths.userConfig, "user", invalidSource, warningSink);
10456
- const project = includeProject ? loadConfigSource(paths.projectConfig, "project", invalidSource, boundedProjectStrip.sink) : {
10538
+ const { user, custom, allowProjectProfiles } = loadUserAndCustomSources(paths, invalidSource, warningSink);
10539
+ const userSource = user.source;
10540
+ const customSource = custom.source;
10541
+ const project = includeProject ? loadConfigSource(paths.projectConfig, "project", invalidSource, boundedProjectStrip.sink, allowProjectProfiles) : {
10457
10542
  metadata: { kind: "project", presence: "absent" },
10458
10543
  source: null
10459
10544
  };
10460
- const custom = paths.customConfig ? loadConfigSource(paths.customConfig, "custom", invalidSource, warningSink) : {
10461
- metadata: { kind: "custom", presence: "absent" },
10462
- source: null
10463
- };
10464
- const userSource = user.source;
10465
10545
  const projectSource = project.source;
10466
- const customSource = custom.source;
10467
- if (projectSource?.protectedFields.some((field) => field.fieldPath === "profiles")) {
10468
- boundedProjectStrip.sink(`[systematic] \`profiles\` in project config (${sanitizeDiagnosticText(projectSource.path)}) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored. Its bundles are not selectable even if this project also sets \`profile\`.`);
10469
- }
10546
+ emitTopLevelProtectedFieldWarning(projectSource, "profiles", `\`profiles\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored. Its bundles are not selectable even if this project also sets \`profile\`.`, boundedProjectStrip.sink);
10547
+ emitTopLevelProtectedFieldWarning(projectSource, "allow_project_profiles", `\`allow_project_profiles\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored.`, boundedProjectStrip.sink);
10470
10548
  const suppressedStripCount = boundedProjectStrip.suppressedCount();
10471
10549
  if (suppressedStripCount > 0) {
10472
10550
  projectStrip.sink(`[systematic] ${suppressedStripCount} additional project-config protected-field warning(s) in (${sanitizeDiagnosticText(paths.projectConfig)}) were suppressed.`);
@@ -10493,13 +10571,15 @@ function loadConfigWithSources(projectDir, options) {
10493
10571
  const projectConfig = projectSource?.config;
10494
10572
  const customConfig = customSource?.config;
10495
10573
  const warned = new Set;
10496
- assertAllProfileBundlesAreValid(userConfig, customConfig);
10574
+ assertAllProfileBundlesAreValid(userConfig, customConfig, projectConfig);
10497
10575
  const profileSelection = resolveActiveProfile({
10498
10576
  userConfig,
10499
10577
  userSource,
10500
10578
  projectConfig,
10579
+ projectSource,
10501
10580
  customConfig,
10502
10581
  customSource,
10582
+ allowProjectProfiles,
10503
10583
  warningSink
10504
10584
  });
10505
10585
  const profileEntry = profileSelection.bundle && profileSelection.bundleSource && typeof profileSelection.activeProfile === "string" ? {
@@ -10511,14 +10591,10 @@ function loadConfigWithSources(projectDir, options) {
10511
10591
  categories: profileSelection.bundle.categories
10512
10592
  },
10513
10593
  protectedFields: [],
10514
- profileName: profileSelection.activeProfile
10594
+ profileName: profileSelection.activeProfile,
10595
+ bundleTrust: profileSelection.bundleSource.trust
10515
10596
  } : null;
10516
- const overlaySources = [
10517
- userSource,
10518
- profileEntry,
10519
- projectSource,
10520
- customSource
10521
- ].filter((source) => source !== null);
10597
+ const overlaySources = buildOverlaySources(profileEntry, profileSelection.bundleSource?.trust, userSource, projectSource, customSource);
10522
10598
  const mergedOverlays = mergeOverlaySources(overlaySources);
10523
10599
  const mergedPiSubagentsOverlays = mergePiSubagentsOverlaySources(sources);
10524
10600
  const droppedCategories = Object.keys(mergedOverlays.categories).filter((name) => REMOVED_AGENT_CATEGORIES_SET.has(name));
@@ -10551,7 +10627,8 @@ function loadConfigWithSources(projectDir, options) {
10551
10627
  categories: overlayValues(mergedPiSubagentsOverlays.categories),
10552
10628
  agents: overlayValues(mergedPiSubagentsOverlays.agents)
10553
10629
  },
10554
- skills_as_commands: customConfig?.skills_as_commands ?? projectConfig?.skills_as_commands ?? userConfig?.skills_as_commands ?? DEFAULT_CONFIG.skills_as_commands
10630
+ skills_as_commands: customConfig?.skills_as_commands ?? projectConfig?.skills_as_commands ?? userConfig?.skills_as_commands ?? DEFAULT_CONFIG.skills_as_commands,
10631
+ allow_project_profiles: customConfig?.allow_project_profiles ?? userConfig?.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles
10555
10632
  };
10556
10633
  const droppedSkills = computeDroppedNames(result.disabled_skills, CURRENT_SKILL_NAMES_SET);
10557
10634
  warnDroppedNames(droppedSkills, "disabled_skills", warned, undefined, warningSink);
@@ -10575,7 +10652,8 @@ function loadConfigWithSources(projectDir, options) {
10575
10652
  user: user.metadata
10576
10653
  }),
10577
10654
  overlays,
10578
- piSubagentsOverlays: mergedPiSubagentsOverlays
10655
+ piSubagentsOverlays: mergedPiSubagentsOverlays,
10656
+ activeProfileSourcePath: profileSelection.bundleSource?.path ?? null
10579
10657
  };
10580
10658
  }
10581
10659
  function buildConfigObservationMetadata(summary) {
@@ -10692,8 +10770,8 @@ function assertProfileBundleCategoryKeysAreBundledCategories(profileName, bundle
10692
10770
  }
10693
10771
  }
10694
10772
  }
10695
- function assertAllProfileBundlesAreValid(userConfig, customConfig) {
10696
- for (const config of [userConfig, customConfig]) {
10773
+ function assertAllProfileBundlesAreValid(userConfig, customConfig, projectConfig) {
10774
+ for (const config of [userConfig, customConfig, projectConfig]) {
10697
10775
  for (const [profileName, bundle] of Object.entries(config?.profiles ?? {})) {
10698
10776
  assertProfileBundleCategoryKeysAreBundledCategories(profileName, bundle);
10699
10777
  }
@@ -10741,13 +10819,50 @@ function mergeOverlayMap(target, source, mapKey) {
10741
10819
  }
10742
10820
  const previous = target[key];
10743
10821
  const nextValue = resolveOverlayEntryValue(previous?.value, value, source);
10822
+ const nextOrigins = resolveOverlayEntryOrigin(previous?.origins, value, source);
10744
10823
  target[key] = {
10745
10824
  value: nextValue,
10746
10825
  sourcePath: source.path,
10747
- keyPath
10826
+ keyPath,
10827
+ origins: nextOrigins
10748
10828
  };
10749
10829
  }
10750
10830
  }
10831
+ function originForSource(source) {
10832
+ if (source.kind === "profile-bundle") {
10833
+ return `${source.bundleTrust}-profile`;
10834
+ }
10835
+ return source.trust;
10836
+ }
10837
+ function routingOriginsFromOwnFields(fragment, tag) {
10838
+ const origins = {};
10839
+ if (Object.hasOwn(fragment, "model"))
10840
+ origins.model = tag;
10841
+ if (Object.hasOwn(fragment, "variant"))
10842
+ origins.variant = tag;
10843
+ const opencodeBlock = fragment.opencode;
10844
+ if (isRecord2(opencodeBlock)) {
10845
+ if (Object.hasOwn(opencodeBlock, "model"))
10846
+ origins.opencodeModel = tag;
10847
+ if (Object.hasOwn(opencodeBlock, "variant"))
10848
+ origins.opencodeVariant = tag;
10849
+ }
10850
+ const piBlock = fragment.pi;
10851
+ if (isRecord2(piBlock)) {
10852
+ if (Object.hasOwn(piBlock, "model"))
10853
+ origins.piModel = tag;
10854
+ if (Object.hasOwn(piBlock, "thinking"))
10855
+ origins.piThinking = tag;
10856
+ }
10857
+ return origins;
10858
+ }
10859
+ function resolveOverlayEntryOrigin(previous, fragment, source) {
10860
+ const own = routingOriginsFromOwnFields(fragment, originForSource(source));
10861
+ if (!previous)
10862
+ return own;
10863
+ const preserves = source.kind === "profile-bundle" || source.trust === "project" || source.trust === "user";
10864
+ return preserves ? { ...previous, ...own } : own;
10865
+ }
10751
10866
  function resolveOverlayEntryValue(previous, next, source) {
10752
10867
  if (!previous)
10753
10868
  return next;
@@ -10756,6 +10871,8 @@ function resolveOverlayEntryValue(previous, next, source) {
10756
10871
  }
10757
10872
  if (source.trust === "project")
10758
10873
  return preserveSecurityFields(previous, next);
10874
+ if (source.trust === "user")
10875
+ return mergeProfileOverlayValue(previous, next);
10759
10876
  return next;
10760
10877
  }
10761
10878
  function stripProjectSecurityOverlay(sourcePath, keyPath, value, warningSink) {