Skip to content

feat(core): per-user capability surface with grant trimming for tools, groups and skills - #3500

Merged
juruoO-o merged 44 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/capability-surface
Nov 12, 2026
Merged

juruoO-o merged 44 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/capability-surface

Conversation

@xzxiaoshan

@xzxiaoshan xzxiaoshan commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Resolves #3298 #1963 #3443 #2247

Summary

Multi-tenant agents currently expose the same tool/skill inventory to every user. This PR introduces a server-side capability surface: an immutable, per-call grant enumeration resolved from the caller identity and enforced at both what the model sees (schema/prompt trimming) and what it can execute (hard gates) — without mutating the shared toolkit.

/**
 * Example resolver: computes the granted skill / tool capability list
 * dynamically, based on the current logged-in user's role.
 */
public class RoleBasedCapabilityResolver implements CapabilityResolver {

    @Override
    public CapabilitySurface resolve(RuntimeContext ctx, Agent agent) {
        // Read the caller's userId from the framework's ctx (RuntimeContext)
        String userId = ctx.getUserId();

        // The project team loads the skill/tool capability list for the user's
        // role based on userId — e.g. from its own permission system / RBAC
        // service (fixed values below stand in for the lookup result)
        // Grants grants = permissionService.findGrantsByUserId(userId);

        // Wrap the list as CapabilitySurface(allowedSkills, allowedToolGroups, allowedTools)
        return new CapabilitySurface(
                Set.of("pdf_export"),     // allowed skill name (one entry covers every source copy)
                Set.of("search"),         // allowed ToolGroup
                Set.of("web_read"));      // allowed individual tool name
    }
}

// ===== Assembling the agent: new the resolver separately, then pass it as an object =====
CapabilityResolver resolver = new RoleBasedCapabilityResolver();

ReActAgent agent = ReActAgent.builder()
        .capabilityResolver(resolver)
        // ... other configuration (model, tools, skills, etc.)
        .build();

// resolver returning null → unrestricted (same as not configured); throwing → the call aborts

Harness agents configure the same resolver via HarnessAgent.builder().capabilityResolver(...) — resolved before the sandbox acquire and skill pre-staging, so staged skill files, the prompt catalog and every gate observe the same surface.

Relation to existing layers

The grant layer composes with the existing mechanisms rather than paralleling them. One line: a capability actually executes only if it passes, in order — configuration intent (SkillFilter) → user grant (this PR) → current activation → per-call Permission approval. Each layer answers exactly one question; they intersect, they never overlap.

  • SkillFilter / dynamic visibility (skillFilter(...), rc overlay, filterVisible) — configuration intent: what the agent is designed to show; runtime overlays may widen or tighten (canary, temporary toggles). Grant runs after it: effective skills = SkillFilter ∩ grant, and overlays cannot raise the grant surface. Grant is deliberately not folded into SkillFilter: authorization may only narrow, while SkillFilter's overlay algebra is intentionally bidirectional (widening is a legitimate canary use) — anything runtime code can raise is not an authorization boundary.
  • Activation (activatedGroups) — a session-level switch over already-granted capabilities; stacks independently with grant.
  • Permission — execution-time approval (ALLOW / DENY / ASK) within the granted set; grant trims up-front, Permission decides the individual call.

Full layer table (incl. external tools): docs/v2/en/docs/building-blocks/capability-grant.md (EN/ZH aligned).

API compatibility

No existing public API is narrowed or removed. The pre-existing Toolkit.getToolSchemas(Collection<String>, ToolRequestConfig) keeps its public visibility and behavior (untrimmed compose, equivalent to the new 3-arg overload with a null surface); its javadoc now recommends the 3-arg overload (getToolSchemas(activeGroups, requestConfig, surface), surface read from the rc via rc.get(CapabilitySurface.class)) for model-facing synthesis inside an agent call.

One new combination is rejected at build time: capabilityResolver(...) together with the static skill path (skillBox(...) or dynamicSkillsEnabled(false)) throws IllegalStateException — the static path has no per-call skill-visibility filtering, and an authorization setting must never silently degrade to an untrimmed agent. Both APIs are new in this PR, so no existing build can break.

How it works

