evolcore 0.0.43-test.1 → 0.0.43-test.3

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.
Files changed (200) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/README.md +22 -0
  3. package/dist/agents/claude-runner.js +26 -2
  4. package/dist/agents/codex/app-server-client.js +12 -0
  5. package/dist/agents/codex-runner.js +49 -8
  6. package/dist/agents/ecagent-runner.js +39 -15
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/aid/agentmd.js +21 -1
  10. package/dist/aun/menu/client.js +1 -1
  11. package/dist/aun/model-headers.js +17 -0
  12. package/dist/aun/msg/p2p.js +7 -2
  13. package/dist/channels/aun.js +522 -50
  14. package/dist/channels/builtin-plugins.js +16 -11
  15. package/dist/channels/daemon.js +4 -0
  16. package/dist/channels/dingtalk.js +83 -31
  17. package/dist/channels/feishu.js +29 -13
  18. package/dist/channels/qqbot.js +32 -11
  19. package/dist/channels/wechat.js +13 -3
  20. package/dist/channels/wecom.js +67 -27
  21. package/dist/cli/agent-command.js +3 -86
  22. package/dist/cli/agent-create.js +20 -6
  23. package/dist/cli/agent.js +1 -79
  24. package/dist/cli/aun-commands.js +18 -19
  25. package/dist/cli/config.js +1 -1
  26. package/dist/cli/daemon-commands.js +47 -2
  27. package/dist/cli/data-command.js +9 -1
  28. package/dist/cli/debug-mode.js +1 -1
  29. package/dist/cli/diag.js +1 -1
  30. package/dist/cli/directory.js +149 -91
  31. package/dist/cli/getmeta-command.js +1 -1
  32. package/dist/cli/index.js +79 -22
  33. package/dist/cli/init.js +1 -23
  34. package/dist/cli/link-rules.js +1 -1
  35. package/dist/cli/managed-command-guard.js +0 -1
  36. package/dist/cli/pa-workspace-command.js +36 -2
  37. package/dist/cli/peer.js +3 -2
  38. package/dist/cli/restart-monitor.js +17 -3
  39. package/dist/cli/role.js +1 -1
  40. package/dist/cli/session-command.js +1 -1
  41. package/dist/cli/stats.js +2 -2
  42. package/dist/cli/task-context.js +3 -1
  43. package/dist/cli/thread-command.js +1 -1
  44. package/dist/cli/watch-msg.js +1 -1
  45. package/dist/config/builtin-role-templates.js +2 -2
  46. package/dist/config/builtin-roles.js +2 -1
  47. package/dist/config/config-field-policy.js +7 -2
  48. package/dist/config/config-manager.js +32 -10
  49. package/dist/config/peer-role-resolver.js +23 -1
  50. package/dist/config/role-schema.js +29 -4
  51. package/dist/config/role-service.js +12 -7
  52. package/dist/config/role-store.js +30 -8
  53. package/dist/config-store.js +75 -4
  54. package/dist/core/agent-ipc-registration.js +16 -59
  55. package/dist/core/auth/auth-gateway.js +14 -4
  56. package/dist/core/auth/authorization-audit.js +52 -14
  57. package/dist/core/auth/operation-authorizer.js +17 -11
  58. package/dist/core/auth/operation-catalog.js +5 -13
  59. package/dist/core/channel-loader.js +152 -16
  60. package/dist/core/channel-runtime.js +5 -0
  61. package/dist/core/command/agent-control.js +2 -1
  62. package/dist/core/command/agentmd-menu-request.js +50 -0
  63. package/dist/core/command/agentmd-menu.js +156 -0
  64. package/dist/core/command/cli-intent-parser.js +0 -8
  65. package/dist/core/command/command-handler.js +47 -40
  66. package/dist/core/command/connect-menu.js +7 -3
  67. package/dist/core/command/menu-catalog.js +16 -2
  68. package/dist/core/command/menu-handler.js +107 -14
  69. package/dist/core/command/menu-protocol.js +28 -0
  70. package/dist/core/command/role-menu.js +23 -9
  71. package/dist/core/command/slash-handler.js +139 -51
  72. package/dist/core/daemon-file-cache.js +3 -3
  73. package/dist/core/daemon-lifecycle.js +9 -1
  74. package/dist/core/evolagent-registry.js +5 -4
  75. package/dist/core/evolagent.js +10 -12
  76. package/dist/core/handoff/argv-parse.js +115 -0
  77. package/dist/core/handoff/ipc-registration.js +1 -1
  78. package/dist/core/ipc-registration.js +19 -2
  79. package/dist/core/lifecycle-notice.js +185 -0
  80. package/dist/core/memory/consolidation.js +8 -1
  81. package/dist/core/memory/relation-sweep.js +20 -8
  82. package/dist/core/message/aun-ipc-sender.js +35 -2
  83. package/dist/core/message/contact-admission.js +530 -0
  84. package/dist/core/message/im-renderer.js +111 -16
  85. package/dist/core/message/message-admission.js +29 -54
  86. package/dist/core/message/message-bridge.js +62 -8
  87. package/dist/core/message/message-utils.js +9 -5
  88. package/dist/core/message/peer-mode.js +55 -13
  89. package/dist/core/message/response-engine.js +298 -78
  90. package/dist/core/message/retry-scheduler.js +4 -0
  91. package/dist/core/ownership/owner-resolver.js +72 -34
  92. package/dist/core/permission/ec-command-parser.js +25 -38
  93. package/dist/core/permission/readonly-shell-query.js +34 -8
  94. package/dist/core/permission/tool-policy.js +50 -5
  95. package/dist/core/relation/pa-team.js +127 -0
  96. package/dist/core/role/runtime-policy.js +18 -5
  97. package/dist/core/session/session-manager.js +9 -1
  98. package/dist/core/soul.js +66 -0
  99. package/dist/core/system-session/memory.js +2 -2
  100. package/dist/core/thread/thread-service.js +6 -4
  101. package/dist/directory/contact-admission-paths.js +9 -0
  102. package/dist/directory/owner-directory-admission.js +125 -29
  103. package/dist/directory/owner-directory-cache.js +554 -58
  104. package/dist/directory/owner-directory-identity.js +60 -0
  105. package/dist/directory/owner-directory-markdown.js +154 -58
  106. package/dist/directory/owner-directory-policy.js +108 -0
  107. package/dist/directory/owner-directory-query-operation.js +399 -90
  108. package/dist/directory/owner-directory-remarks.js +29 -2
  109. package/dist/directory/owner-directory-request-operation.js +76 -0
  110. package/dist/directory/owner-directory-scope.js +35 -4
  111. package/dist/directory/owner-directory-search.js +118 -33
  112. package/dist/directory/owner-directory-store.js +117 -30
  113. package/dist/directory/owner-directory-text.js +60 -0
  114. package/dist/eck/kit-renderer.js +18 -8
  115. package/dist/eck/manifest-engine.js +55 -6
  116. package/dist/ecweb/basic-settings-service.js +2 -2
  117. package/dist/ecweb/message-context-service.js +28 -16
  118. package/dist/index.js +20 -5
  119. package/dist/ipc.js +1 -1
  120. package/dist/paths.js +29 -1
  121. package/dist/product.js +1 -0
  122. package/dist/response-system/config-resolver.js +1 -1
  123. package/dist/response-system/engines/v1/index.js +2 -1
  124. package/dist/response-system/modes/single-session/index.js +7 -2
  125. package/dist/trigger/scheduler.js +7 -4
  126. package/dist/trigger/validation.js +4 -0
  127. package/dist/utils/error-utils.js +12 -7
  128. package/dist/utils/logger.js +13 -4
  129. package/dist/utils/npm-ops.js +2 -2
  130. package/dist/utils/windows-autostart.js +1 -1
  131. package/ecagent/README.md +18 -0
  132. package/ecagent/dist/agent-loop.js +43 -1
  133. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  134. package/ecagent/dist/harness/agent-harness.js +24 -8
  135. package/ecagent/dist/harness/compaction/compaction.js +3 -0
  136. package/ecagent/dist/harness/types.d.ts +1 -0
  137. package/kits/docs/INDEX.md +1 -0
  138. package/kits/docs/channels/aun.md +1 -1
  139. package/kits/docs/context-assembly.md +21 -6
  140. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  141. package/kits/docs/evolcore/INDEX.md +4 -1
  142. package/kits/docs/evolcore/agent-create.md +5 -5
  143. package/kits/docs/evolcore/agent.md +4 -9
  144. package/kits/docs/evolcore/directory.md +227 -0
  145. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  146. package/kits/docs/evolcore/file-navigation.md +265 -0
  147. package/kits/docs/evolcore/menu-protocol.md +55 -0
  148. package/kits/docs/evolcore/msg.md +1 -0
  149. package/kits/docs/evolcore/peer.md +2 -1
  150. package/kits/docs/evolcore/response.md +7 -1
  151. package/kits/docs/evolcore/task.md +2 -0
  152. package/kits/docs/evolcore/tool-authorization.md +1 -1
  153. package/kits/docs/evolcore/trigger.md +4 -0
  154. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  155. package/kits/docs/prompt-loading-architecture.md +6 -2
  156. package/kits/eck_manifest.auxiliary.json +1 -0
  157. package/kits/eck_manifest.json +64 -7
  158. package/kits/eck_manifest.memory.json +93 -4
  159. package/kits/rules/01-overview.md +2 -2
  160. package/kits/rules/03-identity.md +10 -9
  161. package/kits/rules/05-venue.md +2 -4
  162. package/kits/rules/06-channel.md +1 -1
  163. package/kits/schemas/_meta.json +44 -3
  164. package/kits/schemas/agent-config.schema.18.json +5 -0
  165. package/kits/schemas/agent-config.schema.19.json +924 -0
  166. package/kits/schemas/agent-config.schema.20.json +925 -0
  167. package/kits/schemas/relation-config.schema.12.json +289 -0
  168. package/kits/schemas/relation-config.schema.13.json +289 -0
  169. package/kits/schemas/role-config.schema.2.json +215 -0
  170. package/kits/schemas/role-config.schema.3.json +1038 -0
  171. package/kits/schemas/role-registry.schema.1.json +3 -2
  172. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  173. package/kits/skills/ec-trigger/SKILL.md +4 -4
  174. package/kits/skills/personal-assistant/SKILL.md +109 -53
  175. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  176. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  177. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  178. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  179. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  180. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  181. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  182. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  183. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  184. package/kits/templates/soul/00-GUIDE.md +39 -0
  185. package/kits/templates/soul/01-identity.md +5 -0
  186. package/kits/templates/soul/02-persona.md +11 -0
  187. package/kits/templates/soul/03-duties.md +5 -0
  188. package/kits/templates/soul/04-working-style.md +5 -0
  189. package/kits/templates/system-fragments/bootstrap.md +7 -7
  190. package/kits/templates/system-fragments/channel.md +2 -2
  191. package/kits/templates/system-fragments/commands.md +3 -2
  192. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  193. package/kits/templates/system-fragments/memory.md +1 -1
  194. package/kits/templates/system-fragments/personal-assistant.md +50 -0
  195. package/kits/templates/system-fragments/reply.md +7 -0
  196. package/kits/templates/system-fragments/session.md +6 -2
  197. package/package.json +3 -2
  198. package/dist/cli/handoff-command.js +0 -353
  199. package/dist/directory/owner-directory-remark-operation.js +0 -147
  200. package/kits/docs/evolcore/self-summary.md +0 -29
