@suifei/dsh-ai-team 0.4.125 → 0.4.127

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.127 - 2026-11-18
4
+
5
+ **人才市场(第 2 步 2d):组队,新建项目时选团队**
6
+
7
+ - 此前新项目用哪个团队只能在插件设置里改 `teamPreset`,全局一个;也没法从人才里自己挑人组队。
8
+ - **新建项目对话框加「团队」**:列出内置与自建团队(引用了不存在人才的团队不让选),下方显示成员与负责人;不选照旧用设置里的默认团队。
9
+ `project.create` 新增 `team`:按这个团队种成员,团队负责人成为项目主理人;团队不存在或坏了回 400,不再悄悄退回默认团队;
10
+ - **组队**:对话框里「组一个新团队」——搜人才、加入(同一人才可招多位)、改名、指定负责人,存成用户团队后自动选中;自建团队可删(内置只读)。
11
+ catalog.js 增加 `writeTeam` / `deleteTeam` / `listTeams` / `uniqueTeamId`(只写用户根,校验复用 `parseTeam`,成员 id 自动去重);
12
+ 新接口 `GET /api/teams`、`POST /api/teams`、`POST /api/teams/delete`;新建撞名(含内置团队名)自动加序号;
13
+ - **修复:设置换成别的内置团队后,重启会往每个已有项目里塞人**。老项目补齐 UX/业务 的迁移原先只看 `source === 'bundled'`,
14
+ 0.4.124 起内置团队不止 default,把 `teamPreset` 设成 `science` 再重启,所有已有项目都会被补进启元、立验……
15
+ 现在只按**内置默认团队**、且只对本来由默认团队组成的项目补岗;用其它团队建的项目重启后原样不动;
16
+ - 测试:`test/talent-routes.test.js` 补组队、按团队建项目与各种拒绝;`test/catalog.test.js` 补补岗回归(旧逻辑下失败、新逻辑通过);
17
+ `test/client-talent-market.test.js` 补 `teamDraftToBody` / `teamMembersLine`。实机 E2E(rc.1 / rc.3):自建「speaking」队(青岚 ×2 + 白砚为负责人)
18
+ 与内置科研团队各建一个项目,成员、主理人按团队;重启宿主后两个项目成员数不变。
19
+
20
+ ## 0.4.126 - 2026-11-18
21
+
22
+ **人才市场(第 2 步 2b):把项目里的成员存为人才**
23
+
24
+ - 成员在项目里干久了,性格会被复盘与手工调整打磨,技能也会越挂越多;此前这些只属于那一个项目。
25
+ 现在成员资料多了「存为人才」:把它此刻的岗位、职责、性格、模型与技能存成可复用的人才,换个项目照样招;
26
+ - 草稿由服务端生成 `GET /api/projects/:p/members/:m/talent-draft`:职责与激活注入同一判定(`skillKindForMember`,主理人即 lead),
27
+ 逐份技能标出找不到正文的(如只是挂了名字);笔记、会话与任务不带——那是这位成员自己的经历;
28
+ - 技能按**成员实际读取的路径**拷进新人才的文件夹(团队目录 → 人才自带 → 工作区 `.dsh` → `~/.dsh` → 项目数据目录):
29
+ `POST /api/talents/:id/skills` 新增 `fromProject` + `fromMember`;查找抽成 `skill-loader.findSkillText` 一份实现,激活注入与存为人才共用;
30
+ - 存为人才复用「新建人才」页:草稿预填、可改,找不到正文的技能单列提示,沿用的模型一并存下;
31
+ - **新建不再静默覆盖**:`POST /api/talents` 撞了已有 id(含内置,如英文名 `editor`)自动加序号,要改写已有自定义人才须显式 `overwrite`(`uniqueTalentId`);
32
+ - 测试:`test/talent-routes.test.js` 补存为人才全流程与去重;`test/catalog.test.js` 补 `uniqueTalentId` / `talentFromMember`;
33
+ `test/client-talent-market.test.js` 补 `talentCreatorInit`。实机 E2E(rc.1 / rc.3):改过性格、挂了工作区独有技能的青岚存为人才,
34
+ 删掉工作区那份后招进新人才并激活——性格、模型与两份技能都随人才走。
35
+
3
36
  ## 0.4.125 - 2026-11-18
4
37
 
5
38
  **人才市场(第 2 步 2a):自定义智能体 + 安装 skill**
package/README.md CHANGED
@@ -30,6 +30,8 @@
30
30
  - 「人员 → 添加成员」先打开人才市场:按分类、关键词挑一位,点「招聘」预填表单,改名、换模型后创建;也可以切到「自定义」从零填写。
31
31
  - 自建:人才放 `~/.dsh/ai-team/catalog/user/talents/<人才>/`,团队放 `~/.dsh/ai-team/catalog/user/teams/<团队>/`,同名覆盖内置;插件设置 `teamPreset` 选新项目用哪个团队。
32
32
  - **新建自定义人才(界面)**:「添加成员 → 新建人才」填名号、岗位、职责、性格,再按需装技能——从现成人才 fork、自写一份、或导入 `.md`,存成可复用的人才(落用户根)。内置没有的角色能自己攒;技能装进人才自己的文件夹,自包含、可分享。走 `POST /api/talents` 与 `POST /api/talents/:id/skills`,内置只读、装删回 `409`。
33
+ - **存为人才**:成员资料「存为人才」把项目里这位成员此刻的岗位、职责、性格、模型与技能存成可复用的人才(技能按成员实际读取的路径拷进人才文件夹,找不到正文的会提示),换个项目照样招。新建与存为都不会静默覆盖已有人才,撞名自动加序号。
34
+ - **组队、建项目选团队**:「新建项目」里选团队(内置或自建),按它种成员、负责人当主理人;「组一个新团队」从人才里挑人(同一人才可招多位)、指定负责人即可保存。插件设置 `teamPreset` 只是不选时的默认值。
33
35
  - 成员在账本里记下来源人才与版本、职责;人才文件之后再改,不会悄悄改动已招成员的性格与职责。已有项目不受新团队影响。文件写坏时跳过它并在诊断日志记 `catalog.load.fail` / `catalog.team.fail`。
34
36
 
35
37
  ---