The grant layer is a funnel with a single decision source (CapabilitySurface query methods); gates never re-derive authorization logic.

  1. Declaration — CapabilityResolver (functional interface) computes pure whitelists from RuntimeContext (userId), optionally per agent. Resolved once at call() entry and carried on the rc for the whole chain; sub-agents inherit the parent surface without re-resolving (derived rc — no parent pollution). Concurrent calls with different users never cross surfaces.
  2. Tri-state surface — three dimensions (skills / tool groups / per-name tools). All-null = unrestricted; any dimension set (even to an empty set) turns the surface into a complete enumeration; default deny.
  3. Read points (model-visible):
    • Toolkit.getToolSchemas(groups, requestConfig, surface) — grant-filtered compose in a single pass; trimmed backend tools are treated as non-existent; external (request-config) tools stay caller-controlled; the reset_equipped_tools enum and description are rebuilt from activatable groups only, so cut-off group names and descriptions do not leak.
    • DynamicSkillMiddleware filters visible skills fail-closed (empty set on missing surface or filter error); the filtered list drives signature, box cache, prompt and loading alike.
  4. Hard gates (execution, orthogonal to activation checks):
    • tools: ToolExecutor.requireToolGranted (backend only)
    • skill loading: SkillToolFactory convergence point (allowsSkill(AgentSkill) — full decision incl. system bypass; the id-based overload remains the grant-set-only fallback)
    • group activation: resetEquippedToolsImpl
  5. System capabilities — isSystem() marking chain (@Tool annotation → ToolBase / ToolGroup / SkillToolGroup / AgentSkill builders, with copy/toBuilder retention) bypasses grant trimming; framework meta tools are marked; every system=true registration leaves an INFO audit trail.
  6. Missing surface = unrestricted — direct executions that never entered an agent call() are trusted assembler code (the agent funnel always writes a surface); the same stance applies at read points and gates.
  7. Harness agents — HarnessAgent.builder().capabilityResolver(...) resolves at the harness call/stream entry, before the sandbox acquire and marketplace pre-staging: only granted skill files are materialised into .skills-cache, and the harness skill chain (HarnessSkillMiddleware prompt/catalog, load_skill_through_path, staging) observes the same surface; harness sub-agents reuse the inherited surface without re-resolving.

Security properties

  • All model-facing denials are byte-identical to not-found wording (tools, skills, groups) — the model channel cannot distinguish "exists but ungranted" from "missing", and cannot relay "no permission" to the end user. The truthful cause is logged with userId/sessionId/agentId at each gate.
  • The tool grant gate runs before the activation gate, so ungranted probes never reach activation wording; the activation message only speaks for granted-but-inactive tools (the designed self-healing path).

Known residual exposure

  • Management/observation planes (aistio adapter, example REST controllers) intentionally export the full inventory — registration-time, not per-user.
  • The static skillBox() path cannot be combined with a resolver (the build fails explicitly, see above); it has no per-call prompt trimming at all. Multi-tenant setups should use skillRepositories(...).
  • The per-call generate_response structured-output tool executes outside the executor (system-equivalent response mechanism).

…ools, groups and skills

Introduce a server-side CapabilityResolver that resolves an immutable, per-call
CapabilitySurface from the caller identity. The surface trims what the model
sees (tool schemas, skill visibility, reset_equipped_tools enum/description)
and is enforced by hard execution gates for tools, skill loading and group
activation. System-marked capabilities bypass trimming; all model-facing
denials are byte-identical to not-found wording; a missing surface means a
trusted direct path (unrestricted).
@xzxiaoshan xzxiaoshan linked an issue Oct 11, 2026 that may be closed by this pull request
- Builder.copy() now carries capabilityResolver (main's copy()-based build
  dropped it, silently disabling the grant layer)
- reset_equipped_tools keeps the RuntimeContext param while adopting
  ToolResultBlock.success from agentscope-ai#2751
- externalToolSchema and rewriteResetToolSchema carry the new deferLoading
  schema field
- grant tests observe the call-scoped rc (main isolates the caller rc) and
  assert the suspended external result
The 2-arg getToolSchemas is package-private since the grant layer landed;
pass a null surface (un-trimmed compose) for the EXTERNAL_ONLY assertion.
@codecov

This comment was marked as outdated.

Unify the skill identifier vocabulary to skillName (the business identity,
unique per agent catalog) end to end; the composite name_source skillId is
now an internal storage detail:

- Grant surface: allowedSkills holds skill names; the skill tool-group
  naming convention derives from skillName ("_skill_tools"), so granting a
  skill reliably releases its tools without any id<->name translation
- SkillRegistry keys by name and enforces per-catalog uniqueness
  (re-registering the same instance is idempotent; a different instance
  under a used name is rejected)
- Loading: load_skill_through_path now takes a "skillName" parameter in
  both core and harness; prompts emit <skill-name>; not-found and denial
  wordings updated to match
- AgentSkill.getName() documents the industry-standard unique identity;
  getSkillId() is deprecated for removal
- Harness skill chain (catalog keying, load tool, prompt builder, usage
  middleware) aligned to the same vocabulary, closing the grant/addressing
  mismatch surfaced in review
- Synced docs/v2 pages (zh/en) and tests; full mvn test green
…urface

A SkillToolGroup bound to a granted skill (activateOnSkill) is now added to
allowedToolGroups once at call entry, so granting a skill implicitly grants
its custom-bound tool groups alongside the naming-convention group.