@@ -33,6 +33,30 @@ export function rolePermissionFields() {
33
33
  patterns: field.patterns?.map((pattern) => ({ ...pattern, kind: 'pattern' })),
34
34
  }));
35
35
  }
36
+ /** Read compatibility for policies saved before group delivery became proactive-only. */
37
+ export function normalizeRoleGroupChatmodeCompat(value) {
38
+ if (!isRecord(value) || !isRecord(value.permissions))
39
+ return value;
40
+ const version = value.$schema_version ?? 1;
41
+ if (version !== 1 && version !== 2)
42
+ return value;
43
+ const group = value.permissions['chatmode.group'];
44
+ if (!isRecord(group))
45
+ return value;
46
+ return {
47
+ ...value,
48
+ permissions: {
49
+ ...value.permissions,
50
+ 'chatmode.group': {
51
+ ...group,
52
+ default: group.default === 'interactive' ? 'proactive' : group.default,
53
+ ...(Array.isArray(group.allowedValues) ? {
54
+ allowedValues: [...new Set(group.allowedValues.map(item => item === 'interactive' ? 'proactive' : item))],
55
+ } : {}),
56
+ },
57
+ },
58
+ };
59
+ }
36
60
  function isDescriptor(value) {
37
61
  if (!value || typeof value !== 'object')
38
62
  return false;
@@ -55,11 +79,12 @@ export function rolePermissionFieldPatterns(field) {
55
79
  }
56
80
  /** Shared RoleService/Menu validation backed by the published role schema. */
57
81
  export function validateRoleConfig(value) {
58
- const compatible = normalizeRoleEffortCompat(value);
59
- const normalized = isRecord(compatible) && !Object.hasOwn(compatible, '$schema_version')
60
- ? { ...compatible, $schema_version: 1 }
61
- : compatible;
82
+ const compatible = normalizeRoleGroupChatmodeCompat(normalizeRoleEffortCompat(value));
62
83
  const schema = loadSchema('role-config');
84
+ const normalized = isRecord(compatible)
85
+ && (!Object.hasOwn(compatible, '$schema_version') || compatible.$schema_version === 1 || compatible.$schema_version === 2)
86
+ ? { ...compatible, $schema_version: schema.version }
87
+ : compatible;
63
88
  if (!schema.validate(normalized)) {
64
89
  return (schema.validate.errors ?? []).map(error => ({
65
90
  field: schemaErrorField(error),
@@ -3,9 +3,9 @@ import path from 'path';
3
3
  import { atomicReadJson, atomicWriteJson } from '../utils/atomic-write.js';
4
4
  import { agentRelationConfig, agentRelationsDir, agentRoleConfig, agentRolesIndex } from '../paths.js';
5
5
  import { registerFile, unregisterFile } from '../core/file-integrity/store.js';
6
- import { loadSchema } from './schema-registry.js';
6
+ import { currentVersion, loadSchema } from './schema-registry.js';
7
7
  import { clearRoleStoreCache, getStoredRoleRegistry, isRoleName, readRoleStore, roleRegistryExists, } from './role-store.js';
8
- import { expectedRoleRank, isManagementRole } from './builtin-roles.js';
8
+ import { DEFAULT_PA_TEAM_ROLE, expectedRoleRank, isManagementRole } from './builtin-roles.js';
9
9
  import { readBuiltinRoleTemplate } from './builtin-role-templates.js';
10
10
  import { normalizeRoleEffortCompat, validateRoleConfig } from './role-schema.js';
11
11
  export class RoleServiceError extends Error {
@@ -30,7 +30,7 @@ export function ensureInitialRoleRegistry(selfAid) {
30
30
  writeRoleRegistry(selfAid, {
31
31
  $schema_version: 1,
32
32
  roles: ['owner', 'admin', 'member', 'visitor'],
33
- defaultRoles: { private: null, group: null },
33
+ defaultRoles: { private: null, group: null, paTeam: DEFAULT_PA_TEAM_ROLE },
34
34
  });
35
35
  return true;
36
36
  }
@@ -48,7 +48,7 @@ export function writeRoleRegistry(selfAid, value) {
48
48
  export function writeRoleDefinition(selfAid, roleId, value) {
49
49
  if (!isRoleName(roleId))
50
50
  throw new RoleServiceError('INVALID_ROLE_ID', `Invalid role id: ${roleId}`);
51
- const normalized = normalizeRoleEffortCompat({ ...value, rank: expectedRoleRank(roleId), $schema_version: 1 });
51
+ const normalized = normalizeRoleEffortCompat({ ...value, rank: expectedRoleRank(roleId), $schema_version: currentVersion('role-config') });
52
52
  validateRoleDefinition(normalized);
53
53
  const registry = readRoleRegistry(selfAid);
54
54
  if (!registry.roles.includes(roleId)) {
@@ -125,8 +125,11 @@ export function unregisterRole(selfAid, roleId, replacementRoleId) {
125
125
  defaultRoles: {
126
126
  private: registry.defaultRoles.private === roleId ? (replacement ?? null) : registry.defaultRoles.private,
127
127
  group: registry.defaultRoles.group === roleId ? (replacement ?? null) : registry.defaultRoles.group,
128
+ paTeam: (registry.defaultRoles.paTeam ?? DEFAULT_PA_TEAM_ROLE) === roleId
129
+ ? (replacement ?? DEFAULT_PA_TEAM_ROLE) : registry.defaultRoles.paTeam,
128
130
  },
129
131
  };
132
+ validateRegistry(selfAid, nextRegistry);
130
133
  if (hasReplacement) {
131
134
  const relations = agentRelationsDir(selfAid);
132
135
  if (fs.existsSync(relations)) {
@@ -157,7 +160,7 @@ export function listRoleDiagnostics(selfAid) {
157
160
  return readRoleStore(selfAid).diagnostics;
158
161
  }
159
162
  function writeRoleDefinitionFile(selfAid, roleId, value) {
160
- const normalized = normalizeRoleEffortCompat({ ...value, rank: expectedRoleRank(roleId), $schema_version: 1 });
163
+ const normalized = normalizeRoleEffortCompat({ ...value, rank: expectedRoleRank(roleId), $schema_version: currentVersion('role-config') });
161
164
  validateRoleDefinition(normalized);
162
165
  const file = agentRoleConfig(selfAid, roleId);
163
166
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -171,8 +174,8 @@ function validateRegistry(selfAid, value) {
171
174
  const registry = normalized;
172
175
  if (!registry.roles.includes('visitor'))
173
176
  throw new RoleServiceError('VISITOR_REQUIRED', 'visitor must remain registered');
174
- for (const role of ['private', 'group']) {
175
- const selected = registry.defaultRoles[role];
177
+ for (const role of ['private', 'group', 'paTeam']) {
178
+ const selected = role === 'paTeam' ? registry.defaultRoles.paTeam ?? DEFAULT_PA_TEAM_ROLE : registry.defaultRoles[role];
176
179
  if (selected !== null && (selected === 'owner' || !registry.roles.includes(selected))) {
177
180
  throw new RoleServiceError('INVALID_DEFAULT_ROLE', `defaultRoles.${role} must reference an assignable registered role`);
178
181
  }
@@ -203,6 +206,8 @@ function findRoleReferences(selfAid, roleId, registry) {
203
206
  references.push('defaultRoles.private');
204
207
  if (registry.defaultRoles.group === roleId)
205
208
  references.push('defaultRoles.group');
209
+ if ((registry.defaultRoles.paTeam ?? DEFAULT_PA_TEAM_ROLE) === roleId)
210
+ references.push('defaultRoles.paTeam');
206
211
  const relations = agentRelationsDir(selfAid);
207
212
  if (!fs.existsSync(relations))
208
213
  return references;
@@ -2,10 +2,10 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { atomicReadJson } from '../utils/atomic-write.js';
4
4
  import { agentRoleConfig, agentRolesDir, agentRolesIndex, kitsRoleTemplatesDir, resolvePaths, } from '../paths.js';
5
- import { applyManagementRoleCeiling, expectedRoleRank, getManagementRoleDefinition } from './builtin-roles.js';
5
+ import { applyManagementRoleCeiling, DEFAULT_PA_TEAM_ROLE, expectedRoleRank, getManagementRoleDefinition } from './builtin-roles.js';
6
6
  import { readBuiltinRoleTemplate } from './builtin-role-templates.js';
7
7
  import { loadSchema } from './schema-registry.js';
8
- import { normalizeRoleEffortCompat, validateRoleConfig } from './role-schema.js';
8
+ import { normalizeRoleEffortCompat, normalizeRoleGroupChatmodeCompat, validateRoleConfig } from './role-schema.js';
9
9
  const ROLE_NAME_RE = /^[a-z0-9_-]+$/;
10
10
  const BUILTIN_ROLES = ['owner', 'admin', 'member', 'visitor'];
11
11
  const cache = new Map();
@@ -88,6 +88,7 @@ export function roleIsAssignable(selfAid, roleId) {
88
88
  function readRegistry(selfAid, diagnostics) {
89
89
  const file = agentRolesIndex(selfAid);
90
90
  let raw;
91
+ let invalidPaTeam = false;
91
92
  try {
92
93
  raw = atomicReadJson(file);
93
94
  }
@@ -101,11 +102,30 @@ function readRegistry(selfAid, diagnostics) {
101
102
  }
102
103
  if (raw !== null) {
103
104
  const schema = loadSchema('role-registry');
105
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
106
+ const record = raw;
107
+ if (record.defaultRoles && typeof record.defaultRoles === 'object' && !Array.isArray(record.defaultRoles)
108
+ && !schema.validate(raw)) {
109
+ const defaults = { ...record.defaultRoles };
110
+ if (Object.hasOwn(defaults, 'paTeam')) {
111
+ delete defaults.paTeam;
112
+ const compatible = { ...record, defaultRoles: defaults };
113
+ if (schema.validate(compatible)) {
114
+ diagnostics.push({ code: 'INVALID_ROLE_ASSIGNMENT', file: path.relative(resolvePaths().root, file),
115
+ message: 'defaultRoles.paTeam is invalid; PA team authorization is disabled' });
116
+ raw = compatible;
117
+ invalidPaTeam = true;
118
+ }
119
+ }
120
+ }
121
+ }
104
122
  if (schema.validate(raw)) {
105
123
  const value = raw;
106
124
  const roles = [...new Set(value.roles)];
107
- const defaultRoles = { ...value.defaultRoles };
108
- for (const scene of ['private', 'group']) {
125
+ const defaultRoles = { ...value.defaultRoles, paTeam: invalidPaTeam ? '' : value.defaultRoles.paTeam ?? DEFAULT_PA_TEAM_ROLE };
126
+ for (const scene of ['private', 'group', 'paTeam']) {
127
+ if (scene === 'paTeam' && invalidPaTeam)
128
+ continue;
109
129
  const selected = defaultRoles[scene];
110
130
  if (selected === null || (roles.includes(selected) && selected !== 'owner'))
111
131
  continue;
@@ -113,9 +133,11 @@ function readRegistry(selfAid, diagnostics) {
113
133
  code: 'INVALID_ROLE_ASSIGNMENT',
114
134
  roleId: selected,
115
135
  file: path.relative(resolvePaths().root, file),
116
- message: `defaultRoles.${scene} references invalid or unregistered role ${selected}; using ${scene === 'group' ? 'member' : 'visitor'} fallback`,
136
+ message: `defaultRoles.${scene} references invalid or unregistered role ${selected}; ${scene === 'paTeam'
137
+ ? 'PA team authorization is disabled' : `using ${scene === 'group' ? 'member' : 'visitor'} fallback`}`,
117
138
  });
118
- defaultRoles[scene] = null;
139
+ if (scene !== 'paTeam')
140
+ defaultRoles[scene] = null;
119
141
  }
120
142
  return { ...value, roles, defaultRoles };
121
143
  }
@@ -134,7 +156,7 @@ function readRegistry(selfAid, diagnostics) {
134
156
  return fallbackRegistry();
135
157
  }
136
158
  function fallbackRegistry() {
137
- return { $schema_version: 1, roles: [...BUILTIN_ROLES], defaultRoles: { private: null, group: null } };
159
+ return { $schema_version: 1, roles: [...BUILTIN_ROLES], defaultRoles: { private: null, group: null, paTeam: DEFAULT_PA_TEAM_ROLE } };
138
160
  }
139
161
  function readDefinition(selfAid, roleId, diagnostics) {
140
162
  const local = agentRoleConfig(selfAid, roleId);
@@ -154,7 +176,7 @@ function readDefinition(selfAid, roleId, diagnostics) {
154
176
  }
155
177
  if (raw === null)
156
178
  continue;
157
- const normalizedRaw = normalizeRoleEffortCompat(raw);
179
+ const normalizedRaw = normalizeRoleGroupChatmodeCompat(normalizeRoleEffortCompat(raw));
158
180
  const issues = validateRoleConfig(normalizedRaw);
159
181
  if (issues.length === 0) {
160
182
  const { $schema_version: _schemaVersion, ...definition } = normalizedRaw;
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import fs from 'fs';
19
19
  import path from 'path';
20
- import { resolvePaths, agentDir, } from './paths.js';
20
+ import { resolvePaths, agentDir, agentPersonalDir, kitsTemplatesDir, SOUL_PERSONA_FILE, } from './paths.js';
21
21
  import { atomicReadJson, atomicWriteJson } from './utils/atomic-write.js';
22
22
  import { registerFile as registerFileIntegrity } from './core/file-integrity/store.js';
23
23
  import { checkAgentDir, isValidAid } from './aun/aid/validation.js';
@@ -644,18 +644,21 @@ export function validateAgentConfig(cfg) {
644
644
  // ── 合并 ───────────────────────────────────────────────────────────────
645
645
  // ── 目录骨架 ───────────────────────────────────────────────────────────
646
646
  /**
647
- * 为某个 self-agent 创建文档约定的子目录骨架(personal/、identities/、venues/ 等)。
647
+ * 为某个 self-agent 创建文档约定的子目录骨架(personal/、identities/、venues/ 等),
648
+ * 并保证 `personal/soul/` 存在且有机制指南与分文件骨架。
648
649
  * 已存在则跳过,幂等可重复调用。
649
650
  *
650
- * 注:本函数只建**目录骨架**,不碰 config.json——由 saveAgent(创建路径)
651
+ * 注:本函数不建 config.json——由 saveAgent(创建路径)
651
652
  * 或 ConfigManager.ensureFile(设计目标)负责。
652
- * 骨架那部分职责,目录骨架职责保留在此。
653
+ * soul 下的文件直接写盘,不走命令行:每轮都会注入 system prompt,
654
+ * 空文件不注入,所以骨架文件刻意保持 0 字节。
653
655
  */
654
656
  export function ensureAgentDirSkeleton(aid) {
655
657
  const root = agentDir(aid);
656
658
  const subs = [
657
659
  'personal',
658
660
  'personal/memory',
661
+ 'personal/soul',
659
662
  'personal/skills',
660
663
  'relations/contacts',
661
664
  'relations/_observed',
@@ -672,6 +675,74 @@ export function ensureAgentDirSkeleton(aid) {
672
675
  for (const sub of subs) {
673
676
  fs.mkdirSync(path.join(root, sub), { recursive: true });
674
677
  }
678
+ ensureSoulDir(aid);
679
+ }
680
+ /** soul 目录骨架:模板位于 `kits/templates/soul/`,文件名与目标完全一致。 */
681
+ export const SOUL_TEMPLATE_DIR = 'soul';
682
+ /** 只有指南有正文;分文件模板刻意为空(空文件不注入,等于还没写)。 */
683
+ const SOUL_TEMPLATE_FILES = ['00-GUIDE.md', '01-identity.md', '02-persona.md', '03-duties.md', '04-working-style.md'];
684
+ /** 旧版合集文件名(`$PERSONAL_DIR/persona.md`)。已废除:内容并进 soul 的「性格」分册。 */
685
+ const LEGACY_PERSONA_FILE = 'persona.md';
686
+ /** 并入时加的分隔标题;重复迁移不会重复追加(按它判断是否已并入)。 */
687
+ const LEGACY_MERGE_MARKER = '## 旧版合集(自动并入)';
688
+ function ensureSoulDir(aid) {
689
+ const personalDir = agentPersonalDir(aid);
690
+ const soulDir = path.join(personalDir, 'soul');
691
+ for (const name of SOUL_TEMPLATE_FILES) {
692
+ ensureSoulFile(soulDir, name);
693
+ }
694
+ mergeLegacyPersona(personalDir, soulDir);
695
+ }
696
+ function ensureSoulFile(soulDir, name) {
697
+ const target = path.join(soulDir, name);
698
+ if (fs.existsSync(target))
699
+ return;
700
+ let content = '';
701
+ try {
702
+ content = fs.readFileSync(path.join(kitsTemplatesDir(), SOUL_TEMPLATE_DIR, name), 'utf-8');
703
+ }
704
+ catch {
705
+ logger.warn(`[soul] 模板缺失:${path.join(kitsTemplatesDir(), SOUL_TEMPLATE_DIR, name)}`);
706
+ }
707
+ try {
708
+ fs.writeFileSync(target, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
709
+ }
710
+ catch (error) {
711
+ // wx 撞车(并发初始化)或权限失败都不该阻断目录骨架,只记日志。
712
+ logger.warn(`[soul] 写入 ${name} 失败 ${target}: ${error?.message || error}`);
713
+ }
714
+ }
715
+ /**
716
+ * 废除旧合集:把 `$PERSONAL_DIR/persona.md` 的内容追加进 `soul/02-persona.md` 后删除原文件。
717
+ * 幂等:靠 LEGACY_MERGE_MARKER 判断是否已经并入过,不会重复追加。
718
+ */
719
+ function mergeLegacyPersona(personalDir, soulDir) {
720
+ const legacy = path.join(personalDir, LEGACY_PERSONA_FILE);
721
+ if (!fs.existsSync(legacy))
722
+ return;
723
+ let legacyContent = '';
724
+ try {
725
+ legacyContent = fs.readFileSync(legacy, 'utf-8').trim();
726
+ }
727
+ catch (error) {
728
+ logger.warn(`[soul] 读取旧合集失败 ${legacy}: ${error?.message || error}`);
729
+ return;
730
+ }
731
+ const target = path.join(soulDir, SOUL_PERSONA_FILE);
732
+ try {
733
+ if (legacyContent) {
734
+ const current = fs.existsSync(target) ? fs.readFileSync(target, 'utf-8') : '';
735
+ if (!current.includes(LEGACY_MERGE_MARKER)) {
736
+ const merged = `${current.trimEnd()}${current.trim() ? '\n\n' : ''}${LEGACY_MERGE_MARKER}\n\n${legacyContent}\n`;
737
+ fs.writeFileSync(target, merged, { encoding: 'utf8', mode: 0o600 });
738
+ }
739
+ }
740
+ fs.unlinkSync(legacy);
741
+ logger.info(`[soul] 已并入 ${legacy} → ${target} 并删除旧合集`);
742
+ }
743
+ catch (error) {
744
+ logger.warn(`[soul] 并入旧合集失败 ${legacy}: ${error?.message || error}`);
745
+ }
675
746
  }
676
747
  // ── identities → relations 迁移 ──────────────────────────────────────
677
748
  /**
@@ -1,6 +1,6 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- import { parseAgentWelcomeArgs, parseInitializationArgs, resolveAgentCreateMode, resolveInitializationPlan, readInitializationPersona, } from '../cli/agent-create.js';
3
+ import { parseAgentWelcomeArgs, parseInitializationArgs, resolveAgentCreateMode, resolveInitializationPlan, } from '../cli/agent-create.js';
4
4
  import { hasTrustedFullAccessDelegation, trustedExecutionIdentityInput } from './auth/agent-delegation.js';
5
5
  import { authorizeFreshOperation as authorizeOperation, buildAuthSubject } from './auth/auth-gateway.js';
6
6
  import { getDaemonOwners } from './ownership/owner-resolver.js';
@@ -55,15 +55,13 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
55
55
  }
56
56
  const targetAid = sub === 'list'
57
57
  ? undefined
58
- : sub === 'persona'
58
+ : sub === 'welcome'
59
59
  ? taskAid
60
- : sub === 'welcome'
61
- ? taskAid
62
- : sub === 'show'
63
- ? (argv[2] && !argv[2].startsWith('--') ? argv[2] : taskAid)
64
- : sub === 'reload'
65
- ? (argv[2] && !argv[2].startsWith('--') ? argv[2] : undefined)
66
- : (argv[2] && !argv[2].startsWith('--') ? argv[2] : undefined);
60
+ : sub === 'show'
61
+ ? (argv[2] && !argv[2].startsWith('--') ? argv[2] : taskAid)
62
+ : sub === 'reload'
63
+ ? (argv[2] && !argv[2].startsWith('--') ? argv[2] : undefined)
64
+ : (argv[2] && !argv[2].startsWith('--') ? argv[2] : undefined);
67
65
  let createMode;
68
66
  if (sub === 'new') {
69
67
  try {
@@ -75,15 +73,14 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
75
73
  }
76
74
  const operation = sub === 'list' ? 'agent.list'
77
75
  : sub === 'show' ? 'agent.show'
78
- : sub === 'persona' ? 'agent.persona'
79
- : sub === 'welcome' ? 'agent.welcome'
80
- : sub === 'rename' ? 'agent.rename'
81
- : sub === 'initialize' || createMode === 'initialize' ? 'agent.initialize'
82
- : sub === 'new' ? 'agent.create'
83
- : sub === 'enable' ? 'agent.enable'
84
- : sub === 'disable' ? 'agent.disable'
85
- : sub === 'reload' ? 'agent.reload'
86
- : sub === 'delete' ? 'agent.delete' : undefined;
76
+ : sub === 'welcome' ? 'agent.welcome'
77
+ : sub === 'rename' ? 'agent.rename'
78
+ : sub === 'initialize' || createMode === 'initialize' ? 'agent.initialize'
79
+ : sub === 'new' ? 'agent.create'
80
+ : sub === 'enable' ? 'agent.enable'
81
+ : sub === 'disable' ? 'agent.disable'
82
+ : sub === 'reload' ? 'agent.reload'
83
+ : sub === 'delete' ? 'agent.delete' : undefined;
87
84
  if (!operation)
88
85
  return fail('INVALID_ARGS', `unsupported managed agent command: ${sub}`);
89
86
  if (sub === 'delete' && argv.includes('--purge') && !argv.includes('--confirm-purge')) {
@@ -112,7 +109,7 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
112
109
  subject,
113
110
  intent: {
114
111
  operation,
115
- scope: operation === 'agent.show' || operation === 'agent.persona' || operation === 'agent.welcome' || operation === 'agent.rename'
112
+ scope: operation === 'agent.show' || operation === 'agent.welcome' || operation === 'agent.rename'
116
113
  ? 'agent'
117
114
  : operation === 'agent.reload' && targetAid
118
115
  ? 'agent'
@@ -188,46 +185,6 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
188
185
  ...(agent.initialization ? { initialization: agent.initialization } : {}),
189
186
  } };
190
187
  }
191
- if (operation === 'agent.persona') {
192
- const rawPersonaArgs = argv.slice(2);
193
- const hasFormatSuffix = rawPersonaArgs.length >= 2
194
- && rawPersonaArgs.at(-2) === '--format'
195
- && rawPersonaArgs.at(-1) === 'json';
196
- const personaArgs = hasFormatSuffix ? rawPersonaArgs.slice(0, -2) : rawPersonaArgs;
197
- if (!hasFormatSuffix && rawPersonaArgs.includes('--format')) {
198
- return fail('INVALID_ARGS', 'persona 仅支持末尾的 --format json');
199
- }
200
- const wantsShow = personaArgs.length === 1 && personaArgs[0] === 'show';
201
- let text = personaArgs.length === 2 && personaArgs[0] === '--text'
202
- ? personaArgs[1]
203
- : undefined;
204
- const file = personaArgs.length === 2 && personaArgs[0] === '--file' ? personaArgs[1] : undefined;
205
- if (file !== undefined) {
206
- try {
207
- text = readInitializationPersona(file, true, {
208
- projectCwd: taskSession.projectPath, tempDir: delegation.grant.sessionRuntimeDir,
209
- });
210
- }
211
- catch (error) {
212
- return fail('INVALID_ARGS', error.message);
213
- }
214
- }
215
- if (!wantsShow && !(personaArgs.length === 2 && (personaArgs[0] === '--text' || personaArgs[0] === '--file'))) {
216
- return fail('INVALID_ARGS', '用法: ec agent persona show | --text <text> | --file <path>');
217
- }
218
- if (text === undefined && !wantsShow)
219
- return fail('INVALID_ARGS', 'persona --text 缺少参数');
220
- const { agentPersona } = await import('../cli/agent.js');
221
- const result = await agentPersona(taskAid, wantsShow ? { trustedLocal: true } : { text, trustedLocal: true });
222
- if (!result.ok)
223
- return fail(result.code ?? 'INTERNAL', result.error);
224
- return { ok: true, result: {
225
- ok: true,
226
- aid: taskAid,
227
- content: result.content,
228
- ...(result.saved ? { saved: true } : {}),
229
- } };
230
- }
231
188
  if (operation === 'agent.welcome') {
232
189
  if (subject.role !== 'owner' && !(welcomeArgs?.action === 'show' && subject.role === 'admin')) {
233
190
  return fail('NOT_ALLOWED', 'welcome requires the current Agent Owner (admin may read)');
@@ -8,6 +8,7 @@ import { ownerResolver, refreshOwnershipForAuthorization, OWNERSHIP_CACHE_MAX_AG
8
8
  import { getOperationMeta } from './operation-catalog.js';
9
9
  import { constrainRuntimePermissionMode, resolveRuntimePermissionMode } from '../role/runtime-policy.js';
10
10
  import { buildAuthorizationEventKey } from '../audit/event-key.js';
11
+ import { preparePaTeamQualification, paTeamQualification, requiresPaTeamVerification } from '../relation/pa-team.js';
11
12
  export function isCrossAgentTriggerOperationAllowed(input) {
12
13
  return input.control || input.daemonOwner === true || input.taskAgentAid === input.targetAgentAid;
13
14
  }
@@ -41,7 +42,10 @@ export function buildAuthSubject(input) {
41
42
  actor: roleDetail.actor,
42
43
  processOwners,
43
44
  }));
44
- const suppliedRole = input.identity?.role && input.identity.role !== 'none' ? input.identity.role : undefined;
45
+ const teamContext = roleDetail.source === 'pa-team-default'
46
+ || (input.channelType === 'aun' && chatType === 'private' && input.selfAid && actorId
47
+ && (paTeamQualification(input.selfAid, actorId) === 'matched' || requiresPaTeamVerification(input.selfAid, actorId)));
48
+ const suppliedRole = !teamContext && input.identity?.role && input.identity.role !== 'none' ? input.identity.role : undefined;
45
49
  const role = suppliedRole ?? roleDetail.effectiveRole ?? 'none';
46
50
  const processRole = isFullAccessRun
47
51
  ? 'fullaccess-run'
@@ -111,16 +115,21 @@ export async function authorizeFreshOperation(params) {
111
115
  && ['owner', 'owners'].includes(configCommand.field.split('.')[0]);
112
116
  const force = changesOwner || ['ec.aid.bind', 'ec.aid.unbind', 'ec.aid.transfer']
113
117
  .includes(params.intent.operation) || params.intent.operation === 'config.restore';
118
+ const forceAgentMdEditor = params.source === 'menu'
119
+ && ['ec.aid.agentmd.get', 'ec.aid.agentmd.put'].includes(params.intent.operation);
114
120
  const operation = getOperationMeta(params.intent.operation);
115
121
  const sensitive = force || params.intent.dangerous || operation?.dangerous || operation?.category !== 'read'
116
122
  || configCommand?.dangerous || subject.processRole === 'fullaccess-run';
117
123
  try {
124
+ if (subject.channelType === 'aun' && subject.chatType === 'private') {
125
+ await preparePaTeamQualification(subject.selfAid, subject.actorId);
126
+ }
118
127
  await refreshOwnershipForAuthorization(subject.selfAid, {
119
- force,
128
+ force: force || forceAgentMdEditor,
120
129
  ...(sensitive ? {} : { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS }),
121
130
  includeDaemon: subject.isDaemonOwner || subject.processRole === 'fullaccess-run'
122
131
  || params.intent.scope === 'process' || params.intent.scope === 'control' || force,
123
- allowTransient: !force,
132
+ allowTransient: !force && !forceAgentMdEditor,
124
133
  });
125
134
  const targetAid = operation?.authorizationTarget === 'same-owner-agent'
126
135
  && subject.processRole !== 'fullaccess-run'
@@ -143,7 +152,8 @@ export async function authorizeFreshOperation(params) {
143
152
  channel: subject.channel, channelType: subject.channelType, channelId: subject.channelId,
144
153
  chatType: subject.chatType, conversationId: subject.conversationId,
145
154
  fromControlChannel: subject.fromControlChannel,
146
- identity: subject.role === 'owner' && subject.principalId ? undefined : subject.identity,
155
+ identity: subject.roleSource === 'pa-team-default' || (subject.role === 'owner' && subject.principalId)
156
+ ? undefined : subject.identity,
147
157
  });
148
158
  if (subject.processRole === 'fullaccess-run') {
149
159
  if (!subject.authorizedBy || !ownerResolver.daemonOwners().includes(subject.authorizedBy)) {
@@ -5,6 +5,20 @@ import crypto from 'node:crypto';
5
5
  import { buildAuthorizationEventKey, buildToolLifecycleEventKey, normalizeToolCorrelation } from '../audit/event-key.js';
6
6
  import { normalizeExecutionPermissionMode } from '../permission/mode.js';
7
7
  import { normalizeToolErrorClassification } from '../permission/tool-error-code.js';
8
+ const auditProjectionKeys = new Set();
9
+ const MAX_AUDIT_PROJECTION_KEYS = 20_000;
10
+ function markAuditProjection(canonicalEventKey) {
11
+ const isMirror = auditProjectionKeys.has(canonicalEventKey);
12
+ if (!isMirror) {
13
+ auditProjectionKeys.add(canonicalEventKey);
14
+ if (auditProjectionKeys.size > MAX_AUDIT_PROJECTION_KEYS) {
15
+ const oldest = auditProjectionKeys.values().next().value;
16
+ if (oldest !== undefined)
17
+ auditProjectionKeys.delete(oldest);
18
+ }
19
+ }
20
+ return isMirror;
21
+ }
8
22
  function permissionAuditDetails(input) {
9
23
  return Object.fromEntries(Object.entries({
10
24
  approvalRequestId: input.approvalRequestId,
@@ -156,6 +170,7 @@ export function auditToolPreflightDenial(input) {
156
170
  // regex/string literals in an otherwise harmless diagnostic command.
157
171
  matchedPath: input.matchedPath,
158
172
  matchedRule: input.matchedRule,
173
+ parsedSegments: input.parsedSegments?.slice(0, 8).map(segment => segment.replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 64)),
159
174
  reason,
160
175
  argsSummary: input.summary ? { summary: input.summary } : undefined,
161
176
  sessionId: input.sessionId ?? 'unknown',
@@ -408,30 +423,43 @@ function buildAuditRecord(event) {
408
423
  const sourceRequestId = event.requestId ?? ecwebRequestId;
409
424
  const requestId = namespaceAuditRequestId(event.source, event.sessionId, sourceRequestId);
410
425
  const correlationId = event.correlationId ?? event.callId ?? sourceRequestId;
426
+ const contextSessionId = knownAuditContextValue(event.sessionId);
427
+ const contextAgentAid = knownAuditContextValue(event.agentAid) ?? knownAuditContextValue(event.selfAid);
428
+ const contextMissing = event.source === 'agent-tool'
429
+ ? [
430
+ ...(!contextSessionId ? ['sessionId'] : []),
431
+ ...(!contextAgentAid ? ['agentAid'] : []),
432
+ ...(!knownAuditContextValue(event.permissionMode) ? ['permissionMode'] : []),
433
+ ]
434
+ : [];
435
+ const eventKey = event.eventKey ?? (ecwebRequestId
436
+ ? `ecweb:${crypto.createHash('sha256').update(JSON.stringify([
437
+ ecwebRequestId, event.targetAgentAid ?? event.selfAid, event.operation,
438
+ ])).digest('hex').slice(0, 20)}`
439
+ : buildAuthorizationEventKey({
440
+ sessionId: event.sessionId,
441
+ callId: event.callId,
442
+ correlationId,
443
+ requestId: sourceRequestId,
444
+ operation: event.operation,
445
+ }));
446
+ const canonicalEventKey = `${eventKey}:decision:${event.decision}`;
411
447
  return {
412
448
  type: 'authorization:audit',
413
449
  ts: event.ts,
414
- eventKey: event.eventKey ?? (ecwebRequestId
415
- ? `ecweb:${crypto.createHash('sha256').update(JSON.stringify([
416
- ecwebRequestId, event.targetAgentAid ?? event.selfAid, event.operation,
417
- ])).digest('hex').slice(0, 20)}`
418
- : buildAuthorizationEventKey({
419
- sessionId: event.sessionId,
420
- callId: event.callId,
421
- correlationId,
422
- requestId: sourceRequestId,
423
- operation: event.operation,
424
- })),
450
+ eventKey,
451
+ canonicalEventKey,
452
+ isMirror: markAuditProjection(canonicalEventKey),
425
453
  eventPhase: event.eventPhase,
426
454
  callId: event.callId,
427
455
  correlationId,
428
456
  requestId,
429
457
  sourceRequestId,
430
458
  sessionId: event.sessionId,
431
- ...(!event.sessionId ? {
459
+ ...(!contextSessionId ? {
432
460
  sessionScope: event.source === 'ecweb' ? 'not_applicable' : 'unknown',
433
461
  } : {}),
434
- agentAid: redactIdentifier(event.agentAid ?? event.selfAid),
462
+ agentAid: redactIdentifier(contextAgentAid ?? event.agentAid ?? event.selfAid),
435
463
  agentName: resolveAgentName(event) ?? 'unknown',
436
464
  permissionMode: normalizeAuditPermissionMode(event.permissionMode),
437
465
  toolName: event.toolName,
@@ -440,10 +468,12 @@ function buildAuditRecord(event) {
440
468
  errorDetailCode: classification?.errorDetailCode,
441
469
  classificationMissing: classification?.classificationMissing || event.classificationMissing,
442
470
  classificationConflict: classification?.classificationConflict || event.classificationConflict,
471
+ ...(contextMissing.length > 0 ? { contextMissing } : {}),
443
472
  policyCode: event.policyCode ?? event.code,
444
473
  protectionClass: event.protectionClass,
445
474
  matchedPath: event.matchedPath,
446
475
  matchedRule: event.matchedRule,
476
+ parsedSegments: event.parsedSegments,
447
477
  parseFailure: sanitizeParseFailure(event.parseFailure),
448
478
  commandIntent: event.commandIntent,
449
479
  canonicalizationStage: event.canonicalizationStage,
@@ -549,8 +579,12 @@ function resolveAgentName(event) {
549
579
  function isUnknownAgentLabel(value) {
550
580
  return value === 'unknown' || value === '<unknown>' || value === '<none>' || value === 'undefined' || value === 'null';
551
581
  }
582
+ function knownAuditContextValue(value) {
583
+ const normalized = value?.trim();
584
+ return normalized && !isUnknownAgentLabel(normalized.toLowerCase()) ? normalized : undefined;
585
+ }
552
586
  function normalizeAuditPermissionMode(value) {
553
- if (!value || value === 'unknown')
587
+ if (!knownAuditContextValue(value))
554
588
  return value;
555
589
  return normalizeExecutionPermissionMode(value);
556
590
  }
@@ -597,8 +631,11 @@ function logAuditEvent(record) {
597
631
  record.callId ? `call=${record.callId}` : null,
598
632
  record.correlationId ? `correlation=${record.correlationId}` : null,
599
633
  record.eventKey ? `eventKey=${record.eventKey}` : null,
634
+ record.canonicalEventKey ? `canonicalEventKey=${record.canonicalEventKey}` : null,
635
+ record.isMirror !== undefined ? `isMirror=${record.isMirror}` : null,
600
636
  record.eventPhase ? `eventPhase=${record.eventPhase}` : null,
601
637
  record.sessionScope ? `sessionScope=${record.sessionScope}` : null,
638
+ record.contextMissing?.length ? `contextMissing=${record.contextMissing.join(',')}` : null,
602
639
  record.sessionId ? `session=${record.sessionId}` : null,
603
640
  record.agentName ? `agentName=${JSON.stringify(record.agentName)}` : null,
604
641
  record.agentAid ? `agent=${record.agentAid}` : null,
@@ -613,6 +650,7 @@ function logAuditEvent(record) {
613
650
  record.protectionClass ? `protectionClass=${record.protectionClass}` : null,
614
651
  record.matchedPath ? `matchedPath=${JSON.stringify(record.matchedPath)}` : null,
615
652
  record.matchedRule ? `matchedRule=${JSON.stringify(record.matchedRule)}` : null,
653
+ record.parsedSegments ? `parsedSegments=${JSON.stringify(record.parsedSegments)}` : null,
616
654
  record.parseFailure ? `parseFailure=${JSON.stringify(record.parseFailure)}` : null,
617
655
  record.commandIntent ? `commandIntent=${record.commandIntent}` : null,
618
656
  record.canonicalizationStage ? `canonicalizationStage=${record.canonicalizationStage}` : null,
@@ -111,6 +111,23 @@ function authorizeCommandInternal(ctx, resolvedConfigCommand) {
111
111
  if (!opMeta) {
112
112
  return denyDecision(ctx, 'NOT_ALLOWED', `Unknown operation: ${operation}`, operation, intent.scope);
113
113
  }
114
+ // The App editor is narrower than public Agent-tool reads and daemon management.
115
+ // No configured role, control token or daemon Owner may impersonate the protocol Owner.
116
+ if (['ec.aid.agentmd.get', 'ec.aid.agentmd.put'].includes(operation) && ctx.source !== 'agent-tool') {
117
+ const view = ctx.selfAid ? ownerResolver.snapshot(ctx.selfAid) : undefined;
118
+ const c = view?.consensus;
119
+ const target = intent.args.aid ?? intent.args.targetAgentAid ?? ctx.selfAid;
120
+ const allowed = ctx.source === 'menu' && intent.scope === 'agent' && ctx.chatType === 'private'
121
+ && !ctx.fromControlChannel && target === ctx.selfAid
122
+ && !!ctx.principalId && ctx.actorId === ctx.principalId
123
+ && view?.consensusStatus === 'consensus' && !view.refreshFailure
124
+ && c?.status === 'consensus' && c.sub_aid === ctx.selfAid && c.lock === 'locked'
125
+ && Number.isSafeInteger(c.relation_version) && c.relation_version > 0
126
+ && ownerResolver.owner(ctx.selfAid) === ctx.principalId && c.owner_aid === ctx.principalId;
127
+ return allowed
128
+ ? { allow: true, operation, scope: intent.scope, role, dangerous: opMeta.dangerous, matchedRule: 'agentmd-protocol-owner' }
129
+ : denyDecision(ctx, 'NOT_ALLOWED', 'AgentMD editor requires the current protocol Owner on its Agent channel', operation, intent.scope, opMeta.dangerous);
130
+ }
114
131
  if (isFieldConfigOperation(operation) && !resolvedConfigCommand) {
115
132
  return denyDecision(ctx, 'NOT_ALLOWED', 'Resolved config operation is required', operation, intent.scope, opMeta.dangerous);
116
133
  }
@@ -292,17 +309,6 @@ function authorizeCommandInternal(ctx, resolvedConfigCommand) {
292
309
  && !hasDaemonOwnerRole(ctx)) {
293
310
  return denyDecision(ctx, 'NOT_ALLOWED', `${operation} may only target the current Agent from a managed Agent task.`, operation, intent.scope, opMeta.dangerous, undefined, 'TARGET_SELF_ONLY');
294
311
  }
295
- if (operation === 'agent.persona' && isCurrentAgentTarget(ctx)
296
- && (role === 'owner' || (ctx.fromControlChannel && hasDaemonOwnerRole(ctx)))) {
297
- return {
298
- allow: true,
299
- operation,
300
- scope: intent.scope,
301
- role,
302
- dangerous: opMeta.dangerous,
303
- matchedRule: role === 'owner' ? 'agent-owner-persona' : 'daemon-owner-persona',
304
- };
305
- }
306
312
  if (operation === 'agent.welcome') {
307
313
  if (!isCurrentAgentTarget(ctx) || ctx.chatType !== 'private'
308
314
  || (role !== 'owner' && !(role === 'admin' && intent.args.action === 'show'))) {