pi-scenes 0.6.0 → 0.8.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.
@@ -3,7 +3,24 @@
3
3
  *
4
4
  * 核心思想:
5
5
  * 生效资源 = 通用层(common) ∪ 当前场景(scene)
6
- * 切换场景 = 改写 ~/.pi/agent/settings.json 的 packages/skills 数组 → ctx.reload() 热重载
6
+ * 切换场景 = 改写 settings 的 packages/skills 数组 → ctx.reload() 热重载
7
+ * v0.8:场景化 prompt 模板 —— 不写 settings,监听 resources_discover 事件
8
+ * 按当前激活场景动态返回 promptPaths(零持久化,切走即无)
9
+ *
10
+ * 双层模型(v0.7):资产层(user 全局)与激活层(project 项目)分离
11
+ * 旧版(≤0.6)把场景条目全部写进 ~/.pi/agent/settings.json —— 换目录启动 pi
12
+ * 场景也跟着带过去。v0.7 起 /scene <name> 默认作用于当前项目(<cwd>/.pi),
13
+ * --global 才写全局。分层规则:
14
+ * · npm/local 条目(工具型扩展,不占系统提示)→ 全局层:装一次全局可用
15
+ * · git 多技能包(object form,全量暴露会污染系统提示)→ 双写:
16
+ * 全局锚点 {source, autoload:false, skills:[]}(零暴露 + 共享全局克隆)
17
+ * 项目 delta {source, autoload:false, skills:[场景子集]}(pi 原生 delta 机制:
18
+ * project 条目 autoload:false 时基于 user 级安装做增量启用,见 pi packages.md
19
+ * "project entry acts as a filtering delta over the personal package")
20
+ * · 场景 scaffold 技能目录 → 项目层:<cwd>/.pi/scenes/<名>/skills
21
+ * · common 通用层 skills → 全局层(任何项目恒加载)
22
+ * 两层互斥单激活:切换时先摘净两层旧 managed 再写新层;资产锚点不摘
23
+ * (零暴露无害,保留可让下次切换零下载秒切)。
7
24
  *
8
25
  * 分层模型(前向兼容「主场景→子场景」层级):
9
26
  * common —— 通用层:任何场景下都恒加载的 packages + skills
@@ -20,9 +37,11 @@
20
37
  *
21
38
  * 命令:
22
39
  * /scene 弹出选择器(当前场景高亮 ●)
23
- * /scene <name> 切换到指定场景(参数 Tab 补全:/scene c<Tab> → /scene coding)
24
- * /scene off|none 仅保留通用层(关闭场景)
25
- * /scene status 显示当前激活与生效资源
40
+ * /scene <name> 切换到指定场景(默认项目级;参数 Tab 补全:/scene c<Tab> → /scene coding)
41
+ * /scene <name> --global 切换为全局场景(所有项目生效,≤0.6 语义)
42
+ * /scene off|none 关闭场景(摘两层,仅保留通用层;资产锚点保留)
43
+ * /scene status 显示当前激活与生效资源(项目/全局两级)
44
+ * /scene migrate 把 ≤0.6 遗留的全局场景转为当前项目场景
26
45
  * /scene init 生成模板 scenes.json 与场景 skill 目录骨架
27
46
  * /scene stats 用量仪表盘(会话数/工具调用/反思评分/未纳管观察)
28
47
  * /scene evolve 生成进化提案并逐条确认应用(备份 + 热重载)
@@ -40,13 +59,17 @@
40
59
  *
41
60
  * 文件:
42
61
  * ~/.pi/agent/scenes.json 场景定义(用户编辑;含 evolve 阈值配置)
43
- * ~/.pi/agent/scenes-state.json 激活状态 + managed 追踪(本扩展维护)
62
+ * ~/.pi/agent/scenes-state.json 全局层激活状态 + managed 追踪(本扩展维护)
44
63
  * ~/.pi/agent/scenes-usage.json 用量记账与自进化数据(本扩展维护)
45
- * ~/.pi/agent/settings.json pi 全局设置(仅动 packages/skills 两个数组)
46
- * ~/.pi/agent/scenes/<名>/skills 各场景专属 skill 目录(约定,可自由改路径)
64
+ * ~/.pi/agent/settings.json pi 全局设置(资产层:npm 扩展 + 锚点 + common skills)
65
+ * ~/.pi/agent/scenes/<名>/skills 全局场景 skill 目录(--global 模式与 vendor 源)
66
+ * <cwd>/.pi/settings.json 项目设置(激活层:delta 条目 + 场景 skills 相对路径)
67
+ * <cwd>/.pi/scenes-state.json 项目层激活状态 + managed 追踪(本扩展维护)
68
+ * <cwd>/.pi/scenes/<名>/skills 项目场景 skill 目录(vendor 复制目标)
47
69
  *
48
70
  * 环境变量:
49
- * PI_SCENES_DIR 覆盖基目录(默认 ~/.pi/agent,测试用)
71
+ * PI_SCENES_DIR 覆盖全局基目录(默认 ~/.pi/agent,测试用)
72
+ * PI_SCENES_PROJECT_DIR 覆盖项目基目录(默认 <cwd>/.pi,测试用)
50
73
  */
51
74
  import fs from "node:fs";
52
75
  import path from "node:path";
@@ -69,6 +92,9 @@ export interface SceneDef {
69
92
  packages?: PackageEntry[];
70
93
  /** skill 文件/目录路径,支持 ~ 前缀 */
71
94
  skills?: string[];
95
+ /** prompt 模板文件/目录路径(.md),支持 ~ 前缀;经 resources_discover 动态注入,不落 settings。
96
+ * 同名时优先级低于用户手写模板(~/.pi/agent/prompts、项目 .pi/prompts)与包模板 */
97
+ prompts?: string[];
72
98
  }
73
99
 