The expansion is a mechanical whitelist union performed while the entry
holds both the surface and the toolkit: the surface stays pure data, every
gate keeps consuming only the query methods, and groups bound to ungranted
skills stay denied. It is idempotent — the same instance is returned when
nothing is added, so sub-agents reusing an inherited surface keep reference
equality across toolkits with identical bindings.
skillId equals the skill name normally, extended to name__s__source only
when a source differentiates same-named skills. Grant entries accept both
forms (lazy failure on unknown sources); model-facing vocabulary back to
skillId; the "custom" source default is removed.
Registry, dynamic middleware and harness catalogs key by skillId: same-named
skills from different repositories coexist, the same skillId re-registration
replaces (version override), and lookups are exact (a bare name is the
source-less id form). SkillFilter matches the exact skillId; upload subdirs
and load echoes use skillId.
# Conflicts:
#	agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java
main's bare-name SkillFilter tests asserted the old composite skillId
format (name_source, default source "custom") and failed after the
merge. Update the literals to the dual-form scheme (name when no
source, name__s__source when sourced) and give the disable-by-name
test an explicit source so it still exercises hiding a composite-id
skill. Test intent is unchanged: filters match the skill name.
Resolve the grant surface at the harness call/stream entry, before the
sandbox acquire, so marketplace skill staging materialises granted-only
files; the inner delegate keeps the surface without re-resolving and an
inherited surface is never overwritten in place. Also fix the stale
catalog-key sentence and document the activateOnSkill grant rule in
capability-grant.md (zh/en).
Conflict resolution in HarnessAgent#forceCompactAndRetry: keep main's
overflow-retry rework (agentscope-ai#3661 — persist compacted state via
updateAgentState, retry with retryInput to avoid duplicate input) and
re-apply the capability-surface re-prepare on the retry call so the
grant surface survives the overflow path.

Adapt HarnessSkillMiddlewareGrantTest to main's agentscope-ai#3691 change: the
skills block now rides a tail runtime material (harness:skills) instead
of the system prompt, so grant-visibility assertions move there.
@mintlify

mintlify Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 44cf311.

Approve preview

activePeersSurviveEvictionOfIdleOnes asserted evictIdlePeers() == 1, but
a >=100ms overshoot of the 900ms sleep let allow("active-peer") fire the
piggybacked sweep first (one full window+cooldown interval had elapsed),
evicting idle-peer before the explicit call and flipping the count to 0.

Restage so the sweep is the deterministic eviction path: idle-peer sits
past the threshold before active-peer's first event, so that allow()
always sweeps it and the explicit call finds nothing. Overshoots only
push the idle peer further past the threshold. Verified 5 consecutive
runs green.
Conflict resolution in SkillPromptBuilder.java: took main's slim-view
usage header verbatim (041ce17 rewrote the block that carried the
branch's leftover 'skillName=' example typo; the branch-side dual-form
skillId semantics live in getSkillId(), unaffected).

Adapted main's new SkillRuntimeTest.defaultRendersSlimViewWithinByteBudget
to the branch's dual-form skillId convention: data-analysis_workspace ->
data-analysis__s__workspace, consistent with every other skill-id
assertion in the file.

Verified: mvn -T1C -pl agentscope-harness -am test (1415 tests, 0 failures);
spotless:check clean.
…ability-surface

# Conflicts:
#	agentscope-core/src/main/java/io/agentscope/core/skill/AgentSkill.java
#	agentscope-core/src/main/java/io/agentscope/core/skill/DynamicSkillMiddleware.java
#	agentscope-core/src/main/java/io/agentscope/core/skill/SkillBox.java
#	agentscope-core/src/main/java/io/agentscope/core/skill/SkillRegistry.java
#	agentscope-core/src/test/java/io/agentscope/core/skill/AgentSkillPromptProviderTest.java
#	agentscope-core/src/test/java/io/agentscope/core/skill/AgentSkillTest.java
#	agentscope-core/src/test/java/io/agentscope/core/skill/DynamicSkillMiddlewareTest.java
#	agentscope-core/src/test/java/io/agentscope/core/skill/SkillBoxTest.java
#	agentscope-core/src/test/java/io/agentscope/core/skill/SkillBoxToolsTest.java
#	agentscope-core/src/test/java/io/agentscope/core/skill/SkillUtilTest.java
#	agentscope-extensions/agentscope-extensions-channel/agentscope-extensions-channel-common/src/test/java/io/agentscope/extensions/channel/common/BotLoopGuardTest.java
…ability-surface

# Conflicts:
#	agentscope-core/src/main/java/io/agentscope/core/tool/Toolkit.java
#	agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillLoadTool.java
…nsolidation

The notificationReachesModelRequestUnderRealScheduling test asserts on
MockModel.getLastMessages() right after call().block() returns. The
default memory hooks schedule a background consolidation model call
after the reply completes; on a fast Linux runner that call can win the
race and become the recorded "last" request, failing the assertion with
the consolidation prompt. Disable memory hooks in this test so the only
model request is the reasoning call under test.

Fixes the ubuntu-latest failure in PR CI run 41024248628.
# Conflicts:
#	agentscope-core/src/main/java/io/agentscope/core/tool/AgentTool.java
@jujn jujn added the P2 重要不紧急 label Nov 3, 2026
…mory pipeline