package/client.js CHANGED
@@ -301,6 +301,8 @@ window.__ModuleLoader__.load({
301
301
  tcName: '名号', tcRole: '岗位', tcDuty: '职责', tcCategory: '分类', tcTags: '标签', tcTagsHint: '逗号分隔', tcPersonality: '性格', tcPersonalityHint: '它怎么做事、什么风格',
302
302
  tcSkills: '技能', tcEmpty: '还没装技能(可选)', tcAddExisting: '从已有装', tcWriteOwn: '自写一份', tcImport: '导入 .md', tcPick: '选一个已有技能…', tcAdd: '加入', tcRemove: '移除',
303
303
  tcSkillName: '技能名(英文/数字/-)', tcSkillBody: '技能正文(SKILL.md)', tcSkillDup: '已经装了同名技能', tcSave: '存为我的人才', tcSaving: '保存中…',
304
+ memberSaveAsTalent: '存为人才', tcFromMember: '从成员「{name}」存出:沿用它此刻的岗位、职责、性格与技能,可先修改再保存。', tcModelKept: '沿用模型:{model}', tcMissing: '这些技能找不到正文,没有带上:{skills}', tcDraftFailed: '读取成员草稿失败:{error}',
305
+ projectTeam: '团队', teamCompose: '组一个新团队', teamComposeTitle: '组队', teamComposeHint: '从人才里挑人组队:同一人才可以招多位,给其中一位定为负责人(新项目的主理人)。', teamName: '团队名', teamDesc: '说明', teamMembers: '成员', teamPick: '从人才里挑人', teamAdd: '加入', teamLead: '负责人', teamEmptyPick: '还没挑人', teamSave: '保存团队', teamBack: '返回', teamDelete: '删除这个团队', teamDeleteConfirm: '删除自建团队「{name}」?团队文件会被删除,已用它建的项目和其中成员不受影响。', teamLoadFailed: '团队列表读取失败:{error}',
304
306
  talentEmpty: '没有符合条件的人才。',
305
307
  talentLoading: '正在读取人才市场…',
306
308
  talentLoadFailed: '人才市场读取失败:{error}',
@@ -749,6 +751,8 @@ window.__ModuleLoader__.load({
749
751
  tcName: 'Name', tcRole: 'Role', tcDuty: 'Duty', tcCategory: 'Category', tcTags: 'Tags', tcTagsHint: 'comma-separated', tcPersonality: 'Personality', tcPersonalityHint: 'how it works, its style',
750
752
  tcSkills: 'Skills', tcEmpty: 'No skills yet (optional)', tcAddExisting: 'From existing', tcWriteOwn: 'Write one', tcImport: 'Import .md', tcPick: 'Pick an existing skill…', tcAdd: 'Add', tcRemove: 'Remove',
751
753
  tcSkillName: 'Skill name (a-z, 0-9, -)', tcSkillBody: 'Skill body (SKILL.md)', tcSkillDup: 'That skill name is already staged', tcSave: 'Save as my talent', tcSaving: 'Saving…',
754
+ memberSaveAsTalent: 'Save as talent', tcFromMember: 'Saved from member “{name}”: its current role, duty, personality and skills are filled in; edit before saving.', tcModelKept: 'Keeps the model: {model}', tcMissing: 'These skills have no readable body and were left out: {skills}', tcDraftFailed: 'Could not read the member draft: {error}',
755
+ projectTeam: 'Team', teamCompose: 'Compose a new team', teamComposeTitle: 'Compose a team', teamComposeHint: 'Pick talents into a team: the same talent can be hired more than once; mark one as the lead (the new project owner).', teamName: 'Team name', teamDesc: 'Description', teamMembers: 'Members', teamPick: 'Pick from talents', teamAdd: 'Add', teamLead: 'Lead', teamEmptyPick: 'Nobody picked yet', teamSave: 'Save team', teamBack: 'Back', teamDelete: 'Delete this team', teamDeleteConfirm: 'Delete your team “{name}”? Its file is removed; projects already created from it and their members are unaffected.', teamLoadFailed: 'Could not load teams: {error}',
752
756
  talentEmpty: 'No talent matches.',
753
757
  talentLoading: 'Loading the talent market…',
754
758
  talentLoadFailed: 'Could not load the talent market: {error}',
@@ -1393,6 +1397,12 @@ window.__ModuleLoader__.load({
1393
1397
  .at-tcskill button { border: 0; background: transparent; cursor: pointer; font-size: 14px; line-height: 1; color: inherit; padding: 0; }
1394
1398
  .at-tcpick { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
1395
1399
  .at-tcpanel { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; }
1400
+ .at-teamrows { display: flex; flex-direction: column; gap: 6px; }
1401
+ .at-teamrow { display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto; gap: 8px; align-items: center; }
1402
+ .at-teamlead { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; white-space: nowrap; }
1403
+ .at-teampick { display: flex; flex-direction: column; gap: 4px; max-height: 240px; overflow-y: auto; }
1404
+ .at-teampickrow { display: flex; justify-content: space-between; align-items: center; gap: 8px; min-width: 0; }
1405
+ .at-teampickrow > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1396
1406
  .at-market { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
1397
1407
  .at-marketsearch { width: 100%; padding: 6px 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-sm); background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; }
1398
1408
  .at-marketcats { display: flex; flex-wrap: wrap; gap: 4px; }
@@ -2738,9 +2748,10 @@ window.__ModuleLoader__.load({
2738
2748
  h('div', { className: 'at-modalactions' },
2739
2749
  h('button', { className: 'at-btn', type: 'button', onClick: onCancel }, t('cancel'))));
2740
2750
  }
2741
- function TalentCreator({ t, onSaved, onCancel }) {
2742
- const [form, setForm] = React.useState(blankTalentForm);
2743
- const [pending, setPending] = React.useState([]);
2751
+ function TalentCreator({ t, initial, onSaved, onCancel }) {
2752
+ const seed = initial && initial.draft ? talentCreatorInit(initial) : null;
2753
+ const [form, setForm] = React.useState(() => (seed ? seed.form : blankTalentForm()));
2754
+ const [pending, setPending] = React.useState(() => (seed ? seed.pending : []));
2744
2755
  const [installable, setInstallable] = React.useState([]);
2745
2756
  const [pick, setPick] = React.useState('');
2746
2757
  const [pickFrom, setPickFrom] = React.useState('');
@@ -2782,12 +2793,12 @@ window.__ModuleLoader__.load({
2782
2793
  if (!form.name.trim() || busy) return;
2783
2794
  setBusy(true); setError('');
2784
2795
  try {
2785
- const res = await fetch('/ai-team/api/talents', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(talentFormToBody(form)) });
2796
+ const res = await fetch('/ai-team/api/talents', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ...talentFormToBody(form), ...(seed && seed.model ? { model: seed.model } : {}) }) });
2786
2797
  const body = await res.json().catch(() => null);
2787
2798
  if (!res.ok) throw new Error((body && body.error && body.error.message) || ('HTTP ' + res.status));
2788
2799
  const id = body && body.talent && body.talent.id;
2789
2800
  for (const sk of pending) {
2790
- const payload = sk.kind === 'fork' ? { name: sk.name, fromTalent: sk.fromTalent, fromSkill: sk.fromSkill } : { name: sk.name, markdown: sk.markdown };
2801
+ const payload = sk.kind === 'fork' ? { name: sk.name, fromTalent: sk.fromTalent, fromSkill: sk.fromSkill } : sk.kind === 'member' ? { name: sk.name, fromProject: sk.fromProject, fromMember: sk.fromMember } : { name: sk.name, markdown: sk.markdown };
2791
2802
  const r2 = await fetch('/ai-team/api/talents/' + encodeURIComponent(id) + '/skills', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) });
2792
2803
  const b2 = await r2.json().catch(() => null);
2793
2804
  if (!r2.ok) throw new Error(((b2 && b2.error && b2.error.message) || ('HTTP ' + r2.status)) + '(' + sk.name + ')');
@@ -2801,6 +2812,10 @@ window.__ModuleLoader__.load({
2801
2812
  }
2802
2813
  return h('div', { className: 'at-market' },
2803
2814
  h('div', { className: 'at-modalmeta' }, t('tcHint')),
2815
+ initial && initial.error ? h('div', { className: 'at-modalerror', role: 'alert' }, initial.error) : null,
2816
+ seed ? h('div', { className: 'at-modalmeta' }, tf(t, 'tcFromMember', { name: seed.sourceName })) : null,
2817
+ seed && seed.model ? h('div', { className: 'at-modalmeta' }, tf(t, 'tcModelKept', { model: [seed.model.provider, seed.model.model].filter(Boolean).join(' / ') })) : null,
2818
+ seed && seed.missing.length ? h('div', { className: 'at-modalmeta' }, tf(t, 'tcMissing', { skills: seed.missing.join('、') })) : null,
2804
2819
  h('label', { className: 'at-field' }, h('span', null, t('tcName')), h('input', { value: form.name, onChange: set('name'), autoFocus: true })),
2805
2820
  h('label', { className: 'at-field' }, h('span', null, t('tcRole')), h('input', { value: form.role, onChange: set('role') })),
2806
2821
  h('label', { className: 'at-field' }, h('span', null, t('tcDuty')), h('select', { value: form.duty, onChange: set('duty') }, ['executor', 'qa', 'lead'].map((d) => h('option', { key: d, value: d }, t(DUTY_LABEL[d]))))),
@@ -2820,6 +2835,54 @@ window.__ModuleLoader__.load({
2820
2835
  h('button', { type: 'button', className: 'at-btn', onClick: onCancel }, t('cancel')),
2821
2836
  h('button', { type: 'button', className: 'at-btn at-btn-primary', disabled: !form.name.trim() || busy, onClick: save }, busy ? t('tcSaving') : t('tcSave'))));
2822
2837
  }
2838
+ function TeamComposer({ t, talents, onSaved, onCancel }) {
2839
+ const [draft, setDraft] = React.useState({ name: '', description: '', members: [], lead: 0 });
2840
+ const [query, setQuery] = React.useState('');
2841
+ const [busy, setBusy] = React.useState(false);
2842
+ const [error, setError] = React.useState('');
2843
+ const shown = filterTalents(talents, query, '').slice(0, 40);
2844
+ const byId = (id) => (talents || []).find((x) => x.id === id);
2845
+ function add(talent) { setDraft((d) => ({ ...d, members: [...d.members, { talent: talent.id, name: '' }] })); }
2846
+ function remove(index) { setDraft((d) => ({ ...d, members: d.members.filter((_, i) => i !== index), lead: d.lead === index ? 0 : d.lead > index ? d.lead - 1 : d.lead })); }
2847
+ function rename(index, name) { setDraft((d) => ({ ...d, members: d.members.map((m, i) => (i === index ? { ...m, name } : m)) })); }
2848
+ async function save() {
2849
+ const body = teamDraftToBody(draft);
2850
+ if (!body.name || body.members.length === 0 || busy) return;
2851
+ setBusy(true); setError('');
2852
+ try {
2853
+ const res = await fetch('/ai-team/api/teams', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
2854
+ const out = await res.json().catch(() => null);
2855
+ if (!res.ok) throw new Error((out && out.error && out.error.message) || ('HTTP ' + res.status));
2856
+ onSaved(out.team);
2857
+ } catch (err) {
2858
+ setError((err && err.message) || String(err));
2859
+ } finally {
2860
+ setBusy(false);
2861
+ }
2862
+ }
2863
+ return h('div', { className: 'at-market' },
2864
+ h('div', { className: 'at-modalmeta' }, t('teamComposeHint')),
2865
+ h('label', { className: 'at-field' }, h('span', null, t('teamName')), h('input', { value: draft.name, onChange: (e) => setDraft({ ...draft, name: e.target.value }), autoFocus: true })),
2866
+ h('label', { className: 'at-field' }, h('span', null, t('teamDesc')), h('input', { value: draft.description, onChange: (e) => setDraft({ ...draft, description: e.target.value }) })),
2867
+ h('div', { className: 'at-field' }, h('span', null, t('teamMembers')),
2868
+ draft.members.length === 0 ? h('div', { className: 'at-modalmeta' }, t('teamEmptyPick')) : h('div', { className: 'at-teamrows' }, draft.members.map((m, i) => {
2869
+ const talent = byId(m.talent) || { name: m.talent, role: '' };
2870
+ return h('div', { key: i, className: 'at-teamrow' },
2871
+ h('input', { value: m.name, placeholder: talent.name, 'aria-label': t('teamName'), onChange: (e) => rename(i, e.target.value) }),
2872
+ h('span', { className: 'at-modalmeta' }, talent.role),
2873
+ h('label', { className: 'at-teamlead' }, h('input', { type: 'radio', name: 'team-lead', checked: draft.lead === i, onChange: () => setDraft({ ...draft, lead: i }) }), t('teamLead')),
2874
+ h('button', { type: 'button', className: 'at-btn at-btn-small', 'aria-label': t('tcRemove'), onClick: () => remove(i) }, '×'));
2875
+ }))),
2876
+ h('div', { className: 'at-field' }, h('span', null, t('teamPick')),
2877
+ h('input', { className: 'at-marketsearch', type: 'search', value: query, placeholder: t('talentSearch'), onChange: (e) => setQuery(e.target.value) }),
2878
+ talents === null ? h('div', { className: 'at-modalmeta' }, t('talentLoading')) : h('div', { className: 'at-teampick' }, shown.map((talent) => h('div', { key: talent.id, className: 'at-teampickrow' },
2879
+ h('span', null, talent.name + ' · ' + talent.role + (talent.source === 'user' ? ' · ' + t('talentUser') : '')),
2880
+ h('button', { type: 'button', className: 'at-btn at-btn-small', onClick: () => add(talent) }, t('teamAdd')))))),
2881
+ error ? h('div', { className: 'at-modalerror', role: 'alert' }, error) : null,
2882
+ h('div', { className: 'at-modalactions' },
2883
+ h('button', { type: 'button', className: 'at-btn', onClick: onCancel }, t('teamBack')),
2884
+ h('button', { type: 'button', className: 'at-btn at-btn-primary', disabled: busy || !draft.name.trim() || draft.members.length === 0, onClick: save }, busy ? t('saving') : t('teamSave'))));
2885
+ }
2823
2886
  function ModelFields({ t, catalog, provider, model, effort, onEffort, onProvider, onModel, error }) {
2824
2887
  const providers = Array.isArray(catalog?.providers) ? catalog.providers.slice() : [];
2825
2888
  // 推理等级按「提供商 + 模型」按需解析:不同模型支持的档位不同,宿主也随时可能
@@ -3089,6 +3152,30 @@ window.__ModuleLoader__.load({
3089
3152
  personality: String((form && form.personality) || '').trim(),
3090
3153
  };
3091
3154
  }
3155
+ /**
3156
+ * 「存为人才」:服务端草稿 → 新建人才页的初值。找得到正文的技能按「从成员拷」暂存,找不到的单列出来。
3157
+ */
3158
+ function talentCreatorInit(initial) {
3159
+ const draft = (initial && initial.draft) || {};
3160
+ const skills = Array.isArray(draft.skills) ? draft.skills : [];
3161
+ return {
3162
+ form: { name: String(draft.name || ''), role: String(draft.role || ''), duty: ['lead', 'qa', 'executor'].includes(draft.duty) ? draft.duty : 'executor', category: String(draft.category || ''), tags: (Array.isArray(draft.tags) ? draft.tags : []).join(', '), personality: String(draft.personality || '') },
3163
+ pending: skills.filter((x) => x && x.found).map((x) => ({ name: x.name, kind: 'member', fromProject: initial.projectId, fromMember: initial.memberId })),
3164
+ missing: skills.filter((x) => x && !x.found).map((x) => x.name),
3165
+ model: draft.model && (draft.model.provider || draft.model.model) ? draft.model : null,
3166
+ sourceName: String(draft.name || ''),
3167
+ };
3168
+ }
3169
+ /** 组队草稿 → POST /api/teams 请求体:成员只带人才 id 与(改过的)名字;负责人按下标,越界退回第一位。 */
3170
+ function teamDraftToBody(draft) {
3171
+ const members = (Array.isArray(draft && draft.members) ? draft.members : []).filter((m) => m && m.talent).map((m) => (String(m.name || '').trim() ? { talent: m.talent, name: String(m.name).trim() } : { talent: m.talent }));
3172
+ const lead = Number.isInteger(draft && draft.lead) && draft.lead >= 0 && draft.lead < members.length ? draft.lead : 0;
3173
+ return { name: String((draft && draft.name) || '').trim(), description: String((draft && draft.description) || '').trim(), members, lead };
3174
+ }
3175
+ /** 团队一行摘要:负责人打星,其余按名字列出。 */
3176
+ function teamMembersLine(team) {
3177
+ return (Array.isArray(team && team.members) ? team.members : []).map((m) => (m.id === team.lead ? '★' : '') + m.name + (m.role ? '·' + m.role : '')).join('、');
3178
+ }
3092
3179
  // </member-copy>
3093
3180
 
3094
3181
  // <composer-rich>
@@ -3219,6 +3306,8 @@ window.__ModuleLoader__.load({
3219
3306
  const [talentError, setTalentError] = React.useState('');
3220
3307
  const [talentQuery, setTalentQuery] = React.useState('');
3221
3308
  const [talentCategory, setTalentCategory] = React.useState('');
3309
+ // 「存为人才」:成员草稿(服务端生成),预填新建人才页。
3310
+ const [talentInit, setTalentInit] = React.useState(null);
3222
3311
  const [mName, setMName] = React.useState('');
3223
3312
  const [mRole, setMRole] = React.useState('');
3224
3313
  const [mPrompt, setMPrompt] = React.useState('');
@@ -3246,6 +3335,12 @@ window.__ModuleLoader__.load({
3246
3335
  const [nName, setNName] = React.useState('');
3247
3336
  const [nGoal, setNGoal] = React.useState('');
3248
3337
  const [nWorkspace, setNWorkspace] = React.useState('');
3338
+ // 新建项目选团队(2d):团队列表、所选团队、组队面板。
3339
+ const [teamList, setTeamList] = React.useState(null);
3340
+ const [nTeam, setNTeam] = React.useState('');
3341
+ const [teamLoadError, setTeamLoadError] = React.useState('');
3342
+ const [teamComposeOpen, setTeamComposeOpen] = React.useState(false);
3343
+ const selectedTeam = (teamList || []).find((entry) => entry.id === nTeam) || null;
3249
3344
  const [workspaceOpen, setWorkspaceOpen] = React.useState(false);
3250
3345
  const [workspaceDraft, setWorkspaceDraft] = React.useState('');
3251
3346
  const [workspaceError, setWorkspaceError] = React.useState('');
@@ -3925,6 +4020,9 @@ window.__ModuleLoader__.load({
3925
4020
  // 工作目录,成员只能在插件数据目录里跑,workspace attach 也会被拒。
3926
4021
  setNWorkspace(data?.defaultWorkspace ?? '');
3927
4022
  setNError('');
4023
+ setNTeam('');
4024
+ setTeamComposeOpen(false);
4025
+ void loadTeams();
3928
4026
  setNewOpen(true);
3929
4027
  }
3930
4028
  async function togglePmo() {
@@ -3980,12 +4078,37 @@ window.__ModuleLoader__.load({
3980
4078
  setWorkspaceBusy(false);
3981
4079
  }
3982
4080
  }
4081
+ /** 每次打开新建项目现取团队列表:刚组的队、刚改的 team.yml 立刻可选。select 留空表示沿用设置里的默认团队。 */
4082
+ async function loadTeams(select) {
4083
+ setTeamLoadError('');
4084
+ try {
4085
+ const response = await fetch('/ai-team/api/teams', { headers: { accept: 'application/json' } });
4086
+ const body = await response.json().catch(() => null);
4087
+ if (!response.ok) throw new Error((body && body.error && body.error.message) || ('HTTP ' + response.status));
4088
+ setTeamList(Array.isArray(body && body.teams) ? body.teams : []);
4089
+ setNTeam(select || (body && body.defaultTeam) || 'default');
4090
+ } catch (error) {
4091
+ setTeamList([]);
4092
+ setTeamLoadError(tf(t, 'teamLoadFailed', { error: (error && error.message) || String(error) }));
4093
+ }
4094
+ }
4095
+ async function removeTeam(team) {
4096
+ if (!(await askConfirm(t('teamDelete'), tf(t, 'teamDeleteConfirm', { name: team.name })))) return;
4097
+ try {
4098
+ const response = await fetch('/ai-team/api/teams/delete', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: team.id }) });
4099
+ const body = await response.json().catch(() => null);
4100
+ if (!response.ok) throw new Error((body && body.error && body.error.message) || ('HTTP ' + response.status));
4101
+ await loadTeams();
4102
+ } catch (error) {
4103
+ setNError((error && error.message) || String(error));
4104
+ }
4105
+ }
3983
4106
  async function createProject() {
3984
4107
  if (!nName.trim() || !nWorkspace.trim() || nBusy) return;
3985
4108
  setNBusy(true);
3986
4109
  setNError('');
3987
4110
  try {
3988
- const result = await runCommand('project.create', { name: nName.trim(), goal: nGoal.trim(), workspacePath: nWorkspace.trim() });
4111
+ const result = await runCommand('project.create', { name: nName.trim(), goal: nGoal.trim(), workspacePath: nWorkspace.trim(), ...(nTeam ? { team: nTeam } : {}) });
3989
4112
  const next = result.project;
3990
4113
  setNewOpen(false);
3991
4114
  setScope('project');
@@ -4055,6 +4178,7 @@ window.__ModuleLoader__.load({
4055
4178
  setMCopy(null);
4056
4179
  setMError('');
4057
4180
  setMTab('market');
4181
+ setTalentInit(null);
4058
4182
  setTalentQuery('');
4059
4183
  setTalentCategory('');
4060
4184
  setAddOpen(true);
@@ -4100,6 +4224,21 @@ window.__ModuleLoader__.load({
4100
4224
  setMError('');
4101
4225
  setAddOpen(true);
4102
4226
  }
4227
+ /** 存为人才:取服务端草稿(职责按身份判定、标出找不到正文的技能),在「新建人才」页预填。 */
4228
+ async function openSaveAsTalent(source) {
4229
+ try {
4230
+ const response = await fetch('/ai-team/api/projects/' + encodeURIComponent(projectId) + '/members/' + encodeURIComponent(source.id) + '/talent-draft', { headers: { accept: 'application/json' } });
4231
+ const body = await response.json().catch(() => null);
4232
+ if (!response.ok) throw new Error((body && body.error && body.error.message) || ('HTTP ' + response.status));
4233
+ setTalentInit(body);
4234
+ } catch (error) {
4235
+ setTalentInit({ error: tf(t, 'tcDraftFailed', { error: (error && error.message) || String(error) }) });
4236
+ }
4237
+ setMCopy(null);
4238
+ setMTab('create');
4239
+ setAddOpen(true);
4240
+ loadTalents();
4241
+ }
4103
4242
  async function createAgent() {
4104
4243
  if (!mName.trim() || mBusy) return;
4105
4244
  setMBusy(true);
@@ -5075,7 +5214,7 @@ window.__ModuleLoader__.load({
5075
5214
  onCategory: setTalentCategory,
5076
5215
  onHire: hireTalent,
5077
5216
  onCancel: () => setAddOpen(false),
5078
- }) : mTab === 'create' && !(mCopy && !mCopy.talent) ? h(TalentCreator, { t, onSaved: () => { loadTalents(); setMTab('market'); }, onCancel: () => setAddOpen(false) }) : [
5217
+ }) : mTab === 'create' && !(mCopy && !mCopy.talent) ? h(TalentCreator, { key: talentInit && talentInit.memberId ? 'm:' + talentInit.memberId : 'blank', t, initial: talentInit, onSaved: () => { loadTalents(); setTalentInit(null); setMTab('market'); }, onCancel: () => { setAddOpen(false); setTalentInit(null); } }) : [
5079
5218
  mCopy?.talent ? h('div', { key: 'from', className: 'at-modalmeta' }, tf(t, 'memberHireFrom', { name: mCopy.sourceName, version: mCopy.talent.version })) : null,
5080
5219
  mCopy && !mCopy.talent ? h('div', { key: 'from', className: 'at-modalmeta' }, tf(t, 'memberCopyFrom', { name: mCopy.sourceName })) : null,
5081
5220
  h('label', { key: 'name', className: 'at-field' }, h('span', null, t('memberName')),
@@ -5189,6 +5328,7 @@ window.__ModuleLoader__.load({
5189
5328
  h('button', { className: 'at-btn', type: 'button', onClick: () => { const target = profileAgent; setProfileAgent(null); openMemberView(target); } }, t('memberTasks')),
5190
5329
  h('button', { className: 'at-btn', type: 'button', onClick: () => { const target = profileAgent; setProfileAgent(null); void openAgentChat(target); } }, t('agentChat')),
5191
5330
  h('button', { className: 'at-btn', type: 'button', onClick: () => { const source = profileAgent; setProfileAgent(null); openCopyAgent(source); }, disabled: pBusy }, t('memberCopy')),
5331
+ h('button', { className: 'at-btn', type: 'button', onClick: () => { const source = profileAgent; setProfileAgent(null); void openSaveAsTalent(source); }, disabled: pBusy }, t('memberSaveAsTalent')),
5192
5332
  h('button', { className: 'at-btn', type: 'button', onClick: leaveProfile, disabled: pBusy }, t('leaveTeam')),
5193
5333
  profileAgent.status === 'failed' ? h('button', { className: 'at-btn', type: 'button', onClick: retryProfile, disabled: pBusy }, t('retry')) : null,
5194
5334
  profileAgent.sessionId ? h('button', { className: 'at-btn', type: 'button', title: t('reseatConfirm'), onClick: reseatProfile, disabled: pBusy }, t('reseatSession')) : null,
@@ -5229,10 +5369,22 @@ window.__ModuleLoader__.load({
5229
5369
  h('div', { className: 'at-inlineadd' },
5230
5370
  h('input', { value: nWorkspace, onChange: (event) => setNWorkspace(event.target.value), placeholder: data?.workspaceExample ?? t('workspacePathPlaceholder') }),
5231
5371
  h('button', { className: 'at-btn at-btn-small', type: 'button', onClick: pickNewWorkspace }, t('workspaceChoose')))),
5372
+ h('label', { className: 'at-field' }, h('span', null, t('projectTeam')),
5373
+ teamList === null ? h('div', { className: 'at-modalmeta' }, t('talentLoading'))
5374
+ : h('select', { value: nTeam, onChange: (event) => setNTeam(event.target.value) }, teamList.filter((entry) => !entry.broken).map((entry) => h('option', { key: entry.id, value: entry.id }, entry.name + '(' + entry.members.length + ')' + (entry.source === 'user' ? ' · ' + t('talentUser') : ''))))),
5375
+ selectedTeam ? h('div', { className: 'at-modalmeta' }, (selectedTeam.description ? selectedTeam.description + ':' : '') + teamMembersLine(selectedTeam)) : null,
5376
+ teamLoadError ? h('div', { className: 'at-modalerror', role: 'alert' }, teamLoadError) : null,
5377
+ h('div', { className: 'at-tcpick' },
5378
+ h('button', { className: 'at-btn at-btn-small', type: 'button', onClick: () => { setTeamComposeOpen(true); loadTalents(); } }, t('teamCompose')),
5379
+ selectedTeam && selectedTeam.source === 'user' ? h('button', { className: 'at-btn at-btn-small', type: 'button', onClick: () => void removeTeam(selectedTeam) }, t('teamDelete')) : null),
5232
5380
  nError ? h('div', { className: 'at-modalerror', role: 'alert' }, nError) : null,
5233
5381
  h('div', { className: 'at-modalactions' },
5234
5382
  h('button', { className: 'at-btn', type: 'button', onClick: () => setNewOpen(false), disabled: nBusy }, t('cancel')),
5235
5383
  h('button', { className: 'at-btn at-btn-primary', type: 'submit', disabled: nBusy || !nName.trim() || !nWorkspace.trim() }, nBusy ? t('saving') : t('projectCreate'))))) : null,
5384
+ teamComposeOpen ? h(ModalBack, { onClose: () => setTeamComposeOpen(false) },
5385
+ h('div', { className: 'at-modal at-modal-wide', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('teamComposeTitle') },
5386
+ h('h2', { className: 'at-modaltitle' }, t('teamComposeTitle')),
5387
+ h(TeamComposer, { t, talents, onSaved: (team) => { setTeamComposeOpen(false); void loadTeams(team && team.id); }, onCancel: () => setTeamComposeOpen(false) }))) : null,
5236
5388
  dialog ? h(WorkbenchDialog, { key: dialogSeqRef.current, t, dialog, onDismiss: () => setDialog(null) }) : null,
5237
5389
  shortcutsOpen ? h(ModalBack, { onClose: () => setShortcutsOpen(false) },
5238
5390
  h('div', { className: 'at-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('shortcutTitle') },
package/index.js CHANGED
@@ -28,7 +28,8 @@ import { activationSpec } from './lib/runtime/activation-spec.js';
28
28
  import { repairArchivedHosts as repairHostSessions } from './lib/runtime/host-repair.js';
29
29
  import { classifyLlmFailure, nextRequestAttempt, retryDecision } from './lib/runtime/failure-policy.js';
30
30
  import { memberIdentity } from './lib/domain/member-profile.js';
31
- import { loadSkillContext } from './lib/runtime/skill-loader.js';
31
+ import { findSkillText, loadSkillContext } from './lib/runtime/skill-loader.js';
32
+ import { skillKindForMember } from './lib/runtime/core-skill.js';
32
33
  import { formatSkillCatalog } from './lib/runtime/skill-catalog.js';
33
34
  import { isSkillExcluded } from './lib/runtime/skill-policy.js';
34
35
  import { installFileSkillProvider, pickProjectForCwd } from './lib/runtime/skill-provider.js';
@@ -71,7 +72,7 @@ import { isInformationalThreadMention } from './lib/domain/inbox.js';
71
72
  import { messageContent, normalizeAttachments } from './lib/domain/rich-message.js';
72
73
  import { readAttachment, uploadAttachment } from './lib/host/attachment-routes.js';
73
74
  import { createDiagLogger, defaultDiagDir, installDiagSink } from './lib/diaglog.js';
74
- import { DEFAULT_TEAM, catalogRoots, deleteTalent, installSkill, listInstallableSkills, listTalents, loadCatalog, readSkillText, resolveTeam, talentIdFrom, userCatalogDir, writeTalent } from './lib/domain/catalog.js';
75
+ import { DEFAULT_TEAM, catalogRoots, deleteTalent, deleteTeam, installSkill, listInstallableSkills, listTalents, listTeams, loadCatalog, readSkillText, resolveTeam, talentFromMember, talentIdFrom, uniqueTalentId, uniqueTeamId, userCatalogDir, writeTalent, writeTeam } from './lib/domain/catalog.js';
75
76
 
76
77
  export const name = 'ai-team';
77
78
 
@@ -138,9 +139,19 @@ function memberCatalogDirs(member, diag) {
138
139
  return talent === undefined ? [] : [talent.dir];
139
140
  }
140
141
 
141
- /** 新项目用哪个团队。 */
142
- function teamPresetFor(config, diag) {
143
- const preset = resolveTeam(talentCatalog(diag), config?.teamPreset || DEFAULT_TEAM, { diag });
142
+ /**
143
+ * 成员技能的查找根(团队规程目录另由 preset 前置):人才自带 → 工作区 `.dsh` → 用户 `~/.dsh` → 项目数据目录。
144
+ * 激活注入与「存为人才」共用,拷出来的技能就是成员实际读到的那份。
145
+ */
146
+ function memberSkillRoots(member, runtime, diag) {
147
+ const workspacePath = runtime?.service?.state?.projects?.[runtime.id]?.workspacePath;
148
+ const dir = member?.workspace || (typeof workspacePath === 'string' ? workspacePath.trim() : '');
149
+ return [...memberCatalogDirs(member, diag), ...(dir ? [join(dir, '.dsh')] : []), dshHome(), runtime?.dir].filter((root) => typeof root === 'string' && root !== '');
150
+ }
151
+
152
+ /** 新项目用哪个团队:新建时选的优先,其次插件设置 `teamPreset`,最后内置默认团队。 */
153
+ function teamPresetFor(config, diag, chosen = '') {
154
+ const preset = resolveTeam(talentCatalog(diag), chosen || config?.teamPreset || DEFAULT_TEAM, { diag });
144
155
  diag?.append?.({ ev: 'catalog.team', name: preset.id, source: preset.source, dir: preset.dir, members: preset.team.members.length });
145
156
  return preset;
146
157
  }
@@ -2134,7 +2145,7 @@ export function apply(ctx, config = {}) {
2134
2145
  // #65:激活时若带着 Human 消息的图片/文件,一并放进首条消息。
2135
2146
  prompt: messageContent(`${memberIdentity(activationMember)}\n\n${typeof body.payload?.prompt === 'string'
2136
2147
  ? body.payload.prompt
2137
- : '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${await formatSkillCatalog(skillsService, { cwd: effectiveDir })}${await loadSkillContext(activationMember, [...memberCatalogDirs(activationMember, diag), join(effectiveDir, '.dsh'), dshHome(), projectRuntime.dir], {
2148
+ : '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${await formatSkillCatalog(skillsService, { cwd: effectiveDir })}${await loadSkillContext(activationMember, memberSkillRoots(activationMember, projectRuntime, diag), {
2138
2149
  vars: {
2139
2150
  GOAL: goalForProject(projectRuntime),
2140
2151
  PROJECT: projectRuntime.service.state.projects?.[projectRuntime.id]?.name ?? '',
@@ -2283,7 +2294,7 @@ export function apply(ctx, config = {}) {
2283
2294
  entry.timer.unref?.();
2284
2295
  };
2285
2296
 
2286
- async function activateProject(nextProjectId, projectName, projectGoal, workspacePath = '') {
2297
+ async function activateProject(nextProjectId, projectName, projectGoal, workspacePath = '', team = '') {
2287
2298
  await ready;
2288
2299
  if (booted === null) throw new Error('team ledger is unavailable');
2289
2300
  let next = projectRuntime(nextProjectId);
@@ -2296,7 +2307,7 @@ export function apply(ctx, config = {}) {
2296
2307
  workspacePath,
2297
2308
  diag,
2298
2309
  pmoMaxRounds: config.pmoMaxRounds,
2299
- teamPreset: teamPresetFor(config, diag),
2310
+ teamPreset: teamPresetFor(config, diag, team),
2300
2311
  });
2301
2312
  booted.runtimes.set(nextProjectId, next);
2302
2313
  attachRuntime(next);
@@ -2366,6 +2377,48 @@ export function apply(ctx, config = {}) {
2366
2377
  if (req.method === 'GET' && url.pathname === '/ai-team/api/talents') {
2367
2378
  return send(res, { talents: listTalents(talentCatalog(diag)) });
2368
2379
  }
2380
+ // 团队列表(新建项目选团队、组队面板);defaultTeam 是插件设置里的默认团队。
2381
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/teams') {
2382
+ return send(res, { teams: listTeams(talentCatalog(diag)), defaultTeam: config?.teamPreset || DEFAULT_TEAM });
2383
+ }
2384
+ // 组队:从人才里挑人建一个用户团队(只写用户根;新建撞名加序号,改写需 overwrite)。
2385
+ if (req.method === 'POST' && url.pathname === '/ai-team/api/teams') {
2386
+ const body = await readJson(req);
2387
+ const cat = talentCatalog(diag);
2388
+ let id = talentIdFrom(body?.id) || talentIdFrom(body?.name);
2389
+ if (id === '' && typeof body?.name === 'string' && body.name.trim() !== '') id = 'team-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
2390
+ if (id === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '团队需要一个名字' } }, 400);
2391
+ if (body?.overwrite !== true) id = uniqueTeamId(cat, id);
2392
+ try {
2393
+ const saved = writeTeam(userCatalogDir(dshHome()), id, body ?? {}, cat);
2394
+ diag?.append({ ev: 'team.write', id, members: saved.members.length });
2395
+ return send(res, { ok: true, team: listTeams(talentCatalog(diag)).find((entry) => entry.id === id) });
2396
+ } catch (error) {
2397
+ return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: error.message } }, 400);
2398
+ }
2399
+ }
2400
+ if (req.method === 'POST' && url.pathname === '/ai-team/api/teams/delete') {
2401
+ const body = await readJson(req);
2402
+ const entry = talentCatalog(diag).teams.get(talentIdFrom(body?.id ?? ''));
2403
+ if (entry === undefined) return send(res, { error: { code: 'NOT_FOUND', message: 'team not found' } }, 404);
2404
+ if (entry.source !== 'user') return send(res, { error: { code: 'E_READONLY', message: '内置团队只读,不能删除' } }, 409);
2405
+ deleteTeam(userCatalogDir(dshHome()), entry.id);
2406
+ diag?.append({ ev: 'team.delete', id: entry.id });
2407
+ return send(res, { ok: true });
2408
+ }
2409
+ // 「存为人才」草稿:按成员此刻的岗位、职责(与激活同一判定)、性格、模型与技能生成;标出每份技能找不找得到。
2410
+ const talentDraftRoute = url.pathname.match(/^\/ai-team\/api\/projects\/([^/]+)\/members\/([^/]+)\/talent-draft$/);
2411
+ if (req.method === 'GET' && talentDraftRoute !== null) {
2412
+ const runtime = projectRuntime(decodeURIComponent(talentDraftRoute[1]));
2413
+ const member = runtime?.service?.state?.members?.[decodeURIComponent(talentDraftRoute[2])];
2414
+ if (member === undefined || member.kind !== 'agent') return send(res, { error: { code: 'NOT_FOUND', message: 'member not found' } }, 404);
2415
+ const project = runtime.service.state.projects?.[runtime.id];
2416
+ const draft = talentFromMember(member, skillKindForMember(member, { ownerId: project?.ownerMemberId ?? project?.ownerId }));
2417
+ const roots = [resolveTeam(talentCatalog(diag), member.team ?? DEFAULT_TEAM, { diag }).dir, ...memberSkillRoots(member, runtime, diag)];
2418
+ const skills = [];
2419
+ for (const name of draft.skills) skills.push({ name, found: (await findSkillText(roots, name)) !== null });
2420
+ return send(res, { draft: { ...draft, skills }, projectId: runtime.id, memberId: member.id });
2421
+ }
2369
2422
  // 可安装的技能清单(每个人才自带的技能),给「从已有装」挑。
2370
2423
  if (req.method === 'GET' && url.pathname === '/ai-team/api/skills-install') {
2371
2424
  return send(res, { skills: listInstallableSkills(talentCatalog(diag)) });
@@ -2388,6 +2441,9 @@ export function apply(ctx, config = {}) {
2388
2441
  let id = talentIdFrom(body?.id) || talentIdFrom(body?.name);
2389
2442
  if (id === '' && typeof body?.name === 'string' && body.name.trim() !== '') id = 'talent-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
2390
2443
  if (id === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '人才需要一个名字(用于生成 id)' } }, 400);
2444
+ // 新建不静默覆盖:撞了已有人才(含内置)就加序号;要改写已有的自定义人才须显式 overwrite。
2445
+ if (body?.overwrite !== true) id = uniqueTalentId(talentCatalog(diag), id);
2446
+ if (id === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '找不到可用的人才 id' } }, 400);
2391
2447
  try {
2392
2448
  const saved = writeTalent(userCatalogDir(dshHome()), id, body ?? {});
2393
2449
  diag?.append({ ev: 'talent.write', id, source: 'user' });
@@ -2421,7 +2477,16 @@ export function apply(ctx, config = {}) {
2421
2477
  if (src === undefined) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '来源人才不存在' } }, 400);
2422
2478
  try { markdown = readSkillText(src.dir, body.fromSkill); } catch (error) { return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: error.message } }, 400); }
2423
2479
  }
2424
- if (markdown === null) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '需要 markdown 正文,或 fromTalent + fromSkill' } }, 400);
2480
+ // 「存为人才」:按来源成员实际读技能的路径找正文(团队规程目录 + 成员技能根),拷进新人才。
2481
+ if (markdown === null && typeof body?.fromProject === 'string' && typeof body?.fromMember === 'string') {
2482
+ const runtime = projectRuntime(body.fromProject);
2483
+ const member = runtime?.service?.state?.members?.[body.fromMember];
2484
+ if (member === undefined) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '来源成员不存在' } }, 400);
2485
+ const roots = [resolveTeam(cat, member.team ?? DEFAULT_TEAM, { diag }).dir, ...memberSkillRoots(member, runtime, diag)];
2486
+ markdown = await findSkillText(roots, body?.name);
2487
+ if (markdown === null) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `成员「${member.name}」能读到的位置里找不到技能 ${String(body?.name)}` } }, 400);
2488
+ }
2489
+ if (markdown === null) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '需要 markdown 正文,或 fromTalent + fromSkill,或 fromProject + fromMember' } }, 400);
2425
2490
  try {
2426
2491
  const name = installSkill(t.dir, body?.name, markdown);
2427
2492
  const saved = writeTalent(userCatalogDir(dshHome()), t.id, { ...t, skills: [...new Set([...t.skills, name])] });
@@ -2913,12 +2978,20 @@ export function apply(ctx, config = {}) {
2913
2978
  return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `工作目录不存在或不是目录:${workspacePath}` } }, 400);
2914
2979
  }
2915
2980
  }
2981
+ // 新建时选的团队:必须在目录里且引用的人才都在(否则种成员会悄悄退回默认团队)。
2982
+ const team = typeof body.payload?.team === 'string' ? body.payload.team.trim() : '';
2983
+ if (team !== '') {
2984
+ const chosen = listTeams(talentCatalog(diag)).find((entry) => entry.id === team);
2985
+ if (chosen === undefined) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `团队不存在:${team}` } }, 400);
2986
+ if (chosen.broken) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `团队「${chosen.name}」引用了不存在的人才,先修好再用` } }, 400);
2987
+ }
2916
2988
  const id = ids.project();
2917
2989
  // 先校验工作目录(上面已做),再写 registry、最后开 runtime:
2918
2990
  // activateProject 内部会调用 registry.setActive(id),因此该行必须已
2919
2991
  // 存在。校验前置后,不会再把一个打不开的项目写进 projects.json。
2920
2992
  booted.registry.add({ id, name, goal, workspacePath });
2921
- const next = await activateProject(id, name, goal, workspacePath);
2993
+ const next = await activateProject(id, name, goal, workspacePath, team);
2994
+ diag?.append({ ev: 'project.create', id, team: team || null });
2922
2995
  return send(res, { ok: true, project: next.service.state.projects[id] ?? { id, name } });
2923
2996
  }
2924
2997
  if (body.type === 'project.activate') {
@@ -295,6 +295,104 @@ export function readSkillText(talentDir, name) {
295
295
  return readFileSync(join(talentDir, 'skills', skillName(name, '技能名'), 'SKILL.md'), 'utf8');
296
296
  }
297
297
 
298
+ /**
299
+ * 新建时取一个不撞车的 id:已被任何来源(用户或内置)占用就加序号 -2、-3…。
300
+ * 新建绝不静默覆盖别人的人才,也不意外遮盖同名内置人才(要覆盖得显式 overwrite)。
301
+ */
302
+ export function uniqueTalentId(catalog, base) {
303
+ return uniqueIn(catalog.talents, base);
304
+ }
305
+
306
+ /** 新建团队同理:撞了已有团队(含内置)就加序号。 */
307
+ export function uniqueTeamId(catalog, base) {
308
+ return uniqueIn(catalog.teams, base);
309
+ }
310
+
311
+ function uniqueIn(taken, base) {
312
+ if (!SLUG.test(base)) return '';
313
+ if (!taken.has(base)) return base;
314
+ for (let n = 2; n < 1000; n += 1) {
315
+ const id = `${base.slice(0, 60)}-${n}`;
316
+ if (!taken.has(id)) return id;
317
+ }
318
+ return '';
319
+ }
320
+
321
+ /**
322
+ * 团队列表(新建项目选团队、组队面板):成员按人才补齐名字、岗位与职责;引用了不存在的人才标 broken
323
+ * ——这种团队建项目时会退回默认团队,界面不让选。
324
+ */
325
+ export function listTeams(catalog) {
326
+ return [...catalog.teams.values()]
327
+ .map((entry) => {
328
+ const members = entry.members.map((m) => {
329
+ const t = catalog.talents.get(m.talent);
330
+ return { id: m.id, talent: m.talent, name: m.name || t?.name || m.talent, role: m.role || t?.role || '', duty: m.duty ?? t?.duty ?? null, missing: t === undefined };
331
+ });
332
+ return { id: entry.id, source: entry.source, name: entry.name || entry.id, description: entry.description, lead: entry.lead, members, broken: members.some((m) => m.missing) };
333
+ })
334
+ .sort((a, b) => (a.id === DEFAULT_TEAM ? -1 : b.id === DEFAULT_TEAM ? 1 : 0) || a.source.localeCompare(b.source) || a.name.localeCompare(b.name, 'zh'));
335
+ }
336
+
337
+ /**
338
+ * 组队:写一个用户团队 `<userRoot>/teams/<id>/team.yml`。
339
+ * `members` 是 [{ talent, name? }](同一人才可招多位,成员 id 自动生成且不重复),`lead` 是成员下标或成员 id(缺省第一位)。
340
+ * 引用的人才必须在目录里;校验复用 parseTeam,验不过就抛、不落盘。
341
+ */
342
+ export function writeTeam(userRoot, id, input, catalog) {
343
+ if (typeof userRoot !== 'string' || userRoot === '') throw new Error('writeTeam: 需要 userRoot');
344
+ if (typeof id !== 'string' || !SLUG.test(id)) throw new Error('团队 id 必须是小写字母、数字、连字符,≤64 位');
345
+ const name = text(input?.name, 60);
346
+ if (name === '') throw new Error('团队需要一个名字');
347
+ const raw = Array.isArray(input?.members) ? input.members : [];
348
+ if (raw.length === 0) throw new Error('团队至少要有一位成员');
349
+ const used = new Set();
350
+ const members = raw.map((m, i) => {
351
+ const talent = text(m?.talent, 64);
352
+ if (!SLUG.test(talent) || (catalog && !catalog.talents.has(talent))) throw new Error(`第 ${i + 1} 位成员引用的人才不存在:${String(m?.talent)}`);
353
+ const base = `mem_${talent.replace(/-/g, '_')}`.slice(0, 60);
354
+ let memberId = base;
355
+ for (let n = 2; used.has(memberId); n += 1) memberId = `${base.slice(0, 56)}_${n}`;
356
+ used.add(memberId);
357
+ const label = text(m?.name, 40);
358
+ return { talent, id: memberId, ...(label ? { name: label } : {}) };
359
+ });
360
+ const leadIndex = Number.isInteger(input?.lead) ? input.lead : members.findIndex((m) => m.id === input?.lead);
361
+ const doc = { name, ...(text(input?.description, 400) ? { description: text(input.description, 400) } : {}), lead: (members[leadIndex] ?? members[0]).id, members };
362
+ const yaml = stringify(doc, { lineWidth: 0 });
363
+ const team = parseTeam(yaml, `team ${id}`); // 先验后写
364
+ const dir = join(userRoot, 'teams', id);
365
+ mkdirSync(dir, { recursive: true });
366
+ writeFileSync(join(dir, 'team.yml'), yaml, 'utf8');
367
+ return { id, source: 'user', dir, ...team };
368
+ }
369
+
370
+ /** 删一个用户团队(只删用户根下的)。 */
371
+ export function deleteTeam(userRoot, id) {
372
+ if (typeof id !== 'string' || !SLUG.test(id)) throw new Error('团队 id 不合法');
373
+ rmSync(join(userRoot, 'teams', id), { recursive: true, force: true });
374
+ }
375
+
376
+ /**
377
+ * 项目成员 → 人才草稿(「存为人才」):带上它此刻的岗位、职责、性格(含复盘长出来的)、模型与技能名;
378
+ * 不带笔记、会话与任务——那是这位成员自己的经历。duty 由调用方按身份判定后传入。
379
+ */
380
+ export function talentFromMember(member, duty) {
381
+ const config = member?.config ?? {};
382
+ const provider = text(config.provider, 80);
383
+ const model = text(config.model, 160);
384
+ return {
385
+ name: text(member?.name, 40),
386
+ role: text(member?.role, 40),
387
+ duty: DUTIES.includes(duty) ? duty : 'executor',
388
+ category: '',
389
+ tags: [],
390
+ personality: text(member?.personality, 2000),
391
+ model: provider || model ? { provider, model, reasoningEffort: text(config.reasoningEffort, 20) } : null,
392
+ skills: (Array.isArray(member?.skills) ? member.skills : []).map((s) => text(String(s), 64)).filter((s) => SKILL_NAME.test(s)),
393
+ };
394
+ }
395
+
298
396
  /** 列出可安装的技能:当前目录里每个人才自带的技能(名字 + 来源人才),给「从已有装」挑。 */
299
397
  export function listInstallableSkills(catalog) {
300
398
  const out = [];
@@ -1,139 +1,139 @@
1
- import { ERRORS, fail } from './errors.js';
2
- import { isQaMember, isReviewerMember } from './member-profile.js';
3
-
4
- /** @typedef {{ kind: 'human'|'agent'|'system', memberId?: string }} Actor */
5
-
6
- /** Member statuses allowed to hold work or review; failed members are out. */
7
- export const ACTIVE_MEMBER_STATUSES = Object.freeze(['provisioning', 'running', 'idle']);
8
-
9
- /**
10
- * The single authority for "which Agent may review this Task" (INV-04/Q-05):
11
- * active, not the current assignee, never a past claimant. QA-required Tasks
12
- * narrow candidates to QA members. The command layer additionally resolves the
13
- * acting member; Human review is the fallback (policy reasons live in
14
- * reviewEligibility below).
15
- */
16
- export function isReviewCandidate(member, task) {
17
- if (member?.kind !== 'agent') return false;
18
- if (!ACTIVE_MEMBER_STATUSES.includes(member.status)) return false;
19
- if (member.id === task.assigneeId) return false;
20
- if (Array.isArray(task.claimHistory) && task.claimHistory.includes(member.id)) return false;
21
- if (task.qaRequired === true && !isQaMember(member)) return false;
22
- return true;
23
- }
24
-
25
- /**
26
- * Ranked review candidates for the Waker: QA first, then reviewer roles,
27
- * then any other eligible Agent. Older members win ties.
28
- */
29
- export function eligibleReviewers(state, task) {
30
- if (task === undefined || task === null) return [];
31
- const candidates = Object.values(state.members ?? {}).filter((member) => isReviewCandidate(member, task));
32
- const rank = (member) => (isQaMember(member) ? 0 : isReviewerMember(member) ? 1 : 2);
33
- return candidates.sort((a, b) => rank(a) - rank(b) || String(a.createdAt).localeCompare(String(b.createdAt)));
34
- }
35
-
36
- export function isHuman(actor) {
37
- return actor?.kind === 'human';
38
- }
39
-
40
- export function memberIdOf(actor) {
41
- return actor?.memberId ?? null;
42
- }
43
-
44
- export function assertRevision(task, expectedRevision) {
45
- if (expectedRevision === undefined || expectedRevision === null) return;
46
- if (task.revision !== expectedRevision) {
47
- fail(ERRORS.REVISION, `task ${task.id} revision ${String(expectedRevision)} is stale; current is ${String(task.revision)}`, {
48
- details: { taskId: task.id, expectedRevision, currentRevision: task.revision },
49
- });
50
- }
51
- }
52
-
53
- export function isOwnerOrHuman(task, actor) {
54
- return isHuman(actor) || (memberIdOf(actor) !== null && task.ownerId === memberIdOf(actor));
55
- }
56
-
57
- export function assertOwnerOrHuman(task, actor) {
58
- if (!isOwnerOrHuman(task, actor)) {
59
- fail(ERRORS.UNAUTHORIZED, 'only the accountable owner or Human may perform this action', {
60
- details: { taskId: task.id, ownerId: task.ownerId, actor: memberIdOf(actor) },
61
- });
62
- }
63
- }
64
-
65
- export function assertAssignee(task, actor) {
66
- if (memberIdOf(actor) === null || task.assigneeId !== memberIdOf(actor)) {
67
- fail(ERRORS.UNAUTHORIZED, 'only the current assignee may perform this action', {
68
- details: { taskId: task.id, assigneeId: task.assigneeId, actor: memberIdOf(actor) },
69
- });
70
- }
71
- }
72
-
73
- export function dependenciesDone(task, tasksById) {
74
- return (task.blockedBy ?? []).every((id) => tasksById?.[id]?.status === 'done');
75
- }
76
-
77
- export function memberHasInProgress(tasksById, memberId) {
78
- if (memberId === null) return undefined;
79
- return Object.values(tasksById ?? {}).find((candidate) => candidate.assigneeId === memberId && candidate.status === 'in_progress');
80
- }
81
-
82
- /** A member must not start the next Task while their previous Task awaits QA. */
83
- export function memberHasPendingAcceptance(tasksById, memberId) {
84
- if (memberId === null) return undefined;
85
- return Object.values(tasksById ?? {}).find((candidate) => candidate.assigneeId === memberId && candidate.status === 'pending_acceptance');
86
- }
87
-
88
- /**
89
- * A reviewer is eligible when the task is in pending_acceptance and the
90
- * reviewer never claimed it (Agent) or is Human. Human self-accept is allowed
91
- * but must be recorded as non-independent.
92
- */
93
- export function reviewEligibility(task, actor) {
94
- if (task.status !== 'pending_acceptance') {
95
- return { eligible: false, reason: 'task is not pending_acceptance', code: ERRORS.INVALID_STATE };
96
- }
97
- const memberId = memberIdOf(actor);
98
- if (isHuman(actor)) {
99
- return {
100
- eligible: true,
101
- selfExecuted: memberId !== null && task.claimHistory.includes(memberId),
102
- reason: 'human fallback',
103
- };
104
- }
105
- if (memberId === null) {
106
- return { eligible: false, reason: 'unknown member', code: ERRORS.UNAUTHORIZED };
107
- }
108
- if (task.assigneeId === memberId) {
109
- return { eligible: false, reason: 'current assignee cannot review', code: ERRORS.NOT_ELIGIBLE };
110
- }
111
- if (task.claimHistory.includes(memberId)) {
112
- return { eligible: false, reason: 'a past claimant cannot review', code: ERRORS.NOT_ELIGIBLE };
113
- }
114
- return { eligible: true, selfExecuted: false, reason: 'independent reviewer' };
115
- }
116
-
117
- export function assertReviewEligible(task, actor) {
118
- const result = reviewEligibility(task, actor);
119
- if (!result.eligible) {
120
- fail(result.code ?? ERRORS.NOT_ELIGIBLE, result.reason ?? 'reviewer is not eligible', {
121
- details: { taskId: task.id, actor: memberIdOf(actor) },
122
- });
123
- }
124
- return result;
125
- }
126
-
127
- export function assertIrreversibleConfirmation(task, actor, confirmed) {
128
- if (!task.irreversible) return;
129
- if (!isHuman(actor)) {
130
- fail(ERRORS.IRREVERSIBLE_CONFIRM, 'an Agent may only suggest acceptance for an irreversible Task', {
131
- details: { taskId: task.id },
132
- });
133
- }
134
- if (confirmed !== true) {
135
- fail(ERRORS.IRREVERSIBLE_CONFIRM, 'Human confirmation is required for an irreversible Task', {
136
- details: { taskId: task.id },
137
- });
138
- }
139
- }
1
+ import { ERRORS, fail } from './errors.js';
2
+ import { isQaMember, isReviewerMember } from './member-profile.js';
3
+
4
+ /** @typedef {{ kind: 'human'|'agent'|'system', memberId?: string }} Actor */
5
+
6
+ /** Member statuses allowed to hold work or review; failed members are out. */
7
+ export const ACTIVE_MEMBER_STATUSES = Object.freeze(['provisioning', 'running', 'idle']);
8
+
9
+ /**
10
+ * The single authority for "which Agent may review this Task" (INV-04/Q-05):
11
+ * active, not the current assignee, never a past claimant. QA-required Tasks
12
+ * narrow candidates to QA members. The command layer additionally resolves the
13
+ * acting member; Human review is the fallback (policy reasons live in
14
+ * reviewEligibility below).
15
+ */
16
+ export function isReviewCandidate(member, task) {
17
+ if (member?.kind !== 'agent') return false;
18
+ if (!ACTIVE_MEMBER_STATUSES.includes(member.status)) return false;
19
+ if (member.id === task.assigneeId) return false;
20
+ if (Array.isArray(task.claimHistory) && task.claimHistory.includes(member.id)) return false;
21
+ if (task.qaRequired === true && !isQaMember(member)) return false;
22
+ return true;
23
+ }
24
+
25
+ /**
26
+ * Ranked review candidates for the Waker: QA first, then reviewer roles,
27
+ * then any other eligible Agent. Older members win ties.
28
+ */
29
+ export function eligibleReviewers(state, task) {
30
+ if (task === undefined || task === null) return [];
31
+ const candidates = Object.values(state.members ?? {}).filter((member) => isReviewCandidate(member, task));
32
+ const rank = (member) => (isQaMember(member) ? 0 : isReviewerMember(member) ? 1 : 2);
33
+ return candidates.sort((a, b) => rank(a) - rank(b) || String(a.createdAt).localeCompare(String(b.createdAt)));
34
+ }
35
+
36
+ export function isHuman(actor) {
37
+ return actor?.kind === 'human';
38
+ }
39
+
40
+ export function memberIdOf(actor) {
41
+ return actor?.memberId ?? null;
42
+ }
43
+
44
+ export function assertRevision(task, expectedRevision) {
45
+ if (expectedRevision === undefined || expectedRevision === null) return;
46
+ if (task.revision !== expectedRevision) {
47
+ fail(ERRORS.REVISION, `task ${task.id} revision ${String(expectedRevision)} is stale; current is ${String(task.revision)}`, {
48
+ details: { taskId: task.id, expectedRevision, currentRevision: task.revision },
49
+ });
50
+ }
51
+ }
52
+
53
+ export function isOwnerOrHuman(task, actor) {
54
+ return isHuman(actor) || (memberIdOf(actor) !== null && task.ownerId === memberIdOf(actor));
55
+ }
56
+
57
+ export function assertOwnerOrHuman(task, actor) {
58
+ if (!isOwnerOrHuman(task, actor)) {
59
+ fail(ERRORS.UNAUTHORIZED, 'only the accountable owner or Human may perform this action', {
60
+ details: { taskId: task.id, ownerId: task.ownerId, actor: memberIdOf(actor) },
61
+ });
62
+ }
63
+ }
64
+
65
+ export function assertAssignee(task, actor) {
66
+ if (memberIdOf(actor) === null || task.assigneeId !== memberIdOf(actor)) {
67
+ fail(ERRORS.UNAUTHORIZED, 'only the current assignee may perform this action', {
68
+ details: { taskId: task.id, assigneeId: task.assigneeId, actor: memberIdOf(actor) },
69
+ });
70
+ }
71
+ }
72
+
73
+ export function dependenciesDone(task, tasksById) {
74
+ return (task.blockedBy ?? []).every((id) => tasksById?.[id]?.status === 'done');
75
+ }
76
+
77
+ export function memberHasInProgress(tasksById, memberId) {
78
+ if (memberId === null) return undefined;
79
+ return Object.values(tasksById ?? {}).find((candidate) => candidate.assigneeId === memberId && candidate.status === 'in_progress');
80
+ }
81
+
82
+ /** A member must not start the next Task while their previous Task awaits QA. */
83
+ export function memberHasPendingAcceptance(tasksById, memberId) {
84
+ if (memberId === null) return undefined;
85
+ return Object.values(tasksById ?? {}).find((candidate) => candidate.assigneeId === memberId && candidate.status === 'pending_acceptance');
86
+ }
87
+
88
+ /**
89
+ * A reviewer is eligible when the task is in pending_acceptance and the
90
+ * reviewer never claimed it (Agent) or is Human. Human self-accept is allowed
91
+ * but must be recorded as non-independent.
92
+ */
93
+ export function reviewEligibility(task, actor) {
94
+ if (task.status !== 'pending_acceptance') {
95
+ return { eligible: false, reason: 'task is not pending_acceptance', code: ERRORS.INVALID_STATE };
96
+ }
97
+ const memberId = memberIdOf(actor);
98
+ if (isHuman(actor)) {
99
+ return {
100
+ eligible: true,
101
+ selfExecuted: memberId !== null && task.claimHistory.includes(memberId),
102
+ reason: 'human fallback',
103
+ };
104
+ }
105
+ if (memberId === null) {
106
+ return { eligible: false, reason: 'unknown member', code: ERRORS.UNAUTHORIZED };
107
+ }
108
+ if (task.assigneeId === memberId) {
109
+ return { eligible: false, reason: 'current assignee cannot review', code: ERRORS.NOT_ELIGIBLE };
110
+ }
111
+ if (task.claimHistory.includes(memberId)) {
112
+ return { eligible: false, reason: 'a past claimant cannot review', code: ERRORS.NOT_ELIGIBLE };
113
+ }
114
+ return { eligible: true, selfExecuted: false, reason: 'independent reviewer' };
115
+ }
116
+
117
+ export function assertReviewEligible(task, actor) {
118
+ const result = reviewEligibility(task, actor);
119
+ if (!result.eligible) {
120
+ fail(result.code ?? ERRORS.NOT_ELIGIBLE, result.reason ?? 'reviewer is not eligible', {
121
+ details: { taskId: task.id, actor: memberIdOf(actor) },
122
+ });
123
+ }
124
+ return result;
125
+ }
126
+
127
+ export function assertIrreversibleConfirmation(task, actor, confirmed) {
128
+ if (!task.irreversible) return;
129
+ if (!isHuman(actor)) {
130
+ fail(ERRORS.IRREVERSIBLE_CONFIRM, 'an Agent may only suggest acceptance for an irreversible Task', {
131
+ details: { taskId: task.id },
132
+ });
133
+ }
134
+ if (confirmed !== true) {
135
+ fail(ERRORS.IRREVERSIBLE_CONFIRM, 'Human confirmation is required for an irreversible Task', {
136
+ details: { taskId: task.id },
137
+ });
138
+ }
139
+ }
@@ -10,7 +10,7 @@
10
10
  * `talents/`, or a user team selected by the `teamPreset` setting (lib/domain/catalog.js).
11
11
  */
12
12
 
13
- import { loadCatalog, resolveTeam } from '../domain/catalog.js';
13
+ import { DEFAULT_TEAM, loadCatalog, resolveTeam } from '../domain/catalog.js';
14
14
 
15
15
  /** Names shipped by 0.3.9 and earlier; only these exact pins are migrated. */
16
16
  const LEGACY_DEFAULT_NAMES = Object.freeze({
@@ -64,8 +64,12 @@ export async function seedDefaultRoster(service, projectId, { humanId = 'mem_hum
64
64
  const roster = team.members;
65
65
  if (agentMembers(service).length > 0) {
66
66
  const renamed = await upgradeLegacyDefaultNames(service, projectId, humanId, roster);
67
- // 补缺岗只是老项目补齐 UX/业务 的迁移,只按内置团队做;用户团队只用于新项目,不改已有项目。
68
- if (preset.source !== 'bundled') return { seeded: false, members: [], renamed };
67
+ // 补缺岗只是老项目补齐 UX/业务 的迁移:只按**内置默认团队**做,且只对本来就由默认团队组成的项目
68
+ // (成员没记团队的老成员,或记的就是 default)。0.4.124 起内置团队不止一个(science、game…),
69
+ // 只看 source === 'bundled' 会让设置换团队后,重启把那个团队的岗位塞进每个已有项目。
70
+ // 用户团队与其它内置团队只用于新项目,不改已有项目。
71
+ if (preset.source !== 'bundled' || preset.id !== DEFAULT_TEAM) return { seeded: false, members: [], renamed };
72
+ if (agentMembers(service).some((member) => typeof member.team === 'string' && member.team !== DEFAULT_TEAM)) return { seeded: false, members: [], renamed };
69
73
  const added = [];
70
74
  const existingRoles = new Set(agentMembers(service).map((member) => member.role));
71
75
  const existingIds = new Set(Object.keys(service.state.members ?? {}));
@@ -20,6 +20,32 @@ export function renderSkillVars(text, vars = {}) {
20
20
  });
21
21
  }
22
22
 
23
+ /** 技能名规范化(防路径穿越):只留文件名里的字母数字与 ._-,不合法返回空串。 */
24
+ export function skillFileName(raw) {
25
+ const name = basename(String(raw ?? '')).replace(/[^a-zA-Z0-9._-]/g, '');
26
+ return name === '' || name === '.' || name === '..' || name.startsWith('.') ? '' : name;
27
+ }
28
+
29
+ /**
30
+ * 按根的顺序找一份技能正文:`<root>/skills/<name>/SKILL.md` 或 `<root>/skills/<name>.md`,先到先得;
31
+ * 找不到返回 null。成员激活注入与「存为人才」拷技能共用这一份查找,保证拷出来的就是成员实际读到的。
32
+ */
33
+ export async function findSkillText(roots, raw) {
34
+ const name = skillFileName(raw);
35
+ if (name === '') return null;
36
+ for (const root of Array.isArray(roots) ? roots : [roots]) {
37
+ if (typeof root !== 'string' || root === '') continue;
38
+ for (const candidate of [join(root, 'skills', name, 'SKILL.md'), join(root, 'skills', `${name}.md`)]) {
39
+ try {
40
+ return await readFile(candidate, 'utf8');
41
+ } catch (error) {
42
+ if (error?.code !== 'ENOENT') break;
43
+ }
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+
23
49
  /**
24
50
  * Read bounded SKILL.md files for member-declared skills from the profile skill library.
25
51
  *
@@ -43,23 +69,10 @@ export async function loadSkillContext(member, dataDir, options = {}) {
43
69
  const roots = [preset?.dir, ...(Array.isArray(dataDir) ? dataDir : [dataDir])]
44
70
  .filter((root) => typeof root === 'string' && root !== '');
45
71
  for (const raw of skills.slice(0, 4)) {
46
- const name = basename(String(raw)).replace(/[^a-zA-Z0-9._-]/g, '');
47
- if (name === '' || name === '.' || name === '..' || name.startsWith('.')) continue;
48
- if (isSkillExcluded(name)) continue;
49
- for (const root of roots) {
50
- let loaded = false;
51
- for (const candidate of [join(root, 'skills', name, 'SKILL.md'), join(root, 'skills', `${name}.md`)]) {
52
- try {
53
- const text = await readFile(candidate, 'utf8');
54
- chunks.push(`### ${name}\n${text.slice(0, MAX_SKILL_CHARS)}`);
55
- loaded = true;
56
- break;
57
- } catch (error) {
58
- if (error?.code !== 'ENOENT') break;
59
- }
60
- }
61
- if (loaded) break;
62
- }
72
+ const name = skillFileName(raw);
73
+ if (name === '' || isSkillExcluded(name)) continue;
74
+ const text = await findSkillText(roots, name);
75
+ if (text !== null) chunks.push(`### ${name}\n${text.slice(0, MAX_SKILL_CHARS)}`);
63
76
  }
64
77
  return chunks.length === 0 ? '' : `\n\n[技能资料]\n${chunks.join('\n\n')}`;
65
78
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.125",
3
+ "version": "0.4.127",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",