Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions go/internal/agent/atomic_composition_workflow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"
"time"

"github.com/nanzhi84/Rushes/go/internal/agentexec"
"github.com/nanzhi84/Rushes/go/internal/agenttest"
"github.com/nanzhi84/Rushes/go/internal/media"
"github.com/nanzhi84/Rushes/go/internal/storage"
Expand Down Expand Up @@ -79,7 +80,7 @@ func TestInitialCompositionFixtureUsesSearchAndAtomicInserts(t *testing.T) {
}
}

func TestBeatCompositionFixtureUsesDetectorSearchAndAtomicEdits(t *testing.T) {
func TestBeatCompositionFixtureUsesHarnessAnalysisSearchAndAtomicEdits(t *testing.T) {
fakeBin := t.TempDir()
for name, body := range map[string]string{
"aubiotrack": "#!/bin/sh\nprintf '0.000000\\n1.000000\\n2.000000\\n3.000000\\n4.000000\\n'\n",
Expand Down Expand Up @@ -114,14 +115,11 @@ func TestBeatCompositionFixtureUsesDetectorSearchAndAtomicEdits(t *testing.T) {
ctx := withTestTurnLeaseSession(t, service, t.Context(), draftID)
trace := []string{}

beatsRaw, err := service.ExecuteTool(ctx, "audio.analyze_beats", rushestools.AudioBeatAnalysisInput{
AssetID: "beat_bgm", MaxBeats: 64, WaveformPoints: 16,
})
beats, err := service.executor.EnsureBeatAnalysis(t.Context(), draftID, "beat_bgm")
if err != nil {
t.Fatal(err)
}
trace = append(trace, "audio.analyze_beats")
beats := beatsRaw.(rushestools.AudioBeatAnalysisResult)
trace = append(trace, "Harness:audio.analyze_beats")
if beats.DurationFrames != 120 || !slices.Contains(beats.BeatFrames, 60) ||
len(beats.Waveform.Samples) == 0 {
t.Fatalf("beats=%#v", beats)
Expand Down Expand Up @@ -149,17 +147,9 @@ func TestBeatCompositionFixtureUsesDetectorSearchAndAtomicEdits(t *testing.T) {
}
trace = append(trace, "timeline.insert")
}
beatGrid := map[string]any{
"bpm": beats.BPM, "beat_frames": beats.BeatFrames,
"strong_beat_frames": beats.StrongBeatFrames,
"downbeat_frames": beats.DownbeatFrames,
"bar_phase": beats.BarPhase,
"analysis_method": beats.AnalysisMethod,
}
bgmRaw, err := service.ExecuteTool(ctx, "timeline.insert", rushestools.TimelineInsertInput{
"kind": "insert_clip", "track_id": "bgm", "asset_id": "beat_bgm", "role": "bgm",
"timeline_start_frame": 0, "source_start_frame": 0, "source_end_frame": 120,
"metadata": map[string]any{"beat_grid": beatGrid},
})
if err != nil || bgmRaw.(rushestools.ToolResult).Status != string(rushestools.StatusSucceeded) {
t.Fatalf("bgm insert=%#v err=%v", bgmRaw, err)
Expand Down Expand Up @@ -204,6 +194,10 @@ func TestBeatCompositionFixtureUsesDetectorSearchAndAtomicEdits(t *testing.T) {
timelineTrackClips(final, "sfx")[0].GainDB != -12 {
t.Fatalf("final=%#v err=%v", final, err)
}
bgmMetadata := timelineTrackClips(final, "bgm")[0].Metadata
if agentexec.StringValue(bgmMetadata["beat_analysis_id"]) != beats.AnalysisID {
t.Fatalf("BGM 缺少 Harness 权威拍点投影: %#v", bgmMetadata)
}
var singleOperationBatches int
if err := database.Read().QueryRowContext(t.Context(), `
SELECT COUNT(*) FROM timeline_edit_batches
Expand Down
19 changes: 7 additions & 12 deletions go/internal/agent/beat_mix_material_live_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"testing"
"time"

"github.com/nanzhi84/Rushes/go/internal/agentexec"
"github.com/nanzhi84/Rushes/go/internal/agenttest"
"github.com/nanzhi84/Rushes/go/internal/media"
"github.com/nanzhi84/Rushes/go/internal/timeline"
Expand Down Expand Up @@ -73,13 +74,10 @@ func TestBeatMixRealMaterialAcceptance(t *testing.T) {
}
t.Cleanup(service.Close)
ctx := rushestools.WithDraftID(t.Context(), "draft_beat_mix_real")
beatOutput, err := service.ExecuteTool(ctx, "audio.analyze_beats", rushestools.AudioBeatAnalysisInput{
AssetID: "beat_bgm", MaxBeats: 512, WaveformPoints: 96,
})
beats, err := service.executor.EnsureBeatAnalysis(t.Context(), "draft_beat_mix_real", "beat_bgm")
if err != nil {
t.Fatal(err)
}
beats := beatOutput.(rushestools.AudioBeatAnalysisResult)
if beats.BPM <= 0 || beats.DurationFrames < 1400 || len(beats.BeatFrames) < 20 || len(beats.Waveform.Samples) == 0 {
t.Fatalf("beats=%#v", beats)
}
Expand All @@ -88,7 +86,7 @@ func TestBeatMixRealMaterialAcceptance(t *testing.T) {
if !ok {
t.Fatalf("三个真实视频不足以按真实拍点覆盖 BGM: target=%d durations=%v", beats.DurationFrames, videoDurations)
}
trace := []string{"audio.analyze_beats"}
trace := []string{"Harness:audio.analyze_beats"}
start := 0
for index, end := range cuts {
raw, executeErr := service.ExecuteTool(ctx, "timeline.insert", rushestools.TimelineInsertInput{
Expand All @@ -104,13 +102,6 @@ func TestBeatMixRealMaterialAcceptance(t *testing.T) {
bgmRaw, err := service.ExecuteTool(ctx, "timeline.insert", rushestools.TimelineInsertInput{
"kind": "insert_clip", "track_id": "bgm", "asset_id": "beat_bgm", "role": "bgm",
"timeline_start_frame": 0, "source_start_frame": 0, "source_end_frame": beats.DurationFrames,
"metadata": map[string]any{"beat_grid": map[string]any{
"bpm": beats.BPM, "beat_frames": beats.BeatFrames,
"strong_beat_frames": beats.StrongBeatFrames,
"downbeat_frames": beats.DownbeatFrames,
"bar_phase": beats.BarPhase,
"analysis_method": beats.AnalysisMethod,
}},
})
if err != nil || bgmRaw.(rushestools.ToolResult).Status != string(rushestools.StatusSucceeded) {
t.Fatalf("bgm insert=%#v err=%v", bgmRaw, err)
Expand All @@ -132,6 +123,10 @@ func TestBeatMixRealMaterialAcceptance(t *testing.T) {
if !timeline.Validate(document).Valid || document.DurationFrames != beats.DurationFrames || len(document.Tracks[0].Clips) != 3 {
t.Fatalf("timeline=%#v", document)
}
bgm := timelineTrackClips(document, "bgm")
if len(bgm) != 1 || agentexec.StringValue(bgm[0].Metadata["beat_analysis_id"]) != beats.AnalysisID {
t.Fatalf("BGM 缺少 Harness 权威拍点投影: %#v", bgm)
}
beatSet := map[int]struct{}{}
for _, frame := range beats.BeatFrames {
beatSet[frame] = struct{}{}
Expand Down
44 changes: 40 additions & 4 deletions go/internal/agent/context_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ func (builder *ContextBuilder) Build(ctx context.Context, draftID string) (strin
return "【当前草稿最新 WorldState】\n" + string(raw) +
"\nsections 是当前客观状态的唯一事实源;历史回复和 recent_edit_history 不能覆盖它。" +
"user_memory 是跨草稿的用户长期偏好;与当前用户指令冲突时以本回合指令为准,并用 memory.set 更新记忆。" +
"assets.material_catalog 是常驻精简素材目录;详细镜头语义必须按创作意图调用 shot.search 检索;完整口播转写不常驻,speech_searchable=true 时按需调用 speech.search,缺少索引时先调用 speech.transcribe。" +
"timeline 中 beat_grid.waveform 仅常驻最多 24 点摘要:point_count 是完整压缩波形点数,sample_interval_frames 是原始 RMS 窗口宽度,sample_frames 是按 timeline_fps 标尺表示的摘要点素材内帧坐标并与 samples 一一对应,loudness_min/mean/max 汇总完整波形的 0–100 原始响度;完整波形必须按创作意图调用 audio.analyze_beats 获取,摘要不包含高潮标签。" +
"assets.material_catalog 是常驻精简素材目录;详细镜头语义必须按创作意图调用 shot.search 检索;完整口播转写不常驻,按需调用 speech.search,Harness 会先确保目标 transcript 就绪。" +
"assets.audio_roles 中已选 BGM 的 beat_analysis 是 Harness 持久化的完整拍点证据;若尚未出现,选定或插入 BGM 时 Harness 会自动分析并在下一次 provider 调用前注入。模型不得自行复制或构造 beat grid。" +
"timeline 中 beat_grid.waveform 仅常驻最多 24 点摘要:point_count 是完整压缩波形点数,sample_interval_frames 是原始 RMS 窗口宽度,sample_frames 是按 timeline_fps 标尺表示的摘要点素材内帧坐标并与 samples 一一对应,loudness_min/mean/max 汇总完整波形的 0–100 原始响度;摘要不包含高潮标签。" +
"人工编辑已经保存,不要要求用户重做;需要继续剪辑时直接基于当前轨道和片段。", nil
}

Expand Down Expand Up @@ -100,6 +101,18 @@ func (builder *ContextBuilder) buildSnapshotMap(
readyUnderstanding := 0
assetByID := make(map[string]storage.Asset, len(assets))
audioRoles := make([]map[string]any, 0)
contentHashes := make([]string, 0, len(assets))
for _, asset := range assets {
if asset.Hash != "" {
contentHashes = append(contentHashes, asset.Hash)
}
}
beatAnalyses, err := storage.LatestAssetAnalysesForContentHashes(
ctx, builder.database.Read(), contentHashes, agentexec.BeatAnalysisType,
)
if err != nil {
return nil, err
}
for _, asset := range assets {
kindCounts[asset.Kind]++
assetByID[asset.ID] = asset
Expand All @@ -108,10 +121,14 @@ func (builder *ContextBuilder) buildSnapshotMap(
}
if asset.Kind == "audio" {
duration, _ := agentexec.NumericValue(asset.Probe["duration_sec"])
audioRoles = append(audioRoles, map[string]any{
role := map[string]any{
"asset_id": asset.ID,
"suggested_role": understanding.ClassifyAudioRole(asset.Filename, duration),
})
}
if analysis, exists := beatAnalyses[asset.Hash]; exists {
role["beat_analysis"] = beatAnalysisWorldState(analysis)
}
audioRoles = append(audioRoles, role)
}
}

Expand Down Expand Up @@ -201,6 +218,25 @@ func (builder *ContextBuilder) buildSnapshotMap(
return sanitizeContextMap(snapshot), nil
}

func beatAnalysisWorldState(analysis storage.AssetAnalysis) map[string]any {
result := map[string]any{
"analysis_id": analysis.ID,
"analyzer_version": analysis.AnalyzerVersion,
"output_schema_version": analysis.OutputSchemaVersion,
}
for _, key := range []string{
"bpm", "timeline_fps", "duration_frames", "beat_frames",
"strong_beat_frames", "downbeat_frames", "every_two_beat_frames",
"every_four_beat_frames", "bar_phase", "analysis_method", "truncated",
"phase_note",
} {
if value, exists := analysis.Result[key]; exists {
result[key] = value
}
}
return result
}

// userMemoryContext 把工作区级用户记忆按 last_confirmed_at DESC 顺序装进预算。
// statement 明确按最近确认/使用顺序注入 top-N;完整 keys 始终提供复用锚点,折叠项另以
// omitted_keys 标出。两份 key 目录都参与预算裁剪,最终快照不超过预算。规模同时进入
Expand Down
44 changes: 44 additions & 0 deletions go/internal/agent/context_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,50 @@ func TestContextBuilderShowsPlanHintAndDeduplicatesAudioRoles(t *testing.T) {
}
}

func TestContextBuilderProjectsPersistentBeatAnalysisWithoutWaveform(t *testing.T) {
t.Parallel()
database := agenttest.AgentTestDatabase(t)
const draftID = "draft_persistent_beat_context"
agenttest.CreateAgentDraft(t, database, draftID)
if _, err := database.Write().ExecContext(t.Context(), `
INSERT INTO assets(
asset_id,storage_mode,reference_path,kind,source,filename,hash,size,
probe_json,ingest_status,understanding_status,usable
) VALUES('audio_persistent_beat','reference','/tmp/context-bgm.wav','audio',
'local_path','context-bgm.wav','persistent_beat_hash',1,
'{"duration_sec":30}','ready','none',1);
INSERT INTO draft_asset_links(draft_id,asset_id,linked_at)
VALUES(?, 'audio_persistent_beat', '2026-08-02T00:00:00Z');
INSERT INTO asset_analyses(
analysis_id,asset_content_hash,analysis_type,analyzer_version,
normalized_options_json,output_schema_version,result_json,created_at
) VALUES(
'analysis_persistent_beat','persistent_beat_hash','beat_grid','fixture-v1',
'{"max_beats":2000}',1,
'{"bpm":120,"timeline_fps":30,"duration_frames":900,"beat_frames":[15,30,45],"strong_beat_frames":[15,45],"downbeat_frames":[15],"every_two_beat_frames":[15,45],"every_four_beat_frames":[15],"bar_phase":0,"analysis_method":"fixture","waveform":{"samples":[1,2,3]}}',
'2026-08-02T00:00:00Z'
)`, draftID); err != nil {
t.Fatal(err)
}

snapshot, err := NewContextBuilder(database).Snapshot(t.Context(), draftID)
if err != nil {
t.Fatal(err)
}
audioRoles := agentexec.WorldStateObjectSlice(
snapshot.Sections["assets"].(map[string]any)["audio_roles"],
)
if len(audioRoles) != 1 {
t.Fatalf("audio_roles=%#v", audioRoles)
}
analysis, ok := audioRoles[0]["beat_analysis"].(map[string]any)
if !ok || analysis["analysis_id"] != "analysis_persistent_beat" ||
analysis["bpm"] != float64(120) || len(agentexec.EffectFrameValues(analysis["beat_frames"])) != 3 ||
analysis["waveform"] != nil {
t.Fatalf("beat_analysis=%#v", analysis)
}
}

func TestMaterialCatalogPrioritizesUsedAndTranscriptAssetsWithStableOutput(t *testing.T) {
t.Parallel()
database := agenttest.AgentTestDatabase(t)
Expand Down
55 changes: 27 additions & 28 deletions go/internal/agent/edit_lease_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,17 +402,14 @@ func TestDiscoveryProviderCallsNeverAcquireTimelineEditLease(t *testing.T) {

func TestReadOnlyBeatAndTranscriptAnalysisNeverAcquireTimelineEditLease(t *testing.T) {
for index, test := range []struct {
prompt string
toolName string
exact bool
prompt string
expectedVisible string
}{
{prompt: "分析 BGM 拍点", toolName: "audio.analyze_beats"},
{prompt: "分析 BGM 拍点"},
{
prompt: "分析当前卡点混剪的 BGM 素材 asset_surface,返回完整可用拍点证据;只做分析,不编辑时间线。",
toolName: "audio.analyze_beats",
exact: true,
prompt: "分析当前卡点混剪的 BGM 素材 asset_surface,返回完整可用拍点证据;只做分析,不编辑时间线。",
},
{prompt: "读取口播逐字稿", toolName: "speech.transcribe"},
{prompt: "读取口播逐字稿", expectedVisible: "speech.search"},
} {
t.Run(test.prompt, func(t *testing.T) {
database := agenttest.AgentTestDatabase(t)
Expand Down Expand Up @@ -443,30 +440,32 @@ func TestReadOnlyBeatAndTranscriptAnalysisNeverAcquireTimelineEditLease(t *testi
if _, err := surface.Generate(turnCtx, []*schema.Message{user}); err != nil {
t.Fatal(err)
}
if !containsName(spy.bound[0], test.toolName) {
t.Fatalf("只读分析缺少 %s: %v", test.toolName, spy.bound[0])
firstBound := []string{}
if len(spy.bound) > 0 {
firstBound = spy.bound[0]
}
if test.exact && (len(spy.bound[0]) != 1 || spy.bound[0][0] != test.toolName) {
t.Fatalf("真实只读分析工具面=%v want=[%s]", spy.bound[0], test.toolName)
for _, internal := range []string{
"audio.analyze_beats", "audio.analyze_speech_pauses", "speech.transcribe",
} {
if containsName(firstBound, internal) {
t.Fatalf("Harness 内部工具泄露到模型面: %s in %v", internal, firstBound)
}
}
if test.expectedVisible != "" && !containsName(firstBound, test.expectedVisible) {
t.Fatalf("只读口播检索缺少 %s: %v", test.expectedVisible, firstBound)
}
if containsTimelineMutationTool(spy.bound[0]) {
t.Fatalf("只读分析泄露 mutation: %v", spy.bound[0])
if containsTimelineMutationTool(firstBound) {
t.Fatalf("只读分析泄露 mutation: %v", firstBound)
}
if _, err := surface.Generate(turnCtx, []*schema.Message{
user,
schema.ToolMessage(
`{"status":"succeeded"}`,
"call-read-analysis",
schema.WithToolName(test.toolName),
),
}); err != nil {
if _, err := surface.Generate(turnCtx, []*schema.Message{user}); err != nil {
t.Fatal(err)
}
if spy.calls != 2 || containsTimelineMutationTool(spy.bound[1]) {
t.Fatalf("分析终态后的工具面=%v calls=%d", spy.bound[1], spy.calls)
lastBound := firstBound
if len(spy.bound) > 1 {
lastBound = spy.bound[1]
}
if test.exact && (len(spy.bound[1]) != 1 || spy.bound[1][0] != test.toolName) {
t.Fatalf("真实只读分析终态工具面=%v want=[%s]", spy.bound[1], test.toolName)
if spy.calls != 2 || containsTimelineMutationTool(lastBound) {
t.Fatalf("分析终态后的工具面=%v calls=%d", lastBound, spy.calls)
}
if session.activeTurnID() != "" {
t.Fatalf("纯分析调用提前取得 edit lease: %q", session.activeTurnID())
Expand Down Expand Up @@ -508,7 +507,7 @@ func TestMixedBeatAnalysisAndTimelineEditBindsMutationUnderLease(t *testing.T) {
}); err != nil {
t.Fatal(err)
}
if spy.calls != 1 || !containsName(spy.bound[0], "audio.analyze_beats") ||
if spy.calls != 1 || containsName(spy.bound[0], "audio.analyze_beats") ||
!containsName(spy.bound[0], "timeline.insert") {
t.Fatalf("混合分析编辑工具面=%v calls=%d", spy.bound[0], spy.calls)
}
Expand Down Expand Up @@ -550,7 +549,7 @@ func TestBeatAnalysisThenCardEditBindsMutationUnderLease(t *testing.T) {
}); err != nil {
t.Fatal(err)
}
if spy.calls != 1 || !containsName(spy.bound[0], "audio.analyze_beats") ||
if spy.calls != 1 || containsName(spy.bound[0], "audio.analyze_beats") ||
!containsName(spy.bound[0], "timeline.insert") {
t.Fatalf("分析后编辑工具面=%v calls=%d", spy.bound[0], spy.calls)
}
Expand Down
Loading
Loading