Main's new memoryRead_* isolation tests assert MEMORY.md contents
immediately after call(), but the fire-and-forget flush -> consolidation
pipeline reuses the stub model: its fixed response gets extracted,
appended to the daily ledger and then consolidated into MEMORY.md,
racing the assertions (CI Linux saw 'done' where '' was expected).
These two tests target namespace isolation, not flush behaviour —
disable memory hooks so they are deterministic.
@xzxiaoshan

Copy link
Copy Markdown
Collaborator Author

[P2] 已修复优化
[P1-2] 已修复优化
[P1-1] 已修复优化(call 拦截校验处理已经处理这个入口校验;并已对标记过时的 skillbox 和 SkillHook 做了兼容处理)

@xzxiaoshan
xzxiaoshan requested a review from juruoO-o November 11, 2026 13:19

@juruoO-o juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复审基于 dcda800f5eed4e7c3dfe3f1337ba4d16bbac18ee。

感谢继续修复。需求和主要设计方向仍然值得支持;本次已实测确认,之前直接使用 DynamicSkillMiddleware、未配置授权时丢失 Skill 目录的兼容问题已经修复。静态提示词裁剪和按调用缩小沙箱缓存投影也是有效改进。

不过,前两项尚未覆盖完整调用链,另外发现一个新的源码兼容问题,因此仍建议 Request changes:

  1. [P1] 静态 Skill 仍通过 loader schema 暴露目录。 静态提示词已按 surface 裁剪,但静态 load_skill_through_path 的 skillId.enum 仍来自完整 SkillRegistry。独立探针实测:继承 DENY_ALL 时,模型提示词已不包含秘密 Skill,模型收到的 loader schema 却仍包含 beta_market。请同步裁剪模型可见的 loader schema,或采用不携带完整目录的 schema,并增加同时检查 messages 和 tool schemas 的回归用例。
    相关位置:SkillHook.java:57-59;SkillToolFactory.java:223-238。

  2. [P1] 缩小投影范围不能撤销复用沙箱中的旧 Skill 文件。 新实现限制本次投影 archive 的内容,但 AbstractBaseSandbox.applyWorkspaceProjectionIfChanged 只 hydrate 新文件,未清理此前投影进入 workspace、如今已不再授权的文件。使用实际 AbstractBaseSandbox 生命周期和本地模拟后端复现:首次投影 beta,stop 后将 includeRoots 缩为空,再次 start,沙箱 workspace 中的 beta/run.sh 仍可读取。当前 projection-narrowing 测试主要断言传给 manager 的 spec,无法发现目标 workspace 残留。请覆盖复用 workspace 和快照恢复路径,确保当前调用的可访问内容符合授权;清理不能破坏其他并发调用。本次未执行真实云端沙箱测试。
    相关位置:SandboxLifecycleMiddleware.narrowSkillsCacheProjection;AbstractBaseSandbox.applyWorkspaceProjectionIfChanged。

  3. [P2] 新增公开重载使原有 null 调用无法编译。 原有 SkillFilter 参数明确支持 null 表示全部可见。新增 getSkillPrompt(CapabilitySurface) 和 getSkillSystemPrompt(Predicate<AgentSkill>) 后,以下原有调用都会因重载歧义而编译失败:

    box.getSkillPrompt(null);
    provider.getSkillSystemPrompt(null);

    已用 javac 验证:上一评审版本可编译,当前版本报 ambiguous method reference。建议将新方法改为不同名称,或仅作为内部方法使用,保留原有源码调用的兼容性。
    相关位置:SkillBox.java:178;AgentSkillPromptProvider 新增 Predicate 重载。

验证:本次运行 10 个相关测试类,共 143 项通过;另外通过模型输入/schema 捕获、本地模拟沙箱生命周期和 javac 编译探针复现上述问题。未运行全量测试或真实云端沙箱测试。

整体设计不需要因这几项问题推倒重来,但需要把展示、实际文件访问和兼容性这几个边界补齐后再合入。

…keep null-call source compat

- rewriteMetaToolSchema now also rewrites the load tool's skillId enum when
  the surface is restricted: candidates come from the schema itself,
  filtered by allowsSkill(id); empty result removes the enum key. The
  static skillBox path baked the full registry into the enum at build
  time, so a restricted surface (incl. inherited DENY_ALL) enumerated
  unauthorized skills to the model. Unrestricted surfaces and external
  request-config overrides pass through untouched.
- SkillBox.getSkillPrompt(CapabilitySurface) and the provider's
  Predicate<AgentSkill> overload become package-private: the public
  same-arity overloads documented 'null treated as all', and a public
  addition made external getSkillPrompt(null) / getSkillSystemPrompt(null)
  calls ambiguous (javac-confirmed source break).
- golden assertions now check messages AND tool schemas; a cross-package
  uncast null call locks the source-compat contract.
…sandboxes

Workspace projection is now authoritative instead of overlaying: the
applied manifest (projectedWorkspacePaths, persisted on SandboxState)
drives revocation of every previously projected file the current call no
longer authorizes — covering the reused-workspace path (Branch A) and
snapshot restores (Branches B/C force the pass past the hash check).
Manifest paths are untrusted input: a strict character whitelist plus
single-quoted rm -f operands leaves no shell expansion vector, and
deletion failures abort the start (fail-closed). Emptied parent dirs are
rmdir-pruned chunked, deepest-first, so revoked skill names do not linger
as empty trees. Default primitive runs through doExec (the only channel
for remote backends); host-backed sandboxes may override with native
deletion. Docs (zh/en) updated to state entered files are revoked.
…ew nits