74
100
  export interface EvolveConfig {
@@ -114,6 +140,13 @@ export interface SceneState {
114
140
  active: string | null;
115
141
  /** 本扩展注入 settings 的条目(切走时精确摘除) */
116
142
  managed: { packages: PackageEntry[]; skills: string[] };
143
+ /** v0.7 资产锚点(git 包 {source, autoload:false, skills:[]}):零暴露 + 共享全局
144
+ * 克隆;off/切换不摘,让下次切换零下载秒切。仅全局层 state 使用。 */
145
+ anchors?: PackageEntry[];
146
+ /** state 结构版本:2 = v0.7+ 双层模型;缺省 = ≤0.6 遗留(全局场景模式) */
147
+ version?: number;
148
+ /** ≤0.6 遗留全局场景的迁移提示是否已弹过(仅全局层 state 使用) */
149
+ migrateNotified?: boolean;
117
150
  }
118
151
 
119
152
  export interface ApplyResult {
@@ -388,12 +421,18 @@ export interface CorePaths {
388
421
  stateFile: string;
389
422
  usageFile: string;
390
423
  settingsFile: string;
391
- scenesRoot: string; // ~/.pi/agent/scenes(场景 skill 目录约定根)
424
+ scenesRoot: string; // ~/.pi/agent/scenes(全局场景 skill 目录约定根)
392
425
  npmDir: string; // ~/.pi/agent/npm
393
426
  gitRoot: string; // ~/.pi/agent/git
427
+ // v0.7 项目层(激活层)
428
+ projectDir: string; // <cwd>/.pi
429
+ projectSettingsFile: string; // <cwd>/.pi/settings.json
430
+ projectStateFile: string; // <cwd>/.pi/scenes-state.json
431
+ projectScenesRoot: string; // <cwd>/.pi/scenes
394
432
  }
395
433
 
396
- export function makeCore(baseDir: string) {
434
+ export function makeCore(baseDir: string, projectDir?: string) {
435
+ const projDir = projectDir || process.env.PI_SCENES_PROJECT_DIR || path.join(process.cwd(), ".pi");
397
436
  const paths: CorePaths = {
398
437
  baseDir,
399
438
  scenesFile: path.join(baseDir, "scenes.json"),
@@ -403,6 +442,10 @@ export function makeCore(baseDir: string) {
403
442
  scenesRoot: path.join(baseDir, "scenes"),
404
443
  npmDir: path.join(baseDir, "npm"),
405
444
  gitRoot: path.join(baseDir, "git"),
445
+ projectDir: projDir,
446
+ projectSettingsFile: path.join(projDir, "settings.json"),
447
+ projectStateFile: path.join(projDir, "scenes-state.json"),
448
+ projectScenesRoot: path.join(projDir, "scenes"),
406
449
  };
407
450
 
408
451
  function loadScenes(): ScenesFile {
@@ -413,21 +456,48 @@ export function makeCore(baseDir: string) {
413
456
  writeJson(paths.scenesFile, cfg);
414
457
  }
415
458
 
416
- function loadState(): SceneState {
417
- const s = readJson<Partial<SceneState>>(paths.stateFile, {});
459
+ function loadStateFrom(file: string): SceneState {
460
+ const s = readJson<Partial<SceneState>>(file, {});
418
461
  return {
419
462
  active: s.active ?? null,
420
463
  managed: {
421
464
  packages: Array.isArray(s.managed?.packages) ? s.managed!.packages : [],
422
465
  skills: Array.isArray(s.managed?.skills) ? s.managed!.skills : [],
423
466
  },
467
+ anchors: Array.isArray(s.anchors) ? s.anchors : [],
468
+ version: s.version,
469
+ migrateNotified: s.migrateNotified,
424
470
  };
425
471
  }
426
472
 
427
- function saveState(st: SceneState): void {
473
+ /** 全局层状态(v0.6 及之前唯一的状态文件;loadState 为其兼容别名) */
474
+ function loadUserState(): SceneState {
475
+ return loadStateFrom(paths.stateFile);
476
+ }
477
+
478
+ function saveUserState(st: SceneState): void {
428
479
  writeJson(paths.stateFile, st);
429
480
  }
430
481
 
482
+ /** 项目层状态(v0.7 激活层) */
483
+ function loadProjectState(): SceneState {
484
+ return loadStateFrom(paths.projectStateFile);
485
+ }
486
+
487
+ function saveProjectState(st: SceneState): void {
488
+ writeJson(paths.projectStateFile, st);
489
+ }
490
+
491
+ /** 生效激活:项目层优先,其次全局层(两层互斥单激活,但演进/边界下取项目优先) */
492
+ function effectiveActive(): string | null {
493
+ return loadProjectState().active ?? loadUserState().active;
494
+ }
495
+
496
+ /** 生效激活的落层 */
497
+ function effectiveScope(): "project" | "user" {
498
+ return loadProjectState().active ? "project" : "user";
499
+ }
500
+
431
501
  function loadUsage(): UsageFile {
432
502
  const u = readJson<Partial<UsageFile>>(paths.usageFile, {});
433
503
  return {
@@ -445,7 +515,7 @@ export function makeCore(baseDir: string) {
445
515
 
446
516
  /** 解析场景(沿 extends 链 union 合并,带环检测)——主场景/子场景的落点 */
447
517
  function resolveScene(name: string, cfg: ScenesFile): SceneDef {
448
- const merged: SceneDef = { packages: [], skills: [] };
518
+ const merged: SceneDef = { packages: [], skills: [], prompts: [] };
449
519
  const seen = new Set<string>();
450
520
  let cur: string | null = name;
451
521
  while (cur) {
@@ -455,6 +525,7 @@ export function makeCore(baseDir: string) {
455
525
  if (!def) throw new Error(`场景不存在:${cur}`);
456
526
  merged.packages = dedupeEntries([...(merged.packages ?? []), ...(def.packages ?? [])]);
457
527
  merged.skills = [...new Set([...(merged.skills ?? []), ...(def.skills ?? [])])];
528
+ merged.prompts = [...new Set([...(merged.prompts ?? []), ...(def.prompts ?? [])])];
458
529
  if (def.description && !merged.description) merged.description = def.description;
459
530
  cur = def.extends ?? null;
460
531
  }
@@ -467,14 +538,20 @@ export function makeCore(baseDir: string) {
467
538
  return out;
468
539
  }
469
540
 
470
- /** 生效集合 = 通用层 ∪ 场景链(skills 展开 ~,去重) */
471
- function computeTarget(active: string | null, cfg: ScenesFile): { packages: PackageEntry[]; skills: string[] } {
541
+ /** 生效集合 = 通用层 ∪ 场景链(skills 展开 ~,去重;拆分 common/scene 归属供双层落点) */
542
+ function computeTarget(
543
+ active: string | null,
544
+ cfg: ScenesFile,
545
+ ): { packages: PackageEntry[]; skills: string[]; commonSkills: string[]; sceneSkills: string[]; prompts: string[] } {
472
546
  const common = cfg.common ?? {};
473
547
  let scene: SceneDef = {};
474
548
  if (active) scene = resolveScene(active, cfg);
475
549
  const packages = dedupeByIdentity(dedupeEntries([...(common.packages ?? []), ...(scene.packages ?? [])]));
476
- const skills = [...new Set([...(common.skills ?? []), ...(scene.skills ?? [])].map(expandHome))];
477
- return { packages, skills };
550
+ const commonSkills = [...new Set([...(common.skills ?? [])].map(expandHome))];
551
+ const sceneSkills = [...new Set([...(scene.skills ?? [])].map(expandHome))];
552
+ const skills = [...new Set([...commonSkills, ...sceneSkills])];
553
+ const prompts = [...new Set([...(common.prompts ?? []), ...(scene.prompts ?? [])].map(expandHome))];
554
+ return { packages, skills, commonSkills, sceneSkills, prompts };
478
555
  }
479
556
 
480
557
  /** 包是否已安装(探测 npm 目录 / git clone 目录 / 本地路径) */
@@ -494,105 +571,231 @@ export function makeCore(baseDir: string) {
494
571
  return false;
495
572
  }
496
573
 
574
+ /** object form 带资源过滤字段(git 多技能包)判定:项目层 delta 候选 */
575
+ function isFilteredEntry(e: PackageEntry): boolean {
576
+ if (typeof e !== "object" || e === null) return false;
577
+ return ["skills", "extensions", "prompts", "themes"].some((k) => Array.isArray((e as Record<string, unknown>)[k]));
578
+ }
579
+
580
+ /** 场景 skill 路径 → 项目层映射:全局 scenesRoot 下的路径转项目相对(相对 <cwd>/.pi 解析),
581
+ * 其余(用户自定义绝对/~ 路径)原样写入项目 settings */
582
+ function mapSceneSkillToProject(p: string): { entry: string; dir?: string; globalDir?: string } {
583
+ const scenesRootAbs = expandHome(paths.scenesRoot);
584
+ const abs = expandHome(p);
585
+ if (abs === scenesRootAbs || abs.startsWith(scenesRootAbs + path.sep)) {
586
+ const rel = path.relative(scenesRootAbs, abs); // e.g. "coding/skills"
587
+ return {
588
+ entry: path.posix.join("scenes", rel.split(path.sep).join("/")),
589
+ dir: path.join(paths.projectScenesRoot, rel),
590
+ globalDir: abs,
591
+ };
592
+ }
593
+ return { entry: p };
594
+ }
595
+
596
+ /** 幂等复制目录内容(仅复制目标缺失项,不覆盖用户已有):返回复制文件数 */
597
+ function copyTreeIfMissing(src: string, dst: string): number {
598
+ let st: fs.Stats;
599
+ try {
600
+ st = fs.statSync(src);
601
+ } catch {
602
+ return 0;
603
+ }
604
+ if (!st.isDirectory()) return 0;
605
+ fs.mkdirSync(dst, { recursive: true });
606
+ let n = 0;
607
+ for (const e of fs.readdirSync(src, { withFileTypes: true })) {
608
+ const s = path.join(src, e.name);
609
+ const d = path.join(dst, e.name);
610
+ if (fs.existsSync(d)) continue;
611
+ if (e.isDirectory()) n += copyTreeIfMissing(s, d);
612
+ else {
613
+ fs.copyFileSync(s, d);
614
+ n++;
615
+ }
616
+ }
617
+ return n;
618
+ }
619
+
497
620
  /**
498
- * 把目标集合落进 settings.json:
499
- * 1. 摘掉 state.managed 里的旧条目(精确匹配)
500
- * 2. 追加目标中原本不存在的条目,记入新 managed
621
+ * 把目标集合落进 settings(v0.7 双层):
622
+ * 1. 摘掉两层 state.managed 里的旧条目(精确匹配;两层互斥单激活)
623
+ * 2. 按层落点追加(项目层 filtered 条目加 autoload:false 转 delta;全局层
624
+ * 补资产锚点;场景 scaffold skills 映射为项目相对路径 + 幂等复制 vendor 资产)
501
625
  * 3. preInstallPackages = 安装缺失包动作之前的快照;
502
626
  * pi install 会自己往 settings 写条目,diff 出来的(在目标集合内的)也归 managed
503
- * 返回统计。settings.json 先备份再原子写。
627
+ * 返回统计。两份 settings.json 先备份再原子写。
628
+ *
629
+ * scope:"project"(默认项目级,v0.7 产品语义)| "user"(--global,≤0.6 兼容语义)。
630
+ * 为向后兼容旧调用(三参),签名默认值取 "user";命令层显式传 scope。
504
631
  */
505
632
  function applyToSettings(
506
- target: { packages: PackageEntry[]; skills: string[] },
633
+ target: { packages: PackageEntry[]; skills: string[]; commonSkills?: string[]; sceneSkills?: string[] },
507
634
  active: string | null,
508
635
  preInstallPackages: PackageEntry[] | undefined,
636
+ scope: "user" | "project" = "user",
509
637
  ): ApplyResult {
510
- const settings = readJson<Record<string, unknown>>(paths.settingsFile, {});
511
- const oldPkgs = Array.isArray(settings.packages) ? (settings.packages as PackageEntry[]) : [];
512
- const oldSkills = Array.isArray(settings.skills) ? (settings.skills as string[]) : [];
513
- const prevManaged = loadState().managed;
514
-
515
- // 1) 摘旧
516
- let pkgs = removeFrom(oldPkgs, prevManaged.packages);
517
- let skills = removeFrom(oldSkills, prevManaged.skills);
638
+ const useProject = scope === "project";
639
+ const sceneSkills = target.sceneSkills ?? [];
640
+ const userSettings = readJson<Record<string, unknown>>(paths.settingsFile, {});
641
+ const projSettings = readJson<Record<string, unknown>>(paths.projectSettingsFile, {});
642
+ const oldUserPkgs = Array.isArray(userSettings.packages) ? (userSettings.packages as PackageEntry[]) : [];
643
+ const oldUserSkills = Array.isArray(userSettings.skills) ? (userSettings.skills as string[]) : [];
644
+ const oldProjPkgs = Array.isArray(projSettings.packages) ? (projSettings.packages as PackageEntry[]) : [];
645
+ const oldProjSkills = Array.isArray(projSettings.skills) ? (projSettings.skills as string[]) : [];
646
+ const prevUser = loadUserState();
647
+ const prevProj = loadProjectState();
648
+
649
+ // 1) 摘旧:两层 managed 都摘(互斥单激活;资产锚点 anchors 不摘)
650
+ let userPkgs = removeFrom(oldUserPkgs, prevUser.managed.packages);
651
+ let userSkills = removeFrom(oldUserSkills, prevUser.managed.skills);
652
+ let projPkgs = removeFrom(oldProjPkgs, prevProj.managed.packages);
653
+ let projSkills = removeFrom(oldProjSkills, prevProj.managed.skills);
654
+ let anchors = prevUser.anchors ?? [];
655
+ // 全局模式:目标 filtered 条目替换同包锚点(sameEntry 精确匹配锚点写法,
656
+ // 不碰用户手配的同包裸 spec —— 后者走 borrowed 语义保留)
657
+ if (!useProject) {
658
+ for (const a of [...anchors]) {
659
+ if (!target.packages.some((t) => isFilteredEntry(t) && sameResource(t, a))) continue;
660
+ userPkgs = userPkgs.filter((x) => !sameEntry(x, a));
661
+ anchors = anchors.filter((x) => x !== a);
662
+ }
663
+ }
518
664
 
519
- // 2) 补新(用户已手配的视为 borrowed,不纳管)
520
665
  const result: ApplyResult = {
521
666
  addedPackages: [],
522
667
  addedSkills: [],
523
- removedPackages: oldPkgs.filter((p) => !pkgs.some((x) => sameEntry(x, p))),
524
- removedSkills: oldSkills.filter((s) => !skills.includes(s)),
668
+ removedPackages: [...oldUserPkgs.filter((p) => !userPkgs.some((x) => sameEntry(x, p))), ...oldProjPkgs.filter((p) => !projPkgs.some((x) => sameEntry(x, p)))],
669
+ removedSkills: [...oldUserSkills.filter((s) => !userSkills.includes(s)), ...oldProjSkills.filter((s) => !projSkills.includes(s))],
525
670
  borrowedPackages: [],
526
671
  borrowedSkills: [],
527
672
  };
528
- const newManagedPkgs: PackageEntry[] = [];
529
- for (const e of target.packages) {
530
- if (pkgs.some((x) => sameEntry(x, e))) {
531
- // 已存在:若来自 pi install 在本次切换中的写入(preInstall 快照里没有)→ 纳管
532
- const inPre = (preInstallPackages ?? oldPkgs).some((x) => sameEntry(x, e));
533
- if (!inPre) newManagedPkgs.push(e);
673
+
674
+ // 2) 补新:包条目按层落点
675
+ const newUserManagedPkgs: PackageEntry[] = [];
676
+ const newProjManagedPkgs: PackageEntry[] = [];
677
+ for (const raw of target.packages) {
678
+ // 项目模式下 filtered 条目 → delta 形态(autoload:false 复用全局克隆 + 白名单启用)
679
+ const e: PackageEntry = useProject && isFilteredEntry(raw) ? { ...(raw as Record<string, unknown>), autoload: false } : raw;
680
+ const landed = useProject && isFilteredEntry(raw);
681
+ let pkgsRef = landed ? projPkgs : userPkgs;
682
+ const sink = landed ? newProjManagedPkgs : newUserManagedPkgs;
683
+ const preList = preInstallPackages ?? (landed ? oldProjPkgs : oldUserPkgs);
684
+ if (pkgsRef.some((x) => sameEntry(x, e))) {
685
+ // 已存在:若来自 pi install 在本次切换中的写入(pre 快照里没有)→ 纳管
686
+ const inPre = preList.some((x) => sameEntry(x, e));
687
+ if (!inPre) sink.push(e);
534
688
  else result.borrowedPackages.push(e);
535
- } else if (typeof e === "object" && e !== null && pkgs.some((x) => sameResource(x, e))) {
689
+ } else if (typeof e === "object" && e !== null && pkgsRef.some((x) => sameResource(x, e))) {
536
690
  // 目标是对象形态(带 skills/extensions 等资源过滤),现存的同包条目是裸 spec:
537
- // - 裸 spec 是 pi install 在本次切换中刚写入的(不在 preInstall 快照里)→ 替换为对象形态,
691
+ // - 裸 spec 是 pi install 在本次切换中刚写入的(不在 pre 快照里)→ 替换为对象形态,
538
692
  // 否则 anthropics/skills 这类多技能包会全量加载,场景级裁剪失效;
539
693
  // - 裸 spec 是用户先前手配的(在快照里)→ 尊重用户全局选择,视为借用。
540
- const preExisting = (preInstallPackages ?? oldPkgs).some((x) => sameResource(x, e));
694
+ const preExisting = preList.some((x) => sameResource(x, e));
541
695
  if (!preExisting) {
542
- pkgs = pkgs.filter((x) => !sameResource(x, e));
543
- pkgs.push(e);
544
- newManagedPkgs.push(e);
696
+ if (landed) {
697
+ projPkgs = projPkgs.filter((x) => !sameResource(x, e));
698
+ pkgsRef = projPkgs;
699
+ } else {
700
+ userPkgs = userPkgs.filter((x) => !sameResource(x, e));
701
+ pkgsRef = userPkgs;
702
+ }
703
+ pkgsRef.push(e);
704
+ sink.push(e);
545
705
  result.addedPackages.push(e);
546
706
  } else {
547
707
  result.borrowedPackages.push(e);
548
708
  }
549
- } else if (pkgs.some((x) => sameResource(x, e))) {
709
+ } else if (pkgsRef.some((x) => sameResource(x, e))) {
550
710
  // 同包不同写法(如用户手动 pin 了版本):视为借用,避免重复注入与重复加载
551
711
  result.borrowedPackages.push(e);
552
712
  } else {
553
- pkgs.push(e);
554
- newManagedPkgs.push(e);
713
+ pkgsRef.push(e);
714
+ sink.push(e);
555
715
  result.addedPackages.push(e);
556
716
  }
717
+ // 项目层 delta 落地 → 全局层确保资产锚点(零暴露 + 共享全局克隆的 delta base)
718
+ if (landed) {
719
+ const anchor: PackageEntry = { source: specOf(raw), autoload: false, skills: [] };
720
+ const anchored = userPkgs.some((x) => sameResource(x, raw)) || anchors.some((a) => sameResource(a, anchor));
721
+ if (!anchored) {
722
+ userPkgs.push(anchor);
723
+ anchors.push(anchor);
724
+ }
725
+ }
557
726
  }
558
- const newManagedSkills: string[] = [];
727
+
728
+ // skills 按层落点:场景 scaffold 目录(项目模式)映射为项目相对路径 + 幂等复制 vendor
729
+ const newUserManagedSkills: string[] = [];
730
+ const newProjManagedSkills: string[] = [];
559
731
  for (const s of target.skills) {
560
- if (skills.includes(s)) {
561
- result.borrowedSkills.push(s);
732
+ const isSceneSkill = sceneSkills.includes(s);
733
+ if (useProject && isSceneSkill) {
734
+ const m = mapSceneSkillToProject(s);
735
+ if (projSkills.includes(m.entry)) {
736
+ result.borrowedSkills.push(m.entry);
737
+ } else {
738
+ projSkills.push(m.entry);
739
+ newProjManagedSkills.push(m.entry);
740
+ result.addedSkills.push(m.entry);
741
+ }
742
+ // vendor 资产:全局 scaffold 目录 → 项目目录(幂等,不覆盖用户已有)
743
+ if (m.dir && m.globalDir) copyTreeIfMissing(m.globalDir, m.dir);
562
744
  } else {
563
- skills.push(s);
564
- newManagedSkills.push(s);
565
- result.addedSkills.push(s);
745
+ if (userSkills.includes(s)) {
746
+ result.borrowedSkills.push(s);
747
+ } else {
748
+ userSkills.push(s);
749
+ newUserManagedSkills.push(s);
750
+ result.addedSkills.push(s);
751
+ }
566
752
  }
567
753
  }
568
754
 
569
- // 3) 落盘:备份 → 原子写
570
- if (fs.existsSync(paths.settingsFile)) {
571
- fs.copyFileSync(paths.settingsFile, `${paths.settingsFile}.scenes-bak`);
755
+ // 3) 落盘:备份 → 原子写(两层)
756
+ for (const f of [paths.settingsFile, paths.projectSettingsFile]) {
757
+ if (fs.existsSync(f)) fs.copyFileSync(f, `${f}.scenes-bak`);
572
758
  }
573
- settings.packages = pkgs;
574
- settings.skills = skills;
575
- writeJson(paths.settingsFile, settings);
576
-
577
- saveState({ active, managed: { packages: newManagedPkgs, skills: newManagedSkills } });
759
+ userSettings.packages = userPkgs;
760
+ userSettings.skills = userSkills;
761
+ writeJson(paths.settingsFile, userSettings);
762
+ projSettings.packages = projPkgs;
763
+ projSettings.skills = projSkills;
764
+ writeJson(paths.projectSettingsFile, projSettings);
765
+
766
+ saveUserState({
767
+ active: useProject ? null : active,
768
+ managed: { packages: newUserManagedPkgs, skills: newUserManagedSkills },
769
+ anchors,
770
+ version: 2,
771
+ });
772
+ saveProjectState({
773
+ active: useProject ? active : null,
774
+ managed: { packages: newProjManagedPkgs, skills: newProjManagedSkills },
775
+ version: 2,
776
+ });
578
777
  return result;
579
778
  }
580
779
 
780
+ // v0.6 兼容别名:loadState/saveState = 全局层(既有测试引用面不变)
781
+ const loadState = loadUserState;
782
+ const saveState = saveUserState;
783
+
581
784
  /** 用量记账:新会话开始(session_file 变化才计数;reload 同文件不重复计) */
582
785
  function beginSession(sessionFile: string | null, settingsPackages: PackageEntry[] | undefined): void {
583
- const st = loadState();
786
+ const active = effectiveActive();
584
787
  const usage = loadUsage();
585
788
  const file = sessionFile ?? "ephemeral";
586
789
  if (usage._current?.file === file) return;
587
790
  const now = new Date().toISOString();
588
- if (st.active) {
589
- const s = (usage.perScene[st.active] ??= { sessions: 0, lastActive: now });
791
+ if (active) {
792
+ const s = (usage.perScene[active] ??= { sessions: 0, lastActive: now });
590
793
  s.sessions += 1;
591
794
  s.lastActive = now;
592
795
  }
593
796
  // 未纳管观察:在 settings 但不在 target 且不在任何场景定义 → 吸收候选
594
797
  const cfg = loadScenes();
595
- const target = computeTarget(st.active, cfg);
798
+ const target = computeTarget(active, cfg);
596
799
  const definedAnywhere: PackageEntry[] = [
597
800
  ...(cfg.common?.packages ?? []),
598
801
  ...Object.values(cfg.scenes ?? {}).flatMap((d) => d.packages ?? []),
@@ -604,9 +807,9 @@ export function makeCore(baseDir: string) {
604
807
  const u = (usage.unmanagedSeen[key] ??= { count: 0, lastSeen: now, scenes: [] });
605
808
  u.count += 1;
606
809
  u.lastSeen = now;
607
- if (st.active && !u.scenes.includes(st.active)) u.scenes.push(st.active);
810
+ if (active && !u.scenes.includes(active)) u.scenes.push(active);
608
811
  }
609
- usage._current = { file, scene: st.active, seen: [] };
812
+ usage._current = { file, scene: active, seen: [] };
610
813
  saveUsage(usage);
611
814
  }
612
815
 
@@ -614,9 +817,8 @@ export function makeCore(baseDir: string) {
614
817
  function recordToolUse(toolName: string, toolMap: Map<string, string>): boolean {
615
818
  const pkg = toolMap.get(toolName);
616
819
  if (!pkg) return false;
617
- const st = loadState();
618
820
  const cfg = loadScenes();
619
- const target = computeTarget(st.active, cfg);
821
+ const target = computeTarget(effectiveActive(), cfg);
620
822
  const entry = target.packages.find((e) => packageIdentity(e).includes(pkg));
621
823
  if (!entry) return false;
622
824
  const key = canonical(entry);
@@ -631,9 +833,8 @@ export function makeCore(baseDir: string) {
631
833
 
632
834
  /** 反思记账:skill 子项有用/无用计数,用到则父目录条目标记 seen(重置 streak) */
633
835
  function recordReflection(used: string[], unused: string[]): void {
634
- const st = loadState();
635
836
  const cfg = loadScenes();
636
- const target = computeTarget(st.active, cfg);
837
+ const target = computeTarget(effectiveActive(), cfg);
637
838
  const usage = loadUsage();
638
839
  const now = new Date().toISOString();
639
840
  const markParent = (id: string) => {
@@ -658,9 +859,8 @@ export function makeCore(baseDir: string) {
658
859
  /** 会话结束:结算 absentStreak(reload 不结算,会话仍在继续) */
659
860
  function endSession(reason: string): void {
660
861
  if (reason === "reload") return;
661
- const st = loadState();
662
862
  const cfg = loadScenes();
663
- const target = computeTarget(st.active, cfg);
863
+ const target = computeTarget(effectiveActive(), cfg);
664
864
  const usage = loadUsage();
665
865
  const seen = usage._current?.seen ?? [];
666
866
  const keys = [...target.packages.map((e) => canonical(e)), ...target.skills];
@@ -797,6 +997,7 @@ export function makeCore(baseDir: string) {
797
997
  "npm:pi-carryover", // 跨会话工作承接(上次干到哪、下次接着干)
798
998
  ],
799
999
  skills: ["~/.pi/agent/scenes/common/skills"],
1000
+ prompts: ["~/.pi/agent/scenes/common/prompts"],
800
1001
  },
801
1002
  scenes: {
802
1003
  coding: {
@@ -817,6 +1018,7 @@ export function makeCore(baseDir: string) {
817
1018
  },
818
1019
  ],
819
1020
  skills: ["~/.pi/agent/scenes/coding/skills"],
1021
+ prompts: ["~/.pi/agent/scenes/coding/prompts"], // scaffold 预置 pre-commit 提交前自检
820
1022
  },
821
1023
  office: {
822
1024
  description: "办公:文档解析与生成、内部沟通",
@@ -829,6 +1031,7 @@ export function makeCore(baseDir: string) {
829
1031
  },
830
1032
  ],
831
1033
  skills: ["~/.pi/agent/scenes/office/skills"],
1034
+ prompts: ["~/.pi/agent/scenes/office/prompts"], // scaffold 预置 doc-from-notes 笔记成文
832
1035
  },
833
1036
  pm: {
834
1037
  description: "产品经理:竞品调研、目标规划与需求跟踪",
@@ -840,6 +1043,7 @@ export function makeCore(baseDir: string) {
840
1043
  "npm:@juicesharp/rpiv-ask-user-question", // 结构化提问:类型化选项代替自由猜测(需求澄清)
841
1044
  ],
842
1045
  skills: ["~/.pi/agent/scenes/pm/skills"],
1046
+ prompts: ["~/.pi/agent/scenes/pm/prompts"], // scaffold 预置 prd-skeleton 需求骨架
843
1047
  },
844
1048
  research: {
845
1049
  description: "咨询调研:多源检索、并行多角度深挖、学术文献",
@@ -849,6 +1053,7 @@ export function makeCore(baseDir: string) {
849
1053
  "npm:pi-subagents", // 多角度并行调研(每个子代理一源)
850
1054
  ],
851
1055
  skills: ["~/.pi/agent/scenes/research/skills"], // scaffold 预置 arxiv-research / openalex-paper-search
1056
+ prompts: ["~/.pi/agent/scenes/research/prompts"], // scaffold 预置 deep-dive 深度调研
852
1057
  },
853
1058
  writing: {
854
1059
  description: "写作:素材检索、事实核查、文体打磨",
@@ -861,6 +1066,7 @@ export function makeCore(baseDir: string) {
861
1066
  },
862
1067
  ],
863
1068
  skills: ["~/.pi/agent/scenes/writing/skills"], // scaffold 预置 humanizer
1069
+ prompts: ["~/.pi/agent/scenes/writing/prompts"], // scaffold 预置 fact-check 事实核查
864
1070
  },
865
1071
  data: {
866
1072
  description: "数据分析:表格抽取、MCP 接数据库/BI",
@@ -870,6 +1076,7 @@ export function makeCore(baseDir: string) {
870
1076
  "npm:pi-mcp-adapter", // 接任意 MCP server(数据库/BI/内部数据服务)
871
1077
  ],
872
1078
  skills: ["~/.pi/agent/scenes/data/skills"],
1079
+ prompts: ["~/.pi/agent/scenes/data/prompts"], // scaffold 预置 data-audit 数据审计
873
1080
  },
874
1081
  },
875
1082
  };
@@ -878,10 +1085,12 @@ export function makeCore(baseDir: string) {
878
1085
  created.push(paths.scenesFile);
879
1086
  }
880
1087
  for (const s of ["common", "coding", "office", "pm", "research", "writing", "data"]) {
881
- const dir = path.join(paths.scenesRoot, s, "skills");
882
- if (!fs.existsSync(dir)) {
883
- fs.mkdirSync(dir, { recursive: true });
884
- created.push(dir);
1088
+ for (const kind of ["skills", "prompts"] as const) {
1089
+ const dir = path.join(paths.scenesRoot, s, kind);
1090
+ if (!fs.existsSync(dir)) {
1091
+ fs.mkdirSync(dir, { recursive: true });
1092
+ created.push(dir);
1093
+ }
885
1094
  }
886
1095
  }
887
1096
  // 预置精选技能:从包内 assets/scene-skills/<场景>/ 复制到场景 skill 目录。
@@ -902,6 +1111,17 @@ export function makeCore(baseDir: string) {
902
1111
  }
903
1112
  }
904
1113
  }
1114
+ // v0.8:预置场景模板 assets/scene-prompts/<场景>/*.md → scenes/<场景>/prompts/(幂等复制,不覆盖用户已有)
1115
+ const promptsAssetsRoot = path.join(pkgRoot, "assets", "scene-prompts");
1116
+ if (fs.existsSync(promptsAssetsRoot)) {
1117
+ for (const scene of fs.readdirSync(promptsAssetsRoot)) {
1118
+ const srcScene = path.join(promptsAssetsRoot, scene);
1119
+ if (!fs.statSync(srcScene).isDirectory()) continue;
1120
+ const dst = path.join(paths.scenesRoot, scene, "prompts");
1121
+ const copied = copyTreeIfMissing(srcScene, dst);
1122
+ if (copied > 0) created.push(dst);
1123
+ }
1124
+ }
905
1125
  } catch {
906
1126
  // 资产复制失败不阻断 scaffold(如测试环境无 assets)
907
1127
  }
@@ -914,6 +1134,12 @@ export function makeCore(baseDir: string) {
914
1134
  saveScenes,
915
1135
  loadState,
916
1136
  saveState,
1137
+ loadUserState,
1138
+ saveUserState,
1139
+ loadProjectState,
1140
+ saveProjectState,
1141
+ effectiveActive,
1142
+ effectiveScope,
917
1143
  loadUsage,
918
1144
  saveUsage,
919
1145
  resolveScene,
@@ -942,21 +1168,20 @@ export default function (pi: ExtensionAPI) {
942
1168
  const core = makeCore(baseDir);
943
1169
 
944
1170
  /**
945
- * 状态栏常驻场景徽标(<icon> <场景名>):切换后用户始终知道自己在哪个场景。
946
- * 前缀可由 scenes.json 每场景 icon 字段定制(建议 emoji),缺省 ◆。
947
- * 设计动机:场景切换器在界面上只弹一次 notify 就消失了,用户无从得知当前场景;
948
- * 而场景附带的工具型扩展(如 pi-lens)的状态栏内脏反而在抢占视觉 ——
949
- * 状态栏应该回答“我在哪”,而不是“工具的内部状态”。
950
- * off(仅通用层)时清除;session_start 时幂等重放(重启 pi 后恢复)。
1171
+ * 状态栏常驻场景徽标:项目场景 ◆ <名>(默认层级);全局场景 ◇ <名> ⌘(--global)。
1172
+ * 切换后用户始终知道自己在哪个场景、哪一层。off 时清除;
1173
+ * session_start 时幂等重放(重启 pi 后恢复)。
951
1174
  */
952
1175
  function updateSceneBadge(ctx: any): void {
953
1176
  try {
954
1177
  const ui = ctx?.ui;
955
1178
  if (!ui || typeof ui.setStatus !== "function") return;
956
- const active = core.loadState().active;
1179
+ const proj = core.loadProjectState().active;
1180
+ const user = core.loadUserState().active;
1181
+ const active = proj ?? user;
957
1182
  if (active) {
958
- const icon = core.loadScenes().scenes?.[active]?.icon?.trim() || "◆";
959
- const text = `${icon} ${active}`;
1183
+ const icon = core.loadScenes().scenes?.[active]?.icon?.trim() || (proj ? "◆" : "◇");
1184
+ const text = `${icon} ${active}${proj ? "" : " ⌘"}`;
960
1185
  ui.setStatus("pi-scene", ui.theme?.fg ? ui.theme.fg("accent", text) : text);
961
1186
  } else {
962
1187
  ui.setStatus("pi-scene", undefined);
@@ -964,14 +1189,27 @@ export default function (pi: ExtensionAPI) {
964
1189
  } catch {}
965
1190
  }
966
1191
 
967
- /** 执行切换(name=null 表示仅通用层) */
968
- async function doSwitch(ctx: any, name: string | null): Promise<void> {
1192
+ /** 读两层 settings 的 packages(供缺失判定与冲突检测) */
1193
+ function readAllSettingsPackages(): { user: PackageEntry[]; project: PackageEntry[] } {
1194
+ const u = readJson<Record<string, unknown>>(core.paths.settingsFile, {});
1195
+ const p = readJson<Record<string, unknown>>(core.paths.projectSettingsFile, {});
1196
+ return {
1197
+ user: Array.isArray(u.packages) ? (u.packages as PackageEntry[]) : [],
1198
+ project: Array.isArray(p.packages) ? (p.packages as PackageEntry[]) : [],
1199
+ };
1200
+ }
1201
+
1202
+ /** 执行切换(name=null 表示仅通用层;scope=project 项目级默认 / user 全局) */
1203
+ async function doSwitch(ctx: any, name: string | null, scope: "user" | "project"): Promise<void> {
969
1204
  const cfg = core.loadScenes();
970
1205
  if (name && !cfg.scenes?.[name]) {
971
1206
  ctx.ui.notify(`场景不存在:${name}(可用:${Object.keys(cfg.scenes ?? {}).join(", ") || "无"})`, "error");
972
1207
  return;
973
1208
  }
974
- const label = name ? `「${name}」${cfg.scenes?.[name]?.description ? ` — ${cfg.scenes[name].description}` : ""}` : "仅通用层";
1209
+ const scopeLabel = scope === "project" ? "(项目级,仅当前目录生效)" : "(全局,所有项目生效)";
1210
+ const label = name
1211
+ ? `「${name}」${cfg.scenes?.[name]?.description ? ` — ${cfg.scenes[name].description}` : ""}${scopeLabel}`
1212
+ : `仅通用层${scopeLabel}`;
975
1213
 
976
1214
  const target = core.computeTarget(name, cfg);
977
1215
 
@@ -986,15 +1224,19 @@ export default function (pi: ExtensionAPI) {
986
1224
  );
987
1225
  }
988
1226
 
989
- const prePkgs = (readJson<Record<string, unknown>>(core.paths.settingsFile, {}).packages ?? []) as PackageEntry[];
1227
+ const pre = readAllSettingsPackages();
1228
+ const prePkgs = [...pre.project, ...pre.user];
990
1229
 
991
- // settings 已有同包异写法并存(无论是否本扩展造成):pi 启动会加载同一扩展两份、
992
- // 工具重名冲突退出 —— 先拦截并给出修复指引,避免加重坏状态
993
- const dups = core.findSettingsDuplicates(prePkgs);
1230
+ // settings 层内同包异写法并存(跨层同包是 v0.7 设计内:delta + 锚点):
1231
+ // pi 启动会加载同一扩展两份、工具重名冲突退出 —— 先拦截并给出修复指引
1232
+ const dups = [
1233
+ ...core.findSettingsDuplicates(pre.user).map((d) => ({ ...d, where: "全局" })),
1234
+ ...core.findSettingsDuplicates(pre.project).map((d) => ({ ...d, where: "项目" })),
1235
+ ];
994
1236
  if (dups.length > 0) {
995
1237
  ctx.ui.notify(
996
- `⚠️ settings.json 里同一包存在多种写法并存,pi 启动时会因工具重名冲突而退出,请先手动删除其中一种:\n${dups
997
- .map((d) => ` · ${d.id}: ${d.entries.join(" | ")}`)
1238
+ `⚠️ settings 里同一包存在多种写法并存,pi 启动时会因工具重名冲突而退出,请先手动删除其中一种:\n${dups
1239
+ .map((d) => ` · [${d.where}] ${d.id}: ${d.entries.join(" | ")}`)
998
1240
  .join("\n")}\n修复后再切换场景`,
999
1241
  "error",
1000
1242
  );
@@ -1009,7 +1251,7 @@ export default function (pi: ExtensionAPI) {
1009
1251
  if (missing.length > 0) {
1010
1252
  const ok = await ctx.ui.confirm(
1011
1253
  "场景包未安装",
1012
- `以下 ${missing.length} 个包尚未安装,现在安装吗?\n${missing.map((m) => ` · ${specOf(m)}`).join("\n")}`,
1254
+ `以下 ${missing.length} 个包尚未安装,现在安装吗?(统一装到全局 ~/.pi/agent,所有项目共享缓存)\n${missing.map((m) => ` · ${specOf(m)}`).join("\n")}`,
1013
1255
  );
1014
1256
  if (!ok) {
1015
1257
  ctx.ui.notify("已取消切换(未做任何修改)", "info");
@@ -1023,18 +1265,19 @@ export default function (pi: ExtensionAPI) {
1023
1265
  return;
1024
1266
  }
1025
1267
  }
1026
- const postPkgs = (readJson<Record<string, unknown>>(core.paths.settingsFile, {}).packages ?? []) as PackageEntry[];
1027
- const still = core.findMissingPackages(target.packages, postPkgs);
1268
+ const post = readAllSettingsPackages();
1269
+ const still = core.findMissingPackages(target.packages, [...post.project, ...post.user]);
1028
1270
  if (still.length > 0) {
1029
1271
  ctx.ui.notify(`仍有包未安装:${still.map(specOf).join(", ")},已中止切换`, "error");
1030
1272
  return;
1031
1273
  }
1032
1274
  }
1033
1275
 
1034
- const r = core.applyToSettings(target, name, preInstallPackages);
1276
+ const r = core.applyToSettings(target, name, preInstallPackages, scope);
1035
1277
  updateSceneBadge(ctx);
1278
+ const promptCount = target.prompts.filter((p) => fs.existsSync(p)).length;
1036
1279
  ctx.ui.notify(
1037
- `已切换到 ${label}\n +${r.addedPackages.length} 包 +${r.addedSkills.length} skill · -${r.removedPackages.length} 包 -${r.removedSkills.length} skill\n 正在热重载…`,
1280
+ `已切换到 ${label}\n +${r.addedPackages.length} 包 +${r.addedSkills.length} skill · -${r.removedPackages.length} 包 -${r.removedSkills.length} skill · 模板目录 ${promptCount}/${target.prompts.length}\n 正在热重载…`,
1038
1281
  "info",
1039
1282
  );
1040
1283
  await ctx.reload();
@@ -1054,7 +1297,7 @@ export default function (pi: ExtensionAPI) {
1054
1297
  let active: string | null = null;
1055
1298
  try {
1056
1299
  cfg = core.loadScenes();
1057
- active = core.loadState().active;
1300
+ active = core.effectiveActive();
1058
1301
  } catch {}
1059
1302
  const items: Array<{ value: string; label: string; description?: string }> = [];
1060
1303
  for (const [name, def] of Object.entries(cfg.scenes ?? {})) {
@@ -1063,8 +1306,9 @@ export default function (pi: ExtensionAPI) {
1063
1306
  items.push({ value: name, label: `${icon} ${name}`, description: desc });
1064
1307
  }
1065
1308
  const subs: Array<[string, string]> = [
1066
- ["off", "仅保留通用层(关闭场景)"],
1067
- ["status", "查看当前场景与生效资源"],
1309
+ ["off", "关闭场景(摘两层,仅保留通用层;资产锚点保留)"],
1310
+ ["status", "查看当前场景与生效资源(项目/全局两级)"],
1311
+ ["migrate", "把 ≤0.6 遗留的全局场景转为当前项目场景"],
1068
1312
  ["init", "生成模板 scenes.json 与 skill 骨架"],
1069
1313
  ["stats", "用量仪表盘(会话/工具调用/反思)"],
1070
1314
  ["evolve", "生成并应用进化提案"],
@@ -1084,12 +1328,19 @@ export default function (pi: ExtensionAPI) {
1084
1328
  return `切换场景(空格后 Tab 列出并补全):${names.join("/") || "<name>"}`;
1085
1329
  }
1086
1330
 
1331
+ /** 解析 --global/-g 标志:返回 [是否全局, 去掉标志后的参数] */
1332
+ function parseScopeFlag(arg: string): [boolean, string] {
1333
+ const global = /(?:^|\s)--global(?:\s|$)|(?:^|\s)-g(?:\s|$)/.test(arg);
1334
+ return [global, arg.replace(/\s*(?:--global|-g)\s*/g, " ").trim()];
1335
+ }
1336
+
1087
1337
  const sceneCommand = {
1088
1338
  title: "场景切换",
1089
1339
  description: sceneCommandDescription(),
1090
1340
  getArgumentCompletions: sceneCompletions,
1091
1341
  handler: async (args: string, ctx: any) => {
1092
- const arg = (args ?? "").trim();
1342
+ const [wantGlobal, arg] = parseScopeFlag((args ?? "").trim());
1343
+ const scope: "user" | "project" = wantGlobal ? "user" : "project";
1093
1344
 
1094
1345
  if (arg === "init") {
1095
1346
  const created = core.scaffold();
@@ -1116,15 +1367,23 @@ export default function (pi: ExtensionAPI) {
1116
1367
 
1117
1368
  if (arg === "status") {
1118
1369
  const cfg = core.loadScenes();
1119
- const st = core.loadState();
1120
- const target = core.computeTarget(st.active, cfg);
1370
+ const proj = core.loadProjectState();
1371
+ const user = core.loadUserState();
1372
+ const active = core.effectiveActive();
1373
+ const target = core.computeTarget(active, cfg);
1121
1374
  const collisions = core.findSpecCollisions(cfg);
1122
1375
  const lines = [
1123
- `当前场景:${st.active ? `${cfg.scenes?.[st.active]?.icon?.trim() || "◆"} ${st.active}` : "(无,仅通用层)"}`,
1376
+ `项目场景(${core.paths.projectDir}):${proj.active ? `${cfg.scenes?.[proj.active]?.icon?.trim() || "◆"} ${proj.active}` : "(无)"}`,
1377
+ `全局场景(--global):${user.active ? `${cfg.scenes?.[user.active]?.icon?.trim() || "◇"} ${user.active}` : "(无)"}`,
1378
+ `生效场景:${active ? `${cfg.scenes?.[active]?.icon?.trim() || "◆"} ${active}` : "(无,仅通用层)"}`,
1124
1379
  `生效 packages(${target.packages.length}):${target.packages.map(specOf).join(", ") || "—"}`,
1125
1380
  `生效 skills(${target.skills.length}):${target.skills.join(", ") || "—"}`,
1381
+ `生效 prompt 模板(${target.prompts.length},resources_discover 注入):${target.prompts.join(", ") || "—"}`,
1126
1382
  `可用场景:${Object.keys(cfg.scenes ?? {}).join(", ") || "—"}`,
1127
1383
  ];
1384
+ if ((user.anchors?.length ?? 0) > 0) {
1385
+ lines.push(`资产锚点(零暴露,全局缓存共享):${user.anchors!.map(specOf).join(", ")}`);
1386
+ }
1128
1387
  if (collisions.length > 0) {
1129
1388
  lines.push(`⚠️ 同包多种写法(已按首个生效):${collisions.map((c) => `${c.id}(${c.entries.map((e) => e.spec).join("|")})`).join("、")}`);
1130
1389
  }
@@ -1156,18 +1415,36 @@ export default function (pi: ExtensionAPI) {
1156
1415
  }
1157
1416
 
1158
1417
  if (arg === "off" || arg === "none") {
1159
- await doSwitch(ctx, null);
1418
+ // off 无论何种 scope 都摘两层(用户意图 = 全部关掉);资产锚点保留
1419
+ await doSwitch(ctx, null, scope);
1420
+ return;
1421
+ }
1422
+
1423
+ if (arg === "migrate") {
1424
+ const user = core.loadUserState();
1425
+ if (!user.active) {
1426
+ ctx.ui.notify("没有 ≤0.6 遗留的全局场景,无需迁移", "info");
1427
+ return;
1428
+ }
1429
+ const ok = await ctx.ui.confirm(
1430
+ "迁移全局场景为项目场景",
1431
+ `检测到全局场景「${user.active}」(≤0.6 模式,所有目录生效)。\n转为当前目录的项目场景?\n· 资产(包与克隆)不动,仍在全局共享\n· 激活条目移到 ${core.paths.projectSettingsFile}`,
1432
+ );
1433
+ if (!ok) return;
1434
+ await doSwitch(ctx, user.active, "project");
1160
1435
  return;
1161
1436
  }
1162
1437
 
1163
1438
  if (arg) {
1164
- await doSwitch(ctx, arg);
1439
+ await doSwitch(ctx, arg, scope);
1165
1440
  return;
1166
1441
  }
1167
1442
 
1168
- // 无参数:选择器
1443
+ // 无参数:选择器(默认项目级;● 当前项目场景 / ◐ 当前全局场景 / ○ 未激活)
1169
1444
  const cfg = core.loadScenes();
1170
- const st = core.loadState();
1445
+ const projActive = core.loadProjectState().active;
1446
+ const userActive = core.loadUserState().active;
1447
+ const active = projActive ?? userActive;
1171
1448
  const names = Object.keys(cfg.scenes ?? {});
1172
1449
  if (names.length === 0) {
1173
1450
  ctx.ui.notify(`scenes.json 里还没有定义场景,编辑 ${core.paths.scenesFile}`, "info");
@@ -1178,30 +1455,31 @@ export default function (pi: ExtensionAPI) {
1178
1455
  const items: string[] = names.map((n) => {
1179
1456
  const d = cfg.scenes![n]?.description ?? "";
1180
1457
  const icon = cfg.scenes![n]?.icon?.trim() || "◆";
1181
- const cur = st.active === n ? "●" : "○";
1182
- const label = `${cur} ${icon} ${n}${d ? ` · ${d}` : ""}${st.active === n ? " [当前]" : ""}`;
1458
+ const cur = projActive === n ? "●" : userActive === n ? "◐" : "○";
1459
+ const layer = projActive === n ? " [项目]" : userActive === n ? " [全局]" : "";
1460
+ const label = `${cur} ${icon} ${n}${d ? ` · ${d}` : ""}${layer}`;
1183
1461
  labelToName.set(label, n);
1184
1462
  return label;
1185
1463
  });
1186
- const extra = [PICKER_OFF + (st.active === null ? " [当前]" : ""), PICKER_CANCEL];
1187
- const choice = await ctx.ui.select(`切换场景(通用层恒生效)`, [...items, ...extra]);
1464
+ const extra = [PICKER_OFF + (active === null ? " [当前]" : ""), PICKER_CANCEL];
1465
+ const choice = await ctx.ui.select(`切换场景(写入 ${core.paths.projectSettingsFile})`, [...items, ...extra]);
1188
1466
  if (!choice || choice === PICKER_CANCEL) return;
1189
1467
  if (choice.startsWith(PICKER_OFF)) {
1190
- if (st.active === null) {
1468
+ if (active === null) {
1191
1469
  ctx.ui.notify("当前已是仅通用层", "info");
1192
1470
  return;
1193
1471
  }
1194
- await doSwitch(ctx, null);
1472
+ await doSwitch(ctx, null, "project");
1195
1473
  return;
1196
1474
  }
1197
1475
  // label → 场景名(含 icon/描述的完整条目作为 key,避免解析歧义)
1198
1476
  const name = labelToName.get(choice);
1199
1477
  if (!name) return;
1200
- if (st.active === name) {
1201
- ctx.ui.notify(`当前已在场景「${name}」`, "info");
1478
+ if (active === name && projActive === name) {
1479
+ ctx.ui.notify(`当前已在项目场景「${name}」`, "info");
1202
1480
  return;
1203
1481
  }
1204
- await doSwitch(ctx, name);
1482
+ await doSwitch(ctx, name, "project");
1205
1483
  },
1206
1484
  };
1207
1485
 
@@ -1219,8 +1497,7 @@ export default function (pi: ExtensionAPI) {
1219
1497
 
1220
1498
  function hasToolsForTarget(): Set<string> {
1221
1499
  const cfg = core.loadScenes();
1222
- const st = core.loadState();
1223
- const target = core.computeTarget(st.active, cfg);
1500
+ const target = core.computeTarget(core.effectiveActive(), cfg);
1224
1501
  const owners = new Set(getToolMap().tools.values());
1225
1502
  return new Set(target.packages.filter((e) => packageIdentity(e).some((id) => owners.has(id))).map((e) => canonical(e)));
1226
1503
  }
@@ -1281,8 +1558,8 @@ export default function (pi: ExtensionAPI) {
1281
1558
  const next = applyProposals(cfg, accepted);
1282
1559
  backupScenes();
1283
1560
  core.saveScenes(next);
1284
- const st = core.loadState();
1285
- core.applyToSettings(core.computeTarget(st.active, next), st.active, undefined);
1561
+ const active = core.effectiveActive();
1562
+ core.applyToSettings(core.computeTarget(active, next), active, undefined, core.effectiveScope());
1286
1563
  ctx.ui.notify(`已应用 ${accepted.length} 条提案,正在热重载…`, "info");
1287
1564
  await ctx.reload();
1288
1565
  }
@@ -1310,9 +1587,8 @@ export default function (pi: ExtensionAPI) {
1310
1587
  }
1311
1588
 
1312
1589
  async function runReflection(ctx: any): Promise<void> {
1313
- const st = core.loadState();
1314
1590
  const cfg = core.loadScenes();
1315
- const target = core.computeTarget(st.active, cfg);
1591
+ const target = core.computeTarget(core.effectiveActive(), cfg);
1316
1592
  const skills = listSkillChildren(target.skills);
1317
1593
  if (!skills.length) return;
1318
1594
  const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
@@ -1344,8 +1620,8 @@ export default function (pi: ExtensionAPI) {
1344
1620
  const next = applyProposals(cfg, proposals);
1345
1621
  backupScenes();
1346
1622
  core.saveScenes(next);
1347
- const st = core.loadState();
1348
- core.applyToSettings(core.computeTarget(st.active, next), st.active, undefined);
1623
+ const active = core.effectiveActive();
1624
+ core.applyToSettings(core.computeTarget(active, next), active, undefined, core.effectiveScope());
1349
1625
  // 不在 shutdown 里 ctx.reload()(会递归触发 shutdown);变更下次自然重载生效
1350
1626
  if (reason !== "quit") {
1351
1627
  try {
@@ -1357,12 +1633,41 @@ export default function (pi: ExtensionAPI) {
1357
1633
  }
1358
1634
  }
1359
1635
 
1636
+ /** ≤0.6 遗留全局场景的一次性迁移提示(不自动改配置,只提醒一次) */
1637
+ function notifyLegacyMigration(ctx: any): void {
1638
+ try {
1639
+ const user = core.loadUserState();
1640
+ // version 缺省 = 0.6.x 写入的全局场景;v0.7 起 --global 切换会写 version:2
1641
+ if (user.active && user.version !== 2 && !user.migrateNotified) {
1642
+ core.saveUserState({ ...user, migrateNotified: true });
1643
+ ctx.ui?.notify(
1644
+ `检测到全局场景「${user.active}」(pi-scenes ≤0.6 模式,所有目录生效)。\nv0.7 起场景默认项目级:/scene migrate 转为当前项目场景,或 /scene off 关闭。`,
1645
+ "info",
1646
+ );
1647
+ }
1648
+ } catch {}
1649
+ }
1650
+
1651
+ // v0.8:场景化 prompt 模板 —— resources_discover 事件动态注入。
1652
+ // 每次 startup/reload pi 都会询问本扩展;按当前激活场景返回 promptPaths,
1653
+ // 切走后不再返回 → 模板自动消失,零 settings 写入、零残留。
1654
+ // 同名时用户手写模板(~/.pi/agent/prompts、项目 .pi/prompts)与包模板优先于场景模板。
1655
+ pi.on("resources_discover", async () => {
1656
+ try {
1657
+ const cfg = core.loadScenes();
1658
+ return { promptPaths: core.computeTarget(core.effectiveActive(), cfg).prompts };
1659
+ } catch {
1660
+ return {};
1661
+ }
1662
+ });
1663
+
1360
1664
  pi.on("session_start", async (_event, ctx) => {
1361
1665
  try {
1362
- const pkgs = readJson<Record<string, unknown>>(core.paths.settingsFile, {}).packages;
1363
- core.beginSession(ctx.sessionManager?.getSessionFile?.() ?? null, Array.isArray(pkgs) ? (pkgs as PackageEntry[]) : []);
1666
+ const all = readAllSettingsPackages();
1667
+ core.beginSession(ctx.sessionManager?.getSessionFile?.() ?? null, [...all.project, ...all.user]);
1364
1668
  } catch {}
1365
1669
  updateSceneBadge(ctx);
1670
+ notifyLegacyMigration(ctx);
1366
1671
  });
1367
1672
 
1368
1673
  pi.on("tool_call", async (event) => {