- pin the generated deletion command shape (rm -f -- with single-quoted
  operands, never rm -r) so the containment cannot regress silently
- end-to-end fail-closed test: a traversal entry in the persisted
  projection manifest aborts the sandbox start
- guard the DENY_ALL loader-enum assertion against a vacuous pass when
  the loader schema is absent entirely
- O(1) set lookup for the projected-path diff on every start
@xzxiaoshan

Copy link
Copy Markdown
Collaborator Author

三项都已修复:

  • loader schema 枚举:沿用 reset_equipped_tools 的模式,在 Toolkit 按 surface 同步收窄 skillId.enum,全部未授予时移除枚举键;回归测试已同时断言 messages 与 tool schemas,DENY_ALL 下枚举键消失。
  • 投影残留:投影改为权威替换——记录上次投影清单,start 时差集撤销,快照恢复分支强制执行;按你的复现场景(复用 workspace、快照恢复)补了测试。删除只针对自己投影过的文件,白名单校验 + 文件级 rm -f、无 -r,篡改清单直接中止启动。
  • 重载歧义:两个新重载降为 package-private,公开 API 零变化,原 null 调用恢复无歧义,有跨包编译测试锁定。

提交: 0d487d9e8、395fc3c0b、d88c74506、5fd49e5e0。请复审。

@juruoO-o juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复审基于 5fd49e5e0f25e55b080d2c2cdd0d775eae4c5ca1。

感谢继续修复。上轮三个问题的直接复现场景已通过:静态 loader schema 不再枚举未授权 Skill;有新投影清单的复用 workspace 可以撤销旧文件;原有 getSkillPrompt(null) / getSkillSystemPrompt(null) 恢复源码兼容。授权能力和主要设计方向仍然值得支持。

目前仍建议 Request changes。新增撤销逻辑还存在以下升级和兼容性问题:

  1. [P1] 旧 SDK 的 workspace 没有投影清单,升级后首次收紧授权仍可能留下旧脚本。 新增 projectedWorkspacePaths 在旧状态中不存在,但 applyWorkspaceProjectionIfChanged 将 null 清单当作没有需要撤销的文件。独立探针实测:保留含 beta 脚本的 workspace、模拟旧状态(projectedWorkspacePaths=null),将当前投影收为空后重新启动,beta/run.sh 仍存在且可读取。需要明确处理缺少可信清单的旧 workspace:安全重建、建立可信清单,或明确拒绝不支持的组合;不能把缺少元数据当作已完成隔离。当前快照测试先经过新版 start,已经有清单,未覆盖这一升级场景。
    位置:AbstractBaseSandbox.java:425-434。

  2. [P1] 合法资源文件名会导致后续启动失败。 requireSafeProjectedPath 只接受 [A-Za-z0-9._/-]+,但投影构建和资源加载并没有禁止空格、中文等合法文件名。独立探针实测:user guide.md 首次可以正常投影,后续撤销时却抛出 unsafe projected path in manifest 并中止启动;中文路径也会被该规则拒绝。这套逻辑作用于所有 projection-managed 文件,而非仅开启授权的调用,因此旧用户未启用授权也可能受影响。建议将路径边界验证与 shell 参数安全编码分开,支持既有合法路径,不能把合法文件名当作篡改清单。
    位置:AbstractBaseSandbox.java:392-399。

  3. [P2] 新增清单字段改变了既有公开构造器。 WorkspaceProjectionApplier.ProjectionPayload 从三参数 record 改成四参数,原公开构造器消失。已用 javac 验证:原有 new ProjectionPayload("hash", new byte[0], 0) 在上轮版本可编译,在当前版本无法编译;已编译调用方也存在链接兼容风险。建议保留原有构造入口,或将新增内部元数据与既有公开契约分离。
    位置:WorkspaceProjectionApplier.java:159-160。

从维护范围看,请特别注意:修复调用级授权不应无条件改变所有用户的通用 workspace 投影语义。撤销范围和启用条件需要清楚,保持未启用新授权时的兼容行为。

验证:本次运行 11 个相关测试类,共 150 项通过;另以实际 AbstractBaseSandbox 生命周期、本地 filesystem/shell 后端探针和 javac 编译探针验证上述问题。未运行全量测试或真实云端沙箱测试。

…it path validation from shell encoding

Review round 3, scope rule: fixing the authorization boundary must not
change the generic workspace projection semantics for everyone else.

- WorkspaceProjectionEntry.authorizationManaged (transient): set only by
  the grant-aware narrowing in SandboxLifecycleMiddleware. Managed specs
  apply authoritatively (manifest-diff revocation, upgrade refusal when
  a hash exists without a manifest); unmanaged specs keep the historic
  overlay semantics — hydrate only, never delete, never refuse. An
  unmanaged content change invalidates the recorded manifest so a later
  managed pass cannot under-revoke against stale bookkeeping.
- Path validation now checks boundaries only (absolute, ./.. segments,
  backslash, NUL); every legal filename — spaces, unicode, shell
  metacharacters — round-trips. Command safety moved to POSIX
  single-quote escaping (shellQuote), so legal resource names can no
  longer break subsequent starts (previously rejected by the charset
  whitelist, affecting users who never enabled authorization).
- ProjectionPayload regains the public three-argument constructor
  (paths default empty) for source and binary compatibility.
- Tests: unmanaged overlay semantics, legacy-state refusal (unchanged
  projection still runs), manifest invalidation on unmanaged change,
  legal-filename round-trip, boundary rejections, compat constructor.
…ting missing bookkeeping

Three independent audits (security/compat/correctness) converged on one
root cause: a missing revocation manifest was treated as 'nothing to
revoke' whenever the hash was null too, so the resume-failure fallback
(fresh state + carried-over snapshot), entry-less specs and pre-manifest
upgrades all failed open.

- managed pass without a manifest now REBUILDS: wipes the managed
  namespaces (new revokeRoots on WorkspaceProjectionEntry, set by the
  grant-aware narrowing to the .skills-cache tree) via doDeleteWorkspaceRoots
  (recursive by design, but on validated spec-declared roots only, quoted
  and fail-closed), then re-projects and records a fresh manifest — no
  stale file of any earlier era survives, no user-facing refusal
- marked entry without revokeRoots fails closed (cannot be made safe)
- unmanaged pass without a projection entry leaves all bookkeeping
  untouched (the diff baseline survives); the workspace-root probe is
  now shell-quoted
- cache-root matching tolerates variant spellings (./x, x/) so
  narrowing is never silently disabled; a WARN fires when the
  projection-aware callback cannot narrow the sandbox
- authorizationManaged is @JsonIgnore (per-call runtime intent);
  ProjectionPayload keeps the 3-arg constructor (source/binary compat)
- tests: rebuild scenarios replace refusals (legacy state, unmanaged
  overlay, resume carry-over), force pinned by an unchanged-spec
  restore, apostrophe filenames via a POSIX-accurate fake operand
  parser, chunk-boundary and trailing/duplicate-slash rejections
Second independent audit round (compliance / regression / integration)
converged on residual issues; all fixed here:

- force revived with real semantics: a managed snapshot restore never
  hash-skips and always rebuilds — restored archives are untrusted events
  (persist-order skew, concurrent last-write-wins, backend snapshot
  rebinding can leave wider-era content no bookkeeping describes). The
  parameter had become dead in 9fa7d54, which both auditors and a
  maintainer-replay audit flagged; docs and the start() comment now
  match the behavior, and the restore test pins it with an intact
  manifest (deleting force turns it red)
- managed semantics gated on authorization being engaged (a restricted
  capability surface on the call context): stager presence alone no
  longer enables revocation/rebuild — deployments that never enable the
  grant layer keep the generic overlay projection semantics entirely
- .skills-cache declared an exclusively managed namespace (javadoc) and
  a test pins that rebuild clears foreign files there on purpose
- narrowed projection entry now copies the inherited ephemeral flag
- cache-root matching normalized via Path comparison (interior // and .
  variants no longer silently disable narrowing); the no-cache-entry
  log demoted to debug when the grant list is empty; a WARN fires when
  grant narrowing is derived for an external-sandbox context (silently
  discarded by the external acquire priorities)
- revokeRoots is @JsonIgnore like the marker (per-call runtime intent)
- external-sandbox semantics documented on SandboxContext
- tests: legacy manifest-less state narrowed to empty (the reviewer's
  literal probe), foreign-file ownership, marker gating in the
  middleware; the fake's tar writer pins UTF-8 entry names to match the
  extractor (with the applier, whose tar output is now UTF-8 too)
…ON shape, comment)

- force rebuilds log mode=rebuild (was mislabeled diff)
- isCacheRoot treats platform-illegal root spellings as a non-match
  instead of an InvalidPathException failing the call
- projectedWorkspacePaths is @JsonInclude(NON_NULL): deployments that
  never engage the grant layer keep the exact pre-grant persisted-state
  shape (removes the rollback-deserialization hazard for them)
- narrowing comment states its provenance accurately (the
  maintainer-requested per-call projection constraint), not 'historic
  behaviour'
…stale javadoc

Same class as the projection-tar fix: this archive is extracted
container-side where tar decodes names as UTF-8, so the platform
default mangles non-ASCII paths on non-UTF-8 JVMs. Also fixes the
acquireForCall javadoc that referenced a caller that does not exist.
The GLOBAL isolation-scope state-slot sharing question is left for
upstream (changing the slot key would alter existing sharing
semantics).
… concurrency posture

Fourth audit round (probe replay x2 + scope convergence): PROBE-1-PASS,
PROBE-2-PASS, SCOPE-HELD. Closing the residual gaps:

- SandboxProjectionStateShapeTest pins the serialization contract: a
  null manifest is omitted (grant-free persisted state keeps the exact
  pre-grant JSON shape, safe to roll back), a recorded manifest
  persists, and a projection entry never serializes the managed marker
  or revoke roots (per-call runtime intent; tampered persisted state
  can neither self-declare managed semantics nor inject revoke roots)
- legal-filename test pins projected existence for every name
- docs (zh/en): grant state is never persisted; grant-free rollbacks
  are shape-identical; grant-enabled downgrades degrade to WARN +
  workspace recreate; multi-instance deployments should configure a
  real execution guard (default Noop is last-write-wins)
@xzxiaoshan

Copy link
Copy Markdown
Collaborator Author

三个问题均已修复,处理方式如下:

[P1] 旧状态投影清单 — 采用您给出的"安全重建"选项:清单缺失时不再当作"无可撤销",而是清除受管命名空间(收窄接线随标记声明 revokeRoots=.skills-cache)后重投影,并建立可信清单;快照恢复视为不可信事件,一律强制重建(防持久化时序错位/快照回绑留下宽授权残留);标记但未声明撤销范围的组合显式拒绝(fail-closed)。您的探针场景(旧状态 + 收窄到空)已钉死测试:beta 被清除、清单建立、无重建循环。

[P1] 合法文件名 — 校验与编码已分离:路径校验只拒绝边界违规(绝对路径、../空段、反斜杠、NUL),空格/中文/撇号/元字符全部放行;命令安全改由 POSIX 单引号转义构造保证。user guide.md、中文路径、it's.md 的投影→撤销往返有测试钉死,tar 名两端钉 UTF-8(防非 UTF-8 JVM 下名字错配)。

[P2] 构造器 — 三参构造器已恢复(委托 paths=空),源码与二进制兼容,有编译级测试锁定。

范围规则:撤销/重建/拒绝语义仅在调用带受限授权面时启用;未配置 resolver 的部署保持纯叠加投影——零删除、零拒绝,持久化 JSON 与旧版逐字段一致(NON_NULL + 运行时意图字段 @JsonIgnore,形状有测试钉死),可安全回滚。

@juruoO-o juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复审基于 44cf311112fe5b3956ea0cb4b61f09b7b4d78e81,此前提出的阻塞项已修复,本轮未发现新的合入阻塞。

已验证:静态 Skill 提示词和 loader schema 均按授权裁剪;直接使用动态 Skill 中间件保持旧行为;旧 workspace 缺失投影清单时,受限授权路径会安全重建受管缓存;空格、中文和撇号文件名可正确撤销;原有 null 参数调用和 ProjectionPayload 三参数构造器保持源码兼容,旧编译产物的构造器调用也通过验证。

修复范围已收敛:未启用授权时保持原来的叠加投影,不执行撤销删除;受限授权下才启用撤销和重建,独立探针确认受管目录外文件保持不变。

需求值得框架支持,当前设计与已有过滤机制、Permission 的职责关系已明确,实现状态可以接受。

验证:165 项定向测试通过;额外本地探针、源码/二进制兼容探针及 diff 检查通过;GitHub Linux/Windows 构建通过。未执行真实云端沙箱测试,外部自管沙箱和多实例并发需遵守文档中的约束。

Approve。

@juruoO-o
juruoO-o merged commit 5e1a102 into agentscope-ai:main Nov 12, 2026
7 checks passed
chaucerj added a commit to chaucerj/agentscope-java that referenced this pull request Nov 12, 2026
…m RuntimeContext grant-resolution (agentscope-ai#3500) alongside reload lever + per-scope entry-delivery dedup; loadSkillResourceImpl signature gains rc, scope, reload
xzxiaoshan added a commit to xzxiaoshan/agentscope-java that referenced this pull request Nov 12, 2026
… capability surface onto the version-contract architecture

Merge main (capability-surface agentscope-ai#3500 + 4 unrelated fixes) into
feat/skill-mirror-1-version-contract. Textual conflicts resolved in 5
files; grant-layer mounting points re-attached semantically:

- DynamicSkillMiddleware: keep the branch rewrite (per-call box, version
  routing) as the skeleton; re-add applyCapabilityFilter from agentscope-ai#3500
  adapted to the SkillEntry view (surface.allowsSkill(entry.skill)),
  mounted in reloadSkills after the filterVisible hook and before
  buildBox — surface absent = unchanged, present = grants filter,
  filter error = fail-closed empty set; empty result yields no box.
  Dropped the stale boxCache/signature tail (box cache is retired).
- HarnessSkillMiddleware: keep agentscope-ai#3500 prestageForProjection /
  applyCapabilityFilter / catalog-install filtering and the branch
  mergeRepositories serving rules side by side; capability filter still
  runs after applySkillFilter at both prestage and install sites.
- AgentSkill: unified seven-arg constructor (metadata, skillContent,
  resources, source, originDir, version, system); public six-arg
  (…, version) delegates system=false; Builder carries both fields and
  toBuilder/copy preserve both (system = grant bypass, version =
  provenance).
- ReActAgent: capabilityResolver and skillVersionPolicy fields coexist;
  build-time ISE check (capabilityResolver × dynamicSkillsEnabled=false)
  and the call-entry surface funnel survive verbatim.
- DynamicSkillMiddlewareTest: branch structure kept; the surface
  present/absent minimal smoke tests (restrictedSurfaceStillFiltersOn-
  DirectUse / directUseWithoutSurfaceKeepsVisibleSkills) cover agentscope-ai#3500
  semantics; the routing test stubs the version-route primitives.
xzxiaoshan added a commit to xzxiaoshan/agentscope-java that referenced this pull request Nov 12, 2026
…rsion-contract serving rules (S4)

Plain repositories are no longer enumerated without an explicit
SkillFilter.only selection, so the agentscope-ai#3500 grant tests' plain stubs served
an empty catalog (a serving-rule artifact, not an authorization one).
The stubs now implement RuntimeContextSkillRepository with a per-request
getAllSkills(ctx) — assertion semantics unchanged:

- CapabilityGrantIntegrationTest.StubRepo: context-scoped; the
  same-name-merge fixture now uses two repositories (the documented
  later-wins merge is a cross-repository rule; the serving primitive is
  name-addressed within one repo), assertions untouched.
- SystemCapabilityMarkerTest.EmptyRepo: implements the serving primitive
  getSkill(name, version); still serves nothing.
- HarnessAgentCapabilityResolverTest.StubRepo,
  HarnessSkillMiddlewareGrantTest.StubRepo,
  SandboxLifecycleMiddlewareCallbackTest.StubSkillRepository:
  context-scoped so prestage/catalog paths enumerate them per request.

§5.3 tripwire table green: core 171+23 (incl. ReActAgentHitlTest),
harness 51.
xzxiaoshan added a commit to xzxiaoshan/agentscope-java that referenced this pull request Nov 12, 2026
… name (§4-S8)

Audited both pages against the version-contract architecture after merging
agentscope-ai#3500: no conflicting "box cache" / "getAllSkills" statements exist (the
pages never mention them; per-call boxes and the no-enumeration serving
rule leave the documented behaviors intact). One deliberate decision was
missing and is now written down symmetrically in EN and ZH: one grant
entry covers every VERSION of the name — PIN-anchored old versions,
mirror-cache-resident historical versions and the current latest —
because version references never participate in grant matching
(per-version authorization is a future requirement, not a current
behavior).

docs npm test + validate green; broken-links reports the known local
false positives (2230 across 328 files, pre-existing on this machine).
xzxiaoshan added a commit to xzxiaoshan/agentscope-java that referenced this pull request Nov 12, 2026
…of the ordering flake

GracefulShutdownManager.resetForTesting() restored state, requests, savers
and the monitor but not the config field, so any test that setConfig()s a
custom timeout (e.g. shutdownTimeoutSignal's 100ms) leaked it into every
later test sharing the singleton JVM — full-load runs then failed
StateAndConfigTests.defaultConfig (expected null, saw PT0.1S) whenever the
method order put it afterwards, while isolation runs passed. Resetting to
GracefulShutdownConfig.DEFAULT mirrors the initial state the method
already promises ("restores initial state") and kills the ordering
dependence at its root.

Diagnosed during the agentscope-ai#3500 merge self-check's full verify; reproduced
twice under -T1C full load, green in isolation before the fix, 51/51
after.
chickenlj added a commit to chickenlj/agentscope-java that referenced this pull request Nov 16, 2026
Address kernel-level failure modes found in bench trajectories so agents
recover from bounded outputs, stale ownership and incomplete memory work
instead of looping or losing facts.

- RepeatedFailureGuard: initialize per invocation at ON_AGENT_STATE_READY
  and track ownership with a private InvocationToken that survives Core
  RuntimeContext copies; missing and ungranted tools stay indistinguishable.
- ReActAgent/MiddlewareBase: deliver producer events and post-acting
  feedback to middleware consistently.
- Shell: bounded capture with archive, raw digest and cancellation cleanup.
- Subagents: dynamic snapshots, owner-registry gating and context-aware
  gateway exposure with materializer recovery.
- Thread history pagination, memory_get long-line recovery, and memory
  commit veto for incomplete flush/consolidation.
- Docs (EN/ZH) updated for middleware, harness architecture, context,
  filesystem, memory, session-log and subagent behavior.

Constraint: Preserve agentscope-ai#3500 - missing vs ungranted tools indistinguishable
Constraint: Kernel only; adapter, PI, H2/H3 and business rules untouched
Rejected: Ctx-reference ownership | Core copies RuntimeContext mid-call
Confidence: high
Scope-risk: moderate
Not-tested: Real Java 17 runtime (built with JDK 21, release 17)
Not-tested: Windows/Linux, e2e group, GitSkillRepositoryTest, WeixinLiveSmokeTest
Not-tested: Real model semantics for memory pipeline; historical bench replay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment